Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import time
- import tarfile
- import subprocess
- import psutil
- # Define paths and time interval as global variables
- movies_path = "/home/caspy/Movies"
- games_path = "/home/caspy/Games"
- time_check = 300
- process_pids = {}
- pid_idle_flags = {}
- # Path to log corrupted folders
- corrupted_log_path = "/home/caspy/corrupted_folders.txt"
- def get_folder_list(base_path):
- """Get the list of folders in the base path."""
- folders = [f for f in os.listdir(base_path) if os.path.isdir(os.path.join(base_path, f))]
- print(f"Found folders in {base_path}: {folders}")
- return folders
- def get_first_file_name(folder_path):
- """Get the first file name in the folder (without extension)."""
- for file_name in os.listdir(folder_path):
- if os.path.isfile(os.path.join(folder_path, file_name)):
- name_without_extension = os.path.splitext(file_name)[0]
- print(f"Found file in {folder_path}: {file_name}, parsed name: {name_without_extension}")
- return name_without_extension
- print(f"No file found in {folder_path}")
- return None
- def find_pid_by_name(process_name):
- """Find the PID of a process by name."""
- for proc in psutil.process_iter(['pid', 'cmdline']):
- try:
- cmdline = proc.info['cmdline']
- if isinstance(cmdline, list):
- cmdline_str = ' '.join(cmdline)
- if process_name in cmdline_str:
- return proc.info['pid']
- except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
- continue
- return None
- def is_file_stable(file_path, interval=5):
- """Check if a file's size is stable over a given interval."""
- try:
- size1 = os.path.getsize(file_path)
- time.sleep(interval)
- size2 = os.path.getsize(file_path)
- return size1 == size2
- except FileNotFoundError:
- return False
- def is_file_locked(file_path):
- """Check if a file is locked by another process."""
- try:
- with open(file_path, 'rb'):
- return False
- except IOError:
- return True
- def log_corrupted_folder(folder_name):
- """Log a corrupted folder to the log file."""
- with open(corrupted_log_path, "a") as log_file:
- log_file.write(f"{folder_name}\n")
- print(f"Logged corrupted folder: {folder_name}")
- def is_folder_corrupted(folder_name):
- """Check if a folder is listed as corrupted."""
- if not os.path.exists(corrupted_log_path):
- return False
- with open(corrupted_log_path, "r") as log_file:
- corrupted_folders = log_file.read().splitlines()
- return folder_name in corrupted_folders
- def extract_and_remove(folder_path, base_path):
- """Extract .rar files in the folder and move .mkv files to movies_path."""
- folder_name = os.path.basename(folder_path)
- extracted_folder_path = os.path.join(base_path, folder_name)
- # Check if the folder is listed as corrupted
- if is_folder_corrupted(folder_name):
- print(f"Skipping corrupted folder: {folder_path}")
- return
- # Ensure the extraction directory exists
- if not os.path.exists(extracted_folder_path):
- os.makedirs(extracted_folder_path)
- # Extract the .rar file
- try:
- for file_name in os.listdir(folder_path):
- file_path = os.path.join(folder_path, file_name)
- # Skip temporary or incomplete files
- if file_name.endswith(('.part', '.tmp')) or is_file_locked(file_path):
- print(f"Skipping incomplete file: {file_name}")
- continue
- if file_name.endswith('.rar'):
- if not is_file_stable(file_path):
- print(f"File {file_name} is still being downloaded, skipping.")
- continue
- print(f"Extracting {file_path} to {extracted_folder_path}")
- subprocess.run(['unrar', 'x', file_path, extracted_folder_path], check=True)
- print(f"Successfully extracted {file_path}")
- break
- except Exception as e:
- print(f"An error occurred while extracting {folder_path}. Error: {e}")
- log_corrupted_folder(folder_name)
- return
- # Rename .mkv file to match folder name
- try:
- for file_name in os.listdir(extracted_folder_path):
- if file_name.endswith('.mkv'):
- old_mkv_path = os.path.join(extracted_folder_path, file_name)
- new_mkv_name = f"{folder_name}.mkv"
- new_mkv_path = os.path.join(movies_path, new_mkv_name)
- print(f"Renaming {old_mkv_path} to {new_mkv_path}")
- os.rename(old_mkv_path, new_mkv_path)
- print(f"Successfully renamed and moved {old_mkv_path}")
- break
- except Exception as e:
- print(f"An error occurred during renaming: {e}")
- log_corrupted_folder(folder_name)
- return
- # Remove the original folder
- try:
- subprocess.run(['rm', '-rf', folder_path], check=True)
- print(f"Removed folder: {folder_path}")
- except Exception as e:
- print(f"An unexpected error occurred while removing folder {folder_path}: {e}")
- log_corrupted_folder(folder_name)
- def archive_and_remove(folder_path, base_path):
- """Archive the folder into a .tar file and remove the original folder."""
- folder_name = os.path.basename(folder_path)
- tar_path = os.path.join(base_path, f"{folder_name}.tar")
- try:
- print(f"Archiving {folder_path} to {tar_path}")
- with tarfile.open(tar_path, "w") as tar:
- tar.add(folder_path, arcname=folder_name)
- subprocess.run(['rm', '-rf', folder_path])
- print(f"Archived and removed folder: {folder_path}")
- except Exception as e:
- print(f"Error archiving {folder_path}: {e}")
- def check_and_process(base_path, category):
- """Check and process folders in the base path."""
- folders = get_folder_list(base_path)
- for folder in folders:
- folder_path = os.path.join(base_path, folder)
- if category == 'Movies':
- extract_and_remove(folder_path, base_path)
- elif category == 'Games':
- archive_and_remove(folder_path, base_path)
- def main():
- """Main script loop."""
- while True:
- print("Starting new iteration")
- check_and_process(movies_path, 'Movies')
- check_and_process(games_path, 'Games')
- print(f"Sleeping for {time_check} seconds")
- time.sleep(time_check)
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement