more mypy extension fixes (#1096)

* mypy fix jukebox

* mypy fix ngrok

* mypy fix satsdice

* remove exts from mypy exclude
This commit is contained in:
dni ⚡
2022-11-19 21:42:10 +01:00
committed by GitHub
parent 0096ce8ad1
commit 604e52c45d
12 changed files with 157 additions and 156 deletions

View File

@@ -1,4 +1,4 @@
from typing import List, Optional from typing import List, Optional, Union
from lnbits.helpers import urlsafe_short_hash from lnbits.helpers import urlsafe_short_hash
@@ -6,11 +6,9 @@ from . import db
from .models import CreateJukeboxPayment, CreateJukeLinkData, Jukebox, JukeboxPayment from .models import CreateJukeboxPayment, CreateJukeLinkData, Jukebox, JukeboxPayment
async def create_jukebox( async def create_jukebox(data: CreateJukeLinkData) -> Jukebox:
data: CreateJukeLinkData, inkey: Optional[str] = ""
) -> Jukebox:
juke_id = urlsafe_short_hash() juke_id = urlsafe_short_hash()
result = await db.execute( await db.execute(
""" """
INSERT INTO jukebox.jukebox (id, "user", title, wallet, sp_user, sp_secret, sp_access_token, sp_refresh_token, sp_device, sp_playlists, price, profit) INSERT INTO jukebox.jukebox (id, "user", title, wallet, sp_user, sp_secret, sp_access_token, sp_refresh_token, sp_device, sp_playlists, price, profit)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -36,13 +34,13 @@ async def create_jukebox(
async def update_jukebox( async def update_jukebox(
data: CreateJukeLinkData, juke_id: Optional[str] = "" data: Union[CreateJukeLinkData, Jukebox], juke_id: str = ""
) -> Optional[Jukebox]: ) -> Optional[Jukebox]:
q = ", ".join([f"{field[0]} = ?" for field in data]) q = ", ".join([f"{field[0]} = ?" for field in data])
items = [f"{field[1]}" for field in data] items = [f"{field[1]}" for field in data]
items.append(juke_id) items.append(juke_id)
q = q.replace("user", '"user"', 1) # hack to make user be "user"! q = q.replace("user", '"user"', 1) # hack to make user be "user"!
await db.execute(f"UPDATE jukebox.jukebox SET {q} WHERE id = ?", (items)) await db.execute(f"UPDATE jukebox.jukebox SET {q} WHERE id = ?", (items,))
row = await db.fetchone("SELECT * FROM jukebox.jukebox WHERE id = ?", (juke_id,)) row = await db.fetchone("SELECT * FROM jukebox.jukebox WHERE id = ?", (juke_id,))
return Jukebox(**row) if row else None return Jukebox(**row) if row else None
@@ -72,7 +70,7 @@ async def delete_jukebox(juke_id: str):
""" """
DELETE FROM jukebox.jukebox WHERE id = ? DELETE FROM jukebox.jukebox WHERE id = ?
""", """,
(juke_id), (juke_id,),
) )
@@ -80,7 +78,7 @@ async def delete_jukebox(juke_id: str):
async def create_jukebox_payment(data: CreateJukeboxPayment) -> JukeboxPayment: async def create_jukebox_payment(data: CreateJukeboxPayment) -> JukeboxPayment:
result = await db.execute( await db.execute(
""" """
INSERT INTO jukebox.jukebox_payment (payment_hash, juke_id, song_id, paid) INSERT INTO jukebox.jukebox_payment (payment_hash, juke_id, song_id, paid)
VALUES (?, ?, ?, ?) VALUES (?, ?, ?, ?)

View File

@@ -1,6 +1,3 @@
from sqlite3 import Row
from typing import NamedTuple, Optional
from fastapi.param_functions import Query from fastapi.param_functions import Query
from pydantic import BaseModel from pydantic import BaseModel
from pydantic.main import BaseModel from pydantic.main import BaseModel
@@ -20,19 +17,19 @@ class CreateJukeLinkData(BaseModel):
class Jukebox(BaseModel): class Jukebox(BaseModel):
id: Optional[str] id: str
user: Optional[str] user: str
title: Optional[str] title: str
wallet: Optional[str] wallet: str
inkey: Optional[str] inkey: str
sp_user: Optional[str] sp_user: str
sp_secret: Optional[str] sp_secret: str
sp_access_token: Optional[str] sp_access_token: str
sp_refresh_token: Optional[str] sp_refresh_token: str
sp_device: Optional[str] sp_device: str
sp_playlists: Optional[str] sp_playlists: str
price: Optional[int] price: int
profit: Optional[int] profit: int
class JukeboxPayment(BaseModel): class JukeboxPayment(BaseModel):

View File

@@ -17,7 +17,8 @@ async def wait_for_paid_invoices():
async def on_invoice_paid(payment: Payment) -> None: async def on_invoice_paid(payment: Payment) -> None:
if payment.extra.get("tag") != "jukebox": if payment.extra:
# not a jukebox invoice if payment.extra.get("tag") != "jukebox":
return # not a jukebox invoice
await update_jukebox_payment(payment.payment_hash, paid=True) return
await update_jukebox_payment(payment.payment_hash, paid=True)

View File

@@ -17,7 +17,9 @@ templates = Jinja2Templates(directory="templates")
@jukebox_ext.get("/", response_class=HTMLResponse) @jukebox_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) # type: ignore
):
return jukebox_renderer().TemplateResponse( return jukebox_renderer().TemplateResponse(
"jukebox/index.html", {"request": request, "user": user.dict()} "jukebox/index.html", {"request": request, "user": user.dict()}
) )
@@ -31,6 +33,7 @@ async def connect_to_jukebox(request: Request, juke_id):
status_code=HTTPStatus.NOT_FOUND, detail="Jukebox does not exist." status_code=HTTPStatus.NOT_FOUND, detail="Jukebox does not exist."
) )
devices = await api_get_jukebox_device_check(juke_id) devices = await api_get_jukebox_device_check(juke_id)
deviceConnected = False
for device in devices["devices"]: for device in devices["devices"]:
if device["id"] == jukebox.sp_device.split("-")[1]: if device["id"] == jukebox.sp_device.split("-")[1]:
deviceConnected = True deviceConnected = True
@@ -48,5 +51,5 @@ async def connect_to_jukebox(request: Request, juke_id):
else: else:
return jukebox_renderer().TemplateResponse( return jukebox_renderer().TemplateResponse(
"jukebox/error.html", "jukebox/error.html",
{"request": request, "jukebox": jukebox.jukebox(req=request)}, {"request": request, "jukebox": jukebox.dict()},
) )

