Advertisement
DaRealNG

Untitled

Dec 20th, 2024
23
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.53 KB | None | 0 0
  1. import os
  2. import time
  3. import tarfile
  4. import subprocess
  5. import psutil
  6.  
  7. # Define paths and time interval as global variables
  8. movies_path = "/home/caspy/Movies"
  9. games_path = "/home/caspy/Games"
  10. time_check = 300
  11. process_pids = {}
  12. pid_idle_flags = {}
  13.  
  14. # Path to log corrupted folders
  15. corrupted_log_path = "/home/caspy/corrupted_folders.txt"
  16.  
  17. def get_folder_list(base_path):
  18. """Get the list of folders in the base path."""
  19. folders = [f for f in os.listdir(base_path) if os.path.isdir(os.path.join(base_path, f))]
  20. print(f"Found folders in {base_path}: {folders}")
  21. return folders
  22.  
  23. def get_first_file_name(folder_path):
  24. """Get the first file name in the folder (without extension)."""
  25. for file_name in os.listdir(folder_path):
  26. if os.path.isfile(os.path.join(folder_path, file_name)):
  27. name_without_extension = os.path.splitext(file_name)[0]
  28. print(f"Found file in {folder_path}: {file_name}, parsed name: {name_without_extension}")
  29. return name_without_extension
  30. print(f"No file found in {folder_path}")
  31. return None
  32.  
  33. def find_pid_by_name(process_name):
  34. """Find the PID of a process by name."""
  35. for proc in psutil.process_iter(['pid', 'cmdline']):
  36. try:
  37. cmdline = proc.info['cmdline']
  38. if isinstance(cmdline, list):
  39. cmdline_str = ' '.join(cmdline)
  40. if process_name in cmdline_str:
  41. return proc.info['pid']
  42. except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
  43. continue
  44. return None
  45.  
  46. def is_file_stable(file_path, interval=5):
  47. """Check if a file's size is stable over a given interval."""
  48. try:
  49. size1 = os.path.getsize(file_path)
  50. time.sleep(interval)
  51. size2 = os.path.getsize(file_path)
  52. return size1 == size2
  53. except FileNotFoundError:
  54. return False
  55.  
  56. def is_file_locked(file_path):
  57. """Check if a file is locked by another process."""
  58. try:
  59. with open(file_path, 'rb'):
  60. return False
  61. except IOError:
  62. return True
  63.  
  64. def log_corrupted_folder(folder_name):
  65. """Log a corrupted folder to the log file."""
  66. with open(corrupted_log_path, "a") as log_file:
  67. log_file.write(f"{folder_name}\n")
  68. print(f"Logged corrupted folder: {folder_name}")
  69.  
  70. def is_folder_corrupted(folder_name):
  71. """Check if a folder is listed as corrupted."""
  72. if not os.path.exists(corrupted_log_path):
  73. return False
  74. with open(corrupted_log_path, "r") as log_file:
  75. corrupted_folders = log_file.read().splitlines()
  76. return folder_name in corrupted_folders
  77.  
  78. def extract_and_remove(folder_path, base_path):
  79. """Extract .rar files in the folder and move .mkv files to movies_path."""
  80. folder_name = os.path.basename(folder_path)
  81. extracted_folder_path = os.path.join(base_path, folder_name)
  82.  
  83. # Check if the folder is listed as corrupted
  84. if is_folder_corrupted(folder_name):
  85. print(f"Skipping corrupted folder: {folder_path}")
  86. return
  87.  
  88. # Ensure the extraction directory exists
  89. if not os.path.exists(extracted_folder_path):
  90. os.makedirs(extracted_folder_path)
  91.  
  92. # Extract the .rar file
  93. try:
  94. for file_name in os.listdir(folder_path):
  95. file_path = os.path.join(folder_path, file_name)
  96.  
  97. # Skip temporary or incomplete files
  98. if file_name.endswith(('.part', '.tmp')) or is_file_locked(file_path):
  99. print(f"Skipping incomplete file: {file_name}")
  100. continue
  101.  
  102. if file_name.endswith('.rar'):
  103. if not is_file_stable(file_path):
  104. print(f"File {file_name} is still being downloaded, skipping.")
  105. continue
  106.  
  107. print(f"Extracting {file_path} to {extracted_folder_path}")
  108. subprocess.run(['unrar', 'x', file_path, extracted_folder_path], check=True)
  109. print(f"Successfully extracted {file_path}")
  110. break
  111. except Exception as e:
  112. print(f"An error occurred while extracting {folder_path}. Error: {e}")
  113. log_corrupted_folder(folder_name)
  114. return
  115.  
  116. # Rename .mkv file to match folder name
  117. try:
  118. for file_name in os.listdir(extracted_folder_path):
  119. if file_name.endswith('.mkv'):
  120. old_mkv_path = os.path.join(extracted_folder_path, file_name)
  121. new_mkv_name = f"{folder_name}.mkv"
  122. new_mkv_path = os.path.join(movies_path, new_mkv_name)
  123. print(f"Renaming {old_mkv_path} to {new_mkv_path}")
  124. os.rename(old_mkv_path, new_mkv_path)
  125. print(f"Successfully renamed and moved {old_mkv_path}")
  126. break
  127. except Exception as e:
  128. print(f"An error occurred during renaming: {e}")
  129. log_corrupted_folder(folder_name)
  130. return
  131.  
  132. # Remove the original folder
  133. try:
  134. subprocess.run(['rm', '-rf', folder_path], check=True)
  135. print(f"Removed folder: {folder_path}")
  136. except Exception as e:
  137. print(f"An unexpected error occurred while removing folder {folder_path}: {e}")
  138. log_corrupted_folder(folder_name)
  139.  
  140. def archive_and_remove(folder_path, base_path):
  141. """Archive the folder into a .tar file and remove the original folder."""
  142. folder_name = os.path.basename(folder_path)
  143. tar_path = os.path.join(base_path, f"{folder_name}.tar")
  144. try:
  145. print(f"Archiving {folder_path} to {tar_path}")
  146. with tarfile.open(tar_path, "w") as tar:
  147. tar.add(folder_path, arcname=folder_name)
  148. subprocess.run(['rm', '-rf', folder_path])
  149. print(f"Archived and removed folder: {folder_path}")
  150. except Exception as e:
  151. print(f"Error archiving {folder_path}: {e}")
  152.  
  153. def check_and_process(base_path, category):
  154. """Check and process folders in the base path."""
  155. folders = get_folder_list(base_path)
  156. for folder in folders:
  157. folder_path = os.path.join(base_path, folder)
  158. if category == 'Movies':
  159. extract_and_remove(folder_path, base_path)
  160. elif category == 'Games':
  161. archive_and_remove(folder_path, base_path)
  162.  
  163. def main():
  164. """Main script loop."""
  165. while True:
  166. print("Starting new iteration")
  167. check_and_process(movies_path, 'Movies')
  168. check_and_process(games_path, 'Games')
  169. print(f"Sleeping for {time_check} seconds")
  170. time.sleep(time_check)
  171.  
  172. if __name__ == "__main__":
  173. main()
  174.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement