89 lines
3.6 KiB
Python
89 lines
3.6 KiB
Python
from autoLoader.config import FILESAPTH
|
|
from autoLoader.loader import ConnectorSFTP
|
|
import datetime, os
|
|
from autoLoader.database import Audio, get_db_session
|
|
|
|
local_path = os.path.join(os.getcwd(), FILESAPTH)
|
|
|
|
class Loader():
|
|
def __init__(self):
|
|
self.call_types = ['in']
|
|
pass
|
|
|
|
def filter_call(self, filename: str):
|
|
if filename.split("-")[0] in self.call_types:
|
|
return True
|
|
return False
|
|
|
|
def load(self):
|
|
date_now = datetime.datetime.now()# - datetime.timedelta(days=1)
|
|
remote_path = f"/{date_now.strftime('%Y/%m/%d')}"
|
|
|
|
connector = ConnectorSFTP()
|
|
connector.connect(remote_path=remote_path)
|
|
|
|
sftp_client = connector.sftp
|
|
ssh_client = connector.ssh
|
|
|
|
if sftp_client is None or ssh_client is None:
|
|
print("Не удалось подключиться к SFTP. Завершение работы.")
|
|
exit(1)
|
|
|
|
try:
|
|
listdir = sftp_client.listdir()
|
|
os.makedirs(local_path, exist_ok = True)
|
|
|
|
for file in listdir:
|
|
if self.filter_call(filename=file):
|
|
remote_file = f"{file}".lstrip('/')
|
|
filepath = os.path.join(local_path, file)
|
|
|
|
# Проверяем, существует ли файл локально
|
|
if os.path.exists(filepath):
|
|
print(f"Файл уже существует: {file}")
|
|
continue
|
|
|
|
try:
|
|
# Скачиваем файл
|
|
sftp_client.get(remote_file, filepath)
|
|
print(f"Скачан файл: {remote_file}")
|
|
|
|
# Получаем размер файла
|
|
file_size = os.path.getsize(filepath)
|
|
|
|
# Сохраняем в БД через контекстный менеджер
|
|
with get_db_session() as db:
|
|
# Проверяем, есть ли уже такой файл в БД
|
|
existing_audio = db.query(Audio).filter(Audio.filename == file).first()
|
|
if existing_audio:
|
|
print(f"Файл {file} уже есть в БД, пропускаем")
|
|
continue
|
|
|
|
# Создаём новую запись
|
|
audio = Audio()
|
|
audio.index_date = datetime.datetime.now()
|
|
audio.filename = file
|
|
audio.file_path = filepath
|
|
audio.file_size = file_size
|
|
|
|
db.add(audio)
|
|
# commit произойдёт автоматически при выходе из контекста
|
|
|
|
print(f"✅ Файл {file} сохранён в БД")
|
|
|
|
except Exception as e:
|
|
print(f"❌ Ошибка при обработке файла {remote_file}: {e}")
|
|
# Если файл скачался, но ошибка в БД - удаляем файл
|
|
if os.path.exists(filepath):
|
|
try:
|
|
os.remove(filepath)
|
|
print(f"🗑️ Файл {file} удалён из-за ошибки")
|
|
except:
|
|
pass
|
|
|
|
finally:
|
|
# Закрываем соединения
|
|
sftp_client.close()
|
|
ssh_client.close()
|
|
|