Skip to content

Commit 30e19e8

Browse files
committed
reformat; fix types and update code to reflect changes in SDK
1 parent 5300b76 commit 30e19e8

File tree

8 files changed

+114
-99
lines changed

8 files changed

+114
-99
lines changed

src/aleph_client/__main__.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
import typer
66

77
from aleph_client.utils import AsyncTyper
8-
from .commands import about, account, aggregate, domain, files, message, program, node
8+
9+
from .commands import about, account, aggregate, domain, files, message, node, program
910

1011
app = AsyncTyper()
1112

@@ -29,9 +30,7 @@
2930
app.add_typer(about.app, name="about", help="Display the informations of Aleph CLI")
3031

3132
app.add_typer(node.app, name="node", help="Get node info on aleph.im network")
32-
app.add_typer(
33-
domain.app, name="domain", help="Manage custom Domain (dns) on aleph.im"
34-
)
33+
app.add_typer(domain.app, name="domain", help="Manage custom Domain (dns) on aleph.im")
3534

3635
if __name__ == "__main__":
3736
app()

src/aleph_client/commands/account.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
from typing import Optional
88

99
import requests
10-
1110
import typer
1211
from aleph.sdk.account import _load_account
1312
from aleph.sdk.chains.common import generate_key
@@ -147,6 +146,7 @@ def sign_bytes(
147146
signature = asyncio.run(coroutine)
148147
typer.echo(signature.hex())
149148

149+
150150
@app.command()
151151
def balance(
152152
address: Optional[str] = typer.Option(None, help="Address"),
@@ -177,4 +177,4 @@ def balance(
177177
else:
178178
typer.echo(
179179
"Error: Please provide either a private key, private key file, or an address."
180-
)
180+
)

src/aleph_client/commands/aggregate.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import json
22
from pathlib import Path
3-
from typing import Any, Mapping, Optional
3+
from typing import Optional
44

55
import typer
66
from aleph.sdk.account import _load_account
@@ -16,8 +16,6 @@
1616

1717
app = AsyncTyper()
1818

19-
from aleph_client.commands.utils import colorful_message_json
20-
2119

2220
@app.command()
2321
async def forget(
@@ -130,5 +128,3 @@ async def get(
130128
typer.echo(json.dumps(aggregates, indent=4))
131129
else:
132130
typer.echo("No aggregates found for the given key and content.")
133-
134-

src/aleph_client/commands/domain.py

Lines changed: 87 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -4,39 +4,46 @@
44

55
import typer
66
from aleph.sdk.account import _load_account
7-
from aleph.sdk.client import AlephClient, AuthenticatedAlephClient
7+
from aleph.sdk.client import AlephHttpClient, AuthenticatedAlephHttpClient
88
from aleph.sdk.conf import settings as sdk_settings
9-
from aleph.sdk.domain import DomainValidator, Hostname, TargetType, hostname_from_url
9+
from aleph.sdk.domain import (
10+
DomainValidator,
11+
Hostname,
12+
TargetType,
13+
get_target_type,
14+
hostname_from_url,
15+
)
1016
from aleph.sdk.exceptions import DomainConfigurationError
17+
from aleph.sdk.query.filters import MessageFilter
1118
from aleph.sdk.types import AccountFromPrivateKey
12-
from aleph_client.commands import help_strings
13-
from aleph_client.commands.utils import coro
1419
from aleph_message.models import AggregateMessage, MessageType
1520
from rich.console import Console
1621
from rich.prompt import Confirm, Prompt
1722
from rich.table import Table
1823

19-
app = typer.Typer()
24+
from aleph_client.commands import help_strings
25+
from aleph_client.utils import AsyncTyper
26+
27+
app = AsyncTyper()
2028

2129

2230
async def get_aggregate_domain_info(account, fqdn):
23-
async with AlephClient(api_server=sdk_settings.API_HOST) as client:
31+
async with AlephHttpClient(api_server=sdk_settings.API_HOST) as client:
2432
aggregates = await client.get_messages(
25-
addresses=[str(account.get_address())],
26-
message_type=MessageType.aggregate,
33+
message_filter=MessageFilter(
34+
addresses=[str(account.get_address())],
35+
message_types=[MessageType.aggregate],
36+
),
2737
page=1,
28-
pagination=1000
38+
page_size=1000,
2939
)
3040

3141
for message in aggregates.messages:
3242
aggregate = cast(AggregateMessage, message)
3343
if aggregate.content.key == "domains":
3444
for domain, info in aggregate.content.content.items():
3545
if domain == fqdn:
36-
return {
37-
"timestamp": aggregate.content.time,
38-
"info": info
39-
}
46+
return {"timestamp": aggregate.content.time, "info": info}
4047
return None
4148

4249

@@ -59,37 +66,39 @@ async def detach_resource(account: AccountFromPrivateKey, fqdn: Hostname):
5966
table.add_column("New resource", justify="right", style="green", no_wrap=True)
6067
table.add_column("Resource type", style="magenta")
6168

62-
domain_validator = DomainValidator()
63-
6469
if domain_info is not None and domain_info.get("info"):
6570
current_resource = domain_info["info"]["message_id"]
71+
else:
72+
current_resource = "null"
6673

67-
resource_type = await domain_validator.get_target_type(fqdn)
68-
table.add_row(f"{current_resource[:16]}...{current_resource[-16:]}", "", resource_type)
74+
resource_type = await get_target_type(fqdn)
75+
table.add_row(
76+
f"{current_resource[:16]}...{current_resource[-16:]}", "", resource_type
77+
)
6978

7079
console.print(table)
7180

7281
if Confirm.ask("Continue"):
7382
"""Update aggregate message"""
7483

75-
async with AuthenticatedAlephClient(
76-
account=account, api_server=sdk_settings.API_HOST
84+
async with AuthenticatedAlephHttpClient(
85+
account=account, api_server=sdk_settings.API_HOST
7786
) as client:
78-
aggregate_content = {
79-
fqdn: None
80-
}
87+
aggregate_content = {fqdn: None}
8188

8289
aggregate_message, message_status = await client.create_aggregate(
83-
key="domains",
84-
content=aggregate_content,
85-
channel="ALEPH-CLOUDSOLUTIONS"
90+
key="domains", content=aggregate_content, channel="ALEPH-CLOUDSOLUTIONS"
8691
)
8792

8893
console.log("[green bold]Resource detached!")
89-
console.log(f"Visualise on: https://explorer.aleph.im/address/ETH/{account.get_address()}/message/AGGREGATE/{aggregate_message.item_hash}")
94+
console.log(
95+
f"Visualise on: https://explorer.aleph.im/address/ETH/{account.get_address()}/message/AGGREGATE/{aggregate_message.item_hash}"
96+
)
9097

9198

92-
async def attach_resource(account: AccountFromPrivateKey, fqdn: Hostname, item_hash: Optional[str] = None):
99+
async def attach_resource(
100+
account: AccountFromPrivateKey, fqdn: Hostname, item_hash: Optional[str] = None
101+
):
93102
domain_info = await get_aggregate_domain_info(account, fqdn)
94103
console = Console()
95104

@@ -101,61 +110,67 @@ async def attach_resource(account: AccountFromPrivateKey, fqdn: Hostname, item_h
101110
table.add_column("New resource", justify="right", style="green", no_wrap=True)
102111
table.add_column("Resource type", style="magenta")
103112

104-
current_resource = "null"
105-
domain_validator = DomainValidator()
106-
107113
"""
108114
Detect target type on the fly to be able to switch to another type
109115
"""
110-
resource_type = await domain_validator.get_target_type(fqdn)
116+
resource_type = await get_target_type(fqdn)
111117

112118
if domain_info is not None and domain_info.get("info"):
113119
current_resource = domain_info["info"]["message_id"]
120+
else:
121+
current_resource = "null"
114122

115-
table.add_row(f"{current_resource[:16]}...{current_resource[-16:]}", f"{item_hash[:16]}...{item_hash[-16:]}", resource_type)
123+
table.add_row(
124+
f"{current_resource[:16]}...{current_resource[-16:]}",
125+
f"{item_hash[:16]}...{item_hash[-16:]}",
126+
resource_type,
127+
)
116128

117129
console.print(table)
118130

119131
if Confirm.ask("Continue"):
120132
"""Create aggregate message"""
121133

122-
async with AuthenticatedAlephClient(
123-
account=account, api_server=sdk_settings.API_HOST
134+
async with AuthenticatedAlephHttpClient(
135+
account=account, api_server=sdk_settings.API_HOST
124136
) as client:
125137
aggregate_content = {
126138
fqdn: {
127139
"message_id": item_hash,
128140
"type": resource_type,
129141
# console page compatibility
130-
"programType": resource_type
142+
"programType": resource_type,
131143
}
132144
}
133145

134146
aggregate_message, message_status = await client.create_aggregate(
135-
key="domains",
136-
content=aggregate_content,
137-
channel="ALEPH-CLOUDSOLUTIONS"
147+
key="domains", content=aggregate_content, channel="ALEPH-CLOUDSOLUTIONS"
138148
)
139149

140150
console.log("[green bold]Resource attached!")
141-
console.log(f"Visualise on: https://explorer.aleph.im/address/ETH/{account.get_address()}/message/AGGREGATE/{aggregate_message.item_hash}")
151+
console.log(
152+
f"Visualise on: https://explorer.aleph.im/address/ETH/{account.get_address()}/message/AGGREGATE/{aggregate_message.item_hash}"
153+
)
142154

143155

144156
@app.command()
145-
@coro
146157
async def add(
147158
private_key: Optional[str] = typer.Option(
148159
sdk_settings.PRIVATE_KEY_STRING, help=help_strings.PRIVATE_KEY
149160
),
150161
private_key_file: Optional[Path] = typer.Option(
151162
sdk_settings.PRIVATE_KEY_FILE, help=help_strings.PRIVATE_KEY_FILE
152163
),
153-
fqdn: str = typer.Argument(..., help=help_strings.CUSTOM_DOMAIN_NAME
154-
),
155-
target: Optional[TargetType] = typer.Option(None,
156-
help=help_strings.CUSTOM_DOMAIN_TARGET_TYPES),
157-
item_hash: Optional[str] = typer.Option(None, help=help_strings.CUSTOM_DOMAIN_ITEM_HASH),
158-
owner: Optional[str] = typer.Option(None, help=help_strings.CUSTOM_DOMAIN_OWNER_ADDRESS)
164+
fqdn: str = typer.Argument(..., help=help_strings.CUSTOM_DOMAIN_NAME),
165+
target: Optional[TargetType] = typer.Option(
166+
None, help=help_strings.CUSTOM_DOMAIN_TARGET_TYPES
167+
),
168+
item_hash: Optional[str] = typer.Option(
169+
None, help=help_strings.CUSTOM_DOMAIN_ITEM_HASH
170+
),
171+
owner: Optional[str] = typer.Option(
172+
None, help=help_strings.CUSTOM_DOMAIN_OWNER_ADDRESS
173+
),
159174
):
160175
"""Add and link a Custom Domain."""
161176
account: AccountFromPrivateKey = _load_account(private_key, private_key_file)
@@ -165,7 +180,10 @@ async def add(
165180
fqdn = hostname_from_url(fqdn)
166181

167182
if target is None:
168-
target = Prompt.ask("Select a resource type", choices={i.name.lower(): i.value.lower() for i in TargetType})
183+
target = Prompt.ask(
184+
"Select a target resource type",
185+
choices=[TargetType.IPFS, TargetType.PROGRAM, TargetType.INSTANCE],
186+
)
169187

170188
table = Table(title=f"Required DNS entries for: {fqdn}")
171189

@@ -174,10 +192,12 @@ async def add(
174192
table.add_column("DNS NAME", style="magenta")
175193
table.add_column("DNS VALUE", justify="right", style="green")
176194

177-
owner = account.get_address()
195+
owner = owner or account.get_address()
178196
dns_rules = domain_validator.get_required_dns_rules(fqdn, target, owner)
179197
for rule_id, rule in enumerate(dns_rules):
180-
table.add_row(str(rule_id), rule["dns"]["type"], rule["dns"]["name"], rule["dns"]["value"])
198+
table.add_row(
199+
str(rule_id), rule.dns["type"], rule.dns["name"], rule.dns["value"]
200+
)
181201

182202
console.print(table)
183203

@@ -191,7 +211,7 @@ async def add(
191211
checks = await check_domain_records(fqdn, target, owner)
192212
completed_rules = []
193213
for index, rule in enumerate(dns_rules):
194-
if checks[rule["rule_name"]] is True:
214+
if checks[rule.name] is True:
195215
"""Pass configured rules"""
196216
completed_rules.append(rule)
197217
console.log(f"record: {index} [bold green] OK")
@@ -202,8 +222,8 @@ async def add(
202222

203223
if dns_rules:
204224
rule = dns_rules[0]
205-
console.log(f"[green]{rule['info']}")
206-
status.update(f"{msg_status} [bold red]{rule['on_error']}")
225+
console.log(f"[green]{rule.info}")
226+
status.update(f"{msg_status} [bold red]{rule.on_error}")
207227

208228
max_retries -= 1
209229
sleep(10)
@@ -225,7 +245,6 @@ async def add(
225245

226246

227247
@app.command()
228-
@coro
229248
async def attach(
230249
private_key: Optional[str] = typer.Option(
231250
sdk_settings.PRIVATE_KEY_STRING, help=help_strings.PRIVATE_KEY
@@ -234,42 +253,43 @@ async def attach(
234253
sdk_settings.PRIVATE_KEY_FILE, help=help_strings.PRIVATE_KEY_FILE
235254
),
236255
fqdn: str = typer.Argument(..., help=help_strings.CUSTOM_DOMAIN_NAME),
237-
item_hash: Optional[str] = typer.Option(None, help=help_strings.CUSTOM_DOMAIN_ITEM_HASH),
256+
item_hash: Optional[str] = typer.Option(
257+
None, help=help_strings.CUSTOM_DOMAIN_ITEM_HASH
258+
),
238259
):
239260
"""Attach resource to a Custom Domain."""
240261
account: AccountFromPrivateKey = _load_account(private_key, private_key_file)
241262

242-
await attach_resource(account, fqdn, item_hash)
263+
await attach_resource(account, Hostname(fqdn), item_hash)
243264
raise typer.Exit()
244265

266+
245267
@app.command()
246-
@coro
247268
async def detach(
248269
private_key: Optional[str] = typer.Option(
249270
sdk_settings.PRIVATE_KEY_STRING, help=help_strings.PRIVATE_KEY
250271
),
251272
private_key_file: Optional[Path] = typer.Option(
252273
sdk_settings.PRIVATE_KEY_FILE, help=help_strings.PRIVATE_KEY_FILE
253274
),
254-
fqdn: str = typer.Argument(..., help=help_strings.CUSTOM_DOMAIN_NAME)
275+
fqdn: str = typer.Argument(..., help=help_strings.CUSTOM_DOMAIN_NAME),
255276
):
256277
"""Unlink Custom Domain."""
257278
account: AccountFromPrivateKey = _load_account(private_key, private_key_file)
258279

259-
await detach_resource(account, fqdn)
280+
await detach_resource(account, Hostname(fqdn))
260281
raise typer.Exit()
261282

262283

263284
@app.command()
264-
@coro
265285
async def info(
266286
private_key: Optional[str] = typer.Option(
267287
sdk_settings.PRIVATE_KEY_STRING, help=help_strings.PRIVATE_KEY
268288
),
269289
private_key_file: Optional[Path] = typer.Option(
270290
sdk_settings.PRIVATE_KEY_FILE, help=help_strings.PRIVATE_KEY_FILE
271291
),
272-
fqdn: str = typer.Argument(..., help=help_strings.CUSTOM_DOMAIN_NAME)
292+
fqdn: str = typer.Argument(..., help=help_strings.CUSTOM_DOMAIN_NAME),
273293
):
274294
"""Show Custom Domain Details."""
275295
account: AccountFromPrivateKey = _load_account(private_key, private_key_file)
@@ -290,16 +310,13 @@ async def info(
290310
resource_type = TargetType(domain_info["info"]["type"])
291311
final_resource = "Unknown"
292312

293-
try:
294-
if resource_type == TargetType.IPFS:
295-
final_resource = ""
296-
elif resource_type == TargetType.PROGRAM:
297-
final_resource = domain_info["info"]["message_id"]
298-
if resource_type == TargetType.INSTANCE:
299-
ips = await domain_validator.get_ipv6_addresses(fqdn)
300-
final_resource = ",".join(ips)
301-
except Exception:
302-
pass
313+
if resource_type == TargetType.IPFS:
314+
final_resource = ""
315+
elif resource_type == TargetType.PROGRAM:
316+
final_resource = domain_info["info"]["message_id"]
317+
if resource_type == TargetType.INSTANCE:
318+
ips = await domain_validator.get_ipv6_addresses(Hostname(fqdn))
319+
final_resource = ",".join([str(ip) for ip in ips])
303320

304321
table.add_row(resource_type, domain_info["info"]["message_id"], final_resource)
305322

0 commit comments

Comments
 (0)