Skip to content

Commit

Permalink
rc4
Browse files Browse the repository at this point in the history
  • Loading branch information
dni committed Oct 17, 2024
1 parent 103f9cd commit 7afd9e0
Show file tree
Hide file tree
Showing 8 changed files with 502 additions and 517 deletions.
113 changes: 44 additions & 69 deletions crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from .helpers import normalize_identifier
from .models import (
Address,
AddressConfig,
AddressExtra,
AddressFilters,
CreateAddressData,
CreateDomainData,
Expand All @@ -23,165 +23,141 @@


async def get_domain(domain_id: str, wallet_id: str) -> Optional[Domain]:
row = await db.fetchone(
return await db.fetchone(
"SELECT * FROM nostrnip5.domains WHERE id = :id AND wallet = :wallet",
{"id": domain_id, "wallet": wallet_id},
Domain,
)
return Domain(**row) if row else None


async def get_domain_by_id(domain_id: str) -> Optional[Domain]:
row = await db.fetchone(
return await db.fetchone(
"SELECT * FROM nostrnip5.domains WHERE id = :id",
{"id": domain_id},
Domain,
)
return Domain(**row) if row else None


async def get_domain_public_data(domain_id: str) -> Optional[PublicDomain]:
row = await db.fetchone(
return await db.fetchone(
"SELECT id, currency, cost, domain FROM nostrnip5.domains WHERE id = :id",
{"id": domain_id},
PublicDomain,
)
return PublicDomain(**row) if row else None


async def get_domain_by_name(domain: str) -> Optional[Domain]:
row = await db.fetchone(
return await db.fetchone(
"SELECT * FROM nostrnip5.domains WHERE domain = :domain",
{"domain": domain.lower()},
Domain,
)
return Domain(**row) if row else None


async def get_domains(wallet_ids: Union[str, list[str]]) -> list[Domain]:
if isinstance(wallet_ids, str):
wallet_ids = [wallet_ids]

q = ",".join([f"'{w}'" for w in wallet_ids])
rows = await db.fetchall(f"SELECT * FROM nostrnip5.domains WHERE wallet IN ({q})")

return [Domain(**row) for row in rows]
return await db.fetchall(
f"SELECT * FROM nostrnip5.domains WHERE wallet IN ({q})",
model=Domain,
)


async def get_address(domain_id: str, address_id: str) -> Optional[Address]:
row = await db.fetchone(
return await db.fetchone(
"""
SELECT * FROM nostrnip5.addresses
WHERE domain_id = :domain_id AND id = :address_id
""",
{"domain_id": domain_id, "address_id": address_id},
Address,
)
return Address(**row) if row else None


async def get_active_address_by_local_part(
domain_id: str, local_part: str
) -> Optional[Address]:
row = await db.fetchone(
return await db.fetchone(
"""
SELECT * FROM nostrnip5.addresses
WHERE active = true AND domain_id = :domain_id AND local_part = :local_part
SELECT * FROM nostrnip5.addresses
WHERE active = true AND domain_id = :domain_id AND local_part = :local_part
""",
{"domain_id": domain_id, "local_part": normalize_identifier(local_part)},
Address,
)
return Address(**row) if row else None


async def get_addresses(domain_id: str) -> list[Address]:
rows = await db.fetchall(
return await db.fetchall(
"SELECT * FROM nostrnip5.addresses WHERE domain_id = :domain_id",
{"domain_id": domain_id},
Address,
)

return [Address(**row) for row in rows]


async def get_address_for_owner(
owner_id: str, domain_id: str, local_part: str
) -> Optional[Address]:
row = await db.fetchone(
return await db.fetchone(
"""
SELECT * FROM nostrnip5.addresses WHERE owner_id = :owner_id
AND domain_id = :domain_id AND local_part = :local_part
""",
{"owner_id": owner_id, "domain_id": domain_id, "local_part": local_part},
Address,
)

return Address(**row) if row else None


async def get_addresses_for_owner(owner_id: str) -> list[Address]:
rows = await db.fetchall(
return await db.fetchall(
"""
SELECT * FROM nostrnip5.addresses WHERE owner_id = :owner_id
ORDER BY time DESC
SELECT * FROM nostrnip5.addresses WHERE owner_id = :owner_id
ORDER BY time DESC
""",
{"owner_id": owner_id},
Address,
)

return [Address(**row) for row in rows]


async def get_all_addresses(wallet_ids: Union[str, list[str]]) -> list[Address]:
if isinstance(wallet_ids, str):
wallet_ids = [wallet_ids]

q = ",".join([f"'{w}'" for w in wallet_ids])
rows = await db.fetchall(
return await db.fetchall(
f"""
SELECT a.* FROM nostrnip5.addresses a
JOIN nostrnip5.domains d ON d.id = a.domain_id
WHERE d.wallet IN ({q})
"""
""",
model=Address,
)

return [Address(**row) for row in rows]


async def get_all_addresses_paginated(
wallet_ids: Union[str, list[str]],
filters: Optional[Filters[AddressFilters]] = None,
) -> Page[Address]:
if isinstance(wallet_ids, str):
wallet_ids = [wallet_ids]

q = ",".join([f"'{w}'" for w in wallet_ids])
query = f"""
return await db.fetch_page(
f"""
SELECT a.* FROM nostrnip5.addresses a
JOIN nostrnip5.domains d ON d.id = a.domain_id
WHERE d.wallet IN ({q})
"""

return await db.fetch_page(
query,
""",
filters=filters,
model=Address,
)


async def activate_domain_address(
domain_id: str, address_id: str, config: AddressConfig
) -> Address:
extra = json.dumps(config, default=lambda o: o.__dict__)
await db.execute(
"""
UPDATE nostrnip5.addresses
SET active = true, extra = :extra
WHERE domain_id = :domain_id AND id = :address_id
""",
{"domain_id": domain_id, "address_id": address_id, "extra": extra},
)

address = await get_address(domain_id, address_id)
assert address, "Newly updated address couldn't be retrieved"
return address


async def update_address(address: Address) -> Address:
years = address.config.years
years = address.extra.years
address.expires_at = datetime.now() + timedelta(days=365 * years)
await db.update("nostrnip5.addresses", address) # type: ignore
await db.update("nostrnip5.addresses", address)
return address


Expand Down Expand Up @@ -227,9 +203,8 @@ async def delete_address_by_id(domain_id, address_id):
async def create_address_internal(
data: CreateAddressData,
owner_id: Optional[str] = None,
config: Optional[AddressConfig] = None,
extra: Optional[AddressExtra] = None,
) -> Address:
extra = json.dumps(config or AddressConfig(), default=lambda o: o.__dict__)
expires_at = datetime.now() + timedelta(days=365 * data.years)
address = Address(
id=urlsafe_short_hash(),
Expand All @@ -238,11 +213,11 @@ async def create_address_internal(
local_part=normalize_identifier(data.local_part),
pubkey=data.pubkey,
active=False,
extra=extra,
extra=extra or AddressExtra(),
expires_at=expires_at,
time=datetime.now(),
)
await db.insert("nostrnip5.addresses", address) # type: ignore
await db.insert("nostrnip5.addresses", address)
return address


Expand Down Expand Up @@ -286,7 +261,7 @@ async def create_domain_internal(wallet_id: str, data: CreateDomainData) -> Doma
cost=data.cost,
domain=data.domain.lower(),
)
await db.insert("nostrnip5.domains", domain) # type: ignore
await db.insert("nostrnip5.domains", domain)
return domain


Expand All @@ -312,11 +287,11 @@ async def update_identifier_ranking(name: str, rank: int):


async def get_identifier_ranking(name: str) -> Optional[IdentifierRanking]:
row = await db.fetchone(
return await db.fetchone(
"SELECT * FROM nostrnip5.identifiers_rankings WHERE name = :name",
{"name": normalize_identifier(name)},
IdentifierRanking,
)
return IdentifierRanking(**row) if row else None


async def delete_inferior_ranking(name: str, rank: int):
Expand All @@ -330,12 +305,12 @@ async def delete_inferior_ranking(name: str, rank: int):


async def create_settings(settings: Nip5Settings):
await db.insert("nostrnip5.settings", settings) # type: ignore
await db.insert("nostrnip5.settings", settings)


async def get_settings(owner_id: str) -> Optional[Nip5Settings]:
row = await db.fetchone(
return await db.fetchone(
"SELECT * FROM nostrnip5.settings WHERE owner_id = :owner_id",
{"owner_id": owner_id},
Nip5Settings,
)
return Nip5Settings(**row) if row else None
13 changes: 3 additions & 10 deletions migrations.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,15 +88,7 @@ async def m006_make_amount_type_real(db: Database):
"ALTER TABLE nostrnip5.domains ADD COLUMN cost REAL NOT NULL DEFAULT 0"
)

rows = await db.fetchall(
"SELECT id, amount FROM nostrnip5.domains",
)
for row in rows:
await db.execute(
"UPDATE nostrnip5.domains SET cost = :amount WHERE id = :id",
{"amount": row["amount"], "id": row["id"]},
)

await db.execute("UPDATE nostrnip5.domains SET cost = amount")
await db.execute("ALTER TABLE nostrnip5.domains DROP COLUMN amount")


Expand All @@ -114,7 +106,8 @@ async def m007_add_cost_extra_column_to_addresses(db: Database):

async def m007_migrate_settings(db: Database):

settings = await db.fetchall("SELECT * FROM nostrnip5.settings")
result = await db.execute("SELECT * FROM nostrnip5.settings")
settings = await result.mappings().all()
await db.execute("ALTER TABLE nostrnip5.settings RENAME TO settings_old")
await db.execute(
"""
Expand Down
25 changes: 7 additions & 18 deletions models.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from datetime import datetime
from typing import Optional

from lnbits.db import FilterModel, FromRowModel
from lnbits.db import FilterModel
from lnbits.utils.exchange_rates import fiat_amount_as_satoshis
from pydantic import BaseModel

Expand Down Expand Up @@ -299,44 +299,33 @@ class LnAddressConfig(BaseModel):
pay_link_id: Optional[str] = ""


class AddressConfig(BaseModel):
class AddressExtra(BaseModel):
currency: Optional[str] = None
price: Optional[float] = None
price_in_sats: Optional[float] = None
payment_hash: Optional[str] = None
reimburse_payment_hash: Optional[str] = None
activated_by_owner: bool = False
years: int = 1
promo_code: Optional[str] = None
referer: Optional[str] = None
activated_by_owner: bool = False
years: int = 1
max_years: int = 1
relays: list[str] = []
ln_address: LnAddressConfig = LnAddressConfig(wallet="")


class Address(FromRowModel):
class Address(BaseModel):
id: str
owner_id: Optional[str] = None
domain_id: str
local_part: str
pubkey: str
active: bool
time: datetime
expires_at: datetime
extra: str
pubkey: Optional[str] = None
reimburse_amount: int = 0
promo_code_status: PromoCodeStatus = PromoCodeStatus()

def update_extra(self, config: AddressConfig) -> None:
self.extra = json.dumps(config.dict())

@property
def config(self) -> AddressConfig:
return AddressConfig(**json.loads(self.extra or ""))

@property
def has_pubkey(self):
return self.pubkey != ""
extra: AddressExtra = AddressExtra()


class AddressStatus(BaseModel):
Expand Down
Loading

0 comments on commit 7afd9e0

Please sign in to comment.