Skip to content

Commit

Permalink
Feature: download File
Browse files Browse the repository at this point in the history
  • Loading branch information
1yam committed Nov 13, 2023
1 parent a74a0a3 commit 14376dd
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
36 changes: 35 additions & 1 deletion src/aleph_client/commands/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from typing import Optional

import typer
from aleph.sdk import AuthenticatedAlephHttpClient
from aleph.sdk import AlephHttpClient, AuthenticatedAlephHttpClient
from aleph.sdk.account import _load_account
from aleph.sdk.conf import settings as sdk_settings
from aleph.sdk.types import AccountFromPrivateKey, StorageEnum
Expand Down Expand Up @@ -99,3 +99,37 @@ async def upload(
)
logger.debug("Upload finished")
typer.echo(f"{result.json(indent=4)}")


@app.command()
async def download(
hash: str = typer.Argument(..., help="hash to download from aleph."),
use_ipfs: bool = typer.Option(
default=False, help="Download using IPFS instead of storage"
),
output_path: Path = typer.Option(Path("."), help="Output directory path"),
file_name: str = typer.Option(None, help="Output file name (without extension)"),
file_extension: str = typer.Option(None, help="Output file extension"),
debug: bool = False,
):
"""Download a file on aleph.im."""

setup_logging(debug)

output_path.mkdir(parents=True, exist_ok=True)

file_name = file_name if file_name else hash
file_extension = file_extension if file_extension else ""

output_file_path = output_path / f"{file_name}{file_extension}"

async with AlephHttpClient(api_server=sdk_settings.API_HOST) as client:
logger.info(f"Downloading {hash} ...")
async with AlephHttpClient(api_server=sdk_settings.API_HOST) as client:
with open(output_file_path, "wb") as fd:
if use_ipfs:
await client.download_file_to_buffer(hash, fd)
else:
await client.download_file_to_buffer(hash, fd)

logger.debug("File downloaded successfully.")
16 changes: 15 additions & 1 deletion tests/unit/test_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ def test_sign_raw_stdin():


def test_file_upload():
# Test upload a file to aleph network by creating a file and upload it to an aleph node
# Test upload a file to aleph network by creating a file and upload it to an aleph node
with NamedTemporaryFile() as temp_file:
temp_file.write(b"Hello World \n")
result = runner.invoke(
Expand All @@ -172,3 +172,17 @@ def test_file_upload():
)
assert result.exit_code == 0
assert result.stdout is not None


def test_file_download():
# Test download a file to aleph network
result = runner.invoke(
app,
[
"file",
"download",
"QmeomffUNfmQy76CQGy9NdmqEnnHU9soCexBnGU3ezPHVH",
], # 5 bytes file
)
assert result.exit_code == 0
assert result.stdout is not None

0 comments on commit 14376dd

Please sign in to comment.