import sys
import os

sys.path.append(os.path.dirname(sys.path[0]))  # 上级目录
import paramiko
from datetime import datetime, timedelta
import subprocess
from func_timeout.exceptions import FunctionTimedOut
from func_timeout import func_set_timeout

import time

# vps拨号服务器 下载图片 上传到服务器
class temu_image():
    def __init__(self, ):
        # SFTP服务器的连接信息
        self.host = "61.145.136.61"
        self.port = 218
        self.username = "vps_ftp"
        self.password = "ysws123!@#"
        self.ssh_connect()


    def ssh_connect(self):
        while True:
            try:
                # 创建SSH客户端
                ssh = paramiko.SSHClient()
                ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                # 连接到SFTP服务器
                ssh.connect(self.host, self.port, self.username, self.password, timeout=15)
                # 创建SFTP客户端
                self.sftp = ssh.open_sftp()
                break
            except:
                print('重新连接')
                time.sleep(5)
    def delete_img_path(self, path):
        try:
            command = f"rm {path}"
            # 使用subprocess运行命令
            subprocess.run(command, shell=True)
        except Exception as e:
            print(f"Error deleting file: {e}")

    def to_fies(self):
        # 替换为你的实际目录
        # top_directory = '/run'
        # # 遍历以2023开头的所有目录
        # for root, dirs, files in os.walk(top_directory):
        #     for dir_name in dirs:
        #         if dir_name.startswith("2023"):
        top_directory = '/run'
        # 遍历以2023开头的所有目录
        top_directory = '/run'
        # Traverse only the top-level directories in /run
        for dir_name in os.listdir(top_directory):
            if dir_name.startswith("2023") and os.path.isdir(os.path.join(top_directory, dir_name)):
                # Your code logic for processing the directories goes here
                current_directory = os.path.join(top_directory, dir_name)
                # Read files in the current directory
                for file_name in os.listdir(os.path.join(current_directory, 'mnt/data/img_data/temu')):
                    if file_name.lower().endswith(('.jpg', '.jpeg', '.png')):
                        image_path = os.path.join(current_directory, 'mnt/data/img_data/temu', file_name)
                        while True:
                                try:
                                    self.to_server_img(image_path, file_name)
                                    break
                                except FunctionTimedOut as e:
                                    print('断网')
                                    time.sleep(10)
                                    # 重新连接并重试上传
                                    self.ssh_connect()

    @func_set_timeout(15)
    def to_server_img(self, local_file_path, file_name):
        print('上传图片')
        current_time = datetime.now()
        # 格式化时间为 'YYYYMMDDHH' 格式
        formatted_time = current_time.strftime('%Y%m%d%H')
        # 目标位置
        remote_file_path = f"/vps_ftp/temu/{formatted_time}/"
        try:
            # 自动创建目标目录和其上级目录
            try:
                self.sftp.chdir(remote_file_path)  # 尝试切换到目标目录，如果目录不存在，会引发异常
            except IOError:
                self.sftp.mkdir(remote_file_path)  # 创建目标目录
                self.sftp.chdir(remote_file_path)  # 切换到目标目录
            # 上传本地文件到远程服务器
            remote_file_path = f"/vps_ftp/temu/{formatted_time}/{file_name}"
            print('服务器目录：', remote_file_path)
            print('本地目录：', local_file_path)
            # 上传本地文件到远程服务器
            self.sftp.put(local_file_path, remote_file_path)
            self.delete_img_path(local_file_path)
        except (paramiko.SSHException, OSError) as e:
            print(f"Error uploading file: {e}")





if __name__ == '__main__':
    temu_image().to_fies()