Skip to content

Commit 8973abd

Browse files
author
Lan
committed
fix: 修复webdav空文件夹未删除
1 parent 0783f47 commit 8973abd

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

core/storage.py

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -409,6 +409,34 @@ async def _mkdir_p(self, directory_path: str):
409409
detail=f"目录创建失败: {content[:200]}",
410410
)
411411

412+
async def _is_dir_empty(self, dir_path: str) -> bool:
413+
"""检查目录是否为空"""
414+
url = self._build_url(dir_path)
415+
416+
async with aiohttp.ClientSession(auth=self.auth) as session:
417+
async with session.request("PROPFIND", url, headers={"Depth": "1"}) as resp:
418+
if resp.status != 207: # 207 是 Multi-Status 响应
419+
return False
420+
content = await resp.text()
421+
# 如果只有一个 response(当前目录),说明目录为空
422+
return content.count("<D:response>") <= 1
423+
424+
async def _delete_empty_dirs(self, file_path: str, session: aiohttp.ClientSession):
425+
"""递归删除空目录"""
426+
path_obj = Path(file_path)
427+
current_path = path_obj.parent
428+
429+
while str(current_path) != ".":
430+
if not await self._is_dir_empty(str(current_path)):
431+
break
432+
433+
url = self._build_url(str(current_path))
434+
async with session.delete(url) as resp:
435+
if resp.status not in (200, 204, 404):
436+
break
437+
438+
current_path = current_path.parent
439+
412440
async def save_file(self, file: UploadFile, save_path: str):
413441
"""保存文件(自动创建目录)"""
414442
# 分离文件名和目录路径
@@ -437,19 +465,24 @@ async def save_file(self, file: UploadFile, save_path: str):
437465
raise HTTPException(status_code=503, detail=f"WebDAV连接异常: {str(e)}")
438466

439467
async def delete_file(self, file_code: FileCodes):
440-
"""删除WebDAV文件"""
468+
"""删除WebDAV文件及空目录"""
441469
file_path = await file_code.get_file_path()
442470
url = self._build_url(file_path)
443471

444472
try:
445473
async with aiohttp.ClientSession(auth=self.auth) as session:
474+
# 删除文件
446475
async with session.delete(url) as resp:
447-
if resp.status not in (200, 204):
476+
if resp.status not in (200, 204, 404):
448477
content = await resp.text()
449478
raise HTTPException(
450479
status_code=resp.status,
451480
detail=f"WebDAV删除失败: {content[:200]}",
452481
)
482+
483+
# 使用同一个 session 删除空目录
484+
await self._delete_empty_dirs(file_path, session)
485+
453486
except aiohttp.ClientError as e:
454487
raise HTTPException(status_code=503, detail=f"WebDAV连接异常: {str(e)}")
455488

0 commit comments

Comments
 (0)