class YandexDiskClass:
    def __init__(self):
        self.path_main = "TelegramCouponBOT"
        self.disk = YaDisk(config.DISK_LOGIN, config.DISK_PASSWORD_APP)
        elements = self.disk.ls("/")
        for element in elements:
            if element['isDir'] and element['displayname'] == self.path_main:
                return
        self.disk.mkdir(self.path_main)

    def get_user(self, userID):
        try:
            return self.disk.ls(f"{self.path_main}/{userID}")
        except:
            return None

    def mkdir_user(self, userID):
        try:
            self.disk.mkdir(f"{self.path_main}/{userID}")
        except:
            print(
                f"YandexDisk Error: <{userID}> Данный пользователь уже создан")

    def add_file(self, userID, file):
        if not self.get_user(userID):
            self.mkdir_user(userID)
        elements_path = file.split('/')
        file_name = elements_path[len(elements_path) - 1]
        self.disk.upload(file, f"/{self.path_main}/{userID}/{file_name}")
Beispiel #2
0
if not os.path.exists( path_backup_today ):
	try:
		os.makedirs( path_backup_today )
	except BaseException:
		print( 'Dir '+ path_backup_today +' already exists' )

os.chdir( path_backup_today ) # переходим в директорию с бекапами
######### <<

######### >> Создаём директорию для бекапа на ЯДиске
try_ = True
try_i = 1

while try_ != False and try_i <= 5:
	try:
		disk.ls( path_webdav_today )
		try_ = False
	except YaDiskException as e:
		if e.code == 404:
			dir_webdav = '/'
			for dir in path_webdav_today.split('/'):
				if dir:
					dir_webdav += dir +"/"
					try:
						dir_webdav_ls = disk.ls( dir_webdav )
					except YaDiskException as e:
						try:
							disk.mkdir( dir_webdav )
							try_ = False
						except YaDiskException as e:
							if e.code == 500:
parser.add_argument('--login', help='YaDisk login')
parser.add_argument('--password', help='YaDisk password')
parser.add_argument('--soft_version', help='Software version')
parser.add_argument('--base_dir', required=True, help='Base directory')
args = parser.parse_args()
BASE = args.base_dir
print(f'BASE DIR: "{BASE}"')

disk = YaDisk(args.login, args.password)
exe_file = None
for f in glob.glob(BASE + '\*.exe'):
    exe_file = f

if exe_file:
    deployed_exes = [
        x['path'] for x in disk.ls(YaDiskDir) if x['path'][-4:] == '.exe'
    ]
    src = os.path.realpath(exe_file)
    dst = YaDiskDir + '/' + os.path.basename(exe_file)
    disk.upload(src, dst)
    try:
        public_url = disk.publish(dst)
        resp = requests.post(
            URL,
            dict(token=args.secret,
                 version=args.soft_version,
                 download_link=public_url))
        assert resp.json()['success'] is True
    except:
        disk.rm(dst)
    else:
Beispiel #4
0
from YaDiskClient.YaDiskClient import YaDisk

login = ''
password = ''

disk = YaDisk(login, password)

