Exemplo n.º 1
0
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}")
Exemplo n.º 2
0
    def handle_noargs(self, **options):
        disk = YaDisk(settings.DUMP_ACCOUNT_NAME, settings.DUMP_PASSWORD)

        def save_mkdir(dir):
            try:
                disk.mkdir(dir)
            except YaDiskException:
                pass

        now = datetime.now()
        save_mkdir('Backup')
        save_mkdir('Backup/db')
        save_mkdir('Backup/db/%s' % now.strftime('%Y_%m'))

        dump_filename = '%s_backup_%s.sql' % (settings.DATABASES['default']['NAME'], now.strftime('%Y%m%d_%H%M'))
        tmp_filename = dump_filename + '.gz'
        tmp = open(tmp_filename, 'wb')

        dump = check_output([
            'mysqldump',
            '--user='******'default']['USER'],
            '--password='******'default']['PASSWORD'],
            '--host=' + settings.DATABASES['default']['HOST'],
            settings.DATABASES['default']['NAME'],
        ])

        archive = zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED)
        archive.writestr(dump_filename, dump)
        archive.close()

        tmp.close()

        disk.upload(tmp_filename, 'Backup/db/%s/%s' % (now.strftime('%Y_%m'), tmp_filename))

        os.remove(tmp_filename)
Exemplo n.º 3
0
def upload(_login, _password, _server_dir, _file):
    if os.path.isfile(_file):
        disk = YaDisk(_login, _password)
        disk.upload(_file, _server_dir + '/' + os.path.basename(_file))
        link = disk.publish_doc(_server_dir + '/' + os.path.basename(_file))
        print link
    else:
        print "Error: file-path is bad"
        return 1
Exemplo n.º 4
0
    def handle_noargs(self, **options):
        disk = YaDisk(settings.DUMP_ACCOUNT_NAME, settings.DUMP_PASSWORD)

        def save_mkdir(dir):
            try:
                disk.mkdir(dir)
            except YaDiskException:
                pass

        now = datetime.now()
        save_mkdir('Backup')
        save_mkdir('Backup/db')
        save_mkdir('Backup/db/%s' % now.strftime('%Y_%m'))

        dump_filename = '%s_backup_%s.sql' % (
            settings.DATABASES['default']['NAME'], now.strftime('%Y%m%d_%H%M'))
        tmp_filename = dump_filename + '.gz'
        tmp = open(tmp_filename, 'wb')

        dump = check_output([
            'mysqldump',
            '--user='******'default']['USER'],
            '--password='******'default']['PASSWORD'],
            '--host=' + settings.DATABASES['default']['HOST'],
            settings.DATABASES['default']['NAME'],
        ])

        archive = zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED)
        archive.writestr(dump_filename, dump)
        archive.close()

        tmp.close()

        disk.upload(tmp_filename,
                    'Backup/db/%s/%s' % (now.strftime('%Y_%m'), tmp_filename))

        os.remove(tmp_filename)
Exemplo n.º 5
0
 def upload_yandex_disk(self):
     disk = YaDisk(self.Ylogin, self.Ypassword)
     print('{0}video.mp4'.format(self.videofolder))
     disk.mkdir('Videos/{0}/{1}'.format(self.game, self.timestamp))
     disk.upload(
         '{0}video.mp4'.format(self.videofolder),
         'Videos/{0}/{1}/video.mp4'.format(self.game, self.timestamp))
     disk.upload(
         '{0}hashtags.txt'.format(self.videofolder),
         'Videos/{0}/{1}/hashtags.txt'.format(self.game, self.timestamp))
     disk.upload(
         '{0}link_to_original.txt'.format(self.videofolder),
         'Videos/{0}/{1}/link_to_original.txt'.format(
             self.game, self.timestamp))
     return
Exemplo n.º 6
0
			if not db in exclude:
				db_file = date_today_str +"-www-"+ db +".sql.bz2"

				try_ = True
				try_i = 1

				while try_ != False and try_i <= 5:
					if not try_:
						break

					subprocess.Popen( "mysqldump --skip-lock-tables -u"+ mysql_u +" -p'"+ mysql_p +"' "+ db +" | bzip2 -c > "+ db_file, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True, universal_newlines=True ).communicate()

					time.sleep(sleep_time)

					if False and try_i % 2 == 0:
						disk.upload( os.path.abspath( db_file ), path_webdav_today + db_file ) # заливаем на ЯДиск
					else:
						subprocess.Popen( "curl --user "+ yd_u +":"+ yd_p +" -T "+ os.path.abspath(db_file) +" https://webdav.yandex.ru"+ path_webdav_today, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True, universal_newlines=True ).communicate()

					os.remove( os.path.abspath(db_file) ) # удаляем файл с сервера

					try:
						list_files = disk.ls( path_webdav_today )
						for today_dump_file in list_files:
							if today_dump_file.get('isDir') == False and today_dump_file.get('displayname') == db_file:
								try_ = False
								break
					except YaDiskException as e:
						if e.code == 404 or e.code == 500:
							continue
