alroyso 1 year ago
parent
commit
5b32ab9e72
2 changed files with 49 additions and 109 deletions
  1. 44 107
      src/api/alist.py
  2. 5 2
      src/main.py

+ 44 - 107
src/api/alist.py

@@ -161,19 +161,22 @@ class AlistAPI:
         )
         return response.json()
 
-    def save_directory_contents_to_json(self, remote_path, local_base_path=None, copy_or_move_destination_path=None,
+    def save_directory_contents_to_json(self, remote_path, local_base_path=None, original_path=None,
+                                        copy_or_move_destination_path=None,
                                         json_file_path=''):
         file_list = self.list_directory(remote_path)
         if not file_list:
             return
 
         directory_contents = self._recursive_collect_contents(remote_path, local_base_path,
+                                                              original_path,
                                                               copy_or_move_destination_path)
 
         with open(json_file_path, 'w', encoding='utf-8') as f:
             json.dump(directory_contents, f, indent=4, ensure_ascii=False)
 
-    def _recursive_collect_contents(self, path, local_base_path, copy_or_move_destination_path, current_sub_path=''):
+    def _recursive_collect_contents(self, path, local_base_path, original_path, copy_or_move_destination_path,
+                                    current_sub_path=''):
         contents = []
         file_list = self.list_directory(path)
         for file_info in file_list['data']['content']:
@@ -183,20 +186,23 @@ class AlistAPI:
             # 初始化本地下载路径和复制/移动目的地路径
             local_download_path = ''
             copy_move_dest_path = ''
-
+            scy_path = ''
             # 根据条件构建本地下载路径和复制/移动目的地路径
             if local_base_path is not None:
                 local_download_path = os.path.join(local_base_path, current_sub_path, file_info['name']).replace('\\',
                                                                                                                  '/')
             if copy_or_move_destination_path is not None:
-                copy_move_dest_path = os.path.join(copy_or_move_destination_path, current_sub_path,
-                                                   file_info['name']).replace('\\', '/')
+                copy_move_dest_path = os.path.join(copy_or_move_destination_path, current_sub_path).replace('\\', '/')
+
+            if copy_or_move_destination_path is not None:
+                scy_path = os.path.join(original_path, current_sub_path).replace('\\', '/')
 
             item = {
                 'name': file_info['name'],
                 'is_dir': file_info['is_dir'],
                 'path': full_path,  # 存储完整的远程路径
                 'downloads_path': local_download_path,
+                'scy_path': scy_path,
                 'copy_des_path': copy_move_dest_path
             }
             contents.append(item)
@@ -205,6 +211,7 @@ class AlistAPI:
                 # 更新子路径为当前文件夹的路径
                 new_sub_path = os.path.join(current_sub_path, file_info['name'])
                 sub_contents = self._recursive_collect_contents(full_path, local_base_path,
+                                                                original_path,
                                                                 copy_or_move_destination_path, new_sub_path)
                 contents.extend(sub_contents)
 
@@ -246,8 +253,9 @@ class AlistAPI:
                 else:
                     logging.info(f"File already downloaded, skipping: {local_file}")
 
-    def monitor_and_copy(self, local_json_path, check_interval=10, is_debug=False, is_running=True):
-        """监控 Aria2 下载完成后,执行拷贝操作"""
+    def monitor_copy_and_delete(self, local_json_path, destination_path, check_interval=10, is_debug=False,
+                                is_running=True):
+        """监控 Aria2 下载完成后,执行拷贝操作并删除原始文件及历史记录"""
         try:
             while is_running:
                 # 读取本地 JSON 文件
@@ -263,128 +271,57 @@ class AlistAPI:
 
                                 for item in directory_contents:
                                     if item['name'] == file_name and not item['is_dir']:
-                                        original_path = item['path']  # 获取原始文件路径
-                                        des_path = item['copy_des_path']  # 获取原始文件路径
+                                        original_path = item['downloads_path']  # 获取原始文件路径
 
                                         if is_debug:
                                             logging.info(f"Debug mode: Copy {file_name}")
                                         else:
                                             # 复制文件
-                                            self.copy_file(original_path, des_path, [file_name])
+                                            self.copy_file(original_path, destination_path, [file_name])
                                             logging.info(
-                                                f"Copied: {file_name} from {original_path} to {des_path}")
+                                                f"Copied: {file_name} from {original_path} to {destination_path}")
+
+                                            # 删除原始文件和 Aria2 历史记录
+                                            self.remove_files_or_folders([file_name], original_path)
+                                            download.remove()
+                                            logging.info(f"Removed: {file_name} from Aria2 and original path")
 
                 time.sleep(check_interval)
         except Exception as e:
             logging.error(f"Error occurred: {e}")
         finally:
-            logging.info("Monitoring and copying completed")
+            logging.info("Monitoring, copying, and deleting completed")
 
-    def monitor_and_move_or_copy(self, local_json_path, check_interval=10,
-                                 is_debug=False, is_running=True, timeout=3600,
-                                 condition=None, action_type=ActionType.COPY):
-        """监控 Aria2 下载完成后,执行移动操作并检查任务完成状态"""
-        start_time = time.time()
+    def monitor_and_copy(self, local_json_path, check_interval=10, is_debug=False, is_running=True):
+        """监控 Aria2 下载完成后,执行拷贝操作"""
         try:
             while is_running:
-                current_time = time.time()
-                if current_time - start_time > timeout:
-                    logging.info(f"Timeout: {timeout} seconds")
-                    break
-
                 # 读取本地 JSON 文件
                 with open(local_json_path, 'r', encoding='utf-8') as f:
                     directory_contents = json.load(f)
 
