chore: code format

This commit is contained in:
Vlad Stan 2023-02-10 17:25:02 +02:00
parent 8678090e7b
commit ebada934b0
6 changed files with 32 additions and 29 deletions

View file

@ -61,13 +61,12 @@ async def get_relay(user_id: str, relay_id: str) -> Optional[NostrRelay]:
return NostrRelay.from_row(row) if row else None return NostrRelay.from_row(row) if row else None
async def get_relay_by_id(relay_id: str) -> Optional[NostrRelay]: async def get_relay_by_id(relay_id: str) -> Optional[NostrRelay]:
"""Note: it does not require `user_id`. Can read any relay. Use it with care.""" """Note: it does not require `user_id`. Can read any relay. Use it with care."""
row = await db.fetchone( row = await db.fetchone(
"""SELECT * FROM nostrrelay.relays WHERE id = ?""", """SELECT * FROM nostrrelay.relays WHERE id = ?""",
( (relay_id,),
relay_id,
),
) )
return NostrRelay.from_row(row) if row else None return NostrRelay.from_row(row) if row else None
@ -111,7 +110,7 @@ async def get_public_relay(relay_id: str) -> Optional[dict]:
"description": relay.description, "description": relay.description,
"pubkey": relay.pubkey, "pubkey": relay.pubkey,
"contact": relay.contact, "contact": relay.contact,
"config": RelayPublicSpec(**dict(relay.config)).dict(by_alias=True) "config": RelayPublicSpec(**dict(relay.config)).dict(by_alias=True),
} }

View file

@ -2,18 +2,18 @@ from bech32 import bech32_decode, convertbits
def normalize_public_key(pubkey: str) -> str: def normalize_public_key(pubkey: str) -> str:
if pubkey.startswith('npub1'): if pubkey.startswith("npub1"):
_, decoded_data = bech32_decode(pubkey) _, decoded_data = bech32_decode(pubkey)
if not decoded_data: if not decoded_data:
raise ValueError("Public Key is not valid npub") raise ValueError("Public Key is not valid npub")
decoded_data_bits = convertbits(decoded_data, 5, 8, False) decoded_data_bits = convertbits(decoded_data, 5, 8, False)
if not decoded_data_bits: if not decoded_data_bits:
raise ValueError("Public Key is not valid npub") raise ValueError("Public Key is not valid npub")
return bytes(decoded_data_bits).hex() return bytes(decoded_data_bits).hex()
#check if valid hex # check if valid hex
if len(pubkey) != 64: if len(pubkey) != 64:
raise ValueError("Public Key is not valid hex") raise ValueError("Public Key is not valid hex")
int(pubkey, 16) int(pubkey, 16)
return pubkey return pubkey

View file

