(self, file_code: FileCodes)
| 666 | return self._convert_link_to_download_link(permission.link.webUrl) |
| 667 | |
| 668 | async def get_file_response(self, file_code: FileCodes): |
| 669 | try: |
| 670 | filename = file_code.prefix + file_code.suffix |
| 671 | link = await asyncio.to_thread( |
| 672 | self._get_file_url, await file_code.get_file_path(), filename |
| 673 | ) |
| 674 | |
| 675 | content_length = None # 初始化为 None,表示未知大小 |
| 676 | |
| 677 | # 创建ClientSession并复用 |
| 678 | session = aiohttp.ClientSession() |
| 679 | |
| 680 | # 尝试发送HEAD请求获取Content-Length |
| 681 | try: |
| 682 | async with session.head(link) as resp: |
| 683 | if resp.status == 200 and 'Content-Length' in resp.headers: |
| 684 | content_length = int(resp.headers['Content-Length']) |
| 685 | except Exception: |
| 686 | # 如果HEAD请求失败,则不提供 Content-Length |
| 687 | pass |
| 688 | |
| 689 | async def stream_generator(): |
| 690 | try: |
| 691 | async with session.get(link) as resp: |
| 692 | if resp.status != 200: |
| 693 | raise HTTPException( |
| 694 | status_code=resp.status, |
| 695 | detail=f"从OneDrive获取文件失败: {resp.status}" |
| 696 | ) |
| 697 | chunk_size = 65536 |
| 698 | while True: |
| 699 | chunk = await resp.content.read(chunk_size) |
| 700 | if not chunk: |
| 701 | break |
| 702 | yield chunk |
| 703 | finally: |
| 704 | await session.close() |
| 705 | |
| 706 | encoded_filename = quote(filename, safe='') |
| 707 | headers = { |
| 708 | "Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}" |
| 709 | } |
| 710 | if content_length is not None: |
| 711 | headers["Content-Length"] = str(content_length) |
| 712 | return StreamingResponse( |
| 713 | stream_generator(), |
| 714 | media_type="application/octet-stream", |
| 715 | headers=headers |
| 716 | ) |
| 717 | except HTTPException: |
| 718 | raise |
| 719 | except Exception: |
| 720 | raise HTTPException(status_code=503, detail="服务代理下载异常,请稍后再试") |
| 721 | |
| 722 | async def get_file_url(self, file_code: FileCodes): |
| 723 | if self.proxy: |
nothing calls this directly
no test coverage detected