views converted

This commit is contained in:
benarc
2021-10-13 21:51:21 +01:00
parent 8db9459501
commit 33cfbe87bb
8 changed files with 252 additions and 209 deletions

View File

@@ -1,4 +1,5 @@
from fastapi import Request from fastapi import Request
from http import HTTPStatus from http import HTTPStatus
from starlette.exceptions import HTTPException from starlette.exceptions import HTTPException
from starlette.responses import HTMLResponse, JSONResponse # type: ignore from starlette.responses import HTMLResponse, JSONResponse # type: ignore

View File

@@ -1,14 +1,30 @@
from quart import Blueprint import asyncio
from fastapi import APIRouter, FastAPI
from fastapi.staticfiles import StaticFiles
from starlette.routing import Mount
from lnbits.db import Database from lnbits.db import Database
from lnbits.helpers import template_renderer
from lnbits.tasks import catch_everything_and_restart
db = Database("ext_satsdice") db = Database("satsdice_ext")
satsdice_ext: APIRouter = APIRouter(prefix="/satsdice", tags=["satsdice"])
satsdice_ext: Blueprint = Blueprint( def satsdice_renderer():
"satsdice", __name__, static_folder="static", template_folder="templates" return template_renderer(
) [
"lnbits/extensions/satsdice/templates",
]
)
from .views_api import * # noqa from .views_api import * # noqa
from .views import * # noqa from .views import * # noqa
from .lnurl import * # noqa from .lnurl import * # noqa
from .tasks import wait_for_paid_invoices
def satsdice_start():
loop = asyncio.get_event_loop()
loop.create_task(catch_everything_and_restart(wait_for_paid_invoices))

View File

@@ -1,23 +1,20 @@
from datetime import datetime from datetime import datetime
from typing import List, Optional, Union from typing import List, Optional, Union
from lnbits.helpers import urlsafe_short_hash from lnbits.helpers import urlsafe_short_hash
from typing import List, Optional
from . import db from . import db
from .models import satsdiceWithdraw, HashCheck, satsdiceLink, satsdicePayment from .models import (
satsdiceWithdraw,
##################SATSDICE PAY LINKS HashCheck,
satsdiceLink,
satsdicePayment,
CreateSatsDiceLink,
)
from lnbits.helpers import urlsafe_short_hash
async def create_satsdice_pay( async def create_satsdice_pay(
*, data: CreateSatsDiceLink,
wallet_id: str,
title: str,
base_url: str,
min_bet: str,
max_bet: str,
multiplier: int = 0,
chance: float = 0,
haircut: int = 0,
) -> satsdiceLink: ) -> satsdiceLink:
satsdice_id = urlsafe_short_hash() satsdice_id = urlsafe_short_hash()
await db.execute( await db.execute(
@@ -41,14 +38,14 @@ async def create_satsdice_pay(
""", """,
( (
satsdice_id, satsdice_id,
wallet_id, data.wallet_id,
title, data.title,
base_url, data.base_url,
min_bet, data.min_bet,
max_bet, data.max_bet,
multiplier, data.multiplier,
chance, data.chance,
haircut, data.haircut,
int(datetime.now().timestamp()), int(datetime.now().timestamp()),
), ),
) )
@@ -111,9 +108,7 @@ async def delete_satsdice_pay(link_id: int) -> None:
##################SATSDICE PAYMENT LINKS ##################SATSDICE PAYMENT LINKS
async def create_satsdice_payment( async def create_satsdice_payment(data: CreateSatsDicePayment) -> satsdicePayment:
*, satsdice_pay: str, value: int, payment_hash: str
) -> satsdicePayment:
await db.execute( await db.execute(
""" """
INSERT INTO satsdice.satsdice_payment ( INSERT INTO satsdice.satsdice_payment (
@@ -126,9 +121,9 @@ async def create_satsdice_payment(
VALUES (?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?)
""", """,
( (
payment_hash, data.payment_hash,
satsdice_pay, data.satsdice_pay,
value, data.value,
False, False,
False, False,
), ),
@@ -165,9 +160,7 @@ async def update_satsdice_payment(
##################SATSDICE WITHDRAW LINKS ##################SATSDICE WITHDRAW LINKS
async def create_satsdice_withdraw( async def create_satsdice_withdraw(data: CreateSatsDiceWithdraw) -> satsdiceWithdraw:
*, payment_hash: str, satsdice_pay: str, value: int, used: int
) -> satsdiceWithdraw:
await db.execute( await db.execute(
""" """
INSERT INTO satsdice.satsdice_withdraw ( INSERT INTO satsdice.satsdice_withdraw (
@@ -182,13 +175,13 @@ async def create_satsdice_withdraw(
VALUES (?, ?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?, ?)
""", """,
( (
payment_hash, data.payment_hash,
satsdice_pay, data.satsdice_pay,
value, data.value,
urlsafe_short_hash(), urlsafe_short_hash(),
urlsafe_short_hash(), urlsafe_short_hash(),
int(datetime.now().timestamp()), int(datetime.now().timestamp()),
used, data.used,
), ),
) )
withdraw = await get_satsdice_withdraw(payment_hash, 0) withdraw = await get_satsdice_withdraw(payment_hash, 0)

View File

@@ -3,7 +3,6 @@ import hashlib
import math import math
from http import HTTPStatus from http import HTTPStatus
from datetime import datetime from datetime import datetime
from quart import jsonify, url_for, request
from lnbits.core.services import pay_invoice, create_invoice from lnbits.core.services import pay_invoice, create_invoice
from lnbits.utils.exchange_rates import get_fiat_rate_satoshis from lnbits.utils.exchange_rates import get_fiat_rate_satoshis

View File

@@ -1,11 +1,14 @@
import json import json
from quart import url_for
from lnurl import Lnurl, LnurlWithdrawResponse, encode as lnurl_encode # type: ignore from lnurl import Lnurl, LnurlWithdrawResponse, encode as lnurl_encode # type: ignore
from urllib.parse import urlparse, urlunparse, parse_qs, urlencode, ParseResult from urllib.parse import urlparse, urlunparse, parse_qs, urlencode, ParseResult
from lnurl.types import LnurlPayMetadata # type: ignore from lnurl.types import LnurlPayMetadata # type: ignore
from sqlite3 import Row from sqlite3 import Row
from typing import NamedTuple, Optional, Dict from typing import NamedTuple, Optional, Dict
import shortuuid # type: ignore import shortuuid # type: ignore
from fastapi.param_functions import Query
from pydantic.main import BaseModel
from pydantic import BaseModel
from typing import Optional
class satsdiceLink(NamedTuple): class satsdiceLink(NamedTuple):
@@ -120,3 +123,36 @@ class HashCheck(NamedTuple):
@classmethod @classmethod
def from_row(cls, row: Row) -> "Hash": def from_row(cls, row: Row) -> "Hash":
return cls(**dict(row)) return cls(**dict(row))
class CreateSatsDiceLink(BaseModel):
wallet_id: str = Query(None)
title: str = Query(None)
base_url: str = Query(None)
min_bet: str = Query(None)
max_bet: str = Query(None)
multiplier: int = Query(0)
chance: float = Query(0)
haircut: int = Query(0)
class CreateSatsDicePayment(BaseModel):
satsdice_pay: str = Query(None)
value: int = Query(0)
payment_hash: str = Query(None)
class CreateSatsDiceWithdraw(BaseModel):
payment_hash: str = Query(None)
satsdice_pay: str = Query(None)
value: int = Query(0)
used: int = Query(0)
class CreateSatsDiceWithdraws(BaseModel):
title: str = Query(None)
min_satsdiceable: int = Query(0)
max_satsdiceable: int = Query(0)
uses: int = Query(0)
wait_time: str = Query(None)
is_unique: bool = Query(False)

View File

@@ -262,8 +262,7 @@
</div> </div>
{% endblock %} {% block scripts %} {{ window_vars(user) }} {% endblock %} {% block scripts %} {{ window_vars(user) }}
<script src="{{ url_for('static', filename='vendor/vue-qrcode@1.0.2/vue-qrcode.min.js') }}"></script>
<style></style>
<script> <script>
/* globals Quasar, Vue, _, VueQrcode, windowMixin, LNbits, LOCALE */ /* globals Quasar, Vue, _, VueQrcode, windowMixin, LNbits, LOCALE */
Vue.component(VueQrcode.name, VueQrcode) Vue.component(VueQrcode.name, VueQrcode)

View File

@@ -1,13 +1,7 @@
from quart import g, abort, render_template from datetime import datetime
from http import HTTPStatus from http import HTTPStatus
import pyqrcode from lnbits.decorators import check_user_exists, WalletTypeInfo, get_key_type
from io import BytesIO from . import satsdice_ext, satsdice_renderer
from lnbits.decorators import check_user_exists, validate_uuids
from lnbits.core.crud import get_user, get_standalone_payment
from lnbits.core.services import check_invoice_status
import random
from . import satsdice_ext
from .crud import ( from .crud import (
get_satsdice_pay, get_satsdice_pay,
update_satsdice_payment, update_satsdice_payment,
@@ -15,30 +9,40 @@ from .crud import (
create_satsdice_withdraw, create_satsdice_withdraw,
get_satsdice_withdraw, get_satsdice_withdraw,
) )
from fastapi import FastAPI, Request
from fastapi.params import Depends
from fastapi.templating import Jinja2Templates
from starlette.exceptions import HTTPException
from starlette.responses import HTMLResponse
from lnbits.core.models import User, Payment
from .views_api import api_get_jukebox_device_check
@satsdice_ext.route("/") templates = Jinja2Templates(directory="templates")
@validate_uuids(["usr"], required=True)
@check_user_exists()
async def index():
return await render_template("satsdice/index.html", user=g.user)
@satsdice_ext.route("/<link_id>") @satsdice_ext.get("/", response_class=HTMLResponse)
async def index(request: Request, user: User = Depends(check_user_exists)):
return satsdice_renderer().TemplateResponse(
"satsdice/index.html", {"request": request, "user": user.dict()}
)
@satsdice_ext.get("/{link_id}")
async def display(link_id): async def display(link_id):
link = await get_satsdice_pay(link_id) or abort( link = await get_satsdice_pay(link_id) or abort(
HTTPStatus.NOT_FOUND, "satsdice link does not exist." HTTPStatus.NOT_FOUND, "satsdice link does not exist."
) )
return await render_template( return satsdice_renderer().TemplateResponse(
"satsdice/display.html", "satsdice/display.html",
chance=link.chance, chance=link.chance,
multiplier=link.multiplier, multiplier=link.multiplier,
lnurl=link.lnurl, lnurl=link.lnurl,
unique=True, unique=True,{"request": request, "user": user.dict()}
) )
@satsdice_ext.route("/win/<link_id>/<payment_hash>") @satsdice_ext.get("/win/{link_id}/{payment_hash}")
async def displaywin(link_id, payment_hash): async def displaywin(link_id, payment_hash):
satsdicelink = await get_satsdice_pay(link_id) or abort( satsdicelink = await get_satsdice_pay(link_id) or abort(
HTTPStatus.NOT_FOUND, "satsdice link does not exist." HTTPStatus.NOT_FOUND, "satsdice link does not exist."
@@ -46,14 +50,14 @@ async def displaywin(link_id, payment_hash):
withdrawLink = await get_satsdice_withdraw(payment_hash) withdrawLink = await get_satsdice_withdraw(payment_hash)
if withdrawLink: if withdrawLink:
return await render_template( return satsdice_renderer().TemplateResponse(
"satsdice/displaywin.html", "satsdice/displaywin.html",
value=withdrawLink.value, value=withdrawLink.value,
chance=satsdicelink.chance, chance=satsdicelink.chance,
multiplier=satsdicelink.multiplier, multiplier=satsdicelink.multiplier,
lnurl=withdrawLink.lnurl, lnurl=withdrawLink.lnurl,
paid=False, paid=False,
lost=False, lost=False
) )
payment = await get_standalone_payment(payment_hash) or abort( payment = await get_standalone_payment(payment_hash) or abort(
@@ -67,8 +71,9 @@ async def displaywin(link_id, payment_hash):
) )
if payment.pending == 1: if payment.pending == 1:
print("pending") print("pending")
return await render_template( return satsdice_renderer().TemplateResponse(
"satsdice/error.html", link=satsdicelink.id, paid=False, lost=False "satsdice/error.html",
link=satsdicelink.id, paid=False, lost=False
) )
await update_satsdice_payment(payment_hash, paid=1) await update_satsdice_payment(payment_hash, paid=1)
@@ -79,15 +84,18 @@ async def displaywin(link_id, payment_hash):
if paylink.lost == 1: if paylink.lost == 1:
print("lost") print("lost")
return await render_template( return satsdice_renderer().TemplateResponse(
"satsdice/error.html", link=satsdicelink.id, paid=False, lost=True "satsdice/error.html",
link=satsdicelink.id, paid=False, lost=True
) )
rand = random.randint(0, 100) rand = random.randint(0, 100)
chance = satsdicelink.chance chance = satsdicelink.chance
if rand > chance: if rand > chance:
await update_satsdice_payment(payment_hash, lost=1) await update_satsdice_payment(payment_hash, lost=1)
return await render_template(
"satsdice/error.html", link=satsdicelink.id, paid=False, lost=True return satsdice_renderer().TemplateResponse(
"satsdice/error.html",
link=satsdicelink.id, paid=False, lost=True
) )
withdrawLink = await create_satsdice_withdraw( withdrawLink = await create_satsdice_withdraw(
@@ -96,8 +104,7 @@ async def displaywin(link_id, payment_hash):
value=paylink.value * satsdicelink.multiplier, value=paylink.value * satsdicelink.multiplier,
used=0, used=0,
) )
return satsdice_renderer().TemplateResponse(
return await render_template(
"satsdice/displaywin.html", "satsdice/displaywin.html",
value=withdrawLink.value, value=withdrawLink.value,
chance=satsdicelink.chance, chance=satsdicelink.chance,
@@ -108,7 +115,7 @@ async def displaywin(link_id, payment_hash):
) )
@satsdice_ext.route("/img/<link_id>") @satsdice_ext.get("/img/{link_id}")
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) or abort(
HTTPStatus.NOT_FOUND, "satsdice link does not exist." HTTPStatus.NOT_FOUND, "satsdice link does not exist."
@@ -124,5 +131,5 @@ async def img(link_id):
"Cache-Control": "no-cache, no-store, must-revalidate", "Cache-Control": "no-cache, no-store, must-revalidate",
"Pragma": "no-cache", "Pragma": "no-cache",
"Expires": "0", "Expires": "0",
}, }
) )

View File

@@ -1,11 +1,14 @@
from quart import g, jsonify, request
from http import HTTPStatus from http import HTTPStatus
from lnurl.exceptions import InvalidUrl as LnurlInvalidUrl # type: ignore from lnurl.exceptions import InvalidUrl as LnurlInvalidUrl # type: ignore
from http import HTTPStatus
from starlette.exceptions import HTTPException
from starlette.responses import HTMLResponse, JSONResponse # type: ignore
from lnbits.core.crud import get_user from lnbits.core.crud import get_user
from lnbits.decorators import api_check_wallet_key, api_validate_post_request from lnbits.decorators import api_validate_post_request
from .models import CreateSatsDiceLink, CreateSatsDiceWithdraws
from . import satsdice_ext from . import satsdice_ext
from fastapi import FastAPI, Request
from fastapi.params import Depends
from .crud import ( from .crud import (
create_satsdice_pay, create_satsdice_pay,
get_satsdice_pay, get_satsdice_pay,
@@ -19,105 +22,105 @@ from .crud import (
delete_satsdice_withdraw, delete_satsdice_withdraw,
create_withdraw_hash_check, create_withdraw_hash_check,
) )
from lnbits.decorators import (
check_user_exists,
WalletTypeInfo,
get_key_type,
api_validate_post_request,
)
################LNURL pay ################LNURL pay
@satsdice_ext.route("/api/v1/links", methods=["GET"]) @satsdice_ext.get("/api/v1/links")
@api_check_wallet_key("invoice") async def api_links(wallet: WalletTypeInfo = Depends(get_key_type)):
async def api_links(): wallet_ids = [wallet.wallet.id]
wallet_ids = [g.wallet.id]
if "all_wallets" in request.args: if "all_wallets" in request.args:
wallet_ids = (await get_user(g.wallet.user)).wallet_ids wallet_ids = (await get_user(wallet.wallet.user)).wallet_ids
try: try:
return ( return [
jsonify( {**link._dict(), **{"lnurl": link.lnurl}}
[
{**link._asdict(), **{"lnurl": link.lnurl}}
for link in await get_satsdice_pays(wallet_ids) for link in await get_satsdice_pays(wallet_ids)
] ]
),
HTTPStatus.OK,
)
except LnurlInvalidUrl: except LnurlInvalidUrl:
return ( raise HTTPException(
jsonify( status_code=HTTPStatus.UPGRADE_REQUIRED,
{ detail="LNURLs need to be delivered over a publically accessible `https` domain or Tor.",
"message": "LNURLs need to be delivered over a publically accessible `https` domain or Tor."
}
),
HTTPStatus.UPGRADE_REQUIRED,
) )
@satsdice_ext.route("/api/v1/links/<link_id>", methods=["GET"]) @satsdice_ext.get("/api/v1/links/{link_id}")
@api_check_wallet_key("invoice") async def api_link_retrieve(data: CreateSatsDiceLink, link_id: str = Query(None)):
async def api_link_retrieve(link_id):
link = await get_satsdice_pay(link_id) link = await get_satsdice_pay(link_id)
if not link: if not link:
return jsonify({"message": "Pay link does not exist."}), HTTPStatus.NOT_FOUND raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail="Pay link does not exist.",
)
if link.wallet != g.wallet.id: if link.wallet != g.wallet.id:
return jsonify({"message": "Not your pay link."}), HTTPStatus.FORBIDDEN raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="Not your pay link.",
)
return jsonify({**link._asdict(), **{"lnurl": link.lnurl}}), HTTPStatus.OK return {**link._asdict(), **{"lnurl": link.lnurl}}
@satsdice_ext.route("/api/v1/links", methods=["POST"]) @satsdice_ext.post("/api/v1/links", status_code=HTTPStatus.CREATED)
@satsdice_ext.route("/api/v1/links/<link_id>", methods=["PUT"]) @satsdice_ext.put("/api/v1/links/{link_id}", status_code=HTTPStatus.OK)
@api_check_wallet_key("invoice") async def api_link_create_or_update(
@api_validate_post_request( data: CreateSatsDiceLink,
schema={ wallet: WalletTypeInfo = Depends(get_key_type),
"title": {"type": "string", "empty": False, "required": True}, link_id: str = Query(None),
"base_url": {"type": "string", "empty": False, "required": True}, ):
"min_bet": {"type": "number", "required": True}, if data.min_bet > data.max_bet:
"max_bet": {"type": "number", "required": True}, raise HTTPException(
"multiplier": {"type": "number", "required": True}, status_code=HTTPStatus.BAD_REQUEST,
"chance": {"type": "float", "required": True}, detail="Bad request",
"haircut": {"type": "number", "required": True}, )
}
)
async def api_link_create_or_update(link_id=None):
if g.data["min_bet"] > g.data["max_bet"]:
return jsonify({"message": "Min is greater than max."}), HTTPStatus.BAD_REQUEST
if link_id: if link_id:
link = await get_satsdice_pay(link_id) link = await get_satsdice_pay(link_id)
if not link: if not link:
return ( raise HTTPException(
jsonify({"message": "Satsdice does not exist."}), status_code=HTTPStatus.NOT_FOUND,
HTTPStatus.NOT_FOUND, detail="Satsdice does not exist",
) )
if link.wallet != g.wallet.id: if link.wallet != wallet.wallet.id:
return ( raise HTTPException(
jsonify({"message": "Come on, seriously, this isn't your satsdice!"}), status_code=HTTPStatus.FORBIDDEN,
HTTPStatus.FORBIDDEN, detail="Come on, seriously, this isn't your satsdice!",
) )
link = await update_satsdice_pay(link_id, **g.data) link = await update_satsdice_pay(data, link_id)
else: else:
link = await create_satsdice_pay(wallet_id=g.wallet.id, **g.data) link = await create_satsdice_pay(data, wallet_id=wallet.wallet.id)
return ( return {**link.dict(), **{"lnurl": link.lnurl}}
jsonify({**link._asdict(), **{"lnurl": link.lnurl}}),
HTTPStatus.OK if link_id else HTTPStatus.CREATED,
)
@satsdice_ext.route("/api/v1/links/<link_id>", methods=["DELETE"]) @satsdice_ext.delete("/api/v1/links/{link_id}")
@api_check_wallet_key("invoice") async def api_link_delete(
async def api_link_delete(link_id): wallet: WalletTypeInfo = Depends(get_key_type), 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:
return jsonify({"message": "Pay link does not exist."}), HTTPStatus.NOT_FOUND raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail="Pay link does not exist.",
)
if link.wallet != g.wallet.id: if link.wallet != g.wallet.id:
return jsonify({"message": "Not your pay link."}), HTTPStatus.FORBIDDEN raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="Not your pay link.",
)
await delete_satsdice_pay(link_id) await delete_satsdice_pay(link_id)
@@ -127,13 +130,12 @@ async def api_link_delete(link_id):
##########LNURL withdraw ##########LNURL withdraw
@satsdice_ext.route("/api/v1/withdraws", methods=["GET"]) @satsdice_ext.get("/api/v1/withdraws")
@api_check_wallet_key("invoice") async def api_withdraws(wallet: WalletTypeInfo = Depends(get_key_type)):
async def api_withdraws(): wallet_ids = [wallet.wallet.id]
wallet_ids = [g.wallet.id]
if "all_wallets" in request.args: if "all_wallets" in request.args:
wallet_ids = (await get_user(g.wallet.user)).wallet_ids wallet_ids = (await get_user(wallet.wallet.user)).wallet_ids
try: try:
return ( return (
jsonify( jsonify(
@@ -148,58 +150,44 @@ async def api_withdraws():
HTTPStatus.OK, HTTPStatus.OK,
) )
except LnurlInvalidUrl: except LnurlInvalidUrl:
return ( raise HTTPException(
jsonify( status_code=HTTPStatus.UPGRADE_REQUIRED,
{ detail="LNURLs need to be delivered over a publically accessible `https` domain or Tor.",
"message": "LNURLs need to be delivered over a publically accessible `https` domain or Tor."
}
),
HTTPStatus.UPGRADE_REQUIRED,
) )
@satsdice_ext.route("/api/v1/withdraws/<withdraw_id>", methods=["GET"]) @satsdice_ext.get("/api/v1/withdraws/{withdraw_id}")
@api_check_wallet_key("invoice") async def api_withdraw_retrieve(
async def api_withdraw_retrieve(withdraw_id): wallet: WalletTypeInfo = Depends(get_key_type), withdraw_id: str = Query(None)
):
withdraw = await get_satsdice_withdraw(withdraw_id, 0) withdraw = await get_satsdice_withdraw(withdraw_id, 0)
if not withdraw: if not withdraw:
return ( raise HTTPException(
jsonify({"message": "satsdice withdraw does not exist."}), status_code=HTTPStatus.NOT_FOUND,
HTTPStatus.NOT_FOUND, detail="satsdice withdraw does not exist.",
) )
if withdraw.wallet != g.wallet.id: if withdraw.wallet != g.wallet.id:
return ( raise HTTPException(
jsonify({"message": "Not your satsdice withdraw."}), status_code=HTTPStatus.FORBIDDEN,
HTTPStatus.FORBIDDEN, detail="Not your satsdice withdraw.",
) )
return jsonify({**withdraw._asdict(), **{"lnurl": withdraw.lnurl}}), HTTPStatus.OK return {**withdraw._asdict(), **{"lnurl": withdraw.lnurl}}, HTTPStatus.OK
@satsdice_ext.route("/api/v1/withdraws", methods=["POST"]) @satsdice_ext.post("/api/v1/withdraws", status_code=HTTPStatus.CREATED)
@satsdice_ext.route("/api/v1/withdraws/<withdraw_id>", methods=["PUT"]) @satsdice_ext.put("/api/v1/withdraws/{withdraw_id}", status_code=HTTPStatus.OK)
@api_check_wallet_key("admin") async def api_withdraw_create_or_update(
@api_validate_post_request( data: CreateSatsDiceWithdraws,
schema={ wallet: WalletTypeInfo = Depends(get_key_type),
"title": {"type": "string", "empty": False, "required": True}, withdraw_id: str = Query(None),
"min_satsdiceable": {"type": "integer", "min": 1, "required": True}, ):
"max_satsdiceable": {"type": "integer", "min": 1, "required": True}, if data.max_satsdiceable < data.min_satsdiceable:
"uses": {"type": "integer", "min": 1, "required": True}, raise HTTPException(
"wait_time": {"type": "integer", "min": 1, "required": True}, status_code=HTTPStatus.BAD_REQUEST,
"is_unique": {"type": "boolean", "required": True}, detail="`max_satsdiceable` needs to be at least `min_satsdiceable`.",
}
)
async def api_withdraw_create_or_update(withdraw_id=None):
if g.data["max_satsdiceable"] < g.data["min_satsdiceable"]:
return (
jsonify(
{
"message": "`max_satsdiceable` needs to be at least `min_satsdiceable`."
}
),
HTTPStatus.BAD_REQUEST,
) )
usescsv = "" usescsv = ""
@@ -213,15 +201,16 @@ async def api_withdraw_create_or_update(withdraw_id=None):
if withdraw_id: if withdraw_id:
withdraw = await get_satsdice_withdraw(withdraw_id, 0) withdraw = await get_satsdice_withdraw(withdraw_id, 0)
if not withdraw: if not withdraw:
return ( raise HTTPException(
jsonify({"message": "satsdice withdraw does not exist."}), status_code=HTTPStatus.NOT_FOUND,
HTTPStatus.NOT_FOUND, detail="satsdice withdraw does not exist.",
) )
if withdraw.wallet != g.wallet.id: if withdraw.wallet != g.wallet.id:
return ( raise HTTPException(
jsonify({"message": "Not your satsdice withdraw."}), status_code=HTTPStatus.FORBIDDEN,
HTTPStatus.FORBIDDEN, detail="Not your satsdice withdraw.",
) )
withdraw = await update_satsdice_withdraw( withdraw = await update_satsdice_withdraw(
withdraw_id, **g.data, usescsv=usescsv, used=0 withdraw_id, **g.data, usescsv=usescsv, used=0
) )
@@ -230,27 +219,27 @@ async def api_withdraw_create_or_update(withdraw_id=None):
wallet_id=g.wallet.id, **g.data, usescsv=usescsv wallet_id=g.wallet.id, **g.data, usescsv=usescsv
) )
return ( return {**withdraw._asdict(), **{"lnurl": withdraw.lnurl}}
jsonify({**withdraw._asdict(), **{"lnurl": withdraw.lnurl}}),
HTTPStatus.OK if withdraw_id else HTTPStatus.CREATED,
)
@satsdice_ext.route("/api/v1/withdraws/<withdraw_id>", methods=["DELETE"]) @satsdice_ext.delete("/api/v1/withdraws/{withdraw_id}")
@api_check_wallet_key("admin") async def api_withdraw_delete(
async def api_withdraw_delete(withdraw_id): data: CreateSatsDiceWithdraws,
wallet: WalletTypeInfo = Depends(get_key_type),
withdraw_id: str = Query(None),
):
withdraw = await get_satsdice_withdraw(withdraw_id) withdraw = await get_satsdice_withdraw(withdraw_id)
if not withdraw: if not withdraw:
return ( raise HTTPException(
jsonify({"message": "satsdice withdraw does not exist."}), status_code=HTTPStatus.NOT_FOUND,
HTTPStatus.NOT_FOUND, detail="satsdice withdraw does not exist.",
) )
if withdraw.wallet != g.wallet.id: if withdraw.wallet != wallet.wallet.id:
return ( raise HTTPException(
jsonify({"message": "Not your satsdice withdraw."}), status_code=HTTPStatus.FORBIDDEN,
HTTPStatus.FORBIDDEN, detail="Not your satsdice withdraw.",
) )
await delete_satsdice_withdraw(withdraw_id) await delete_satsdice_withdraw(withdraw_id)
@@ -258,8 +247,11 @@ async def api_withdraw_delete(withdraw_id):
return "", HTTPStatus.NO_CONTENT return "", HTTPStatus.NO_CONTENT
@satsdice_ext.route("/api/v1/withdraws/<the_hash>/<lnurl_id>", methods=["GET"]) @satsdice_ext.get("/api/v1/withdraws/{the_hash}/{lnurl_id}")
@api_check_wallet_key("invoice") async def api_withdraw_hash_retrieve(
async def api_withdraw_hash_retrieve(the_hash, lnurl_id): wallet: WalletTypeInfo = Depends(get_key_type),
lnurl_id: str = Query(None),
the_hash: str = Query(None),
):
hashCheck = await get_withdraw_hash_check(the_hash, lnurl_id) hashCheck = await get_withdraw_hash_check(the_hash, lnurl_id)
return jsonify(hashCheck), HTTPStatus.OK return hashCheck