@ -11,10 +11,13 @@ from secp256k1 import PublicKey
class Spec(BaseModel): class Spec(BaseModel):
class Config: class Config:
allow_population_by_field_name = True allow_population_by_field_name = True
class FilterSpec(Spec): class FilterSpec(Spec):
max_client_filters = Field(0, alias="maxClientFilters") max_client_filters = Field(0, alias="maxClientFilters")
limit_per_filter = Field(1000, alias="limitPerFilter") limit_per_filter = Field(1000, alias="limitPerFilter")
class EventSpec(Spec): class EventSpec(Spec):
max_events_per_second = Field(0, alias="maxEventsPerSecond") max_events_per_second = Field(0, alias="maxEventsPerSecond")
@ -28,7 +31,6 @@ class EventSpec(Spec):
created_at_minutes_future = Field(0, alias="createdAtMinutesFuture") created_at_minutes_future = Field(0, alias="createdAtMinutesFuture")
created_at_seconds_future = Field(0, alias="createdAtSecondsFuture") created_at_seconds_future = Field(0, alias="createdAtSecondsFuture")
@property @property
def created_at_in_past(self) -> int: def created_at_in_past(self) -> int:
return ( return (
@ -47,6 +49,7 @@ class EventSpec(Spec):
+ self.created_at_seconds_future + self.created_at_seconds_future
) )
class StorageSpec(Spec): class StorageSpec(Spec):
free_storage_value = Field(1, alias="freeStorageValue") free_storage_value = Field(1, alias="freeStorageValue")
free_storage_unit = Field("MB", alias="freeStorageUnit") free_storage_unit = Field("MB", alias="freeStorageUnit")
@ -59,6 +62,7 @@ class StorageSpec(Spec):
value *= 1024 value *= 1024
return value return value
class AuthorSpec(Spec): class AuthorSpec(Spec):
allowed_public_keys = Field([], alias="allowedPublicKeys") allowed_public_keys = Field([], alias="allowedPublicKeys")
blocked_public_keys = Field([], alias="blockedPublicKeys") blocked_public_keys = Field([], alias="blockedPublicKeys")
@ -78,15 +82,22 @@ class PaymentSpec(BaseModel):
storage_cost_value = Field(0, alias="storageCostValue") storage_cost_value = Field(0, alias="storageCostValue")
storage_cost_unit = Field("MB", alias="storageCostUnit") storage_cost_unit = Field("MB", alias="storageCostUnit")
class WalletSpec(Spec): class WalletSpec(Spec):
wallet = Field("") wallet = Field("")
class RelaySpec(FilterSpec, EventSpec, StorageSpec, AuthorSpec, PaymentSpec, WalletSpec):
class RelaySpec(
FilterSpec, EventSpec, StorageSpec, AuthorSpec, PaymentSpec, WalletSpec
):
pass pass
class RelayPublicSpec(FilterSpec, EventSpec, StorageSpec, PaymentSpec): class RelayPublicSpec(FilterSpec, EventSpec, StorageSpec, PaymentSpec):
pass pass
class NostrRelay(BaseModel): class NostrRelay(BaseModel):
id: str id: str
name: str name: str
@ -99,7 +110,7 @@ class NostrRelay(BaseModel):
@property @property
def is_free_to_join(self): def is_free_to_join(self):
return not self.config.is_paid_relay or self.config.cost_to_join == 0 return not self.config.is_paid_relay or self.config.cost_to_join == 0
@classmethod @classmethod
def from_row(cls, row: Row) -> "NostrRelay": def from_row(cls, row: Row) -> "NostrRelay":
@ -298,4 +309,4 @@ class NostrFilter(BaseModel):
class RelayJoin(BaseModel): class RelayJoin(BaseModel):
relay_id: str relay_id: str
pubkey: str pubkey: str

View file

@ -42,7 +42,7 @@
<q-card-section v-if="joinInvoice"> <q-card-section v-if="joinInvoice">
<q-expansion-item <q-expansion-item
group="join-invoice" group="join-invoice"
label="Join Invoice" label="Pay invoice to join relay"
:content-inset-level="0.5" :content-inset-level="0.5"
default-opened default-opened
> >

View file

@ -24,12 +24,12 @@ async def index(request: Request, user: User = Depends(check_user_exists)):
@nostrrelay_ext.get("/{relay_id}") @nostrrelay_ext.get("/{relay_id}")
async def nostrrelay(request: Request, relay_id: str): async def nostrrelay(request: Request, relay_id: str):
relay_public_data = await get_public_relay(relay_id) relay_public_data = await get_public_relay(relay_id)
if not relay_public_data: if not relay_public_data:
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, status_code=HTTPStatus.NOT_FOUND,
detail="Cannot find relay", detail="Cannot find relay",
) )
if request.headers.get("accept") == "application/nostr+json": if request.headers.get("accept") == "application/nostr+json":
return JSONResponse( return JSONResponse(

View file

@ -155,10 +155,8 @@ async def api_delete_relay(
@nostrrelay_ext.put("/api/v1/join") @nostrrelay_ext.put("/api/v1/join")
async def api_pay_to_join( async def api_pay_to_join(data: RelayJoin):
data: RelayJoin
):
try: try:
pubkey = normalize_public_key(data.pubkey) pubkey = normalize_public_key(data.pubkey)
relay = await get_relay_by_id(data.relay_id) relay = await get_relay_by_id(data.relay_id)
@ -179,13 +177,11 @@ async def api_pay_to_join(
"tag": "nostrrely", "tag": "nostrrely",
"action": "join", "action": "join",
"relay": relay.id, "relay": relay.id,
"pubkey": pubkey "pubkey": pubkey,
}, },
) )
print("### payment_request", payment_request) print("### payment_request", payment_request)
return { return {"invoice": payment_request}
"invoice": payment_request
}
except ValueError as ex: except ValueError as ex:
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST, status_code=HTTPStatus.BAD_REQUEST,
@ -199,6 +195,3 @@ async def api_pay_to_join(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR, status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
detail="Cannot create invoice for client to join", detail="Cannot create invoice for client to join",
) )