mirror of
https://github.com/lnbits/lnbits.git
synced 2025-09-29 05:12:39 +02:00
Revert "chore: apply black to all .py files"
This reverts commit 83b7779972
.
This commit is contained in:
committed by
benarc
parent
83b7779972
commit
efec7cb8f0
2
conv.py
2
conv.py
@@ -1,5 +1,5 @@
|
|||||||
## Python script to migrate an LNbits SQLite DB to Postgres
|
## Python script to migrate an LNbits SQLite DB to Postgres
|
||||||
## All credits to @Fritz446 for the awesome work
|
## All credits to @Fritz446 for the awesome work
|
||||||
|
|
||||||
## pip install psycopg2 OR psycopg2-binary
|
## pip install psycopg2 OR psycopg2-binary
|
||||||
|
|
||||||
|
@@ -278,9 +278,7 @@ async def get_payments(
|
|||||||
return [Payment.from_row(row) for row in rows]
|
return [Payment.from_row(row) for row in rows]
|
||||||
|
|
||||||
|
|
||||||
async def delete_expired_invoices(
|
async def delete_expired_invoices(conn: Optional[Connection] = None,) -> None:
|
||||||
conn: Optional[Connection] = None,
|
|
||||||
) -> None:
|
|
||||||
# first we delete all invoices older than one month
|
# first we delete all invoices older than one month
|
||||||
await (conn or db).execute(
|
await (conn or db).execute(
|
||||||
f"""
|
f"""
|
||||||
|
@@ -316,7 +316,8 @@ async def check_invoice_status(
|
|||||||
if not payment.pending:
|
if not payment.pending:
|
||||||
return status
|
return status
|
||||||
if payment.is_out and status.failed:
|
if payment.is_out and status.failed:
|
||||||
print(f" - deleting outgoing failed payment {payment.checking_id}: {status}")
|
print(
|
||||||
|
f" - deleting outgoing failed payment {payment.checking_id}: {status}")
|
||||||
await payment.delete()
|
await payment.delete()
|
||||||
elif not status.pending:
|
elif not status.pending:
|
||||||
print(
|
print(
|
||||||
|
@@ -15,7 +15,6 @@ from ..tasks import api_invoice_listeners
|
|||||||
@core_app.get("/.well-known/lnurlp/{username}")
|
@core_app.get("/.well-known/lnurlp/{username}")
|
||||||
async def lnaddress(username: str, request: Request):
|
async def lnaddress(username: str, request: Request):
|
||||||
from lnbits.extensions.lnaddress.lnurl import lnurl_response
|
from lnbits.extensions.lnaddress.lnurl import lnurl_response
|
||||||
|
|
||||||
domain = request.client.host
|
domain = request.client.host
|
||||||
return await lnurl_response(username, domain)
|
return await lnurl_response(username, domain)
|
||||||
|
|
||||||
|
@@ -76,7 +76,7 @@ class Track(BaseModel):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
url = request.url_for("livestream.track_redirect_download", track_id=self.id)
|
url = request.url_for("livestream.track_redirect_download", track_id=self.id)
|
||||||
url_with_query = f"{url}?p={payment_hash}"
|
url_with_query = f"{url}?p={payment_hash}"
|
||||||
|
|
||||||
return UrlAction(
|
return UrlAction(
|
||||||
url=url_with_query,
|
url=url_with_query,
|
||||||
|
@@ -8,8 +8,10 @@ from lnbits.tasks import catch_everything_and_restart
|
|||||||
|
|
||||||
db = Database("ext_lnaddress")
|
db = Database("ext_lnaddress")
|
||||||
|
|
||||||
lnaddress_ext: APIRouter = APIRouter(prefix="/lnaddress", tags=["lnaddress"])
|
lnaddress_ext: APIRouter = APIRouter(
|
||||||
|
prefix="/lnaddress",
|
||||||
|
tags=["lnaddress"]
|
||||||
|
)
|
||||||
|
|
||||||
def lnaddress_renderer():
|
def lnaddress_renderer():
|
||||||
return template_renderer(["lnbits/extensions/lnaddress/templates"])
|
return template_renderer(["lnbits/extensions/lnaddress/templates"])
|
||||||
|
@@ -2,7 +2,9 @@ from lnbits.extensions.lnaddress.models import Domains
|
|||||||
import httpx, json
|
import httpx, json
|
||||||
|
|
||||||
|
|
||||||
async def cloudflare_create_record(domain: Domains, ip: str):
|
async def cloudflare_create_record(
|
||||||
|
domain: Domains, ip: str
|
||||||
|
):
|
||||||
url = (
|
url = (
|
||||||
"https://api.cloudflare.com/client/v4/zones/"
|
"https://api.cloudflare.com/client/v4/zones/"
|
||||||
+ domain.cf_zone_id
|
+ domain.cf_zone_id
|
||||||
|
@@ -7,7 +7,9 @@ from . import db
|
|||||||
from .models import Addresses, CreateAddress, CreateDomain, Domains
|
from .models import Addresses, CreateAddress, CreateDomain, Domains
|
||||||
|
|
||||||
|
|
||||||
async def create_domain(data: CreateDomain) -> Domains:
|
async def create_domain(
|
||||||
|
data: CreateDomain
|
||||||
|
) -> Domains:
|
||||||
domain_id = urlsafe_short_hash()
|
domain_id = urlsafe_short_hash()
|
||||||
await db.execute(
|
await db.execute(
|
||||||
"""
|
"""
|
||||||
@@ -35,20 +37,21 @@ async def update_domain(domain_id: str, **kwargs) -> Domains:
|
|||||||
await db.execute(
|
await db.execute(
|
||||||
f"UPDATE lnaddress.domain SET {q} WHERE id = ?", (*kwargs.values(), domain_id)
|
f"UPDATE lnaddress.domain SET {q} WHERE id = ?", (*kwargs.values(), domain_id)
|
||||||
)
|
)
|
||||||
row = await db.fetchone("SELECT * FROM lnaddress.domain WHERE id = ?", (domain_id,))
|
row = await db.fetchone(
|
||||||
|
"SELECT * FROM lnaddress.domain WHERE id = ?", (domain_id,)
|
||||||
|
)
|
||||||
assert row, "Newly updated domain couldn't be retrieved"
|
assert row, "Newly updated domain couldn't be retrieved"
|
||||||
return Domains(**row)
|
return Domains(**row)
|
||||||
|
|
||||||
|
|
||||||
async def delete_domain(domain_id: str) -> None:
|
async def delete_domain(domain_id: str) -> None:
|
||||||
await db.execute("DELETE FROM lnaddress.domain WHERE id = ?", (domain_id,))
|
await db.execute("DELETE FROM lnaddress.domain WHERE id = ?", (domain_id,))
|
||||||
|
|
||||||
|
|
||||||
async def get_domain(domain_id: str) -> Optional[Domains]:
|
async def get_domain(domain_id: str) -> Optional[Domains]:
|
||||||
row = await db.fetchone("SELECT * FROM lnaddress.domain WHERE id = ?", (domain_id,))
|
row = await db.fetchone(
|
||||||
|
"SELECT * FROM lnaddress.domain WHERE id = ?", (domain_id,)
|
||||||
|
)
|
||||||
return Domains(**row) if row else None
|
return Domains(**row) if row else None
|
||||||
|
|
||||||
|
|
||||||
async def get_domains(wallet_ids: Union[str, List[str]]) -> List[Domains]:
|
async def get_domains(wallet_ids: Union[str, List[str]]) -> List[Domains]:
|
||||||
if isinstance(wallet_ids, str):
|
if isinstance(wallet_ids, str):
|
||||||
wallet_ids = [wallet_ids]
|
wallet_ids = [wallet_ids]
|
||||||
@@ -60,12 +63,12 @@ async def get_domains(wallet_ids: Union[str, List[str]]) -> List[Domains]:
|
|||||||
|
|
||||||
return [Domains(**row) for row in rows]
|
return [Domains(**row) for row in rows]
|
||||||
|
|
||||||
|
|
||||||
## ADRESSES
|
## ADRESSES
|
||||||
|
|
||||||
|
|
||||||
async def create_address(
|
async def create_address(
|
||||||
payment_hash: str, wallet: str, data: CreateAddress
|
payment_hash: str,
|
||||||
|
wallet: str,
|
||||||
|
data: CreateAddress
|
||||||
) -> Addresses:
|
) -> Addresses:
|
||||||
await db.execute(
|
await db.execute(
|
||||||
"""
|
"""
|
||||||
@@ -90,7 +93,6 @@ async def create_address(
|
|||||||
assert new_address, "Newly created address couldn't be retrieved"
|
assert new_address, "Newly created address couldn't be retrieved"
|
||||||
return new_address
|
return new_address
|
||||||
|
|
||||||
|
|
||||||
async def get_address(address_id: str) -> Optional[Addresses]:
|
async def get_address(address_id: str) -> Optional[Addresses]:
|
||||||
row = await db.fetchone(
|
row = await db.fetchone(
|
||||||
"SELECT a.* FROM lnaddress.address AS a INNER JOIN lnaddress.domain AS d ON a.id = ? AND a.domain = d.id",
|
"SELECT a.* FROM lnaddress.address AS a INNER JOIN lnaddress.domain AS d ON a.id = ? AND a.domain = d.id",
|
||||||
@@ -98,24 +100,18 @@ async def get_address(address_id: str) -> Optional[Addresses]:
|
|||||||
)
|
)
|
||||||
return Addresses(**row) if row else None
|
return Addresses(**row) if row else None
|
||||||
|
|
||||||
|
|
||||||
async def get_address_by_username(username: str, domain: str) -> Optional[Addresses]:
|
async def get_address_by_username(username: str, domain: str) -> Optional[Addresses]:
|
||||||
row = await db.fetchone(
|
row = await db.fetchone(
|
||||||
"SELECT a.* FROM lnaddress.address AS a INNER JOIN lnaddress.domain AS d ON a.username = ? AND d.domain = ?",
|
"SELECT a.* FROM lnaddress.address AS a INNER JOIN lnaddress.domain AS d ON a.username = ? AND d.domain = ?",
|
||||||
# "SELECT * FROM lnaddress.address WHERE username = ? AND domain = ?",
|
# "SELECT * FROM lnaddress.address WHERE username = ? AND domain = ?",
|
||||||
(
|
(username, domain,),
|
||||||
username,
|
|
||||||
domain,
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
print("ADD", row)
|
print("ADD", row)
|
||||||
return Addresses(**row) if row else None
|
return Addresses(**row) if row else None
|
||||||
|
|
||||||
|
|
||||||
async def delete_address(address_id: str) -> None:
|
async def delete_address(address_id: str) -> None:
|
||||||
await db.execute("DELETE FROM lnaddress.address WHERE id = ?", (address_id,))
|
await db.execute("DELETE FROM lnaddress.address WHERE id = ?", (address_id,))
|
||||||
|
|
||||||
|
|
||||||
async def get_addresses(wallet_ids: Union[str, List[str]]) -> List[Addresses]:
|
async def get_addresses(wallet_ids: Union[str, List[str]]) -> List[Addresses]:
|
||||||
if isinstance(wallet_ids, str):
|
if isinstance(wallet_ids, str):
|
||||||
wallet_ids = [wallet_ids]
|
wallet_ids = [wallet_ids]
|
||||||
@@ -128,7 +124,6 @@ async def get_addresses(wallet_ids: Union[str, List[str]]) -> List[Addresses]:
|
|||||||
print([Addresses(**row) for row in rows])
|
print([Addresses(**row) for row in rows])
|
||||||
return [Addresses(**row) for row in rows]
|
return [Addresses(**row) for row in rows]
|
||||||
|
|
||||||
|
|
||||||
async def set_address_paid(payment_hash: str) -> Addresses:
|
async def set_address_paid(payment_hash: str) -> Addresses:
|
||||||
_address = await get_address(payment_hash)
|
_address = await get_address(payment_hash)
|
||||||
address = _address._asdict()
|
address = _address._asdict()
|
||||||
@@ -147,7 +142,6 @@ async def set_address_paid(payment_hash: str) -> Addresses:
|
|||||||
assert new_address, "Newly paid address couldn't be retrieved"
|
assert new_address, "Newly paid address couldn't be retrieved"
|
||||||
return new_address
|
return new_address
|
||||||
|
|
||||||
|
|
||||||
async def set_address_renewed(address_id: str, duration: int):
|
async def set_address_renewed(address_id: str, duration: int):
|
||||||
_address = await get_address(address_id)
|
_address = await get_address(address_id)
|
||||||
address = _address._asdict()
|
address = _address._asdict()
|
||||||
@@ -159,10 +153,7 @@ async def set_address_renewed(address_id: str, duration: int):
|
|||||||
SET duration = ?
|
SET duration = ?
|
||||||
WHERE id = ?
|
WHERE id = ?
|
||||||
""",
|
""",
|
||||||
(
|
(extend_duration, address_id,),
|
||||||
extend_duration,
|
|
||||||
address_id,
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
updated_address = await get_address(address_id)
|
updated_address = await get_address(address_id)
|
||||||
assert updated_address, "Renewed address couldn't be retrieved"
|
assert updated_address, "Renewed address couldn't be retrieved"
|
||||||
@@ -170,21 +161,17 @@ async def set_address_renewed(address_id: str, duration: int):
|
|||||||
|
|
||||||
|
|
||||||
async def check_address_available(username: str, domain: str):
|
async def check_address_available(username: str, domain: str):
|
||||||
(row,) = await db.fetchone(
|
row, = await db.fetchone(
|
||||||
"SELECT COUNT(username) FROM lnaddress.address WHERE username = ? AND domain = ?",
|
"SELECT COUNT(username) FROM lnaddress.address WHERE username = ? AND domain = ?",
|
||||||
(
|
(username, domain,),
|
||||||
username,
|
|
||||||
domain,
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
return row
|
return row
|
||||||
|
|
||||||
|
|
||||||
async def purge_addresses(domain_id: str):
|
async def purge_addresses(domain_id: str):
|
||||||
|
|
||||||
rows = await db.fetchall(
|
rows = await db.fetchall(
|
||||||
"SELECT * FROM lnaddress.address WHERE domain = ?",
|
"SELECT * FROM lnaddress.address WHERE domain = ?",
|
||||||
(domain_id,),
|
(domain_id, ),
|
||||||
)
|
)
|
||||||
|
|
||||||
now = datetime.now().timestamp()
|
now = datetime.now().timestamp()
|
||||||
@@ -194,10 +181,8 @@ async def purge_addresses(domain_id: str):
|
|||||||
|
|
||||||
start = datetime.fromtimestamp(r["time"])
|
start = datetime.fromtimestamp(r["time"])
|
||||||
paid = r["paid"]
|
paid = r["paid"]
|
||||||
pay_expire = now > start.timestamp() + 86400 # if payment wasn't made in 1 day
|
pay_expire = now > start.timestamp() + 86400 #if payment wasn't made in 1 day
|
||||||
expired = (
|
expired = now > (start + timedelta(days = r["duration"] + 1)).timestamp() #give user 1 day to topup is address
|
||||||
now > (start + timedelta(days=r["duration"] + 1)).timestamp()
|
|
||||||
) # give user 1 day to topup is address
|
|
||||||
|
|
||||||
if not paid and pay_expire:
|
if not paid and pay_expire:
|
||||||
print("DELETE UNP_PAY_EXP", r["username"])
|
print("DELETE UNP_PAY_EXP", r["username"])
|
||||||
|
@@ -23,15 +23,13 @@ async def lnurl_response(username: str, domain: str, request: Request):
|
|||||||
## CHECK IF USER IS STILL VALID/PAYING
|
## CHECK IF USER IS STILL VALID/PAYING
|
||||||
now = datetime.now().timestamp()
|
now = datetime.now().timestamp()
|
||||||
start = datetime.fromtimestamp(address.time)
|
start = datetime.fromtimestamp(address.time)
|
||||||
expiration = (start + timedelta(days=address.duration)).timestamp()
|
expiration = (start + timedelta(days = address.duration)).timestamp()
|
||||||
|
|
||||||
if now > expiration:
|
if now > expiration:
|
||||||
return LnurlErrorResponse(reason="Address has expired.").dict()
|
return LnurlErrorResponse(reason="Address has expired.").dict()
|
||||||
|
|
||||||
resp = LnurlPayResponse(
|
resp = LnurlPayResponse(
|
||||||
callback=request.url_for(
|
callback=request.url_for("lnaddress.lnurl_callback", address_id=address.id, _external=True),
|
||||||
"lnaddress.lnurl_callback", address_id=address.id, _external=True
|
|
||||||
),
|
|
||||||
min_sendable=1000,
|
min_sendable=1000,
|
||||||
max_sendable=1000000000,
|
max_sendable=1000000000,
|
||||||
metadata=await address.lnurlpay_metadata(),
|
metadata=await address.lnurlpay_metadata(),
|
||||||
@@ -39,13 +37,14 @@ async def lnurl_response(username: str, domain: str, request: Request):
|
|||||||
|
|
||||||
return resp.dict()
|
return resp.dict()
|
||||||
|
|
||||||
|
|
||||||
@lnaddress_ext.get("/lnurl/cb/{address_id}", name="lnaddress.lnurl_callback")
|
@lnaddress_ext.get("/lnurl/cb/{address_id}", name="lnaddress.lnurl_callback")
|
||||||
async def lnurl_callback(address_id, amount: int = Query(...)):
|
async def lnurl_callback(address_id, amount: int = Query(...)):
|
||||||
address = await get_address(address_id)
|
address = await get_address(address_id)
|
||||||
|
|
||||||
if not address:
|
if not address:
|
||||||
return LnurlErrorResponse(reason=f"Address not found").dict()
|
return LnurlErrorResponse(
|
||||||
|
reason=f"Address not found"
|
||||||
|
).dict()
|
||||||
|
|
||||||
amount_received = amount
|
amount_received = amount
|
||||||
# min = 1000
|
# min = 1000
|
||||||
@@ -65,26 +64,17 @@ async def lnurl_callback(address_id, amount: int = Query(...)):
|
|||||||
|
|
||||||
domain = await get_domain(address.domain)
|
domain = await get_domain(address.domain)
|
||||||
|
|
||||||
base_url = (
|
base_url = address.wallet_endpoint[:-1] if address.wallet_endpoint.endswith('/') else address.wallet_endpoint
|
||||||
address.wallet_endpoint[:-1]
|
|
||||||
if address.wallet_endpoint.endswith("/")
|
|
||||||
else address.wallet_endpoint
|
|
||||||
)
|
|
||||||
|
|
||||||
async with httpx.AsyncClient() as client:
|
async with httpx.AsyncClient() as client:
|
||||||
try:
|
try:
|
||||||
call = await client.post(
|
call = await client.post(
|
||||||
base_url + "/api/v1/payments",
|
base_url + "/api/v1/payments",
|
||||||
headers={
|
headers={"X-Api-Key": address.wallet_key, "Content-Type": "application/json"},
|
||||||
"X-Api-Key": address.wallet_key,
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
},
|
|
||||||
json={
|
json={
|
||||||
"out": False,
|
"out": False,
|
||||||
"amount": int(amount_received / 1000),
|
"amount": int(amount_received / 1000),
|
||||||
"description_hash": hashlib.sha256(
|
"description_hash": hashlib.sha256((await address.lnurlpay_metadata()).encode("utf-8")).hexdigest(),
|
||||||
(await address.lnurlpay_metadata()).encode("utf-8")
|
|
||||||
).hexdigest(),
|
|
||||||
"extra": {"tag": f"Payment to {address.username}@{domain.domain}"},
|
"extra": {"tag": f"Payment to {address.username}@{domain.domain}"},
|
||||||
},
|
},
|
||||||
timeout=40,
|
timeout=40,
|
||||||
|
@@ -16,7 +16,6 @@ async def m001_initial(db):
|
|||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
async def m002_addresses(db):
|
async def m002_addresses(db):
|
||||||
await db.execute(
|
await db.execute(
|
||||||
"""
|
"""
|
||||||
@@ -38,6 +37,5 @@ async def m002_addresses(db):
|
|||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
# async def m003_create_unique_indexes(db):
|
# async def m003_create_unique_indexes(db):
|
||||||
# await db.execute("CREATE UNIQUE INDEX IF NOT EXISTS address_at_domain ON lnaddress.address (domain, username);")
|
# await db.execute("CREATE UNIQUE INDEX IF NOT EXISTS address_at_domain ON lnaddress.address (domain, username);")
|
||||||
|
@@ -7,14 +7,13 @@ from pydantic.main import BaseModel # type: ignore
|
|||||||
|
|
||||||
|
|
||||||
class CreateDomain(BaseModel):
|
class CreateDomain(BaseModel):
|
||||||
wallet: str = Query(...)
|
wallet: str = Query(...)
|
||||||
domain: str = Query(...)
|
domain: str = Query(...)
|
||||||
cf_token: str = Query(...)
|
cf_token: str = Query(...)
|
||||||
cf_zone_id: str = Query(...)
|
cf_zone_id: str = Query(...)
|
||||||
webhook: str = Query(None)
|
webhook: str = Query(None)
|
||||||
cost: int = Query(..., ge=0)
|
cost: int = Query(..., ge=0)
|
||||||
|
|
||||||
|
|
||||||
class Domains(BaseModel):
|
class Domains(BaseModel):
|
||||||
id: str
|
id: str
|
||||||
wallet: str
|
wallet: str
|
||||||
@@ -25,7 +24,6 @@ class Domains(BaseModel):
|
|||||||
cost: int
|
cost: int
|
||||||
time: int
|
time: int
|
||||||
|
|
||||||
|
|
||||||
class CreateAddress(BaseModel):
|
class CreateAddress(BaseModel):
|
||||||
domain: str = Query(...)
|
domain: str = Query(...)
|
||||||
username: str = Query(...)
|
username: str = Query(...)
|
||||||
@@ -35,7 +33,6 @@ class CreateAddress(BaseModel):
|
|||||||
sats: int = Query(..., ge=0)
|
sats: int = Query(..., ge=0)
|
||||||
duration: int = Query(..., ge=1)
|
duration: int = Query(..., ge=1)
|
||||||
|
|
||||||
|
|
||||||
class Addresses(BaseModel):
|
class Addresses(BaseModel):
|
||||||
id: str
|
id: str
|
||||||
wallet: str
|
wallet: str
|
||||||
|
@@ -52,9 +52,7 @@ async def on_invoice_paid(payment: Payment) -> None:
|
|||||||
elif "renew lnaddress" == payment.extra.get("tag"):
|
elif "renew lnaddress" == payment.extra.get("tag"):
|
||||||
|
|
||||||
await payment.set_pending(False)
|
await payment.set_pending(False)
|
||||||
await set_address_renewed(
|
await set_address_renewed(address_id=payment.extra["id"], duration=payment.extra["duration"])
|
||||||
address_id=payment.extra["id"], duration=payment.extra["duration"]
|
|
||||||
)
|
|
||||||
await call_webhook_on_paid(payment.payment_hash)
|
await call_webhook_on_paid(payment.payment_hash)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
@@ -18,10 +18,7 @@ templates = Jinja2Templates(directory="templates")
|
|||||||
|
|
||||||
@lnaddress_ext.get("/", response_class=HTMLResponse)
|
@lnaddress_ext.get("/", response_class=HTMLResponse)
|
||||||
async def index(request: Request, user: User = Depends(check_user_exists)):
|
async def index(request: Request, user: User = Depends(check_user_exists)):
|
||||||
return lnaddress_renderer().TemplateResponse(
|
return lnaddress_renderer().TemplateResponse("lnaddress/index.html", {"request": request, "user": user.dict()})
|
||||||
"lnaddress/index.html", {"request": request, "user": user.dict()}
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@lnaddress_ext.get("/{domain_id}")
|
@lnaddress_ext.get("/{domain_id}")
|
||||||
async def display(domain_id, request: Request):
|
async def display(domain_id, request: Request):
|
||||||
@@ -36,12 +33,11 @@ async def display(domain_id, request: Request):
|
|||||||
wallet = await get_wallet(domain.wallet)
|
wallet = await get_wallet(domain.wallet)
|
||||||
|
|
||||||
return lnaddress_renderer().TemplateResponse(
|
return lnaddress_renderer().TemplateResponse(
|
||||||
"lnaddress/display.html",
|
"lnaddress/display.html",{
|
||||||
{
|
|
||||||
"request": request,
|
"request": request,
|
||||||
"domain_id": domain.id,
|
"domain_id":domain.id,
|
||||||
"domain_domain": domain.domain,
|
"domain_domain": domain.domain,
|
||||||
"domain_cost": domain.cost,
|
"domain_cost": domain.cost,
|
||||||
"domain_wallet_inkey": wallet.inkey,
|
"domain_wallet_inkey": wallet.inkey
|
||||||
},
|
}
|
||||||
)
|
)
|
||||||
|
@@ -43,12 +43,7 @@ async def api_domains(
|
|||||||
|
|
||||||
@lnaddress_ext.post("/api/v1/domains")
|
@lnaddress_ext.post("/api/v1/domains")
|
||||||
@lnaddress_ext.put("/api/v1/domains/{domain_id}")
|
@lnaddress_ext.put("/api/v1/domains/{domain_id}")
|
||||||
async def api_domain_create(
|
async def api_domain_create(request: Request,data: CreateDomain, domain_id=None, g: WalletTypeInfo = Depends(get_key_type)):
|
||||||
request: Request,
|
|
||||||
data: CreateDomain,
|
|
||||||
domain_id=None,
|
|
||||||
g: WalletTypeInfo = Depends(get_key_type),
|
|
||||||
):
|
|
||||||
if domain_id:
|
if domain_id:
|
||||||
domain = await get_domain(domain_id)
|
domain = await get_domain(domain_id)
|
||||||
|
|
||||||
@@ -69,7 +64,7 @@ async def api_domain_create(
|
|||||||
|
|
||||||
domain = await create_domain(data=data)
|
domain = await create_domain(data=data)
|
||||||
root_url = urlparse(request.url.path).netloc
|
root_url = urlparse(request.url.path).netloc
|
||||||
# root_url = request.url_root
|
#root_url = request.url_root
|
||||||
|
|
||||||
cf_response = await cloudflare_create_record(
|
cf_response = await cloudflare_create_record(
|
||||||
domain=domain,
|
domain=domain,
|
||||||
@@ -80,36 +75,32 @@ async def api_domain_create(
|
|||||||
await delete_domain(domain.id)
|
await delete_domain(domain.id)
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=HTTPStatus.BAD_REQUEST,
|
status_code=HTTPStatus.BAD_REQUEST,
|
||||||
detail="Problem with cloudflare: "
|
detail="Problem with cloudflare: " + cf_response["errors"][0]["message"],
|
||||||
+ cf_response["errors"][0]["message"],
|
|
||||||
)
|
)
|
||||||
|
|
||||||
return domain.dict()
|
return domain.dict()
|
||||||
|
|
||||||
|
|
||||||
@lnaddress_ext.delete("/api/v1/domains/{domain_id}")
|
@lnaddress_ext.delete("/api/v1/domains/{domain_id}")
|
||||||
async def api_domain_delete(domain_id, g: WalletTypeInfo = Depends(get_key_type)):
|
async def api_domain_delete(domain_id, g: WalletTypeInfo = Depends(get_key_type)):
|
||||||
domain = await get_domain(domain_id)
|
domain = await get_domain(domain_id)
|
||||||
|
|
||||||
if not domain:
|
if not domain:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=HTTPStatus.NOT_FOUND,
|
status_code=HTTPStatus.NOT_FOUND,
|
||||||
detail="Domain does not exist.",
|
detail="Domain does not exist.",
|
||||||
)
|
)
|
||||||
|
|
||||||
if domain.wallet != g.wallet.id:
|
if domain.wallet != g.wallet.id:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=HTTPStatus.FORBIDDEN,
|
status_code=HTTPStatus.FORBIDDEN,
|
||||||
detail="Not your domain",
|
detail="Not your domain",
|
||||||
)
|
)
|
||||||
|
|
||||||
await delete_domain(domain_id)
|
await delete_domain(domain_id)
|
||||||
raise HTTPException(status_code=HTTPStatus.NO_CONTENT)
|
raise HTTPException(status_code=HTTPStatus.NO_CONTENT)
|
||||||
|
|
||||||
|
|
||||||
# ADDRESSES
|
# ADDRESSES
|
||||||
|
|
||||||
|
|
||||||
@lnaddress_ext.get("/api/v1/addresses")
|
@lnaddress_ext.get("/api/v1/addresses")
|
||||||
async def api_addresses(
|
async def api_addresses(
|
||||||
g: WalletTypeInfo = Depends(get_key_type),
|
g: WalletTypeInfo = Depends(get_key_type),
|
||||||
@@ -122,7 +113,6 @@ async def api_addresses(
|
|||||||
|
|
||||||
return [address.dict() for address in await get_addresses(wallet_ids)]
|
return [address.dict() for address in await get_addresses(wallet_ids)]
|
||||||
|
|
||||||
|
|
||||||
@lnaddress_ext.get("/api/v1/address/{domain}/{username}/{wallet_key}")
|
@lnaddress_ext.get("/api/v1/address/{domain}/{username}/{wallet_key}")
|
||||||
async def api_get_user_info(username, wallet_key, domain):
|
async def api_get_user_info(username, wallet_key, domain):
|
||||||
address = await get_address_by_username(username, domain)
|
address = await get_address_by_username(username, domain)
|
||||||
@@ -135,43 +125,39 @@ async def api_get_user_info(username, wallet_key, domain):
|
|||||||
|
|
||||||
if address.wallet_key != wallet_key:
|
if address.wallet_key != wallet_key:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=HTTPStatus.FORBIDDEN,
|
status_code=HTTPStatus.FORBIDDEN,
|
||||||
detail="Incorrect user/wallet information.",
|
detail="Incorrect user/wallet information.",
|
||||||
)
|
)
|
||||||
|
|
||||||
return address.dict()
|
return address.dict()
|
||||||
|
|
||||||
|
|
||||||
@lnaddress_ext.get("/api/v1/address/availabity/{domain_id}/{username}")
|
@lnaddress_ext.get("/api/v1/address/availabity/{domain_id}/{username}")
|
||||||
async def api_check_available_username(domain_id, username):
|
async def api_check_available_username(domain_id, username):
|
||||||
used_username = await check_address_available(username, domain_id)
|
used_username = await check_address_available(username, domain_id)
|
||||||
|
|
||||||
return used_username
|
return used_username
|
||||||
|
|
||||||
|
|
||||||
@lnaddress_ext.post("/api/v1/address/{domain_id}")
|
@lnaddress_ext.post("/api/v1/address/{domain_id}")
|
||||||
@lnaddress_ext.put("/api/v1/address/{domain_id}/{user}/{wallet_key}")
|
@lnaddress_ext.put("/api/v1/address/{domain_id}/{user}/{wallet_key}")
|
||||||
async def api_lnaddress_make_address(
|
async def api_lnaddress_make_address(domain_id, data: CreateAddress, user=None, wallet_key=None):
|
||||||
domain_id, data: CreateAddress, user=None, wallet_key=None
|
|
||||||
):
|
|
||||||
domain = await get_domain(domain_id)
|
domain = await get_domain(domain_id)
|
||||||
|
|
||||||
# If the request is coming for the non-existant domain
|
# If the request is coming for the non-existant domain
|
||||||
if not domain:
|
if not domain:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=HTTPStatus.FORBIDDEN,
|
status_code=HTTPStatus.FORBIDDEN,
|
||||||
detail="The domain does not exist.",
|
detail="The domain does not exist.",
|
||||||
)
|
)
|
||||||
|
|
||||||
domain_cost = domain[6]
|
domain_cost = domain[6]
|
||||||
sats = data.sats
|
sats = data.sats
|
||||||
|
|
||||||
## FAILSAFE FOR CREATING ADDRESSES BY API
|
## FAILSAFE FOR CREATING ADDRESSES BY API
|
||||||
if domain_cost * data.duration != data.sats:
|
if(domain_cost * data.duration != data.sats):
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=HTTPStatus.FORBIDDEN,
|
status_code=HTTPStatus.FORBIDDEN,
|
||||||
detail="The amount is not correct. Either 'duration', or 'sats' are wrong.",
|
detail="The amount is not correct. Either 'duration', or 'sats' are wrong.",
|
||||||
)
|
)
|
||||||
|
|
||||||
if user:
|
if user:
|
||||||
print("USER", user, domain.domain)
|
print("USER", user, domain.domain)
|
||||||
@@ -197,7 +183,7 @@ async def api_lnaddress_make_address(
|
|||||||
extra={
|
extra={
|
||||||
"tag": "renew lnaddress",
|
"tag": "renew lnaddress",
|
||||||
"id": address.id,
|
"id": address.id,
|
||||||
"duration": data.duration,
|
"duration": data.duration
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -229,7 +215,7 @@ async def api_lnaddress_make_address(
|
|||||||
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
|
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
|
||||||
detail=str(e),
|
detail=str(e),
|
||||||
)
|
)
|
||||||
|
|
||||||
address = await create_address(
|
address = await create_address(
|
||||||
payment_hash=payment_hash, wallet=domain.wallet, data=data
|
payment_hash=payment_hash, wallet=domain.wallet, data=data
|
||||||
)
|
)
|
||||||
@@ -242,7 +228,6 @@ async def api_lnaddress_make_address(
|
|||||||
|
|
||||||
return {"payment_hash": payment_hash, "payment_request": payment_request}
|
return {"payment_hash": payment_hash, "payment_request": payment_request}
|
||||||
|
|
||||||
|
|
||||||
@lnaddress_ext.get("/api/v1/addresses/{payment_hash}")
|
@lnaddress_ext.get("/api/v1/addresses/{payment_hash}")
|
||||||
async def api_address_send_address(payment_hash):
|
async def api_address_send_address(payment_hash):
|
||||||
address = await get_address(payment_hash)
|
address = await get_address(payment_hash)
|
||||||
@@ -251,27 +236,27 @@ async def api_address_send_address(payment_hash):
|
|||||||
status = await check_invoice_status(domain.wallet, payment_hash)
|
status = await check_invoice_status(domain.wallet, payment_hash)
|
||||||
is_paid = not status.pending
|
is_paid = not status.pending
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return {"paid": False, "error": str(e)}
|
return {"paid": False, 'error': str(e)}
|
||||||
|
|
||||||
if is_paid:
|
if is_paid:
|
||||||
return {"paid": True}
|
return {"paid": True}
|
||||||
|
|
||||||
return {"paid": False}
|
return {"paid": False}
|
||||||
|
|
||||||
|
|
||||||
@lnaddress_ext.delete("/api/v1/addresses/{address_id}")
|
@lnaddress_ext.delete("/api/v1/addresses/{address_id}")
|
||||||
async def api_address_delete(address_id, g: WalletTypeInfo = Depends(get_key_type)):
|
async def api_address_delete(address_id, g: WalletTypeInfo = Depends(get_key_type)):
|
||||||
address = await get_address(address_id)
|
address = await get_address(address_id)
|
||||||
if not address:
|
if not address:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=HTTPStatus.NOT_FOUND,
|
status_code=HTTPStatus.NOT_FOUND,
|
||||||
detail="Address does not exist.",
|
detail="Address does not exist.",
|
||||||
)
|
)
|
||||||
if address.wallet != g.wallet.id:
|
if address.wallet != g.wallet.id:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=HTTPStatus.FORBIDDEN,
|
status_code=HTTPStatus.FORBIDDEN,
|
||||||
detail="Not your address.",
|
detail="Not your address.",
|
||||||
)
|
)
|
||||||
|
|
||||||
await delete_address(address_id)
|
await delete_address(address_id)
|
||||||
raise HTTPException(status_code=HTTPStatus.NO_CONTENT)
|
raise HTTPException(status_code=HTTPStatus.NO_CONTENT)
|
||||||
|
|
@@ -108,9 +108,7 @@ async def lndhub_payinvoice(
|
|||||||
|
|
||||||
|
|
||||||
@lndhub_ext.get("/ext/balance")
|
@lndhub_ext.get("/ext/balance")
|
||||||
async def lndhub_balance(
|
async def lndhub_balance(wallet: WalletTypeInfo = Depends(check_wallet),):
|
||||||
wallet: WalletTypeInfo = Depends(check_wallet),
|
|
||||||
):
|
|
||||||
return {"BTC": {"AvailableBalance": wallet.wallet.balance}}
|
return {"BTC": {"AvailableBalance": wallet.wallet.balance}}
|
||||||
|
|
||||||
|
|
||||||
|
@@ -8,9 +8,7 @@ from .models import lnurlposs, lnurlpospayment, createLnurlpos
|
|||||||
###############lnurlposS##########################
|
###############lnurlposS##########################
|
||||||
|
|
||||||
|
|
||||||
async def create_lnurlpos(
|
async def create_lnurlpos(data: createLnurlpos,) -> lnurlposs:
|
||||||
data: createLnurlpos,
|
|
||||||
) -> lnurlposs:
|
|
||||||
print(data)
|
print(data)
|
||||||
lnurlpos_id = urlsafe_short_hash()
|
lnurlpos_id = urlsafe_short_hash()
|
||||||
lnurlpos_key = urlsafe_short_hash()
|
lnurlpos_key = urlsafe_short_hash()
|
||||||
@@ -62,7 +60,6 @@ async def get_lnurlposs(wallet_ids: Union[str, List[str]]) -> List[lnurlposs]:
|
|||||||
|
|
||||||
return [lnurlposs(**row) if row else None for row in rows]
|
return [lnurlposs(**row) if row else None for row in rows]
|
||||||
|
|
||||||
|
|
||||||
async def delete_lnurlpos(lnurlpos_id: str) -> None:
|
async def delete_lnurlpos(lnurlpos_id: str) -> None:
|
||||||
await db.execute("DELETE FROM lnurlpos.lnurlposs WHERE id = ?", (lnurlpos_id,))
|
await db.execute("DELETE FROM lnurlpos.lnurlposs WHERE id = ?", (lnurlpos_id,))
|
||||||
|
|
||||||
|
@@ -51,12 +51,19 @@ async def api_lnurl_response(request: Request, unique_hash):
|
|||||||
|
|
||||||
|
|
||||||
# CALLBACK
|
# CALLBACK
|
||||||
|
|
||||||
|
#https://5650-2001-8a0-fa12-2900-4c13-748a-fbb9-a47f.ngrok.io/withdraw/api/v1/lnurl/cb/eJHybS8hqcBWajZM63H3FP?k1=MUaYBGrUPuAs8SLpfizmCk&pr=lnbc100n1pse2tsypp5ju0yn3w9j0n8rr3squg0knddawu2ude2cgrm6zje5f34e9jzpmlsdq8w3jhxaqxqyjw5qcqpjsp5tyhu78pamqg5zfy96kup329zt40ramc8gs2ev6jxgp66zca2348qrzjqwac3nxyg3f5mfa4ke9577c4u8kvkx8pqtdsusqdfww0aymk823x6znwa5qqzyqqqyqqqqlgqqqqppgq9q9qy9qsq66zp6pctnlmk59xwtqjga5lvqrkyccmafmn43enhhc6ugew80sanxymepshpv44m9yyhfgh8r2upvxhgk00d36rpqzfy3fxemeu4jhqp96l8hx
|
||||||
|
|
||||||
|
|
||||||
@withdraw_ext.get(
|
@withdraw_ext.get(
|
||||||
"/api/v1/lnurl/cb/{unique_hash}",
|
"/api/v1/lnurl/cb/{unique_hash}",
|
||||||
name="withdraw.api_lnurl_callback",
|
name="withdraw.api_lnurl_callback",
|
||||||
)
|
)
|
||||||
async def api_lnurl_callback(
|
async def api_lnurl_callback(
|
||||||
unique_hash, request: Request, k1: str = Query(...), pr: str = Query(...)
|
unique_hash,
|
||||||
|
request: Request,
|
||||||
|
k1: str = Query(...),
|
||||||
|
pr: str = Query(...)
|
||||||
):
|
):
|
||||||
link = await get_withdraw_link_by_hash(unique_hash)
|
link = await get_withdraw_link_by_hash(unique_hash)
|
||||||
now = int(datetime.now().timestamp())
|
now = int(datetime.now().timestamp())
|
||||||
@@ -94,8 +101,8 @@ async def api_lnurl_callback(
|
|||||||
"usescsv": usescsv,
|
"usescsv": usescsv,
|
||||||
}
|
}
|
||||||
await update_withdraw_link(link.id, **changes)
|
await update_withdraw_link(link.id, **changes)
|
||||||
|
|
||||||
payment_request = pr
|
payment_request=pr
|
||||||
|
|
||||||
await pay_invoice(
|
await pay_invoice(
|
||||||
wallet_id=link.wallet,
|
wallet_id=link.wallet,
|
||||||
|
@@ -63,9 +63,7 @@ class LNbitsWallet(Wallet):
|
|||||||
|
|
||||||
async with httpx.AsyncClient() as client:
|
async with httpx.AsyncClient() as client:
|
||||||
r = await client.post(
|
r = await client.post(
|
||||||
url=f"{self.endpoint}/api/v1/payments",
|
url=f"{self.endpoint}/api/v1/payments", headers=self.key, json=data,
|
||||||
headers=self.key,
|
|
||||||
json=data,
|
|
||||||
)
|
)
|
||||||
ok, checking_id, payment_request, error_message = (
|
ok, checking_id, payment_request, error_message = (
|
||||||
not r.is_error,
|
not r.is_error,
|
||||||
@@ -87,7 +85,7 @@ class LNbitsWallet(Wallet):
|
|||||||
r = await client.post(
|
r = await client.post(
|
||||||
url=f"{self.endpoint}/api/v1/payments",
|
url=f"{self.endpoint}/api/v1/payments",
|
||||||
headers=self.key,
|
headers=self.key,
|
||||||
json={"out": True, "bolt11": bolt11},
|
json={"out": True, "bolt11": bolt11},
|
||||||
timeout=100,
|
timeout=100,
|
||||||
)
|
)
|
||||||
ok, checking_id, fee_msat, error_message = not r.is_error, None, 0, None
|
ok, checking_id, fee_msat, error_message = not r.is_error, None, 0, None
|
||||||
|
Reference in New Issue
Block a user