-                for item in directory_contents:
-                    if not item['is_dir']:
-                        local_file_path = item['downloads_path']
-                        remote_file_name = item['remote_file_name']
-                        scy_des_path = item['path']
-                        des_des_path = item['copy_des_path']
-                        # 检查 Aria2 是否已完成该文件的下载
-                        downloads = self.aria2_api.get_downloads()
-                        for download in downloads:
-                            if download.is_complete:
-                                for file in download.files:
-                                    if file.selected and os.path.basename(file.path) == remote_file_name:
+                downloads = self.aria2_api.get_downloads()
+                for download in downloads:
+                    if download.is_complete:
+                        for file in download.files:
+                            if file.selected:
+                                file_name = os.path.basename(file.path)
+
+                                for item in directory_contents:
+                                    if item['name'] == file_name and not item['is_dir']:
+                                        original_path = item['scy_path']  # 获取原始文件路径
+                                        des_path = item['copy_des_path']  # 获取原始文件路径
+
                                         if is_debug:
-                                            logging.info(f"Debug mode: {action_type} {remote_file_name}")
+                                            logging.info(f"Debug mode: Copy {file_name}")
                                         else:
-                                            if action_type == ActionType.MOVE:
-                                                self.move_file(scy_des_path, des_des_path)
-                                                logging.info(f"Moved: {scy_des_path} to {des_des_path}")
-                                            elif action_type == ActionType.COPY:
-                                                self.copy_file(scy_des_path, des_des_path)
-                                                logging.info(f"Copied: {scy_des_path} to {des_des_path}")
-                                                # self.remove_files_or_folders([scy_des_path], item['path'])
-                                                # logging.info(
-                                                #     f"Removed original: {scy_des_path} from {item['path']}")
-
-                if condition is not None and condition():
-                    logging.info("Condition met, stopping monitoring")
-                    break
+                                            # 复制文件
+                                            self.copy_file(original_path, des_path, [file_name])
+                                            logging.info(
+                                                f"Copied: {file_name} from {original_path} to {des_path}")
 
                 time.sleep(check_interval)
         except Exception as e:
             logging.error(f"Error occurred: {e}")
         finally:
-            logging.info("Monitoring stopped")
-    # def monitor_and_move_or_copy(self, download_path, destination_path, check_interval=10,
-    #                              is_debug=False, is_running=True, timeout=3600,
-    #                              condition=None, action_type=ActionType.COPY):
-    #     """监控 Aria2 下载完成后,执行移动操作并检查任务完成状态"""
-    #     # 记录开始监控的时间
-    #     start_time = time.time()
-    #     try:
-    #         while is_running:
-    #             # 检查是否超时
-    #             current_time = time.time()
-    #             if current_time - start_time > timeout:
-    #                 logging.info(f"Timeout: {timeout} seconds")
-    #                 break
-    #             downloads = self.aria2_api.get_downloads()
-    #             for download in downloads:
-    #                 if download.is_complete:
-    #                     all_tasks_completed = True
-    #                     for file in download.files:
-    #                         if file.selected:
-    #                             file_name = os.path.basename(file.path)
-    #                             names = [file_name]
-    #
-    #                             if is_debug is False:
-    #                                 if action_type == ActionType.MOVE:
-    #                                     # 移动文件
-    #                                     self.move_file(download_path, destination_path, names)
-    #                                     logging.info(f"Moved: {file_name} from {download_path} to {destination_path}")
-    #                                 if action_type == ActionType.COPY:
-    #                                     # 复制文件
-    #                                     self.copy_file(download_path, destination_path, names)
-    #                                     logging.info(f"Copied: {file_name} from {download_path} to {destination_path}")
-    #
-    #                                     # 检查任务完成状态
-
-    #                             else:
-    #                                 """调试信息不真到进行操作"""
-    #                                 if action_type == ActionType.MOVE:
-    #                                     # 移动文件
-    #                                     logging.info(f"Moved: {file_name} from {download_path} to {destination_path}")
-    #                                 if action_type == ActionType.COPY:
-    #                                     # 复制文件
-    #                                     logging.info(f"Copied: {file_name} from {download_path} to {destination_path}")
-    #
-    #             # 检查是否满足条件
-    #             if condition is not None and condition():
-    #                 logging.info(f"Condition met: {condition}")
-    #                 break
-    #
-    #             time.sleep(check_interval)
-    #     except Exception as e:
-    #         # 捕获异常,并记录日志
-    #         logging.error(f"An error occurred: {e}")
-    #     finally:
-    #         # 做一些清理工作,比如关闭 Aria2 的连接,删除临时文件等
-    #         # self.aria2_api.close()
-    #         logging.info(f"Closed Aria2 connection")
-    #         # ...其他清理工作
-    #         logging.info(f"monitor_and_move_or_copy is run {is_running}")
+            logging.info("Monitoring and copying completed")

+ 5 - 2
src/main.py

@@ -40,12 +40,15 @@ def my_custom_action(movie,
     logging.info(f" remote save_directory path {remote_download_path} to data/remote.json")
     # 这里是 home 路径
     home_alist_api.save_directory_contents_to_json(home_download_path,
+                                                   original_path=copy_or_move_download_path,
                                                    copy_or_move_destination_path=copy_or_move_destination_path,
                                                    json_file_path='data/home.json')
     logging.info(f" remote save_directory path {home_download_path} to data/home.json")
     # 从服务器上遍历需要下载的数据,推送到本地
-    remote_alist_api.download_directory(is_debug=True,
-                                        json_file_path='data/remote.json')
+    # remote_alist_api.download_directory(is_debug=True,
+    #                                     json_file_path='data/remote.json')
+
+    home_alist_api.monitor_and_copy('data/home.json', is_running=is_running)
 
     logging.info("Task completion")