Exemplo n.º 7
0
logging.info("PID is {}".format(pid))
if sett['pidfile']:
    with open(sett['pidfile'], "w") as f:
        f.write(pid)

# Set up relays
rs = RelaySet(sett)

# Set up camera
camera = PiCamera(resolution=(2592, 1944))
time.sleep(2)

# Set Up YaDisk webdav
disk = YaDisk(sett['yandex']['login'], sett['yandex']['pass'])

while True:
    rs.actualize()
    photo_path = make_photo()
    photo_name = photo_path.split("/")[-1]
    ya_path = "asparagus/%s" % photo_name
    if photo_path:
        try:
            rotate_photo(photo_path)
            disk.upload(photo_path, ya_path)
        except:
            logging.info('Could not upload photo')
            pass
    else:
        logging.info('Could not capture photo')
    time.sleep(300)
Exemplo n.º 8
0
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:
        for f in deployed_exes:
            disk.rm(f)
else:
    raise EnvironmentError('Exe file list is EMPTY!!!')
Exemplo n.º 9
0
from YaDiskClient.YaDiskClient import YaDisk

login = ''
password = ''

disk = YaDisk(login, password)

print(disk.ls('/'))
disk.upload('example.py', 'example.py')
Exemplo n.º 10
0
        fname, ext = os.path.splitext(name)

        if ext.lower() in (
                '.gif',
                '.jpg',
                '.png',
        ):

            remote_folder = 'FotoSite'
            if os.getenv('EGAX_DEBUG') == '1':
                remote_folder = 'Foto'
            remote_file = name
            remote_path = E_OS('/{folder}/{file}'.format(folder=remote_folder,
                                                         file=remote_file))

            yadisk.upload(remote_file, remote_path)
            url = yadisk.publish_doc(remote_path)

            param = []

            param += [("album", E_OS(os.path.basename(cwd)))]
            param += [("thumb_url", url)]
            param += [("title", E_OS(fname))]
            param += [("memberonly", memberonly)]
            param += [("user", user)]

            print os.path.basename(cwd), name, url

            register_openers()
            datagen, headers = multipart_encode(param)
Exemplo n.º 11
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}"
        )
Exemplo n.º 12
0
from YaDiskClient.YaDiskClient import YaDisk
import os
import sys

f_accounts = open('acc.txt','r')
acc_arr = [account for account in f_accounts]
f_accounts.close()
files_arr = os.listdir('.')
f_urls = open('urls.txt','w')
for files in files_arr:
    for account in acc_arr:
        email = account.split(':')[0]
        password = account.replace('\n','').split(':')[1]
        disk = YaDisk(email, password)
        disk.df()
        if files == 'urls.txt' or files == os.path.basename(__file__) or files == 'acc.txt':
            continue
        print(os.path.join(os.path.dirname(os.path.abspath(__file__)),files) + ' ---> ' + files)
        disk.upload(os.path.join(os.path.dirname(os.path.abspath(__file__)),files), files)
        shared_url = disk.publish('/' + files)
        f_urls.write('{} -->  Filename : {} -->  Shared Url : {}\n'.format(email,files,shared_url))
f_urls.close()
sys.exit()
Exemplo n.º 13
0
                    if not try_:
                        break

                    subprocess.Popen("mysqldump --skip-lock-tables -u" +
                                     mysql_u + " -p'" + mysql_p + "' " + db +
                                     " | bzip2 -c > " + db_file,
                                     stderr=subprocess.PIPE,
                                     stdout=subprocess.PIPE,
                                     shell=True,
                                     universal_newlines=True).communicate()

                    time.sleep(sleep_time)

                    if False and try_i % 2 == 0:
                        disk.upload(os.path.abspath(db_file),
                                    path_webdav_today +
                                    db_file)  # заливаем на ЯДиск
                    else:
                        subprocess.Popen(
                            "curl --user " + yd_u + ":" + yd_p + " -T " +
                            os.path.abspath(db_file) +
                            " https://webdav.yandex.ru" + path_webdav_today,
                            stderr=subprocess.PIPE,
                            stdout=subprocess.PIPE,
                            shell=True,
                            universal_newlines=True).communicate()

                    os.remove(
                        os.path.abspath(db_file))  # удаляем файл с сервера

                    try: