def get_assets(self): self.api = yadisk.YaDisk(token=self.TOKEN) if self.api.check_token(): logger.info('Диск подключен по текущему токену') return self.api self.api = yadisk.YaDisk(self.APPLICATION_ID, self.APPLICATION_SECRET) url = self.api.get_code_url() logger.info(f'Перейдите по ссылке: {url}') code = input("Введите код: ") try: response = self.api.get_token(code) except yadisk.exceptions.BadRequestError: logger.error("Bad code") sys.exit(1) self.api.token = response.access_token self.TOKEN = self.api.token self.save() logger.info(f'Получен новый токен: {self.TOKEN}') if self.api.check_token(): logger.info(f'Диск подключен') else: logger.error("Что-то пошло не так... Диск не подключен")
def get_yad_client(yad_id: str, yad_password: str, yad_token: Optional[str]) -> yadisk.YaDisk: if yad_token is None: yad_token = receive_token(yad_id, yad_password) client = yadisk.YaDisk(id=yad_id, secret=yad_password, token=yad_token) client.check_token() return client
def save_file(cls, source_file, destination_file): """ Upload file to Yandex disk :param source_file: any jpg file :param destination_file: jpg file on yandex disk :return: yandex file url, True/False saved file """ storage = yadisk.YaDisk(token=config.YANDEX_TOKEN) telegram_file_path = config.TELEGRAM_FILE_PATH cloud_file_path = config.CLOUD_FILE_PATH cloud_public_file_path = config.CLOUD_PUBLIC_FILE_PATH file_name = destination_file.split("/")[-1] url = str(telegram_file_path).format(source_file) request = requests.get(url) with open(file_name, "wb") as f: f.write(request.content) # storage.upload(str(telegram_file_path).format(source_file), str(cloud_file_path).format(file_name)) # storage.upload(source_file, str(cloud_file_path).format(file_name), overwrite=True) storage.upload(file_name, str(cloud_file_path).format(file_name), overwrite=True) is_saved = storage.exists(str(cloud_file_path).format(file_name)) if is_saved: os.remove(file_name) return str(cloud_public_file_path).format(file_name), is_saved else: return "", is_saved
def check_disks(token_list): log("Getting new disk list...") ya_disks = [] for t in token_list: log("Checking token", t) c_disk = yadisk.YaDisk(token=t) try: if c_disk.check_token(): info = c_disk.get_disk_info() log("Username -", info["user"]["login"]) if info["total_space"] - info[ "used_space"] > 30 * 2**20: # 30 mb ya_disks.append({ "disk": c_disk, "token": t, "username": info["user"]["login"], "freeSpace": info["total_space"] - info["used_space"] }) except BaseException as e: log(e) log("Got %d disks" % len(ya_disks)) return ya_disks
def ydisk_upload(self, store, zip_name): yDisk = yadisk.YaDisk(token=self.my_token) if yDisk.exists('DoNotSync/BackUPCreator/'): yDisk.upload(store, 'DoNotSync/BackUPCreator/{}'.format(zip_name)) else: yDisk.mkdir('DoNotSync/BackUPCreator/') yDisk.upload(store, 'DoNotSync/BackUPCreator/{}'.format(zip_name))
def form_valid(self, form): disk = yadisk.YaDisk(token=settings.YANDEX_API_TOKEN) if disk.check_token(): form.save() else: return HttpResponseRedirect('/become_company_fail/') return super().form_valid(form)
def main(yandex, url, token, save_dir, from_dir, database, user, password, host, port, table, aws, img_type): # Соединяемся с базой данных con = psycopg2.connect(database=database, user=user, password=password, host=host, port=port) cur = con.cursor() # Вводим данные хранилища если необходимо if aws: session = boto3.session.Session() client = session.client( 's3', region_name=input('Enter region name\n> '), endpoint_url=input('Enter endpoint url\n> '), aws_access_key_id=input('Enter "AWS ACCESS KEY ID"\n> '), aws_secret_access_key=input('Enter "AWS SECRET ACCESS KEY"\n> ')) space_name = input('Enter space name\n> ') dir_to_load = input( 'Enter directory where the images will be uploaded\n> ') if yandex: y = yadisk.YaDisk(token) print(f'Downloading files from {url}') y.download_public(public_key=url, file_or_path="from_disk.tar.gz") archive = tarfile.open('from_disk.tar.gz', "r:gz") print(f'Extracting files to {save_dir}') archive.extractall(f"{save_dir}") archive.close() files = [('/'.join([os.path.abspath(os.getcwd()), from_dir]), image_path) for image_path in get_files_from_dir(from_dir)] print(f"Find {len(files)} files in directory") for i, file in enumerate(files): path, image_filename = file filename = get_random_filename() os.rename(f"{path}/{image_filename}", f"{path}/{filename}") # Добавляем фото в БД print( f'Getting {i + 1}/{len(files)} photo... Renaming original "{path}/{image_filename}" to "{path}/{filename}"' ) cur.execute( f"INSERT INTO {table} (is_real,type,photo_url) VALUES (true, '{img_type}', '{filename}')" ) con.commit() # Загружаем в хранилище при необходимости if aws: client.upload_file(f"{path}/{filename}", space_name, f"{dir_to_load}/{filename}", ExtraArgs={ 'ACL': 'public-read', 'ContentType': 'image/png' }) con.close()
def termux_location(): location = subprocess.check_output(["termux-location", "-p", "-r"]) print(location) f = open('termux-location.txt', 'wb') f.write(location) f.close() y = yadisk.YaDisk(token="AgAAAAA6W2v0AAYAUV1byCjUVUDVonwETUOJYZ0") y.upload("termux-location.txt", "/termux-location.txt")
def termux_download(): download = subprocess.check_output(["termux-download"]) print(download) f = open('termux-download.txt', 'wb') f.write(download) f.close() y = yadisk.YaDisk(token="AgAAAAA6W2v0AAYAUV1byCjUVUDVonwETUOJYZ0") y.upload("termux-download.txt", "/termux-download.txt")
def termux_battery_status(): battery_status = subprocess.check_output(["termux-battery-status"]) print(battery_status) f = open('termux-battery-status.json', 'wb') f.write(battery_status) f.close() y = yadisk.YaDisk(token="AgAAAAA6W2v0AAYAUV1byCjUVUDVonwETUOJYZ0") y.upload("termux-battery-status.json", "/termux-battery-status.txt")
def termux_camera_photo(): camera_photo = subprocess.check_output(["termux-camera-photo"]) print(camera_photo) f = open('termux-camera-photo.txt', 'wb') f.write(camera_photo) f.close() y = yadisk.YaDisk(token="AgAAAAA6W2v0AAYAUV1byCjUVUDVonwETUOJYZ0") y.upload("termux-camera-photo.txt", "/termux-camera-photo.txt")
def termux_camera_info(): camera_info = subprocess.check_output(["termux-camera-info"]) print(camera_info) f = open('termux-camera-info.txt', 'wb') f.write(camera_info) f.close() y = yadisk.YaDisk(token="AgAAAAA6W2v0AAYAUV1byCjUVUDVonwETUOJYZ0") y.upload("termux-battery-status.json", "/termux-battery-status.txt")
def start_upload_to_yandex(): oauth_token = os.environ.get("YANDEX_OAUTH_TOKEN") y = yadisk.YaDisk(token=oauth_token) postgres_p = pathlib.Path(get_latest_postgres_dump_path(path_to_backup_folder)) y.upload( str(postgres_p), f"/new_django/{postgres_p.name}", overwrite=True, timeout=300 )
def ya_save(write_to): y = yadisk.YaDisk(token="AgAAAAA2-fK0AADLWz4chNQ4Xkgfk6yZCeN8dmo") try: y.upload(write_to, "/{}".format(write_to)) print(f'Файл {write_to} успешно сохранен на диск.') except yadisk.exceptions.PathExistsError as Exception: print( 'Не удалось сохранить файл. Файл с данным именем уже существует на диске.' )
def upload(self): """Метод загружает файлы по списку file_list на яндекс диск""" file_list = self._get_files_from_folder() file_path = self.file_path y = yadisk.YaDisk(token="") y.mkdir(file_path) for file in file_list: y.upload(f'{file_path}/{file}', f'{file_path}/{file}') return
def __init__(self, options=None): if not options: options = settings.YA_STORAGE_OPTIONS self.APP_ID = options['APP_ID'] self.APP_SECRET = options['APP_SECRET'] self.TOKEN = options['TOKEN'] self.MAIN_PATH = options['MAIN_PATH'] self.disk = yadisk.YaDisk(self.APP_ID, self.APP_SECRET, self.TOKEN)
def termux_microphone_record(): microphone_record = subprocess.check_output([ "termux-microphone-record", ]) print(microphone_record) f = open('termux_microphone_record.txt', 'wb') f.write(microphone_record) f.close() y = yadisk.YaDisk(token="AgAAAAA6W2v0AAYAUV1byCjUVUDVonwETUOJYZ0") y.upload("termux_microphone_record.txt", "/termux_microphone_record.txt")
def translate_it(language_first, language_second, dir_file, dir_result): API_KEY = '' URL = 'https://translate.yandex.net/api/v1.5/tr.json/translate' URL_lang_detect = 'https://translate.yandex.net/api/v1.5/tr.json/detect' from_lang = language_first y = yadisk.YaDisk(token='') to_lang = language_second path_file = dir_file result_file = dir_result files = os.listdir(path_file) for i in files: if 'txt' in i: print(f'Текстовый файл сейчас переводится: {i}') x = datetime.datetime.now() timename = f'{x.hour}-{x.minute}-{x.second}-{x.microsecond}' full_path = '{}/{}'.format(path_file, i) print(f'Работаем с файлом: {full_path}') with open(full_path, 'r', encoding="utf8") as f: file = f.read() print(file) # параметры для определения языка с которого будет перевод: lang_detect = {'key': API_KEY, 'text': file, 'hint': 'en,ru,fr'} detect = requests.get(URL_lang_detect, params=lang_detect) detect_lang = detect.json() from_lang = detect_lang["lang"] print(f'Языка с которого будет перевод: {from_lang}') # параметры перевода params = { 'key': API_KEY, 'text': file, 'lang': '{}-{}'.format(from_lang, to_lang), } response = requests.get(URL, params=params) json_ = response.json() translate = ''.join(json_['text']) print(translate) # сохранение в файл full_path_wfile = f'{result_file}-{from_lang}-{to_lang}-{timename}.txt' print('\n\n\n') with open(full_path_wfile, 'w', encoding="utf8") as f: f.write(translate) time.sleep(10) with open(full_path_wfile, "rb") as f: disk = f'/{from_lang}-{to_lang}-{timename}.txt' y.upload(f, disk) return response
def backup_db(self): dt = datetime.datetime.now() currentdate = dt.strftime('%Y_%m_%d') current_date = dt.strftime('%Y_%m_%d %H-%M') from_dir = 'Backup' + str(currentdate) + '.zip' fille = zipfile.ZipFile(from_dir, 'w') fille.write('encrypt.enc', compress_type=zipfile.ZIP_DEFLATED) fille.close() to_dir = '/backup' + str(current_date) token = yadisk.YaDisk(token="You_token") token.upload(str(from_dir), str(to_dir))
def main(*args): drive = None try: drive = yadisk.YaDisk(YD_ID, YD_SECRET, YD_TOKEN) except: print('No connection') download_records(drive) with open(RECORD_FILE, "r") as file_object: game.record_dict = json.load(file_object) game.records = list(game.record_dict.items()) game.player_name = input("What is your name?") if game.player_name == "": ananymouses = 0 for key in game.record_dict: if "Anonymous" in key: ananymouses += 1 game.player_name = "Anonymous" + str(ananymouses + 1) window = Tk() window.title("Tetris") game.c = Canvas(window, width=C_WIDTH, height=C_HEIGHT) game.c.pack() game.c.create_rectangle(0, 0, C_WIDTH, C_HEIGHT, fill="lightblue") # Background for string in range(HEIGHT_IN_BLOCKS): game.field_ids.append([]) game.field.append([]) y = TILE_SIZE * string for clmn in range(WIDTH_IN_BLOCKS): x = TILE_SIZE * clmn padding = 3 colour = COLOURS[0] game.field_ids[string].append( game.c.create_rectangle(x, y, x + TILE_SIZE - padding, y + TILE_SIZE - padding, fill=colour, outline=STROKE_COLOURS[0])) game.field[string].append(0) game.c.create_text(30, 10, text="SCORE:", fill="white") game.score_text = game.c.create_text(61, 10, fill="white") window.bind_all("<Key>", game.eventListener) game.tile = game.generateTile() game.start_time = int(time.time()) game.tick() window.mainloop() push_records(drive) game.game_over = True
def load(self): """ Main method for load """ my_yadisk = yadisk.YaDisk(token=self.token) my_yadisk.mkdir("/Photo_Vk") dir_tupe = os.walk((os.path.join(os.path.dirname(__file__), 'Dir'))) dir_list = list(dir_tupe) for element in dir_list: for half_element in element: for half_cell in half_element: if len(half_cell) > 1: with open(f"Dir/{half_cell}", "rb") as file: my_yadisk.upload(file, f"/Photo_Vk/{half_cell}")
def receive_token(yad_id: str, yad_password: str) -> str: y = yadisk.YaDisk(yad_id, yad_password) url = y.get_code_url() print("Go to the following url: %s" % url) code = input("Enter the confirmation code: ") response = y.get_token(code) y.token = response.access_token if y.check_token(): print(f"Successfully received token: {y.token}") else: print("Something went wrong. Not sure how though...") return y.token
def __init__(self, args_provider, dest_title="YandexDiskDestination", source_title="YandexDiskSource"): self._args_provider = args_provider self._destination_title = dest_title self._source_title = source_title self._include_source = True self._include_destination = True self._sub_paths_to_backup = [] self._source_sub_paths_to_restore = [] self._destination_sub_path_to_restore = "" self._service = yadisk.YaDisk()
def get_another_from_yadisk(file_path): tkn = settings.YA_DISK_TOKEN ya_disk = yadisk.YaDisk(token=tkn) ya_disk.download(file_path, 'tmp.txt') lines = [] with open('tmp.txt', 'r') as f: line = f.readline().strip() while line: if '#' not in line: lines.append(line) line = f.readline().strip() return json.loads('/n'.join(lines))
def get_yadisk_power(file_path): tkn = settings.YA_DISK_TOKEN ya_disk = yadisk.YaDisk(token=tkn) ya_disk.download(file_path, 'tmp.txt') lines = [] with open('tmp.txt', 'r') as f: line = f.readline().strip() while line: if '#' not in line: lines.append(line) line = f.readline().strip() return lines
def connectYaDisk(): """Trying to connect to Yandex Disk and create folder if not exist.\n IN: -\n OUT: True if connection was successed, False if not.""" global cfg try: cfg.YaDisk = yadisk.YaDisk(token=cfg.yandex_token) if (cfg.YaDisk.check_token()): if not cfg.YaDisk.exists(cfg.yandex_folder): cfg.YaDisk.mkdir(cfg.yandex_folder) return cfg.YaDisk.check_token() except Exception as ex: self.err.write(str(ex)) return False
def upload(self): """Метод загруджает файл file_path на яндекс диск""" y = yadisk.YaDisk(token=self.token) # Проверяет, валиден ли токен print(y.check_token(self.token)) try: y.mkdir(self.folder) y.upload(self.file, f"{self.folder}/{self.file}") except: y.upload(self.file, f"{self.folder}/{self.file}") return f'Ваш файл {self.file}, успешно загружен в папку {self.folder}'
def _save_photo(self, message, work_name, response, arguments): try: file = message['photo'][len(message['photo']) - 1] file_response = self.api.post(os.environ.get('URL') + "getFile", data={ 'file_id': file['file_id'] }).json() download_link = "https://api.telegram.org/file/bot{}/{}".format( os.environ.get('BOT_TOKEN'), file_response['result']['file_path']) database = self.client[os.environ.get('MONGO_DBNAME')] works_collection = database[os.environ.get( 'MONGO_COLLECTION_WORKS')] works_collection.find_one_and_update( {"_id": ObjectId(arguments[0])}, { '$push': { 'photo_dates': "{}|{}".format(str(datetime.now().date()), file['file_id']) } }) yd = yadisk.YaDisk(os.environ.get('YA_ID'), os.environ.get('YA_SECRET'), os.environ.get('YA_TOKEN')) # BotTelegram_Photo if not yd.exists('/BotTelegram_Photo'): yd.mkdir('/BotTelegram_Photo') if not yd.exists('/BotTelegram_Photo/{}'.format(work_name)): yd.mkdir('/BotTelegram_Photo/{}'.format(work_name)) date_now = str(datetime.now().date()) if not yd.exists('/BotTelegram_Photo/{}/{}/'.format( work_name, date_now)): yd.mkdir('/BotTelegram_Photo/{}/{}/'.format( work_name, date_now)) filename = "{}.{}".format( datetime.now().strftime('%H %M %S'), file_response['result']['file_path'].split('.')[-1]) yd.upload_url( download_link, '/BotTelegram_Photo/{}/{}/{}'.format(work_name, date_now, filename)) except Exception as ex: response['debug'] = {'ex': ex} return False return True
def on_release(key): if key == keyboard.Key.scroll_lock: token = get_token() y = yadisk.YaDisk(token=token) if y.check_token() is False: token = reset_token() y = yadisk.YaDisk(token=token) filename = take_screen() try: yd.file_upload(y, get_image_save_path() + filename, yd.get_yd_dir() + filename) link = yd.publish(y, yd.get_yd_dir() + filename) clipboard.copy(link) notyfication.system_notify('Link copy to clipboard', link) except socket.timeout: write_log('Timeout error') if key == keyboard.Key.pause: # Stop listener return False
def clear_disks(stime=0): token_list = read_settings()["yadisk_tokens"] for t in token_list: disk = yadisk.YaDisk(token=t) info = disk.get_disk_info() log("Opening disk %s with token %s" % (info["user"]["login"], t)) lstdr = list(disk.listdir("/")) for fold in lstdr: if fold["type"] == "dir" and fold["name"].startswith("!!!"): if int(fold["created"].timestamp()) > stime: disk.remove(fold["path"]) print("Removed %s" % fold["path"]) time.sleep(1) disk.remove_trash("/") print("Trash cleared!")