"""WebDAV offset writes: one remote staging object, no local whole-file merge.""" import hashlib import asyncio from pathlib import PurePosixPath import aiohttp from fastapi import HTTPException from apps.base.models import FileCodes, UploadChunk OFFSET_MODE = 'webdav-offset' # Total verification time scales with file size; only stalled I/O is bounded. OFFSET_TIMEOUT = aiohttp.ClientTimeout(total=None, connect=30, sock_read=120) class WebDAVOffsetMixin: def _offset_path(self, upload_id, save_path): return str(PurePosixPath(save_path).parent / 'chunks' / upload_id / 'upload.bin') async def chunk_upload_mode(self): from core.clouddrive_upload import native_configured, NATIVE_MODE return NATIVE_MODE if native_configured() else "webdav-stream" async def offset_upload_mode(self): async with aiohttp.ClientSession(auth=self.auth, timeout=OFFSET_TIMEOUT) as client: async with client.options(self.base_url) as response: if response.status not in (200,204): raise HTTPException(503, '无法确认 WebDAV 分片能力,请重试') return OFFSET_MODE if 'sabredav-partialupdate' in response.headers.get('DAV','').lower() else 'legacy' async def _offset_session(self, upload_id): return await UploadChunk.filter(upload_id=upload_id, chunk_index=-1, storage_mode=OFFSET_MODE).first() async def save_offset_chunk(self, info, index, data): expected = min(info.chunk_size, info.file_size-index*info.chunk_size) if len(data) != expected: raise HTTPException(400, '分片大小与声明值不一致') previous = await UploadChunk.filter(upload_id=info.upload_id, completed=True, chunk_index__lt=index).count() if previous != index: raise HTTPException(409, '请先上传前面的分片,再重试当前分片') path = self._offset_path(info.upload_id, info.save_path) await self._mkdir_p(str(PurePosixPath(path).parent)) url = self._build_url(path) async with aiohttp.ClientSession(auth=self.auth, timeout=OFFSET_TIMEOUT) as client: if index == 0: # A lost first-PUT response must not truncate a previously written object. async with client.put(url, data=data, headers={'If-None-Match':'*'}) as response: if response.status in (200,201,204): return if response.status != 412: raise HTTPException(503, 'WebDAV 分片写入失败,请重试') start = index*info.chunk_size async with client.patch(url, data=data, headers={ 'Content-Type':'application/x-sabredav-partialupdate', 'X-Update-Range':f'bytes={start}-{start+len(data)-1}', }) as response: if response.status not in (200,204): raise HTTPException(503, 'WebDAV 偏移写入失败,请重试') async def _verify_offset_file(self, client, path, info, records): full = hashlib.sha256(); chunk_hash = hashlib.sha256() total = 0; index = 0; in_chunk = 0 async with client.get(self._build_url(path)) as response: if response.status == 404: return None if response.status != 200: raise HTTPException(503, 'WebDAV 文件校验读取失败,请重试') async for data in response.content.iter_chunked(65536): if total + len(data) > info.file_size: raise ValueError('WebDAV 文件大小与声明值不一致') total += len(data); full.update(data) offset = 0 while offset < len(data): boundary = min(info.chunk_size, info.file_size-index*info.chunk_size) amount = min(boundary-in_chunk, len(data)-offset) chunk_hash.update(data[offset:offset+amount]); in_chunk += amount; offset += amount if in_chunk == boundary: if index >= len(records) or chunk_hash.hexdigest() != records[index].chunk_hash: raise ValueError('WebDAV 分片内容校验失败,请取消后重新上传') index += 1; in_chunk = 0; chunk_hash = hashlib.sha256() if total != info.file_size or index != info.total_chunks: raise ValueError('WebDAV 文件大小与声明值不一致') # Session chunk_hash is a resumability fingerprint (large clients hash # first/last segments), not the full-file digest. Per-chunk SHA-256 # above proves contents; the SHA-256 stored on FileCodes covers all bytes. return full.hexdigest() async def _publish_offset(self, client, staging, save_path): async with client.request('MOVE', self._build_url(staging), headers={ 'Destination':self._build_url(save_path), 'Overwrite':'F', }) as response: if response.status not in (201,204): raise HTTPException(503, 'WebDAV 文件发布失败,请重试完成上传') async def finish_offset_upload(self, info, save_path): records = await UploadChunk.filter(upload_id=info.upload_id, completed=True).order_by('chunk_index') if [r.chunk_index for r in records] != list(range(info.total_chunks)): raise ValueError('分片不完整') staging = self._offset_path(info.upload_id, save_path) async with aiohttp.ClientSession(auth=self.auth, timeout=OFFSET_TIMEOUT) as client: digest = await self._verify_offset_file(client, staging, info, records) if digest is None: # MOVE may have completed even when its response/DB write was lost. digest = await self._verify_offset_file(client, save_path, info, records) if digest is None: raise ValueError('上传临时文件不存在,请取消后重新上传') return save_path, digest await self._mkdir_p(str(PurePosixPath(save_path).parent)) # Disconnecting our request does not cancel the server-side MOVE. # Wait for the remote commit to settle before cancellation can clean it. move = asyncio.create_task(self._publish_offset(client, staging, save_path)) try: await asyncio.shield(move) except asyncio.CancelledError: await move raise return save_path, digest async def clean_offset_upload(self, upload_id, save_path): directory = str(PurePosixPath(self._offset_path(upload_id,save_path)).parent) paths = [directory] if not await FileCodes.filter(upload_id=upload_id).exists(): paths.append(save_path) async with aiohttp.ClientSession(auth=self.auth, timeout=OFFSET_TIMEOUT) as client: for path in paths: async with client.delete(self._build_url(path)) as response: if response.status not in (200,204,404): raise HTTPException(503, 'WebDAV 上传清理失败,请重试')