Skip to content

Commit

Permalink
修复:下载断点续传功能 #17
Browse files Browse the repository at this point in the history
  • Loading branch information
rachpt committed May 28, 2020
1 parent 3d46ebb commit a5a40fa
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
15 changes: 9 additions & 6 deletions cloud189/api/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -694,21 +694,24 @@ def down_file_by_id(self, fid, save_path='./Download', callback=None) -> int:
return Cloud189.FAILED
total_size = int(resp.headers['Content-Length'])

# ---
file_path = save_path + os.sep + infos.name
logger.debug(f'Save file to {file_path=}')
if os.path.exists(file_path):
now_size = os.path.getsize(file_path) # 本地已经下载的文件大小
if now_size >= total_size: # 已经下载完成
if callback is not None:
callback(infos.name, total_size, now_size)
return Cloud189.SUCCESS
else:
now_size = 0
chunk_size = 4096
logger.debug(f'Download file info: {file_path=}, {now_size=}, {total_size=}')

scale = get_down_chunk_size_scale(total_size)
chunk_size = 1024 * 1024 * scale # scale * 1 MB
headers = {**self._headers, 'Range': 'bytes=%d-' % now_size}
resp = self._get(durl, stream=True, headers=headers)

if not resp:
return Cloud189.FAILED
# if resp.status_code == 416: # 已经下载完成
# return Cloud189.SUCCESS

with open(file_path, "ab") as f:
for chunk in resp.iter_content(chunk_size):
Expand All @@ -718,7 +721,7 @@ def down_file_by_id(self, fid, save_path='./Download', callback=None) -> int:
now_size += len(chunk)
if callback is not None:
callback(infos.name, total_size, now_size)
logger.debug(f"{total_size=}, {now_size=}")
logger.debug(f"Dwonload finished: {total_size=}, {now_size=}")
return Cloud189.SUCCESS

def delete_by_id(self, fid):
Expand Down
16 changes: 14 additions & 2 deletions cloud189/api/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@
4anY+YzZJcyOcEGKVQIDAQAB
-----END PUBLIC KEY-----
"""
b64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
BI_RM = list("0123456789abcdefghijklmnopqrstuvwxyz")


def encrypt(password: str) -> str:
return b64encode(
Expand All @@ -43,12 +46,11 @@ def encrypt(password: str) -> str:
)
).decode()

b64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
BI_RM = list("0123456789abcdefghijklmnopqrstuvwxyz")

def int2char(a):
return BI_RM[a]


def b64tohex(a):
d = ""
e = 0
Expand Down Expand Up @@ -143,3 +145,13 @@ def get_chunks(file, chunk_size=1):
data = file.read(chunk_size)
if not data: break
yield data


def get_down_chunk_size_scale(total_size: int) -> int:
"""获取文件下载 块系数"""
if total_size >= 1024 * 1024 * 1024: # 1 GB
return 10
elif total_size >= 1024 * 1024 * 100: # 100 MB
return 4
else:
return 1

0 comments on commit a5a40fa

Please sign in to comment.