(self, filename: str, target_path: str, download_name: str,
call_log: Callable[[int, str], None] = None)
| 866 | return self._download_file(filename, target_path, download_name, call_log) |
| 867 | |
| 868 | def _download_file(self, filename: str, target_path: str, download_name: str, |
| 869 | call_log: Callable[[int, str], None] = None) -> str: |
| 870 | data, err = self.upload_check([filename]) |
| 871 | if err: |
| 872 | return "请求文件:{}的状态失败,错误信息为:{}".format(filename, err) |
| 873 | file_size: Optional[int] = None |
| 874 | for i in data: |
| 875 | if i["filename"] == filename and i["isfile"] == True: |
| 876 | file_size = i["size"] |
| 877 | break |
| 878 | |
| 879 | if file_size is None: |
| 880 | return "文件{}不存在, 跳过下载".format(filename) |
| 881 | try: |
| 882 | if not os.path.isdir(target_path): |
| 883 | os.makedirs(target_path) |
| 884 | except Exception as e: |
| 885 | return "创建文件夹{}失败,请检查文件夹权限,错误信息为:{}".format(target_path, str(e)) |
| 886 | |
| 887 | if file_size == 0: |
| 888 | fp = open(os.path.join(target_path, download_name), "w") |
| 889 | fp.close() |
| 890 | return "" |
| 891 | |
| 892 | tmp_file = os.path.join(target_path, "{}.{}".format(download_name, uuid4().hex)) |
| 893 | try: |
| 894 | if not os.path.exists(target_path): |
| 895 | os.makedirs(target_path) |
| 896 | fb = open(tmp_file, 'wb') |
| 897 | except Exception as e: |
| 898 | return "创建临时文件{}失败,请检查文件夹权限,错误信息为:{}".format(tmp_file, str(e)) |
| 899 | |
| 900 | url = "{}/download".format(self.origin) |
| 901 | bt_p = self.get_bt_params() |
| 902 | header = {"User-Agent": "Bt-Panel/Node Manager"} |
| 903 | try: |
| 904 | resp = requests.get(url, params={"filename": filename}, data=bt_p, headers=header, stream=True, verify=False, timeout=self.timeout) |
| 905 | if not resp.status_code == 200: |
| 906 | return "下载文件响应状态码错误,请检查节点地址和api是否正确,目前状态码为{},返回信息为:{}".format( |
| 907 | resp.status_code, resp.text) |
| 908 | |
| 909 | now_size = 0 |
| 910 | for chunk in resp.iter_content(chunk_size=1024 * 1024 * 3): |
| 911 | if chunk: |
| 912 | now_size += len(chunk) |
| 913 | fb.write(chunk) |
| 914 | fb.flush() |
| 915 | call_log(now_size * 100 // file_size, |
| 916 | "下载文件{}, 已下载: {}".format(filename, public.to_size(now_size))) |
| 917 | if fb.tell() != file_size: |
| 918 | return "下载文件{}失败,文件大小检查错误".format(filename) |
| 919 | fb.close() |
| 920 | shutil.move(tmp_file, os.path.join(target_path, download_name)) |
| 921 | return "" |
| 922 | except Exception as e: |
| 923 | return "下载文件{}失败,错误信息为:{}".format(filename, str(e)) |
| 924 | finally: |
| 925 | if not fb.closed: |
no test coverage detected