下載oss2上面的螢幕截圖檔案的程式碼

*感悟人生*發表於2024-07-08
import os
import re
import oss2
import tkinter as tk
from tkinter import filedialog, messagebox
from tkinter.scrolledtext import ScrolledText
import pickle
from tkinter import filedialog
import subprocess


def on_entry_focus_in(event):
    # 當Entry獲得焦點時,檢查是否包含預設文字並刪除它
    if entry_date.get() == "例:2024-01-01":
        entry_date.delete(0, tk.END)
        # 如果需要,也可以在這裡將前景色改回黑色或其他顏色


def on_entry_focus_out(event):
    # 當Entry失去焦點時,如果它是空的,則新增預設文字
    if not entry_date.get():
        entry_date.insert(0, "2024-01-01")


def create_dir_if_not_exists(path):
    if not os.path.exists(path):
        os.makedirs(path)


def mac_to_name(file_name, mac_to_name_dict):
    mac_address_pattern = re.compile(r'([0-9a-fA-F]{2}[_-]){5}[0-9a-fA-F]{2}')
    match = mac_address_pattern.search(file_name)
    if match:
        mac_address = match.group(0)
        if mac_address in mac_to_name_dict:
            return file_name.replace(mac_address, mac_to_name_dict[mac_address])
    return file_name


def download_matching_files(bucket, file_name_part, download_path, mac_to_name_dict, log_text):
    file_count = 0
    for obj in oss2.ObjectIterator(bucket):
        if file_name_part in obj.key:
            file_name = mac_to_name(obj.key, mac_to_name_dict)
            file_path = os.path.join(download_path, file_name)
            create_dir_if_not_exists(os.path.dirname(file_path))  # 確保目錄存在
            try:
                bucket.get_object_to_file(obj.key, file_path)
                log_text.insert(tk.END, f'下載 {obj.key} 到 {file_path}\n')
                log_text.see(tk.END)  # 自動滾動到最後一行
                log_text.update()
                file_count += 1
            except Exception as e:
                log_text.insert(tk.END, f'下載 {obj.key} 失敗: {str(e)}\n')
                log_text.see(tk.END)  # 自動滾動到最後一行
                log_text.update()
    return file_count


def save_mac_to_name_dict(mac_to_name_dict, filename='mac_to_name_dict.pkl'):
    with open(filename, 'wb') as f:
        pickle.dump(mac_to_name_dict, f)


def load_mac_to_name_dict(filename='mac_to_name_dict.pkl'):
    if os.path.exists(filename):
        with open(filename, 'rb') as f:
            return pickle.load(f)
    return {}


def start_download():
    file_name_part = entry_date.get()
    if not file_name_part:
        messagebox.showerror("錯誤", "請輸入檔名中包含的日期")
        return

    download_path = entry_download_path.get()
    if not download_path:
        messagebox.showerror("錯誤", "請選擇儲存下載檔案的路徑")
        return

    mac_to_name_dict = load_mac_to_name_dict()

    auth = oss2.Auth('123', '456')
    bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', 'singsongpic')

    log_text.insert(tk.END, "開始下載檔案...\n")
    file_count = download_matching_files(bucket, file_name_part, download_path, mac_to_name_dict, log_text)
    messagebox.showinfo("完成", f"總共下載的檔案數:{file_count}")
    log_text.insert(tk.END, f"下載完成,總共下載的檔案數:{file_count}\n")


# def add_mac_to_name():
#     mac = entry_mac.get()
#     name = entry_name.get()
#     if not mac or not name:
#         messagebox.showerror("錯誤", "請輸入MAC地址和對應的姓名")
#         return
#
#     mac_to_name_dict = load_mac_to_name_dict()
#     mac_to_name_dict[mac] = name
#     save_mac_to_name_dict(mac_to_name_dict)
#     messagebox.showinfo("完成", "MAC地址和姓名已新增")
def open_download_folder():
    """開啟下載資料夾"""
    # 確保entry_download_path中有有效的路徑
    if entry_download_path.get():
        path = entry_download_path.get()
        if os.path.isdir(path):
            # 使用subprocess呼叫系統預設的資料夾開啟程式
            if os.name == 'nt':  # Windows系統
                subprocess.Popen(['explorer', path])
            else:  # Linux或macOS系統
                subprocess.Popen(['xdg-open', path])
        else:
            print("路徑不是有效的資料夾")
    else:
        print("請先選擇下載路徑")

def choose_directory():
    download_path = filedialog.askdirectory()
    if download_path:
        entry_download_path.delete(0, tk.END)
        entry_download_path.insert(0, download_path)


# GUI部分
root = tk.Tk()
root.title("OSS螢幕檔案下載器-SINGSONG專用")

tk.Label(root, text="檔名中包含的日期:").grid(row=0, column=0)
entry_date = tk.Entry(root, foreground='dim gray')  # 使用淺灰色作為前景色
entry_date.insert(0, "例:2024-01-01")  # 插入預設文字
entry_date.grid(row=0, column=1)

# 繫結FocusIn事件以便在使用者點選時刪除預設文字
entry_date.bind("<FocusIn>", on_entry_focus_in)

tk.Label(root, text="下載檔案儲存路徑:").grid(row=1, column=0)
entry_download_path = tk.Entry(root)
entry_download_path.grid(row=1, column=1)
tk.Button(root, text="選擇下載路徑", command=choose_directory).grid(row=1, column=2)

tk.Button(root, text="下載檔案", command=start_download).grid(row=2, column=0, columnspan=3)
# # 建立開啟下載資料夾按鈕
# tk.Button(root, text="開啟下載資料夾", command=open_download_folder).grid(row=2, column=2)
# #
# tk.Label(root, text="MAC地址:").grid(row=3, column=0)
# entry_mac = tk.Entry(root)
# entry_mac.grid(row=3, column=1)

# tk.Label(root, text="對應的姓名:").grid(row=4, column=0)
# entry_name = tk.Entry(root)
# entry_name.grid(row=4, column=1)

# tk.Button(root, text="新增MAC地址和姓名", command=add_mac_to_name).grid(row=5, column=0, columnspan=3)

# 新增用於顯示下載資訊的文字框
log_text = ScrolledText(root, wrap=tk.WORD, width=50, height=10)
log_text.grid(row=6, column=0, columnspan=3)

root.mainloop()

相關文章