print(disk.ls('/'))
disk.upload('example.py', 'example.py')
Beispiel #5
0
class YandexDiskClass:
    def __init__(self):
        self.path_main = "TelegramBOT"
        self.disk = YaDisk(config.DISK_LOGIN, config.DISK_PASSWORD_APP)
        elements = self.disk.ls("/")
        for element in elements:
            if element['isDir'] and element['displayname'] == self.path_main:
                return
        self.disk.mkdir(self.path_main)

    def get_departments(self):
        return self.disk.ls(self.path_main)

    def get_department(self, departmentName):
        try:
            return self.disk.ls(f"{self.path_main}/{departmentName}")
        except:
            return None

    def get_staffer(self, stafferID, departmentName):
        try:
            return self.disk.ls(
                f"{self.path_main}/{departmentName}/{stafferID}")
        except:
            return None

    def get_order_staffer(self, orderID, stafferID, departmentName):
        try:
            return self.disk.ls(
                f"{self.path_main}/{departmentName}/{stafferID}/{orderID}")
        except:
            return None

    def mkdir_department(self, departmentName):
        try:
            self.disk.mkdir(f"{self.path_main}/{departmentName}")
        except:
            print(
                f"YandexDisk Error: <{departmentName}> Данный отдел уже создан"
            )

    def mkdir_staffer(self, stafferID, departmentName):
        try:
            if self.get_department(departmentName):
                self.disk.mkdir(
                    f"{self.path_main}/{departmentName}/{stafferID}")
            else:
                print(
                    f"YandexDisk Error: <{departmentName}> Данный отдел не создан"
                )
        except:
            print(
                f"YandexDisk Error: <{stafferID}> Данный сотрудник уже добавлен в <{departmentName}>"
            )

    def mkdir_order(self, orderID, stafferID, departmentName):
        try:
            if self.get_staffer(stafferID, departmentName):
                self.disk.mkdir(
                    f"{self.path_main}/{departmentName}/{stafferID}/{orderID}")
            else:
                print(
                    f"YandexDisk Error: В <{departmentName}> этом отделе нет сотрудника <{stafferID}>"
                )
        except:
            print(
                f"YandexDisk Error: <{orderID}> Данный заказ уже добавлен сотруднику <{stafferID}> отдела <{departmentName}>"
            )

    def rename_department(self, departmentNameOld, departmentNameNew):
        try:
            self.disk.mkdir(f"/{self.path_main}/{departmentNameNew}/")
        except:
            print(
                f"YandexDisk Error: <{departmentNameNew}> Данный отдел уже создан"
            )
            return
        self.disk.cp(f"/{self.path_main}/{departmentNameOld}/",
                     f"/{self.path_main}/{departmentNameNew}/")
        time.sleep(2)
        self.disk.rm(f"{self.path_main}/{departmentNameOld}")

    def add_file(self, stafferID, departmentName, orderID, file):
        if not self.get_department(departmentName):
            self.mkdir_department(departmentName)
        if not self.get_staffer(stafferID, departmentName):
            self.mkdir_staffer(stafferID, departmentName)
        if not self.get_order_staffer(orderID, stafferID, departmentName):
            self.mkdir_order(orderID, stafferID, departmentName)
        elements_path = file.split('/')
        file_name = elements_path[len(elements_path) - 1]
        self.disk.upload(
            file,
            f"/{self.path_main}/{departmentName}/{stafferID}/{orderID}/{file_name}"
        )
Beispiel #6
0
class CertPublisher:
    def __init__(self, src_file_csv, ya_dir):
        self.src_file_csv = src_file_csv
        self.ya_dir = ya_dir

        self.ya = YaDisk(conf['ya']['login'], conf['ya']['pass'])
        self.certs = {
            c['displayname'].split(".")[0]: c['path']
            for c in self.ya.ls('/{}'.format(ya_dir))
        }

    def share_cert_for(self, name):
        retries = 0
        while retries <= 5:
            retries += 1
            try:
                cert = self.certs[name]
                return self.ya.publish(cert)
            except Exception as e:
                click.echo(repr(e))
                sleep(1)
        return "###"

    def process_one(self, client, clients_processed):
        name, mail = client[:2]
        name = self._normalize_name(name)
        mail = self._normalize_mail(mail)
        ref = self.share_cert_for(name)
        res = (name.strip(), mail, ref)
        click.echo(res)
        clients_processed.append(res)

    def publish(self):
        # Read & schedule
        executor = ThreadPoolExecutor(max_workers=10)
        tasks = []
        clients_processed = []
        with open(self.src_file_csv) as inp:
            reader = csv.reader(inp, delimiter=',')
            for client in reader:
                tasks.append(
                    executor.submit(self.process_one, client,
                                    clients_processed))
        # Execute
        wait(tasks)
        click.echo("Processed {} certs".format(len(tasks)))
        # Write out
        out_path = os.path.join(
            os.path.dirname(self.src_file_csv),
            os.path.basename(self.src_file_csv).split(".")[0] + "_done.csv")
        with open(out_path, "w") as out:
            writer = csv.writer(out, delimiter=',')
            for p in clients_processed:
                writer.writerow(p)
        return out_path

    def _normalize_name(self, name):
        name = name.strip("'")
        name = name.strip()
        #name = name.split()
        #name = " ".join(part for part in name if part)
        return name

    def _normalize_mail(self, mail):
        mail = mail.strip("'")
        mail = mail.strip()
        return mail
Beispiel #7
0
if not os.path.exists(path_backup_today):
    try:
        os.makedirs(path_backup_today)
    except BaseException:
        print('Dir ' + path_backup_today + ' already exists')

os.chdir(path_backup_today)  # переходим в директорию с бекапами
######### <<

######### >> Создаём директорию для бекапа на ЯДиске
try_ = True
try_i = 1

while try_ != False and try_i <= 5:
    try:
        disk.ls(path_webdav_today)
        try_ = False
    except YaDiskException as e:
        if e.code == 404:
            dir_webdav = '/'
            for dir in path_webdav_today.split('/'):
                if dir:
                    dir_webdav += dir + "/"
                    try:
                        dir_webdav_ls = disk.ls(dir_webdav)
                    except YaDiskException as e:
                        try:
                            disk.mkdir(dir_webdav)
                            try_ = False
                        except YaDiskException as e:
                            if e.code == 500: