migrate to sqlalchemy-aio.

a big refactor that:

- fixes some issues that might have happened (or not) with asynchronous
    reactions to payments;
- paves the way to https://github.com/lnbits/lnbits/issues/121;
- uses more async/await notation which just looks nice; and
- makes it simple(r?) for one extension to modify stuff from other extensions.
This commit is contained in:
fiatjaf
2020-11-21 23:02:14 -03:00
parent f877dde2b0
commit d3fc52cd49
68 changed files with 971 additions and 1075 deletions
+2
View File
@@ -1,5 +1,7 @@
from quart import Blueprint
from lnbits.db import Database
db = Database("ext_paywall")
paywall_ext: Blueprint = Blueprint("paywall", __name__, static_folder="static", template_folder="templates")
+20 -22
View File
@@ -1,45 +1,43 @@
from typing import List, Optional, Union
from lnbits.db import open_ext_db
from lnbits.helpers import urlsafe_short_hash
from . import db
from .models import Paywall
def create_paywall(
async def create_paywall(
*, wallet_id: str, url: str, memo: str, description: Optional[str] = None, amount: int = 0, remembers: bool = True
) -> Paywall:
with open_ext_db("paywall") as db:
paywall_id = urlsafe_short_hash()
db.execute(
"""
INSERT INTO paywalls (id, wallet, url, memo, description, amount, remembers)
VALUES (?, ?, ?, ?, ?, ?, ?)
""",
(paywall_id, wallet_id, url, memo, description, amount, int(remembers)),
)
paywall_id = urlsafe_short_hash()
await db.execute(
"""
INSERT INTO paywalls (id, wallet, url, memo, description, amount, remembers)
VALUES (?, ?, ?, ?, ?, ?, ?)
""",
(paywall_id, wallet_id, url, memo, description, amount, int(remembers)),
)
return get_paywall(paywall_id)
paywall = await get_paywall(paywall_id)
assert paywall, "Newly created paywall couldn't be retrieved"
return paywall
def get_paywall(paywall_id: str) -> Optional[Paywall]:
with open_ext_db("paywall") as db:
row = db.fetchone("SELECT * FROM paywalls WHERE id = ?", (paywall_id,))
async def get_paywall(paywall_id: str) -> Optional[Paywall]:
row = await db.fetchone("SELECT * FROM paywalls WHERE id = ?", (paywall_id,))
return Paywall.from_row(row) if row else None
def get_paywalls(wallet_ids: Union[str, List[str]]) -> List[Paywall]:
async def get_paywalls(wallet_ids: Union[str, List[str]]) -> List[Paywall]:
if isinstance(wallet_ids, str):
wallet_ids = [wallet_ids]
with open_ext_db("paywall") as db:
q = ",".join(["?"] * len(wallet_ids))
rows = db.fetchall(f"SELECT * FROM paywalls WHERE wallet IN ({q})", (*wallet_ids,))
q = ",".join(["?"] * len(wallet_ids))
rows = await db.fetchall(f"SELECT * FROM paywalls WHERE wallet IN ({q})", (*wallet_ids,))
return [Paywall.from_row(row) for row in rows]
def delete_paywall(paywall_id: str) -> None:
with open_ext_db("paywall") as db:
db.execute("DELETE FROM paywalls WHERE id = ?", (paywall_id,))
async def delete_paywall(paywall_id: str) -> None:
await db.execute("DELETE FROM paywalls WHERE id = ?", (paywall_id,))
+11 -11
View File
@@ -1,11 +1,11 @@
from sqlite3 import OperationalError
from sqlalchemy.exc import OperationalError # type: ignore
def m001_initial(db):
async def m001_initial(db):
"""
Initial paywalls table.
"""
db.execute(
await db.execute(
"""
CREATE TABLE IF NOT EXISTS paywalls (
id TEXT PRIMARY KEY,
@@ -20,16 +20,16 @@ def m001_initial(db):
)
def m002_redux(db):
async def m002_redux(db):
"""
Creates an improved paywalls table and migrates the existing data.
"""
try:
db.execute("SELECT remembers FROM paywalls")
await db.execute("SELECT remembers FROM paywalls")
except OperationalError:
db.execute("ALTER TABLE paywalls RENAME TO paywalls_old")
db.execute(
await db.execute("ALTER TABLE paywalls RENAME TO paywalls_old")
await db.execute(
"""
CREATE TABLE IF NOT EXISTS paywalls (
id TEXT PRIMARY KEY,
@@ -44,10 +44,10 @@ def m002_redux(db):
);
"""
)
db.execute("CREATE INDEX IF NOT EXISTS wallet_idx ON paywalls (wallet)")
await db.execute("CREATE INDEX IF NOT EXISTS wallet_idx ON paywalls (wallet)")
for row in [list(row) for row in db.fetchall("SELECT * FROM paywalls_old")]:
db.execute(
for row in [list(row) for row in await db.fetchall("SELECT * FROM paywalls_old")]:
await db.execute(
"""
INSERT INTO paywalls (
id,
@@ -62,4 +62,4 @@ def m002_redux(db):
(row[0], row[1], row[3], row[4], row[5], row[6]),
)
db.execute("DROP TABLE paywalls_old")
await db.execute("DROP TABLE paywalls_old")
+2 -2
View File
@@ -3,7 +3,7 @@ from http import HTTPStatus
from lnbits.decorators import check_user_exists, validate_uuids
from lnbits.extensions.paywall import paywall_ext
from . import paywall_ext
from .crud import get_paywall
@@ -16,5 +16,5 @@ async def index():
@paywall_ext.route("/<paywall_id>")
async def display(paywall_id):
paywall = get_paywall(paywall_id) or abort(HTTPStatus.NOT_FOUND, "Paywall does not exist.")
paywall = await get_paywall(paywall_id) or abort(HTTPStatus.NOT_FOUND, "Paywall does not exist.")
return await render_template("paywall/display.html", paywall=paywall)
+14 -14
View File
@@ -5,7 +5,7 @@ from lnbits.core.crud import get_user, get_wallet
from lnbits.core.services import create_invoice, check_invoice_status
from lnbits.decorators import api_check_wallet_key, api_validate_post_request
from lnbits.extensions.paywall import paywall_ext
from . import paywall_ext
from .crud import create_paywall, get_paywall, get_paywalls, delete_paywall
@@ -15,9 +15,9 @@ async def api_paywalls():
wallet_ids = [g.wallet.id]
if "all_wallets" in request.args:
wallet_ids = get_user(g.wallet.user).wallet_ids
wallet_ids = (await get_user(g.wallet.user)).wallet_ids
return jsonify([paywall._asdict() for paywall in get_paywalls(wallet_ids)]), HTTPStatus.OK
return jsonify([paywall._asdict() for paywall in await get_paywalls(wallet_ids)]), HTTPStatus.OK
@paywall_ext.route("/api/v1/paywalls", methods=["POST"])
@@ -32,15 +32,14 @@ async def api_paywalls():
}
)
async def api_paywall_create():
paywall = create_paywall(wallet_id=g.wallet.id, **g.data)
paywall = await create_paywall(wallet_id=g.wallet.id, **g.data)
return jsonify(paywall._asdict()), HTTPStatus.CREATED
@paywall_ext.route("/api/v1/paywalls/<paywall_id>", methods=["DELETE"])
@api_check_wallet_key("invoice")
async def api_paywall_delete(paywall_id):
paywall = get_paywall(paywall_id)
paywall = await get_paywall(paywall_id)
if not paywall:
return jsonify({"message": "Paywall does not exist."}), HTTPStatus.NOT_FOUND
@@ -48,7 +47,7 @@ async def api_paywall_delete(paywall_id):
if paywall.wallet != g.wallet.id:
return jsonify({"message": "Not your paywall."}), HTTPStatus.FORBIDDEN
delete_paywall(paywall_id)
await delete_paywall(paywall_id)
return "", HTTPStatus.NO_CONTENT
@@ -56,14 +55,14 @@ async def api_paywall_delete(paywall_id):
@paywall_ext.route("/api/v1/paywalls/<paywall_id>/invoice", methods=["POST"])
@api_validate_post_request(schema={"amount": {"type": "integer", "min": 1, "required": True}})
async def api_paywall_create_invoice(paywall_id):
paywall = get_paywall(paywall_id)
paywall = await get_paywall(paywall_id)
if g.data["amount"] < paywall.amount:
return jsonify({"message": f"Minimum amount is {paywall.amount} sat."}), HTTPStatus.BAD_REQUEST
try:
amount = g.data["amount"] if g.data["amount"] > paywall.amount else paywall.amount
payment_hash, payment_request = create_invoice(
payment_hash, payment_request = await create_invoice(
wallet_id=paywall.wallet, amount=amount, memo=f"{paywall.memo}", extra={"tag": "paywall"}
)
except Exception as e:
@@ -75,20 +74,21 @@ async def api_paywall_create_invoice(paywall_id):
@paywall_ext.route("/api/v1/paywalls/<paywall_id>/check_invoice", methods=["POST"])
@api_validate_post_request(schema={"payment_hash": {"type": "string", "empty": False, "required": True}})
async def api_paywal_check_invoice(paywall_id):
paywall = get_paywall(paywall_id)
paywall = await get_paywall(paywall_id)
if not paywall:
return jsonify({"message": "Paywall does not exist."}), HTTPStatus.NOT_FOUND
try:
is_paid = not check_invoice_status(paywall.wallet, g.data["payment_hash"]).pending
status = await check_invoice_status(paywall.wallet, g.data["payment_hash"])
is_paid = not status.pending
except Exception:
return jsonify({"paid": False}), HTTPStatus.OK
if is_paid:
wallet = get_wallet(paywall.wallet)
payment = wallet.get_payment(g.data["payment_hash"])
payment.set_pending(False)
wallet = await get_wallet(paywall.wallet)
payment = await wallet.get_payment(g.data["payment_hash"])
await payment.set_pending(False)
return jsonify({"paid": True, "url": paywall.url, "remembers": paywall.remembers}), HTTPStatus.OK