Advertisement
MizunoBrasil

Gigacopy 2.6

Oct 30th, 2024
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.99 KB | None | 0 0
  1. import os
  2. import shutil
  3. import threading
  4. import time
  5. from tkinter import *
  6. from tkinter.ttk import *
  7. from tkinter import filedialog, messagebox
  8. from datetime import datetime
  9.  
  10. def start_copy_move():
  11.     src_paths = src_entry.get().split(";")
  12.     dst_folder = dst_entry.get()
  13.  
  14.     if not src_paths or src_paths == ['']:
  15.         messagebox.showwarning("Aviso", "É necessário escolher um ou mais arquivos ou pastas para copiar ou mover.")
  16.         return
  17.  
  18.     total_size = sum(
  19.         os.path.getsize(path) if os.path.isfile(path) else sum(
  20.             os.path.getsize(os.path.join(dp, f)) for dp, dn, filenames in os.walk(path) for f in filenames
  21.         ) for path in src_paths
  22.     )
  23.     free_space = shutil.disk_usage(dst_folder).free
  24.  
  25.     if total_size > free_space:
  26.         messagebox.showerror("Erro", "O destino não possui espaço suficiente para a operação. Libere espaço e tente novamente.")
  27.         return
  28.  
  29.     log_entries = []
  30.  
  31.     for src in src_paths:
  32.         if os.path.isfile(src):
  33.             copy_or_move_file(src, dst_folder, log_entries)
  34.         elif os.path.isdir(src):
  35.             copy_or_move_folder(src, dst_folder, log_entries)
  36.  
  37.     if log_entries:
  38.         with open("gigacopy_log.txt", "a", encoding="utf-8") as log_file:
  39.             for entry in log_entries:
  40.                 log_file.write(entry + "\n")
  41.  
  42.     messagebox.showinfo("Sucesso", f"{'Copiado' if operation.get() == 'copy' else 'Movido'} com sucesso!")
  43.     os.startfile(dst_folder)
  44.  
  45. def copy_or_move_file(src, dst_folder, log_entries):
  46.     filename = os.path.basename(src)
  47.     dst = os.path.join(dst_folder, filename)
  48.     GB = os.path.getsize(src) / (1024 * 1024 * 1024)
  49.     copied = 0
  50.     chunk_size = 1024 * 1024  # 1MB
  51.     start_time = time.time()
  52.  
  53.     with open(src, 'rb') as fsrc, open(dst, 'wb') as fdst:
  54.         while chunk := fsrc.read(chunk_size):
  55.             fdst.write(chunk)
  56.             copied += len(chunk) / (1024 * 1024 * 1024)
  57.             update_progress(copied, GB, start_time)
  58.  
  59.     if operation.get() == "move":
  60.         os.remove(src)
  61.  
  62.     now = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
  63.     log_entries.append(f"{now} - {'Copiado' if operation.get() == 'copy' else 'Movido'}: {src} -> {dst}")
  64.     log_text.insert(END, f"{now} - {'Copiado' if operation.get() == 'copy' else 'Movido'}: {src} -> {dst}\n")
  65.     log_text.see(END)
  66.  
  67. def copy_or_move_folder(src_folder, dst_folder, log_entries):
  68.     folder_name = os.path.basename(src_folder)
  69.     dst = os.path.join(dst_folder, folder_name)
  70.  
  71.     if not os.path.exists(dst):
  72.         os.makedirs(dst)
  73.  
  74.     for root, dirs, files in os.walk(src_folder):
  75.         for file in files:
  76.             file_src = os.path.join(root, file)
  77.             rel_path = os.path.relpath(root, src_folder)
  78.             file_dst = os.path.join(dst, rel_path, file)
  79.  
  80.             os.makedirs(os.path.dirname(file_dst), exist_ok=True)
  81.             copy_or_move_file(file_src, os.path.dirname(file_dst), log_entries)
  82.  
  83.     if operation.get() == "move":
  84.         shutil.rmtree(src_folder)
  85.  
  86.     now = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
  87.     log_entries.append(f"{now} - {'Copiado' if operation.get() == 'copy' else 'Movido'}: {src_folder} -> {dst}")
  88.     log_text.insert(END, f"{now} - {'Copiado' if operation.get() == 'copy' else 'Movido'}: {src_folder} -> {dst}\n")
  89.     log_text.see(END)
  90.  
  91. def update_progress(copied, GB, start_time):
  92.     progress = (copied / GB) * 100
  93.     bar['value'] = progress
  94.     percent.set(f"{int(progress)}%")
  95.     text.set(f"{round(copied, 2)}/{round(GB, 2)} GB completos")
  96.  
  97.     elapsed_time = time.time() - start_time
  98.     if copied > 0 and elapsed_time > 0:
  99.         transfer_speed = copied / elapsed_time
  100.         remaining_time = (GB - copied) / transfer_speed
  101.         time_remaining.set(f"Tempo restante: {time.strftime('%H:%M:%S', time.gmtime(remaining_time))}")
  102.  
  103.     window.update_idletasks()
  104.  
  105. def select_src():
  106.     src_files = filedialog.askopenfilenames()
  107.     src_entry.insert(END, ";".join(src_files) + ";")
  108.  
  109. def select_folder():
  110.     folder = filedialog.askdirectory()
  111.     src_entry.insert(END, folder + ";")
  112.  
  113. def select_dst():
  114.     dst_folder = filedialog.askdirectory()
  115.     dst_entry.delete(0, END)
  116.     dst_entry.insert(0, dst_folder)
  117.  
  118. def start_thread():
  119.     threading.Thread(target=start_copy_move).start()
  120.  
  121. def show_about():
  122.     messagebox.showinfo("Sobre", "GigaCopy 2.6 - Programa para copiar ou mover múltiplos arquivos e pastas\n31/10/2024, Mizuno")
  123.  
  124. def exit_program():
  125.     window.quit()
  126.  
  127. # Configuração da janela
  128. window = Tk()
  129. window.title("GigaCopy 2.6")
  130. window.geometry('710x440')
  131. window.eval('tk::PlaceWindow . center')
  132. window.resizable(False, False)
  133.  
  134. menu_bar = Menu(window)
  135. actions_menu = Menu(menu_bar, tearoff=0)
  136. actions_menu.add_command(label="Adicionar arquivos", command=select_src)
  137. actions_menu.add_command(label="Adicionar pasta", command=select_folder)
  138. actions_menu.add_separator()
  139. actions_menu.add_command(label="Sobre", command=show_about)
  140. actions_menu.add_command(label="Sair", command=exit_program)
  141. menu_bar.add_cascade(label="Ações", menu=actions_menu)
  142. window.config(menu=menu_bar)
  143.  
  144. percent = StringVar()
  145. text = StringVar()
  146. time_remaining = StringVar()
  147. operation = StringVar(value="copy")
  148.  
  149. style = Style()
  150. style.configure('TButton', padding=(4, 2))
  151. style.configure('TEntry', padding=(4, 2))
  152. style.configure('TProgressbar', thickness=20)
  153.  
  154. Label(window, text="Origem:").grid(row=0, column=0, padx=10, pady=5, sticky=W)
  155. src_entry = Entry(window, width=52)  # Ajuste de largura para alinhamento uniforme
  156. src_entry.grid(row=0, column=1, padx=10, pady=5, columnspan=2, sticky=W)
  157.  
  158. Label(window, text="Destino:").grid(row=1, column=0, padx=10, pady=5, sticky=W)
  159. dst_entry = Entry(window, width=52)  # Largura igual à caixa de texto "Origem"
  160. dst_entry.grid(row=1, column=1, padx=10, pady=5, sticky=W)
  161. Button(window, text="Escolher destino", command=select_dst, width=15).grid(row=1, column=2, padx=5, sticky=W)
  162.  
  163. Label(window, text="Operação:").grid(row=2, column=0, padx=10, pady=5, sticky=W)
  164. Radiobutton(window, text="Copiar", variable=operation, value="copy").grid(row=2, column=1, sticky=W, padx=5)
  165. Radiobutton(window, text="Mover", variable=operation, value="move").grid(row=2, column=1, padx=130, sticky=W)
  166.  
  167. # Barra de progresso alinhada e espaçamento ajustado
  168. bar = Progressbar(window, orient=HORIZONTAL, mode='determinate', length=510)
  169. bar.grid(row=3, column=0, columnspan=2, padx=10, pady=(5, 10), sticky=W)
  170.  
  171. Label(window, textvariable=percent).grid(row=4, column=0, columnspan=4)
  172. Label(window, textvariable=text).grid(row=5, column=0, columnspan=4)
  173. Label(window, textvariable=time_remaining).grid(row=6, column=0, columnspan=4)
  174.  
  175. button = Button(window, text="Iniciar", command=start_thread, width=10)  # Largura e alinhamento ajustados
  176. button.grid(row=3, column=2, padx=(0, 10), pady=(5, 10), sticky=W)  # Espaço adequado ao lado do botão
  177.  
  178. log_text = Text(window, height=8, width=85, state='normal')
  179. log_text.grid(row=8, column=0, columnspan=4, padx=10, pady=10)
  180.  
  181. window.mainloop()
  182.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement