Skip to content

Commit

Permalink
add download_file, improve upload_file
Browse files Browse the repository at this point in the history
  • Loading branch information
mib1185 committed Jan 5, 2025
1 parent 57da4bc commit 2e6ff04
Showing 1 changed file with 30 additions and 4 deletions.
34 changes: 30 additions & 4 deletions src/synology_dsm/api/file_station/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
from collections.abc import AsyncIterator
from io import BufferedReader

from aiohttp import StreamReader

from synology_dsm.api import SynoBaseApi

from .models import (
Expand Down Expand Up @@ -110,16 +112,40 @@ async def get_files(

return files

async def upload_files(
async def upload_file(
self,
path: str,
filename: str,
content: bytes | BufferedReader | AsyncIterator[bytes],
source: bytes | BufferedReader | AsyncIterator[bytes] | str,
) -> bool | None:
"""Upload a file to a folder."""
"""Upload a file to a folder from eather a local source_file or content."""
if isinstance(source, str):
source = open(source, "rb")

raw_data = await self._dsm.post(
self.UPLOAD_API_KEY, "upload", path=path, filename=filename, content=content
self.UPLOAD_API_KEY, "upload", path=path, filename=filename, content=source
)
if not isinstance(raw_data, dict):
return None
return raw_data.get("success")

async def download_file(
self, path: str, filename: str, target_file: str | None = None
) -> StreamReader | bool | None:
"""Download a file to local target_file or returns an async StreamReader."""
response_content = await self._dsm.get(
self.DOWNLOAD_API_KEY,
"download",
{"path": f"{path}/{filename}", "mode": "download"},
raw_response_content=True,
)
if not isinstance(response_content, StreamReader):
return None

if target_file:
with open(target_file, "wb") as fh:
async for data in response_content.iter_chunked(8192):
fh.write(data)
return True

return response_content

0 comments on commit 2e6ff04

Please sign in to comment.