View File

@@ -3,7 +3,6 @@ import json
from http import HTTPStatus from http import HTTPStatus
import httpx import httpx
from fastapi import Request
from fastapi.param_functions import Query from fastapi.param_functions import Query
from fastapi.params import Depends from fastapi.params import Depends
from starlette.exceptions import HTTPException from starlette.exceptions import HTTPException
@@ -29,9 +28,7 @@ from .models import CreateJukeboxPayment, CreateJukeLinkData
@jukebox_ext.get("/api/v1/jukebox") @jukebox_ext.get("/api/v1/jukebox")
async def api_get_jukeboxs( async def api_get_jukeboxs(
req: Request, wallet: WalletTypeInfo = Depends(require_admin_key), # type: ignore
wallet: WalletTypeInfo = Depends(require_admin_key),
all_wallets: bool = Query(False),
): ):
wallet_user = wallet.wallet.user wallet_user = wallet.wallet.user
@@ -53,54 +50,52 @@ async def api_check_credentials_callbac(
access_token: str = Query(None), access_token: str = Query(None),
refresh_token: str = Query(None), refresh_token: str = Query(None),
): ):
sp_code = "" jukebox = await get_jukebox(juke_id)
sp_access_token = "" if not jukebox:
sp_refresh_token = ""
try:
jukebox = await get_jukebox(juke_id)
except:
raise HTTPException(detail="No Jukebox", status_code=HTTPStatus.FORBIDDEN) raise HTTPException(detail="No Jukebox", status_code=HTTPStatus.FORBIDDEN)
if code: if code:
jukebox.sp_access_token = code jukebox.sp_access_token = code
jukebox = await update_jukebox(jukebox, juke_id=juke_id) await update_jukebox(jukebox, juke_id=juke_id)
if access_token: if access_token:
jukebox.sp_access_token = access_token jukebox.sp_access_token = access_token
jukebox.sp_refresh_token = refresh_token jukebox.sp_refresh_token = refresh_token
jukebox = await update_jukebox(jukebox, juke_id=juke_id) await update_jukebox(jukebox, juke_id=juke_id)
return "<h1>Success!</h1><h2>You can close this window</h2>" return "<h1>Success!</h1><h2>You can close this window</h2>"
@jukebox_ext.get("/api/v1/jukebox/{juke_id}") @jukebox_ext.get("/api/v1/jukebox/{juke_id}", dependencies=[Depends(require_admin_key)])
async def api_check_credentials_check( async def api_check_credentials_check(juke_id: str = Query(None)):
juke_id: str = Query(None), wallet: WalletTypeInfo = Depends(require_admin_key)
):
jukebox = await get_jukebox(juke_id) jukebox = await get_jukebox(juke_id)
return jukebox return jukebox
@jukebox_ext.post("/api/v1/jukebox", status_code=HTTPStatus.CREATED) @jukebox_ext.post(
"/api/v1/jukebox",
status_code=HTTPStatus.CREATED,
dependencies=[Depends(require_admin_key)],
)
@jukebox_ext.put("/api/v1/jukebox/{juke_id}", status_code=HTTPStatus.OK) @jukebox_ext.put("/api/v1/jukebox/{juke_id}", status_code=HTTPStatus.OK)
async def api_create_update_jukebox( async def api_create_update_jukebox(
data: CreateJukeLinkData, data: CreateJukeLinkData, juke_id: str = Query(None)
juke_id: str = Query(None),
wallet: WalletTypeInfo = Depends(require_admin_key),
): ):
if juke_id: if juke_id:
jukebox = await update_jukebox(data, juke_id=juke_id) jukebox = await update_jukebox(data, juke_id=juke_id)
else: else:
jukebox = await create_jukebox(data, inkey=wallet.wallet.inkey) jukebox = await create_jukebox(data)
return jukebox return jukebox
@jukebox_ext.delete("/api/v1/jukebox/{juke_id}") @jukebox_ext.delete(
"/api/v1/jukebox/{juke_id}", dependencies=[Depends(require_admin_key)]
)
async def api_delete_item( async def api_delete_item(
juke_id=None, wallet: WalletTypeInfo = Depends(require_admin_key) juke_id: str = Query(None),
): ):
await delete_jukebox(juke_id) await delete_jukebox(juke_id)
try: # try:
return [{**jukebox} for jukebox in await get_jukeboxs(wallet.wallet.user)] # return [{**jukebox} for jukebox in await get_jukeboxs(wallet.wallet.user)]
except: # except:
raise HTTPException(status_code=HTTPStatus.NO_CONTENT, detail="No Jukebox") # raise HTTPException(status_code=HTTPStatus.NO_CONTENT, detail="No Jukebox")
################JUKEBOX ENDPOINTS################## ################JUKEBOX ENDPOINTS##################
@@ -114,9 +109,8 @@ async def api_get_jukebox_song(
sp_playlist: str = Query(None), sp_playlist: str = Query(None),
retry: bool = Query(False), retry: bool = Query(False),
): ):
try: jukebox = await get_jukebox(juke_id)
jukebox = await get_jukebox(juke_id) if not jukebox:
except:
raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="No Jukeboxes") raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="No Jukeboxes")
tracks = [] tracks = []
async with httpx.AsyncClient() as client: async with httpx.AsyncClient() as client:
@@ -152,14 +146,13 @@ async def api_get_jukebox_song(
} }
) )
except: except:
something = None pass
return [track for track in tracks] return [track for track in tracks]
async def api_get_token(juke_id=None): async def api_get_token(juke_id):
try: jukebox = await get_jukebox(juke_id)
jukebox = await get_jukebox(juke_id) if not jukebox:
except:
raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="No Jukeboxes") raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="No Jukeboxes")
async with httpx.AsyncClient() as client: async with httpx.AsyncClient() as client:
@@ -187,7 +180,7 @@ async def api_get_token(juke_id=None):
jukebox.sp_access_token = r.json()["access_token"] jukebox.sp_access_token = r.json()["access_token"]
await update_jukebox(jukebox, juke_id=juke_id) await update_jukebox(jukebox, juke_id=juke_id)
except: except:
something = None pass
return True return True
@@ -198,9 +191,8 @@ async def api_get_token(juke_id=None):
async def api_get_jukebox_device_check( async def api_get_jukebox_device_check(
juke_id: str = Query(None), retry: bool = Query(False) juke_id: str = Query(None), retry: bool = Query(False)
): ):
try: jukebox = await get_jukebox(juke_id)
jukebox = await get_jukebox(juke_id) if not jukebox:
except:
raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="No Jukeboxes") raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="No Jukeboxes")
async with httpx.AsyncClient() as client: async with httpx.AsyncClient() as client:
rDevice = await client.get( rDevice = await client.get(
@@ -221,7 +213,7 @@ async def api_get_jukebox_device_check(
status_code=HTTPStatus.FORBIDDEN, detail="Failed to get auth" status_code=HTTPStatus.FORBIDDEN, detail="Failed to get auth"
) )
else: else:
return api_get_jukebox_device_check(juke_id, retry=True) return await api_get_jukebox_device_check(juke_id, retry=True)
else: else:
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.FORBIDDEN, detail="No device connected" status_code=HTTPStatus.FORBIDDEN, detail="No device connected"
@@ -233,10 +225,8 @@ async def api_get_jukebox_device_check(
@jukebox_ext.get("/api/v1/jukebox/jb/invoice/{juke_id}/{song_id}") @jukebox_ext.get("/api/v1/jukebox/jb/invoice/{juke_id}/{song_id}")
async def api_get_jukebox_invoice(juke_id, song_id): async def api_get_jukebox_invoice(juke_id, song_id):
try: jukebox = await get_jukebox(juke_id)
jukebox = await get_jukebox(juke_id) if not jukebox:
except:
raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="No jukebox") raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="No jukebox")
try: try:
@@ -266,8 +256,7 @@ async def api_get_jukebox_invoice(juke_id, song_id):
invoice=invoice[1], payment_hash=payment_hash, juke_id=juke_id, song_id=song_id invoice=invoice[1], payment_hash=payment_hash, juke_id=juke_id, song_id=song_id
) )
jukebox_payment = await create_jukebox_payment(data) jukebox_payment = await create_jukebox_payment(data)
return jukebox_payment
return data
@jukebox_ext.get("/api/v1/jukebox/jb/checkinvoice/{pay_hash}/{juke_id}") @jukebox_ext.get("/api/v1/jukebox/jb/checkinvoice/{pay_hash}/{juke_id}")
@@ -296,13 +285,12 @@ async def api_get_jukebox_invoice_paid(
pay_hash: str = Query(None), pay_hash: str = Query(None),
retry: bool = Query(False), retry: bool = Query(False),
): ):
try: jukebox = await get_jukebox(juke_id)
jukebox = await get_jukebox(juke_id) if not jukebox:
except:
raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="No jukebox") raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="No jukebox")
await api_get_jukebox_invoice_check(pay_hash, juke_id) await api_get_jukebox_invoice_check(pay_hash, juke_id)
jukebox_payment = await get_jukebox_payment(pay_hash) jukebox_payment = await get_jukebox_payment(pay_hash)
if jukebox_payment.paid: if jukebox_payment and jukebox_payment.paid:
async with httpx.AsyncClient() as client: async with httpx.AsyncClient() as client:
r = await client.get( r = await client.get(
"https://api.spotify.com/v1/me/player/currently-playing?market=ES", "https://api.spotify.com/v1/me/player/currently-playing?market=ES",
@@ -407,9 +395,8 @@ async def api_get_jukebox_invoice_paid(
async def api_get_jukebox_currently( async def api_get_jukebox_currently(
retry: bool = Query(False), juke_id: str = Query(None) retry: bool = Query(False), juke_id: str = Query(None)
): ):
try: jukebox = await get_jukebox(juke_id)
jukebox = await get_jukebox(juke_id) if not jukebox:
except:
raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="No jukebox") raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="No jukebox")
async with httpx.AsyncClient() as client: async with httpx.AsyncClient() as client:
try: try:

View File

@@ -1,3 +1,4 @@
# type: ignore
from os import getenv from os import getenv
from fastapi import Request from fastapi import Request
@@ -34,7 +35,9 @@ ngrok_tunnel = ngrok.connect(port)
@ngrok_ext.get("/") @ngrok_ext.get("/")
async def index(request: Request, user: User = Depends(check_user_exists)): async def index(
request: Request, user: User = Depends(check_user_exists) # type: ignore
):
return ngrok_renderer().TemplateResponse( return ngrok_renderer().TemplateResponse(
"ngrok/index.html", {"request": request, "ngrok": string5, "user": user.dict()} "ngrok/index.html", {"request": request, "ngrok": string5, "user": user.dict()}
) )

View File

@@ -8,7 +8,6 @@ from .models import (
CreateSatsDiceLink, CreateSatsDiceLink,
CreateSatsDicePayment, CreateSatsDicePayment,
CreateSatsDiceWithdraw, CreateSatsDiceWithdraw,
HashCheck,
satsdiceLink, satsdiceLink,
satsdicePayment, satsdicePayment,
satsdiceWithdraw, satsdiceWithdraw,
@@ -76,7 +75,7 @@ async def get_satsdice_pays(wallet_ids: Union[str, List[str]]) -> List[satsdiceL
return [satsdiceLink(**row) for row in rows] return [satsdiceLink(**row) for row in rows]
async def update_satsdice_pay(link_id: int, **kwargs) -> Optional[satsdiceLink]: async def update_satsdice_pay(link_id: str, **kwargs) -> satsdiceLink:
q = ", ".join([f"{field[0]} = ?" for field in kwargs.items()]) q = ", ".join([f"{field[0]} = ?" for field in kwargs.items()])
await db.execute( await db.execute(
f"UPDATE satsdice.satsdice_pay SET {q} WHERE id = ?", f"UPDATE satsdice.satsdice_pay SET {q} WHERE id = ?",
@@ -85,10 +84,10 @@ async def update_satsdice_pay(link_id: int, **kwargs) -> Optional[satsdiceLink]:
row = await db.fetchone( row = await db.fetchone(
"SELECT * FROM satsdice.satsdice_pay WHERE id = ?", (link_id,) "SELECT * FROM satsdice.satsdice_pay WHERE id = ?", (link_id,)
) )
return satsdiceLink(**row) if row else None return satsdiceLink(**row)
async def increment_satsdice_pay(link_id: int, **kwargs) -> Optional[satsdiceLink]: async def increment_satsdice_pay(link_id: str, **kwargs) -> Optional[satsdiceLink]:
q = ", ".join([f"{field[0]} = {field[0]} + ?" for field in kwargs.items()]) q = ", ".join([f"{field[0]} = {field[0]} + ?" for field in kwargs.items()])
await db.execute( await db.execute(
f"UPDATE satsdice.satsdice_pay SET {q} WHERE id = ?", f"UPDATE satsdice.satsdice_pay SET {q} WHERE id = ?",
@@ -100,7 +99,7 @@ async def increment_satsdice_pay(link_id: int, **kwargs) -> Optional[satsdiceLin
return satsdiceLink(**row) if row else None return satsdiceLink(**row) if row else None
async def delete_satsdice_pay(link_id: int) -> None: async def delete_satsdice_pay(link_id: str) -> None:
await db.execute("DELETE FROM satsdice.satsdice_pay WHERE id = ?", (link_id,)) await db.execute("DELETE FROM satsdice.satsdice_pay WHERE id = ?", (link_id,))
@@ -119,9 +118,15 @@ async def create_satsdice_payment(data: CreateSatsDicePayment) -> satsdicePaymen
) )
VALUES (?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?)
""", """,
(data["payment_hash"], data["satsdice_pay"], data["value"], False, False), (
data.payment_hash,
data.satsdice_pay,
data.value,
False,
False,
),
) )
payment = await get_satsdice_payment(data["payment_hash"]) payment = await get_satsdice_payment(data.payment_hash)
assert payment, "Newly created withdraw couldn't be retrieved" assert payment, "Newly created withdraw couldn't be retrieved"
return payment return payment
@@ -134,9 +139,7 @@ async def get_satsdice_payment(payment_hash: str) -> Optional[satsdicePayment]:
return satsdicePayment(**row) if row else None return satsdicePayment(**row) if row else None
async def update_satsdice_payment( async def update_satsdice_payment(payment_hash: str, **kwargs) -> satsdicePayment:
payment_hash: int, **kwargs
) -> Optional[satsdicePayment]:
q = ", ".join([f"{field[0]} = ?" for field in kwargs.items()]) q = ", ".join([f"{field[0]} = ?" for field in kwargs.items()])
await db.execute( await db.execute(
@@ -147,7 +150,7 @@ async def update_satsdice_payment(
"SELECT * FROM satsdice.satsdice_payment WHERE payment_hash = ?", "SELECT * FROM satsdice.satsdice_payment WHERE payment_hash = ?",
(payment_hash,), (payment_hash,),
) )
return satsdicePayment(**row) if row else None return satsdicePayment(**row)
##################SATSDICE WITHDRAW LINKS ##################SATSDICE WITHDRAW LINKS
@@ -168,16 +171,16 @@ async def create_satsdice_withdraw(data: CreateSatsDiceWithdraw) -> satsdiceWith
VALUES (?, ?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?, ?)
""", """,
( (
data["payment_hash"], data.payment_hash,
data["satsdice_pay"], data.satsdice_pay,
data["value"], data.value,
urlsafe_short_hash(), urlsafe_short_hash(),
urlsafe_short_hash(), urlsafe_short_hash(),
int(datetime.now().timestamp()), int(datetime.now().timestamp()),
data["used"], data.used,
), ),
) )
withdraw = await get_satsdice_withdraw(data["payment_hash"], 0) withdraw = await get_satsdice_withdraw(data.payment_hash, 0)
assert withdraw, "Newly created withdraw couldn't be retrieved" assert withdraw, "Newly created withdraw couldn't be retrieved"
return withdraw return withdraw
@@ -247,7 +250,7 @@ async def delete_satsdice_withdraw(withdraw_id: str) -> None:
) )
async def create_withdraw_hash_check(the_hash: str, lnurl_id: str) -> HashCheck: async def create_withdraw_hash_check(the_hash: str, lnurl_id: str):
await db.execute( await db.execute(
""" """
INSERT INTO satsdice.hash_checkw ( INSERT INTO satsdice.hash_checkw (
@@ -262,19 +265,15 @@ async def create_withdraw_hash_check(the_hash: str, lnurl_id: str) -> HashCheck:
return hashCheck return hashCheck
async def get_withdraw_hash_checkw(the_hash: str, lnurl_id: str) -> Optional[HashCheck]: async def get_withdraw_hash_checkw(the_hash: str, lnurl_id: str):
rowid = await db.fetchone( rowid = await db.fetchone(
"SELECT * FROM satsdice.hash_checkw WHERE id = ?", (the_hash,) "SELECT * FROM satsdice.hash_checkw WHERE id = ?", (the_hash,)
) )
rowlnurl = await db.fetchone( rowlnurl = await db.fetchone(
"SELECT * FROM satsdice.hash_checkw WHERE lnurl_id = ?", (lnurl_id,) "SELECT * FROM satsdice.hash_checkw WHERE lnurl_id = ?", (lnurl_id,)
) )
if not rowlnurl: if not rowlnurl or not rowid:
await create_withdraw_hash_check(the_hash, lnurl_id) await create_withdraw_hash_check(the_hash, lnurl_id)
return {"lnurl": True, "hash": False} return {"lnurl": True, "hash": False}
else: else:
if not rowid: return {"lnurl": True, "hash": True}
await create_withdraw_hash_check(the_hash, lnurl_id)
return {"lnurl": True, "hash": False}
else:
return {"lnurl": True, "hash": True}

View File

@@ -1,4 +1,3 @@
import hashlib
import json import json
import math import math
from http import HTTPStatus from http import HTTPStatus
@@ -83,15 +82,18 @@ async def api_lnurlp_callback(
success_action = link.success_action(payment_hash=payment_hash, req=req) success_action = link.success_action(payment_hash=payment_hash, req=req)
data: CreateSatsDicePayment = { data = CreateSatsDicePayment(
"satsdice_pay": link.id, satsdice_pay=link.id,
"value": amount_received / 1000, value=amount_received / 1000,
"payment_hash": payment_hash, payment_hash=payment_hash,
} )
await create_satsdice_payment(data) await create_satsdice_payment(data)
payResponse = {"pr": payment_request, "successAction": success_action, "routes": []} payResponse: dict = {
"pr": payment_request,
"successAction": success_action,
"routes": [],
}
return json.dumps(payResponse) return json.dumps(payResponse)
@@ -133,9 +135,7 @@ async def api_lnurlw_response(req: Request, unique_hash: str = Query(None)):
name="satsdice.api_lnurlw_callback", name="satsdice.api_lnurlw_callback",
) )
async def api_lnurlw_callback( async def api_lnurlw_callback(
req: Request,
unique_hash: str = Query(None), unique_hash: str = Query(None),
k1: str = Query(None),
pr: str = Query(None), pr: str = Query(None),
): ):
@@ -146,12 +146,13 @@ async def api_lnurlw_callback(
return {"status": "ERROR", "reason": "spent"} return {"status": "ERROR", "reason": "spent"}
paylink = await get_satsdice_pay(link.satsdice_pay) paylink = await get_satsdice_pay(link.satsdice_pay)
await update_satsdice_withdraw(link.id, used=1) if paylink:
await pay_invoice( await update_satsdice_withdraw(link.id, used=1)
wallet_id=paylink.wallet, await pay_invoice(
payment_request=pr, wallet_id=paylink.wallet,
max_sat=link.value, payment_request=pr,
extra={"tag": "withdraw"}, max_sat=link.value,
) extra={"tag": "withdraw"},
)
return {"status": "OK"} return {"status": "OK"}

View File

@@ -4,7 +4,7 @@ from typing import Dict, Optional
from fastapi import Request from fastapi import Request
from fastapi.param_functions import Query from fastapi.param_functions import Query
from lnurl import Lnurl, LnurlWithdrawResponse from lnurl import Lnurl
from lnurl import encode as lnurl_encode # type: ignore from lnurl import encode as lnurl_encode # type: ignore
from lnurl.types import LnurlPayMetadata # type: ignore from lnurl.types import LnurlPayMetadata # type: ignore
from pydantic import BaseModel from pydantic import BaseModel
@@ -80,8 +80,7 @@ class satsdiceWithdraw(BaseModel):
def is_spent(self) -> bool: def is_spent(self) -> bool:
return self.used >= 1 return self.used >= 1
@property def lnurl_response(self, req: Request):
def lnurl_response(self, req: Request) -> LnurlWithdrawResponse:
url = req.url_for("satsdice.api_lnurlw_callback", unique_hash=self.unique_hash) url = req.url_for("satsdice.api_lnurlw_callback", unique_hash=self.unique_hash)
withdrawResponse = { withdrawResponse = {
"tag": "withdrawRequest", "tag": "withdrawRequest",
@@ -99,7 +98,7 @@ class HashCheck(BaseModel):
lnurl_id: str lnurl_id: str
@classmethod @classmethod
def from_row(cls, row: Row) -> "Hash": def from_row(cls, row: Row):
return cls(**dict(row)) return cls(**dict(row))

View File

@@ -1,6 +1,8 @@
import random import random
from http import HTTPStatus from http import HTTPStatus
from io import BytesIO
import pyqrcode
from fastapi import Request from fastapi import Request
from fastapi.param_functions import Query from fastapi.param_functions import Query
from fastapi.params import Depends from fastapi.params import Depends
@@ -20,13 +22,15 @@ from .crud import (
get_satsdice_withdraw, get_satsdice_withdraw,
update_satsdice_payment, update_satsdice_payment,
) )
from .models import CreateSatsDiceWithdraw, satsdiceLink from .models import CreateSatsDiceWithdraw
templates = Jinja2Templates(directory="templates") templates = Jinja2Templates(directory="templates")
@satsdice_ext.get("/", response_class=HTMLResponse) @satsdice_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) # type: ignore
):
return satsdice_renderer().TemplateResponse( return satsdice_renderer().TemplateResponse(
"satsdice/index.html", {"request": request, "user": user.dict()} "satsdice/index.html", {"request": request, "user": user.dict()}
) )
@@ -67,7 +71,7 @@ async def displaywin(
) )
withdrawLink = await get_satsdice_withdraw(payment_hash) withdrawLink = await get_satsdice_withdraw(payment_hash)
payment = await get_satsdice_payment(payment_hash) payment = await get_satsdice_payment(payment_hash)
if payment.lost: if not payment or payment.lost:
return satsdice_renderer().TemplateResponse( return satsdice_renderer().TemplateResponse(
"satsdice/error.html", "satsdice/error.html",
{"request": request, "link": satsdicelink.id, "paid": False, "lost": True}, {"request": request, "link": satsdicelink.id, "paid": False, "lost": True},
@@ -96,13 +100,18 @@ async def displaywin(
) )
await update_satsdice_payment(payment_hash, paid=1) await update_satsdice_payment(payment_hash, paid=1)
paylink = await get_satsdice_payment(payment_hash) paylink = await get_satsdice_payment(payment_hash)
if not paylink:
return satsdice_renderer().TemplateResponse(
"satsdice/error.html",
{"request": request, "link": satsdicelink.id, "paid": False, "lost": True},
)
data: CreateSatsDiceWithdraw = { data = CreateSatsDiceWithdraw(
"satsdice_pay": satsdicelink.id, satsdice_pay=satsdicelink.id,
"value": paylink.value * satsdicelink.multiplier, value=paylink.value * satsdicelink.multiplier,
"payment_hash": payment_hash, payment_hash=payment_hash,
"used": 0, used=0,
} )
withdrawLink = await create_satsdice_withdraw(data) withdrawLink = await create_satsdice_withdraw(data)
return satsdice_renderer().TemplateResponse( return satsdice_renderer().TemplateResponse(
@@ -121,9 +130,12 @@ async def displaywin(
@satsdice_ext.get("/img/{link_id}", response_class=HTMLResponse) @satsdice_ext.get("/img/{link_id}", response_class=HTMLResponse)
async def img(link_id): async def img(link_id):
link = await get_satsdice_pay(link_id) or abort( link = await get_satsdice_pay(link_id)
HTTPStatus.NOT_FOUND, "satsdice link does not exist." if not link:
) raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="satsdice link does not exist."
)
qr = pyqrcode.create(link.lnurl) qr = pyqrcode.create(link.lnurl)
stream = BytesIO() stream = BytesIO()
qr.svg(stream, scale=3) qr.svg(stream, scale=3)

View File

@@ -15,9 +15,10 @@ from .crud import (
delete_satsdice_pay, delete_satsdice_pay,
get_satsdice_pay, get_satsdice_pay,
get_satsdice_pays, get_satsdice_pays,
get_withdraw_hash_checkw,
update_satsdice_pay, update_satsdice_pay,
) )
from .models import CreateSatsDiceLink, CreateSatsDiceWithdraws, satsdiceLink from .models import CreateSatsDiceLink
################LNURL pay ################LNURL pay
@@ -25,13 +26,15 @@ from .models import CreateSatsDiceLink, CreateSatsDiceWithdraws, satsdiceLink
@satsdice_ext.get("/api/v1/links") @satsdice_ext.get("/api/v1/links")
async def api_links( async def api_links(
request: Request, request: Request,
wallet: WalletTypeInfo = Depends(get_key_type), wallet: WalletTypeInfo = Depends(get_key_type), # type: ignore
all_wallets: bool = Query(False), all_wallets: bool = Query(False),
): ):
wallet_ids = [wallet.wallet.id] wallet_ids = [wallet.wallet.id]
if all_wallets: if all_wallets:
wallet_ids = (await get_user(wallet.wallet.user)).wallet_ids user = await get_user(wallet.wallet.user)
if user:
wallet_ids = user.wallet_ids
try: try:
links = await get_satsdice_pays(wallet_ids) links = await get_satsdice_pays(wallet_ids)
@@ -46,7 +49,7 @@ async def api_links(
@satsdice_ext.get("/api/v1/links/{link_id}") @satsdice_ext.get("/api/v1/links/{link_id}")
async def api_link_retrieve( async def api_link_retrieve(
link_id: str = Query(None), wallet: WalletTypeInfo = Depends(get_key_type) link_id: str = Query(None), wallet: WalletTypeInfo = Depends(get_key_type) # type: ignore
): ):
link = await get_satsdice_pay(link_id) link = await get_satsdice_pay(link_id)
@@ -67,7 +70,7 @@ async def api_link_retrieve(
@satsdice_ext.put("/api/v1/links/{link_id}", status_code=HTTPStatus.OK) @satsdice_ext.put("/api/v1/links/{link_id}", status_code=HTTPStatus.OK)
async def api_link_create_or_update( async def api_link_create_or_update(
data: CreateSatsDiceLink, data: CreateSatsDiceLink,
wallet: WalletTypeInfo = Depends(get_key_type), wallet: WalletTypeInfo = Depends(get_key_type), # type: ignore
link_id: str = Query(None), link_id: str = Query(None),
): ):
if data.min_bet > data.max_bet: if data.min_bet > data.max_bet:
@@ -95,10 +98,10 @@ async def api_link_create_or_update(
@satsdice_ext.delete("/api/v1/links/{link_id}") @satsdice_ext.delete("/api/v1/links/{link_id}")
async def api_link_delete( async def api_link_delete(
wallet: WalletTypeInfo = Depends(get_key_type), link_id: str = Query(None) wallet: WalletTypeInfo = Depends(get_key_type), # type: ignore
link_id: str = Query(None),
): ):
link = await get_satsdice_pay(link_id) link = await get_satsdice_pay(link_id)
if not link: if not link:
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="Pay link does not exist." status_code=HTTPStatus.NOT_FOUND, detail="Pay link does not exist."
@@ -117,11 +120,12 @@ async def api_link_delete(
##########LNURL withdraw ##########LNURL withdraw
@satsdice_ext.get("/api/v1/withdraws/{the_hash}/{lnurl_id}") @satsdice_ext.get(
"/api/v1/withdraws/{the_hash}/{lnurl_id}", dependencies=[Depends(get_key_type)]
)
async def api_withdraw_hash_retrieve( async def api_withdraw_hash_retrieve(
wallet: WalletTypeInfo = Depends(get_key_type),
lnurl_id: str = Query(None), lnurl_id: str = Query(None),
the_hash: str = Query(None), the_hash: str = Query(None),
): ):
hashCheck = await get_withdraw_hash_check(the_hash, lnurl_id) hashCheck = await get_withdraw_hash_checkw(the_hash, lnurl_id)
return hashCheck return hashCheck

View File

@@ -95,7 +95,6 @@ exclude = """(?x)(
| ^lnbits/extensions/events. | ^lnbits/extensions/events.
| ^lnbits/extensions/hivemind. | ^lnbits/extensions/hivemind.
| ^lnbits/extensions/invoices. | ^lnbits/extensions/invoices.
| ^lnbits/extensions/jukebox.
| ^lnbits/extensions/livestream. | ^lnbits/extensions/livestream.
| ^lnbits/extensions/lnaddress. | ^lnbits/extensions/lnaddress.
| ^lnbits/extensions/lndhub. | ^lnbits/extensions/lndhub.
@@ -103,10 +102,8 @@ exclude = """(?x)(
| ^lnbits/extensions/lnurldevice. | ^lnbits/extensions/lnurldevice.
| ^lnbits/extensions/lnurlp. | ^lnbits/extensions/lnurlp.
| ^lnbits/extensions/lnurlpayout. | ^lnbits/extensions/lnurlpayout.
| ^lnbits/extensions/ngrok.
| ^lnbits/extensions/offlineshop. | ^lnbits/extensions/offlineshop.
| ^lnbits/extensions/paywall. | ^lnbits/extensions/paywall.
| ^lnbits/extensions/satsdice.
| ^lnbits/extensions/satspay. | ^lnbits/extensions/satspay.
| ^lnbits/extensions/scrub. | ^lnbits/extensions/scrub.
| ^lnbits/extensions/splitpayments. | ^lnbits/extensions/splitpayments.