Browse Source

run black on everything.

aiosqlite
fiatjaf 4 years ago
parent
commit
660d56d400
  1. 5
      Makefile
  2. 9
      lnbits/__init__.py
  3. 2
      lnbits/extensions/amilk/crud.py
  4. 6
      lnbits/extensions/amilk/migrations.py
  5. 8
      lnbits/extensions/amilk/views_api.py
  6. 72
      lnbits/extensions/diagonalley/crud.py
  7. 22
      lnbits/extensions/diagonalley/migrations.py
  8. 5
      lnbits/extensions/diagonalley/models.py
  9. 74
      lnbits/extensions/diagonalley/views_api.py
  10. 31
      lnbits/extensions/events/crud.py
  11. 13
      lnbits/extensions/events/migrations.py
  12. 1
      lnbits/extensions/events/models.py
  13. 18
      lnbits/extensions/events/views.py
  14. 32
      lnbits/extensions/events/views_api.py
  15. 19
      lnbits/extensions/example/views_api.py
  16. 8
      lnbits/extensions/lnticket/crud.py
  17. 13
      lnbits/extensions/lnticket/migrations.py
  18. 1
      lnbits/extensions/lnticket/models.py
  19. 8
      lnbits/extensions/lnticket/views.py
  20. 24
      lnbits/extensions/lnticket/views_api.py
  21. 16
      lnbits/extensions/usermanager/crud.py
  22. 15
      lnbits/extensions/usermanager/migrations.py
  23. 4
      lnbits/extensions/usermanager/models.py
  24. 48
      lnbits/extensions/usermanager/views_api.py
  25. 3
      lnbits/extensions/withdraw/crud.py
  26. 13
      lnbits/extensions/withdraw/migrations.py
  27. 8
      lnbits/extensions/withdraw/models.py
  28. 14
      lnbits/helpers.py

5
Makefile

@ -1,5 +1,10 @@
all: prettier mypy black
prettier: $(shell find lnbits -name "*.js" -name ".html") prettier: $(shell find lnbits -name "*.js" -name ".html")
./node_modules/.bin/prettier --write lnbits/static/js/*.js lnbits/core/static/js/*.js lnbits/extensions/*/templates/*/*.html ./lnbits/core/templates/core/*.html lnbits/templates/*.html lnbits/extensions/*/static/js/*.js ./node_modules/.bin/prettier --write lnbits/static/js/*.js lnbits/core/static/js/*.js lnbits/extensions/*/templates/*/*.html ./lnbits/core/templates/core/*.html lnbits/templates/*.html lnbits/extensions/*/static/js/*.js
mypy: $(shell find lnbits -name "*.py") mypy: $(shell find lnbits -name "*.py")
mypy lnbits mypy lnbits
mypy: $(shell find lnbits -name "*.py")
black lnbits

9
lnbits/__init__.py

@ -29,13 +29,7 @@ Talisman(
app, app,
force_https=FORCE_HTTPS, force_https=FORCE_HTTPS,
content_security_policy={ content_security_policy={
"default-src": [ "default-src": ["'self'", "'unsafe-eval'", "'unsafe-inline'", "blob:", "api.opennode.co",]
"'self'",
"'unsafe-eval'",
"'unsafe-inline'",
"blob:",
"api.opennode.co",
]
}, },
) )
@ -72,6 +66,7 @@ assets.register("base_css", Bundle("scss/base.scss", filters="pyscss", output="c
# commands # commands
# -------- # --------
@app.cli.command("migrate") @app.cli.command("migrate")
def migrate_databases(): def migrate_databases():
"""Creates the necessary databases if they don't exist already; or migrates them.""" """Creates the necessary databases if they don't exist already; or migrates them."""

2
lnbits/extensions/amilk/crud.py

@ -9,7 +9,7 @@ from .models import AMilk
def create_amilk(*, wallet_id: str, lnurl: str, atime: int, amount: int) -> AMilk: def create_amilk(*, wallet_id: str, lnurl: str, atime: int, amount: int) -> AMilk:
with open_ext_db("amilk") as db: with open_ext_db("amilk") as db:
amilk_id = urlsafe_b64encode(uuid4().bytes_le).decode('utf-8') amilk_id = urlsafe_b64encode(uuid4().bytes_le).decode("utf-8")
db.execute( db.execute(
""" """
INSERT INTO amilks (id, wallet, lnurl, atime, amount) INSERT INTO amilks (id, wallet, lnurl, atime, amount)

6
lnbits/extensions/amilk/migrations.py

@ -5,7 +5,8 @@ def m001_initial(db):
""" """
Initial amilks table. Initial amilks table.
""" """
db.execute(""" db.execute(
"""
CREATE TABLE IF NOT EXISTS amilks ( CREATE TABLE IF NOT EXISTS amilks (
id TEXT PRIMARY KEY, id TEXT PRIMARY KEY,
wallet TEXT NOT NULL, wallet TEXT NOT NULL,
@ -13,7 +14,8 @@ def m001_initial(db):
atime INTEGER NOT NULL, atime INTEGER NOT NULL,
amount INTEGER NOT NULL amount INTEGER NOT NULL
); );
""") """
)
def migrate(): def migrate():

8
lnbits/extensions/amilk/views_api.py

@ -15,6 +15,7 @@ from time import sleep
import requests import requests
from lnbits.settings import WALLET from lnbits.settings import WALLET
@amilk_ext.route("/api/v1/amilk", methods=["GET"]) @amilk_ext.route("/api/v1/amilk", methods=["GET"])
@api_check_wallet_key("invoice") @api_check_wallet_key("invoice")
def api_amilks(): def api_amilks():
@ -37,7 +38,6 @@ def api_amilkit(amilk_id):
abort(HTTPStatus.INTERNAL_SERVER_ERROR, "Could not process withdraw LNURL.") abort(HTTPStatus.INTERNAL_SERVER_ERROR, "Could not process withdraw LNURL.")
print(withdraw_res.max_sats) print(withdraw_res.max_sats)
try: try:
checking_id, payment_request = create_invoice(wallet_id=milk.wallet, amount=withdraw_res.max_sats, memo=memo) checking_id, payment_request = create_invoice(wallet_id=milk.wallet, amount=withdraw_res.max_sats, memo=memo)
# print(payment_request) # print(payment_request)
@ -67,11 +67,13 @@ def api_amilkit(amilk_id):
@amilk_ext.route("/api/v1/amilk", methods=["POST"]) @amilk_ext.route("/api/v1/amilk", methods=["POST"])
@api_check_wallet_key("invoice") @api_check_wallet_key("invoice")
@api_validate_post_request(schema={ @api_validate_post_request(
schema={
"lnurl": {"type": "string", "empty": False, "required": True}, "lnurl": {"type": "string", "empty": False, "required": True},
"atime": {"type": "integer", "min": 0, "required": True}, "atime": {"type": "integer", "min": 0, "required": True},
"amount": {"type": "integer", "min": 0, "required": True}, "amount": {"type": "integer", "min": 0, "required": True},
}) }
)
def api_amilk_create(): def api_amilk_create():
amilk = create_amilk(wallet_id=g.wallet.id, lnurl=g.data["lnurl"], atime=g.data["atime"], amount=g.data["amount"]) amilk = create_amilk(wallet_id=g.wallet.id, lnurl=g.data["lnurl"], atime=g.data["atime"], amount=g.data["amount"])

72
lnbits/extensions/diagonalley/crud.py

@ -6,19 +6,25 @@ from lnbits.db import open_ext_db
from lnbits.settings import WALLET from lnbits.settings import WALLET
from .models import Products, Orders, Indexers from .models import Products, Orders, Indexers
import re import re
regex = re.compile( regex = re.compile(
r'^(?:http|ftp)s?://' # http:// or https:// r"^(?:http|ftp)s?://" # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' r"(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|"
r'localhost|' r"localhost|"
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})"
r'(?::\d+)?' r"(?::\d+)?"
r'(?:/?|[/?]\S+)$', re.IGNORECASE) r"(?:/?|[/?]\S+)$",
re.IGNORECASE,
)
###Products ###Products
def create_diagonalleys_product(*, wallet_id: str, product: str, categories: str, description: str, image: str, price: int, quantity: int) -> Products:
def create_diagonalleys_product(
*, wallet_id: str, product: str, categories: str, description: str, image: str, price: int, quantity: int
) -> Products:
with open_ext_db("diagonalley") as db: with open_ext_db("diagonalley") as db:
product_id = urlsafe_b64encode(uuid4().bytes_le).decode('utf-8') product_id = urlsafe_b64encode(uuid4().bytes_le).decode("utf-8")
db.execute( db.execute(
""" """
INSERT INTO products (id, wallet, product, categories, description, image, price, quantity) INSERT INTO products (id, wallet, product, categories, description, image, price, quantity)
@ -63,19 +69,39 @@ def delete_diagonalleys_product(product_id: str) -> None:
db.execute("DELETE FROM products WHERE id = ?", (product_id,)) db.execute("DELETE FROM products WHERE id = ?", (product_id,))
###Indexers ###Indexers
def create_diagonalleys_indexer(wallet_id: str, shopname: str, indexeraddress: str, shippingzone1: str, shippingzone2: str, zone1cost: int, zone2cost: int, email: str) -> Indexers:
def create_diagonalleys_indexer(
wallet_id: str,
shopname: str,
indexeraddress: str,
shippingzone1: str,
shippingzone2: str,
zone1cost: int,
zone2cost: int,
email: str,
) -> Indexers:
with open_ext_db("diagonalley") as db: with open_ext_db("diagonalley") as db:
indexer_id = urlsafe_b64encode(uuid4().bytes_le).decode('utf-8') indexer_id = urlsafe_b64encode(uuid4().bytes_le).decode("utf-8")
db.execute( db.execute(
""" """
INSERT INTO indexers (id, wallet, shopname, indexeraddress, online, rating, shippingzone1, shippingzone2, zone1cost, zone2cost, email) INSERT INTO indexers (id, wallet, shopname, indexeraddress, online, rating, shippingzone1, shippingzone2, zone1cost, zone2cost, email)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", """,
(indexer_id, wallet_id, shopname, indexeraddress, False, 0, shippingzone1, shippingzone2, zone1cost, zone2cost, email), (
indexer_id,
wallet_id,
shopname,
indexeraddress,
False,
0,
shippingzone1,
shippingzone2,
zone1cost,
zone2cost,
email,
),
) )
return get_diagonalleys_indexer(indexer_id) return get_diagonalleys_indexer(indexer_id)
@ -140,12 +166,24 @@ def delete_diagonalleys_indexer(indexer_id: str) -> None:
db.execute("DELETE FROM indexers WHERE id = ?", (indexer_id,)) db.execute("DELETE FROM indexers WHERE id = ?", (indexer_id,))
###Orders ###Orders
def create_diagonalleys_order(*, productid: str, wallet: str, product: str, quantity: int, shippingzone: str, address: str, email: str, invoiceid: str, paid: bool, shipped: bool) -> Indexers:
with open_ext_db("diagonalley") as db: def create_diagonalleys_order(
order_id = urlsafe_b64encode(uuid4().bytes_le).decode('utf-8') *,
productid: str,
wallet: str,
product: str,
quantity: int,
shippingzone: str,
address: str,
email: str,
invoiceid: str,
paid: bool,
shipped: bool,
) -> Indexers:
with open_ext_db("diagonalley") as db:
order_id = urlsafe_b64encode(uuid4().bytes_le).decode("utf-8")
db.execute( db.execute(
""" """
INSERT INTO orders (id, productid, wallet, product, quantity, shippingzone, address, email, invoiceid, paid, shipped) INSERT INTO orders (id, productid, wallet, product, quantity, shippingzone, address, email, invoiceid, paid, shipped)

22
lnbits/extensions/diagonalley/migrations.py

@ -5,7 +5,8 @@ def m001_initial(db):
""" """
Initial products table. Initial products table.
""" """
db.execute(""" db.execute(
"""
CREATE TABLE IF NOT EXISTS products ( CREATE TABLE IF NOT EXISTS products (
id TEXT PRIMARY KEY, id TEXT PRIMARY KEY,
wallet TEXT NOT NULL, wallet TEXT NOT NULL,
@ -16,13 +17,14 @@ def m001_initial(db):
price INTEGER NOT NULL, price INTEGER NOT NULL,
quantity INTEGER NOT NULL quantity INTEGER NOT NULL
); );
""") """
)
""" """
Initial indexers table. Initial indexers table.
""" """
db.execute(""" db.execute(
"""
CREATE TABLE IF NOT EXISTS indexers ( CREATE TABLE IF NOT EXISTS indexers (
id TEXT PRIMARY KEY, id TEXT PRIMARY KEY,
wallet TEXT NOT NULL, wallet TEXT NOT NULL,
@ -36,13 +38,14 @@ def m001_initial(db):
zone2cost INTEGER NOT NULL, zone2cost INTEGER NOT NULL,
email TEXT NOT NULL email TEXT NOT NULL
); );
""") """
)
""" """
Initial orders table. Initial orders table.
""" """
db.execute(""" db.execute(
"""
CREATE TABLE IF NOT EXISTS orders ( CREATE TABLE IF NOT EXISTS orders (
id TEXT PRIMARY KEY, id TEXT PRIMARY KEY,
productid TEXT NOT NULL, productid TEXT NOT NULL,
@ -56,9 +59,10 @@ def m001_initial(db):
paid BOOLEAN NOT NULL, paid BOOLEAN NOT NULL,
shipped BOOLEAN NOT NULL shipped BOOLEAN NOT NULL
); );
""") """
)
def migrate(): def migrate():
with open_ext_db("diagonalley") as db: with open_ext_db("diagonalley") as db:
m001_initial(db) m001_initial(db)

5
lnbits/extensions/diagonalley/models.py

@ -1,5 +1,6 @@
from typing import NamedTuple from typing import NamedTuple
class Indexers(NamedTuple): class Indexers(NamedTuple):
id: str id: str
wallet: str wallet: str
@ -13,6 +14,7 @@ class Indexers(NamedTuple):
zone2cost: int zone2cost: int
email: str email: str
class Products(NamedTuple): class Products(NamedTuple):
id: str id: str
wallet: str wallet: str
@ -23,6 +25,7 @@ class Products(NamedTuple):
price: int price: int
quantity: int quantity: int
class Orders(NamedTuple): class Orders(NamedTuple):
id: str id: str
productid: str productid: str
@ -35,5 +38,3 @@ class Orders(NamedTuple):
invoiceid: str invoiceid: str
paid: bool paid: bool
shipped: bool shipped: bool

74
lnbits/extensions/diagonalley/views_api.py

@ -5,7 +5,21 @@ from lnbits.core.crud import get_user
from lnbits.decorators import api_check_wallet_key, api_validate_post_request from lnbits.decorators import api_check_wallet_key, api_validate_post_request
from lnbits.extensions.diagonalley import diagonalley_ext from lnbits.extensions.diagonalley import diagonalley_ext
from .crud import create_diagonalleys_product,get_diagonalleys_product,get_diagonalleys_products,delete_diagonalleys_product,create_diagonalleys_indexer,update_diagonalleys_indexer,get_diagonalleys_indexer,get_diagonalleys_indexers,delete_diagonalleys_indexer,create_diagonalleys_order,get_diagonalleys_order,get_diagonalleys_orders,delete_diagonalleys_order from .crud import (
create_diagonalleys_product,
get_diagonalleys_product,
get_diagonalleys_products,
delete_diagonalleys_product,
create_diagonalleys_indexer,
update_diagonalleys_indexer,
get_diagonalleys_indexer,
get_diagonalleys_indexers,
delete_diagonalleys_indexer,
create_diagonalleys_order,
get_diagonalleys_order,
get_diagonalleys_orders,
delete_diagonalleys_order,
)
from lnbits.core.services import create_invoice from lnbits.core.services import create_invoice
from base64 import urlsafe_b64encode from base64 import urlsafe_b64encode
from uuid import uuid4 from uuid import uuid4
@ -13,6 +27,7 @@ from lnbits.db import open_ext_db
###Products ###Products
@diagonalley_ext.route("/api/v1/diagonalley/products", methods=["GET"]) @diagonalley_ext.route("/api/v1/diagonalley/products", methods=["GET"])
@api_check_wallet_key(key_type="invoice") @api_check_wallet_key(key_type="invoice")
def api_diagonalley_products(): def api_diagonalley_products():
@ -27,14 +42,16 @@ def api_diagonalley_products():
@diagonalley_ext.route("/api/v1/diagonalley/products", methods=["POST"]) @diagonalley_ext.route("/api/v1/diagonalley/products", methods=["POST"])
@diagonalley_ext.route("/api/v1/diagonalley/products<product_id>", methods=["PUT"]) @diagonalley_ext.route("/api/v1/diagonalley/products<product_id>", methods=["PUT"])
@api_check_wallet_key(key_type="invoice") @api_check_wallet_key(key_type="invoice")
@api_validate_post_request(schema={ @api_validate_post_request(
schema={
"product": {"type": "string", "empty": False, "required": True}, "product": {"type": "string", "empty": False, "required": True},
"categories": {"type": "string", "empty": False, "required": True}, "categories": {"type": "string", "empty": False, "required": True},
"description": {"type": "string", "empty": False, "required": True}, "description": {"type": "string", "empty": False, "required": True},
"image": {"type": "string", "empty": False, "required": True}, "image": {"type": "string", "empty": False, "required": True},
"price": {"type": "integer", "min": 0, "required": True}, "price": {"type": "integer", "min": 0, "required": True},
"quantity": {"type": "integer", "min": 0, "required": True} "quantity": {"type": "integer", "min": 0, "required": True},
}) }
)
def api_diagonalley_product_create(product_id=None): def api_diagonalley_product_create(product_id=None):
if product_id: if product_id:
@ -53,7 +70,6 @@ def api_diagonalley_product_create(product_id=None):
return jsonify(product._asdict()), HTTPStatus.OK if product_id else HTTPStatus.CREATED return jsonify(product._asdict()), HTTPStatus.OK if product_id else HTTPStatus.CREATED
@diagonalley_ext.route("/api/v1/diagonalley/products/<product_id>", methods=["DELETE"]) @diagonalley_ext.route("/api/v1/diagonalley/products/<product_id>", methods=["DELETE"])
@api_check_wallet_key(key_type="invoice") @api_check_wallet_key(key_type="invoice")
def api_diagonalley_products_delete(product_id): def api_diagonalley_products_delete(product_id):
@ -70,9 +86,9 @@ def api_diagonalley_products_delete(product_id):
return "", HTTPStatus.NO_CONTENT return "", HTTPStatus.NO_CONTENT
###Indexers ###Indexers
@diagonalley_ext.route("/api/v1/diagonalley/indexers", methods=["GET"]) @diagonalley_ext.route("/api/v1/diagonalley/indexers", methods=["GET"])
@api_check_wallet_key(key_type="invoice") @api_check_wallet_key(key_type="invoice")
def api_diagonalley_indexers(): def api_diagonalley_indexers():
@ -87,15 +103,17 @@ def api_diagonalley_indexers():
@diagonalley_ext.route("/api/v1/diagonalley/indexers", methods=["POST"]) @diagonalley_ext.route("/api/v1/diagonalley/indexers", methods=["POST"])
@diagonalley_ext.route("/api/v1/diagonalley/indexers<indexer_id>", methods=["PUT"]) @diagonalley_ext.route("/api/v1/diagonalley/indexers<indexer_id>", methods=["PUT"])
@api_check_wallet_key(key_type="invoice") @api_check_wallet_key(key_type="invoice")
@api_validate_post_request(schema={ @api_validate_post_request(
schema={
"shopname": {"type": "string", "empty": False, "required": True}, "shopname": {"type": "string", "empty": False, "required": True},
"indexeraddress": {"type": "string", "empty": False, "required": True}, "indexeraddress": {"type": "string", "empty": False, "required": True},
"shippingzone1": {"type": "string", "empty": False, "required": True}, "shippingzone1": {"type": "string", "empty": False, "required": True},
"shippingzone2": {"type": "string", "empty": False, "required": True}, "shippingzone2": {"type": "string", "empty": False, "required": True},
"email": {"type": "string", "empty": False, "required": True}, "email": {"type": "string", "empty": False, "required": True},
"zone1cost": {"type": "integer", "min": 0, "required": True}, "zone1cost": {"type": "integer", "min": 0, "required": True},
"zone2cost": {"type": "integer", "min": 0, "required": True} "zone2cost": {"type": "integer", "min": 0, "required": True},
}) }
)
def api_diagonalley_indexer_create(indexer_id=None): def api_diagonalley_indexer_create(indexer_id=None):
if indexer_id: if indexer_id:
@ -132,6 +150,7 @@ def api_diagonalley_indexer_delete(indexer_id):
###Orders ###Orders
@diagonalley_ext.route("/api/v1/diagonalley/orders", methods=["GET"]) @diagonalley_ext.route("/api/v1/diagonalley/orders", methods=["GET"])
@api_check_wallet_key(key_type="invoice") @api_check_wallet_key(key_type="invoice")
def api_diagonalley_orders(): def api_diagonalley_orders():
@ -145,13 +164,15 @@ def api_diagonalley_orders():
@diagonalley_ext.route("/api/v1/diagonalley/orders", methods=["POST"]) @diagonalley_ext.route("/api/v1/diagonalley/orders", methods=["POST"])
@api_check_wallet_key(key_type="invoice") @api_check_wallet_key(key_type="invoice")
@api_validate_post_request(schema={ @api_validate_post_request(
schema={
"id": {"type": "string", "empty": False, "required": True}, "id": {"type": "string", "empty": False, "required": True},
"address": {"type": "string", "empty": False, "required": True}, "address": {"type": "string", "empty": False, "required": True},
"email": {"type": "string", "empty": False, "required": True}, "email": {"type": "string", "empty": False, "required": True},
"quantity": {"type": "integer", "empty": False, "required": True}, "quantity": {"type": "integer", "empty": False, "required": True},
"shippingzone": {"type": "integer", "empty": False, "required": True}, "shippingzone": {"type": "integer", "empty": False, "required": True},
}) }
)
def api_diagonalley_order_create(): def api_diagonalley_order_create():
order = create_diagonalleys_order(wallet_id=g.wallet.id, **g.data) order = create_diagonalleys_order(wallet_id=g.wallet.id, **g.data)
return jsonify(order._asdict()), HTTPStatus.CREATED return jsonify(order._asdict()), HTTPStatus.CREATED
@ -193,6 +214,7 @@ def api_diagonalleys_order_shipped(order_id):
###List products based on indexer id ###List products based on indexer id
@diagonalley_ext.route("/api/v1/diagonalley/stall/products/<indexer_id>", methods=["GET"]) @diagonalley_ext.route("/api/v1/diagonalley/stall/products/<indexer_id>", methods=["GET"])
def api_diagonalleys_stall_products(indexer_id): def api_diagonalleys_stall_products(indexer_id):
with open_ext_db("diagonalley") as db: with open_ext_db("diagonalley") as db:
@ -207,8 +229,10 @@ def api_diagonalleys_stall_products(indexer_id):
return jsonify([products._asdict() for products in get_diagonalleys_products(rows[1])]), HTTPStatus.OK return jsonify([products._asdict() for products in get_diagonalleys_products(rows[1])]), HTTPStatus.OK
###Check a product has been shipped ###Check a product has been shipped
@diagonalley_ext.route("/api/v1/diagonalley/stall/checkshipped/<checking_id>", methods=["GET"]) @diagonalley_ext.route("/api/v1/diagonalley/stall/checkshipped/<checking_id>", methods=["GET"])
def api_diagonalleys_stall_checkshipped(checking_id): def api_diagonalleys_stall_checkshipped(checking_id):
with open_ext_db("diagonalley") as db: with open_ext_db("diagonalley") as db:
@ -216,16 +240,20 @@ def api_diagonalleys_stall_checkshipped(checking_id):
return jsonify({"shipped": rows["shipped"]}), HTTPStatus.OK return jsonify({"shipped": rows["shipped"]}), HTTPStatus.OK
###Place order ###Place order
@diagonalley_ext.route("/api/v1/diagonalley/stall/order/<indexer_id>", methods=["POST"]) @diagonalley_ext.route("/api/v1/diagonalley/stall/order/<indexer_id>", methods=["POST"])
@api_validate_post_request(schema={ @api_validate_post_request(
schema={
"id": {"type": "string", "empty": False, "required": True}, "id": {"type": "string", "empty": False, "required": True},
"email": {"type": "string", "empty": False, "required": True}, "email": {"type": "string", "empty": False, "required": True},
"address": {"type": "string", "empty": False, "required": True}, "address": {"type": "string", "empty": False, "required": True},
"quantity": {"type": "integer", "empty": False, "required": True}, "quantity": {"type": "integer", "empty": False, "required": True},
"shippingzone": {"type": "integer", "empty": False, "required": True}, "shippingzone": {"type": "integer", "empty": False, "required": True},
}) }
)
def api_diagonalley_stall_order(indexer_id): def api_diagonalley_stall_order(indexer_id):
product = get_diagonalleys_product(g.data["id"]) product = get_diagonalleys_product(g.data["id"])
shipping = get_diagonalleys_indexer(indexer_id) shipping = get_diagonalleys_indexer(indexer_id)
@ -235,14 +263,28 @@ def api_diagonalley_stall_order(indexer_id):
else: else:
shippingcost = shipping.zone2cost shippingcost = shipping.zone2cost
checking_id, payment_request = create_invoice(wallet_id=product.wallet, amount=shippingcost + (g.data["quantity"] * product.price), memo=g.data["id"]) checking_id, payment_request = create_invoice(
selling_id = urlsafe_b64encode(uuid4().bytes_le).decode('utf-8') wallet_id=product.wallet, amount=shippingcost + (g.data["quantity"] * product.price), memo=g.data["id"]
)
selling_id = urlsafe_b64encode(uuid4().bytes_le).decode("utf-8")
with open_ext_db("diagonalley") as db: with open_ext_db("diagonalley") as db:
db.execute( db.execute(
""" """
INSERT INTO orders (id, productid, wallet, product, quantity, shippingzone, address, email, invoiceid, paid, shipped) INSERT INTO orders (id, productid, wallet, product, quantity, shippingzone, address, email, invoiceid, paid, shipped)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", """,
(selling_id ,g.data["id"] , product.wallet, product.product, g.data["quantity"], g.data["shippingzone"], g.data["address"], g.data["email"], checking_id, False, False), (
selling_id,
g.data["id"],
product.wallet,
product.product,
g.data["quantity"],
g.data["shippingzone"],
g.data["address"],
g.data["email"],
checking_id,
False,
False,
),
) )
return jsonify({"checking_id": checking_id, "payment_request": payment_request}), HTTPStatus.OK return jsonify({"checking_id": checking_id, "payment_request": payment_request}), HTTPStatus.OK

31
lnbits/extensions/events/crud.py

@ -21,6 +21,7 @@ def create_ticket(checking_id: str, wallet: str, event: str, name: str, email:
return get_ticket(checking_id) return get_ticket(checking_id)
def update_ticket(paid: bool, checking_id: str) -> Tickets: def update_ticket(paid: bool, checking_id: str) -> Tickets:
with open_ext_db("events") as db: with open_ext_db("events") as db:
row = db.fetchone("SELECT * FROM ticket WHERE id = ?", (checking_id,)) row = db.fetchone("SELECT * FROM ticket WHERE id = ?", (checking_id,))
@ -72,11 +73,20 @@ def delete_ticket(checking_id: str) -> None:
db.execute("DELETE FROM ticket WHERE id = ?", (checking_id,)) db.execute("DELETE FROM ticket WHERE id = ?", (checking_id,))
########EVENTS######### ########EVENTS#########
def create_event(*, wallet: str, name: str, info: str, closing_date: str, event_start_date: str, event_end_date: str, amount_tickets: int, price_per_ticket: int) -> Events: def create_event(
*,
wallet: str,
name: str,
info: str,
closing_date: str,
event_start_date: str,
event_end_date: str,
amount_tickets: int,
price_per_ticket: int,
) -> Events:
with open_ext_db("events") as db: with open_ext_db("events") as db:
event_id = urlsafe_short_hash() event_id = urlsafe_short_hash()
db.execute( db.execute(
@ -84,12 +94,24 @@ def create_event(*, wallet: str, name: str, info: str, closing_date: str, event_
INSERT INTO events (id, wallet, name, info, closing_date, event_start_date, event_end_date, amount_tickets, price_per_ticket, sold) INSERT INTO events (id, wallet, name, info, closing_date, event_start_date, event_end_date, amount_tickets, price_per_ticket, sold)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", """,
(event_id, wallet, name, info, closing_date, event_start_date, event_end_date, amount_tickets, price_per_ticket, 0), (
event_id,
wallet,
name,
info,
closing_date,
event_start_date,
event_end_date,
amount_tickets,
price_per_ticket,
0,
),
) )
print(event_id) print(event_id)
return get_event(event_id) return get_event(event_id)
def update_event(event_id: str, **kwargs) -> Events: def update_event(event_id: str, **kwargs) -> Events:
q = ", ".join([f"{field[0]} = ?" for field in kwargs.items()]) q = ", ".join([f"{field[0]} = ?" for field in kwargs.items()])
with open_ext_db("events") as db: with open_ext_db("events") as db:
@ -122,8 +144,10 @@ def delete_event(event_id: str) -> None:
with open_ext_db("events") as db: with open_ext_db("events") as db:
db.execute("DELETE FROM events WHERE id = ?", (event_id,)) db.execute("DELETE FROM events WHERE id = ?", (event_id,))
########EVENTTICKETS######### ########EVENTTICKETS#########
def get_event_tickets(event_id: str, wallet_id: str) -> Tickets: def get_event_tickets(event_id: str, wallet_id: str) -> Tickets:
with open_ext_db("events") as db: with open_ext_db("events") as db:
@ -132,6 +156,7 @@ def get_event_tickets(event_id: str, wallet_id: str) -> Tickets:
return [Tickets(**row) for row in rows] return [Tickets(**row) for row in rows]
def reg_ticket(ticket_id: str) -> Tickets: def reg_ticket(ticket_id: str) -> Tickets:
with open_ext_db("events") as db: with open_ext_db("events") as db:
db.execute("UPDATE ticket SET registered = ? WHERE id = ?", (True, ticket_id)) db.execute("UPDATE ticket SET registered = ? WHERE id = ?", (True, ticket_id))

13
lnbits/extensions/events/migrations.py

@ -1,5 +1,6 @@
from lnbits.db import open_ext_db from lnbits.db import open_ext_db
def m001_initial(db): def m001_initial(db):
db.execute( db.execute(
@ -74,20 +75,12 @@ def m002_changed(db):
) )
VALUES (?, ?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?, ?)
""", """,
( (row[0], row[1], row[2], row[3], row[4], row[5], True,),
row[0],
row[1],
row[2],
row[3],
row[4],
row[5],
True,
),
) )
db.execute("DROP TABLE tickets") db.execute("DROP TABLE tickets")
def migrate(): def migrate():
with open_ext_db("events") as db: with open_ext_db("events") as db:
m001_initial(db) m001_initial(db)
m002_changed(db) m002_changed(db)

1
lnbits/extensions/events/models.py

@ -14,6 +14,7 @@ class Events(NamedTuple):
sold: int sold: int
time: int time: int
class Tickets(NamedTuple): class Tickets(NamedTuple):
id: str id: str
wallet: str wallet: str

18
lnbits/extensions/events/views.py

@ -20,12 +20,19 @@ def display(event_id):
event = get_event(event_id) or abort(HTTPStatus.NOT_FOUND, "Event does not exist.") event = get_event(event_id) or abort(HTTPStatus.NOT_FOUND, "Event does not exist.")
if event.amount_tickets < 1: if event.amount_tickets < 1:
return render_template("events/error.html", event_name=event.name, event_error="Sorry, tickets are sold out :(") return render_template("events/error.html", event_name=event.name, event_error="Sorry, tickets are sold out :(")
datetime_object = datetime.strptime(event.closing_date, '%Y-%m-%d').date() datetime_object = datetime.strptime(event.closing_date, "%Y-%m-%d").date()
if date.today() > datetime_object: if date.today() > datetime_object:
return render_template("events/error.html", event_name=event.name, event_error="Sorry, ticket closing date has passed :(") return render_template(
"events/error.html", event_name=event.name, event_error="Sorry, ticket closing date has passed :("
)
return render_template(
return render_template("events/display.html", event_id=event_id, event_name=event.name, event_info=event.info, event_price=event.price_per_ticket) "events/display.html",
event_id=event_id,
event_name=event.name,
event_info=event.info,
event_price=event.price_per_ticket,
)
@events_ext.route("/ticket/<ticket_id>") @events_ext.route("/ticket/<ticket_id>")
@ -40,6 +47,3 @@ def register(event_id):
event = get_event(event_id) or abort(HTTPStatus.NOT_FOUND, "Event does not exist.") event = get_event(event_id) or abort(HTTPStatus.NOT_FOUND, "Event does not exist.")
return render_template("events/register.html", event_id=event_id, event_name=event.name, wallet_id=event.wallet) return render_template("events/register.html", event_id=event_id, event_name=event.name, wallet_id=event.wallet)

32
lnbits/extensions/events/views_api.py

@ -7,7 +7,20 @@ from lnbits.decorators import api_check_wallet_key, api_validate_post_request
from lnbits.settings import WALLET from lnbits.settings import WALLET
from lnbits.extensions.events import events_ext from lnbits.extensions.events import events_ext
from .crud import create_ticket, update_ticket, get_ticket, get_tickets, delete_ticket, create_event, update_event, get_event, get_events, delete_event, get_event_tickets, reg_ticket from .crud import (
create_ticket,
update_ticket,
get_ticket,
get_tickets,
delete_ticket,
create_event,
update_event,
get_event,
get_events,
delete_event,
get_event_tickets,
reg_ticket,
)
#########Events########## #########Events##########
@ -36,7 +49,7 @@ def api_events():
"event_start_date": {"type": "string", "empty": False, "required": True}, "event_start_date": {"type": "string", "empty": False, "required": True},
"event_end_date": {"type": "string", "empty": False, "required": True}, "event_end_date": {"type": "string", "empty": False, "required": True},
"amount_tickets": {"type": "integer", "min": 0, "required": True}, "amount_tickets": {"type": "integer", "min": 0, "required": True},
"price_per_ticket": {"type": "integer", "min": 0, "required": True} "price_per_ticket": {"type": "integer", "min": 0, "required": True},
} }
) )
def api_event_create(event_id=None): def api_event_create(event_id=None):
@ -75,6 +88,7 @@ def api_form_delete(event_id):
#########Tickets########## #########Tickets##########
@events_ext.route("/api/v1/tickets", methods=["GET"]) @events_ext.route("/api/v1/tickets", methods=["GET"])
@api_check_wallet_key("invoice") @api_check_wallet_key("invoice")
def api_tickets(): def api_tickets():
@ -90,8 +104,9 @@ def api_tickets():
@api_validate_post_request( @api_validate_post_request(
schema={ schema={
"name": {"type": "string", "empty": False, "required": True}, "name": {"type": "string", "empty": False, "required": True},
"email": {"type": "string", "empty": False, "required": True} "email": {"type": "string", "empty": False, "required": True},
}) }
)
def api_ticket_make_ticket(event_id, sats): def api_ticket_make_ticket(event_id, sats):
event = get_event(event_id) event = get_event(event_id)
@ -150,10 +165,15 @@ def api_ticket_delete(ticket_id):
#########EventTickets########## #########EventTickets##########
@events_ext.route("/api/v1/eventtickets/<wallet_id>/<event_id>", methods=["GET"]) @events_ext.route("/api/v1/eventtickets/<wallet_id>/<event_id>", methods=["GET"])
def api_event_tickets(wallet_id, event_id): def api_event_tickets(wallet_id, event_id):
return jsonify([ticket._asdict() for ticket in get_event_tickets(wallet_id=wallet_id, event_id=event_id)]), HTTPStatus.OK return (
jsonify([ticket._asdict() for ticket in get_event_tickets(wallet_id=wallet_id, event_id=event_id)]),
HTTPStatus.OK,
)
@events_ext.route("/api/v1/register/ticket/<ticket_id>", methods=["GET"]) @events_ext.route("/api/v1/register/ticket/<ticket_id>", methods=["GET"])
def api_event_register_ticket(ticket_id): def api_event_register_ticket(ticket_id):
@ -166,6 +186,4 @@ def api_event_register_ticket(ticket_id):
if ticket.registered == True: if ticket.registered == True:
return jsonify({"message": "Ticket already registered"}), HTTPStatus.FORBIDDEN return jsonify({"message": "Ticket already registered"}), HTTPStatus.FORBIDDEN
return jsonify([ticket._asdict() for ticket in reg_ticket(ticket_id)]), HTTPStatus.OK return jsonify([ticket._asdict() for ticket in reg_ticket(ticket_id)]), HTTPStatus.OK

19
lnbits/extensions/example/views_api.py

@ -13,25 +13,14 @@ from lnbits.extensions.example import example_ext
# add your endpoints here # add your endpoints here
@example_ext.route("/api/v1/tools", methods=["GET"]) @example_ext.route("/api/v1/tools", methods=["GET"])
def api_example(): def api_example():
"""Try to add descriptions for others.""" """Try to add descriptions for others."""
tools = [ tools = [
{ {"name": "Flask", "url": "https://flask.palletsprojects.com/", "language": "Python",},
"name": "Flask", {"name": "Vue.js", "url": "https://vuejs.org/", "language": "JavaScript",},
"url": "https://flask.palletsprojects.com/", {"name": "Quasar Framework", "url": "https://quasar.dev/", "language": "JavaScript",},
"language": "Python",
},
{
"name": "Vue.js",
"url": "https://vuejs.org/",
"language": "JavaScript",
},
{
"name": "Quasar Framework",
"url": "https://quasar.dev/",
"language": "JavaScript",
}
] ]
return jsonify(tools), HTTPStatus.OK return jsonify(tools), HTTPStatus.OK

8
lnbits/extensions/lnticket/crud.py

@ -6,10 +6,9 @@ from lnbits.helpers import urlsafe_short_hash
from .models import Tickets, Forms from .models import Tickets, Forms
#######TICKETS######## #######TICKETS########
def create_ticket(checking_id: str, wallet: str, form: str, name: str, email: str, ltext: str, sats: int) -> Tickets: def create_ticket(checking_id: str, wallet: str, form: str, name: str, email: str, ltext: str, sats: int) -> Tickets:
with open_ext_db("lnticket") as db: with open_ext_db("lnticket") as db:
db.execute( db.execute(
@ -22,6 +21,7 @@ def create_ticket(checking_id: str, wallet: str, form: str, name: str, email:
return get_ticket(checking_id) return get_ticket(checking_id)
def update_ticket(paid: bool, checking_id: str) -> Tickets: def update_ticket(paid: bool, checking_id: str) -> Tickets:
with open_ext_db("lnticket") as db: with open_ext_db("lnticket") as db:
row = db.fetchone("SELECT * FROM ticket WHERE id = ?", (checking_id,)) row = db.fetchone("SELECT * FROM ticket WHERE id = ?", (checking_id,))
@ -48,6 +48,7 @@ def update_ticket(paid: bool, checking_id: str) -> Tickets:
) )
return get_ticket(checking_id) return get_ticket(checking_id)
def get_ticket(ticket_id: str) -> Optional[Tickets]: def get_ticket(ticket_id: str) -> Optional[Tickets]:
with open_ext_db("lnticket") as db: with open_ext_db("lnticket") as db:
row = db.fetchone("SELECT * FROM ticket WHERE id = ?", (ticket_id,)) row = db.fetchone("SELECT * FROM ticket WHERE id = ?", (ticket_id,))
@ -71,8 +72,6 @@ def delete_ticket(ticket_id: str) -> None:
db.execute("DELETE FROM ticket WHERE id = ?", (ticket_id,)) db.execute("DELETE FROM ticket WHERE id = ?", (ticket_id,))
########FORMS######### ########FORMS#########
@ -89,6 +88,7 @@ def create_form(*, wallet: str, name: str, description: str, costpword: int) ->
return get_form(form_id) return get_form(form_id)
def update_form(form_id: str, **kwargs) -> Forms: def update_form(form_id: str, **kwargs) -> Forms:
q = ", ".join([f"{field[0]} = ?" for field in kwargs.items()]) q = ", ".join([f"{field[0]} = ?" for field in kwargs.items()])
with open_ext_db("lnticket") as db: with open_ext_db("lnticket") as db:

13
lnbits/extensions/lnticket/migrations.py

@ -1,5 +1,6 @@
from lnbits.db import open_ext_db from lnbits.db import open_ext_db
def m001_initial(db): def m001_initial(db):
db.execute( db.execute(
@ -50,7 +51,6 @@ def m002_changed(db):
""" """
) )
for row in [list(row) for row in db.fetchall("SELECT * FROM tickets")]: for row in [list(row) for row in db.fetchall("SELECT * FROM tickets")]:
usescsv = "" usescsv = ""
@ -74,16 +74,7 @@ def m002_changed(db):
) )
VALUES (?, ?, ?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""", """,
( (row[0], row[1], row[2], row[3], row[4], row[5], row[6], True,),
row[0],
row[1],
row[2],
row[3],
row[4],
row[5],
row[6],
True,
),
) )
db.execute("DROP TABLE tickets") db.execute("DROP TABLE tickets")

1
lnbits/extensions/lnticket/models.py

@ -21,4 +21,3 @@ class Tickets(NamedTuple):
sats: int sats: int
paid: bool paid: bool
time: int time: int

8
lnbits/extensions/lnticket/views.py

@ -19,4 +19,10 @@ def display(form_id):
form = get_form(form_id) or abort(HTTPStatus.NOT_FOUND, "LNTicket does not exist.") form = get_form(form_id) or abort(HTTPStatus.NOT_FOUND, "LNTicket does not exist.")
print(form.id) print(form.id)
return render_template("lnticket/display.html", form_id=form.id, form_name=form.name, form_desc=form.description, form_costpword=form.costpword) return render_template(
"lnticket/display.html",
form_id=form.id,
form_name=form.name,
form_desc=form.description,
form_costpword=form.costpword,
)

24
lnbits/extensions/lnticket/views_api.py

@ -7,11 +7,23 @@ from lnbits.decorators import api_check_wallet_key, api_validate_post_request
from lnbits.settings import WALLET from lnbits.settings import WALLET
from lnbits.extensions.lnticket import lnticket_ext from lnbits.extensions.lnticket import lnticket_ext
from .crud import create_ticket, update_ticket, get_ticket, get_tickets, delete_ticket, create_form, update_form, get_form, get_forms, delete_form from .crud import (
create_ticket,
update_ticket,
get_ticket,
get_tickets,
delete_ticket,
create_form,
update_form,
get_form,
get_forms,
delete_form,
)
#########FORMS########## #########FORMS##########
@lnticket_ext.route("/api/v1/forms", methods=["GET"]) @lnticket_ext.route("/api/v1/forms", methods=["GET"])
@api_check_wallet_key("invoice") @api_check_wallet_key("invoice")
def api_forms(): def api_forms():
@ -31,7 +43,7 @@ def api_forms():
"wallet": {"type": "string", "empty": False, "required": True}, "wallet": {"type": "string", "empty": False, "required": True},
"name": {"type": "string", "empty": False, "required": True}, "name": {"type": "string", "empty": False, "required": True},
"description": {"type": "string", "min": 0, "required": True}, "description": {"type": "string", "min": 0, "required": True},
"costpword": {"type": "integer", "min": 0, "required": True} "costpword": {"type": "integer", "min": 0, "required": True},
} }
) )
def api_form_create(form_id=None): def api_form_create(form_id=None):
@ -66,8 +78,10 @@ def api_form_delete(form_id):
return "", HTTPStatus.NO_CONTENT return "", HTTPStatus.NO_CONTENT
#########tickets########## #########tickets##########
@lnticket_ext.route("/api/v1/tickets", methods=["GET"]) @lnticket_ext.route("/api/v1/tickets", methods=["GET"])
@api_check_wallet_key("invoice") @api_check_wallet_key("invoice")
def api_tickets(): def api_tickets():
@ -86,8 +100,9 @@ def api_tickets():
"name": {"type": "string", "empty": False, "required": True}, "name": {"type": "string", "empty": False, "required": True},
"email": {"type": "string", "empty": False, "required": True}, "email": {"type": "string", "empty": False, "required": True},
"ltext": {"type": "string", "empty": False, "required": True}, "ltext": {"type": "string", "empty": False, "required": True},
"sats": {"type": "integer", "min": 0, "required": True} "sats": {"type": "integer", "min": 0, "required": True},
}) }
)
def api_ticket_make_ticket(form_id, sats): def api_ticket_make_ticket(form_id, sats):
event = get_form(form_id) event = get_form(form_id)
@ -127,6 +142,7 @@ def api_ticket_send_ticket(checking_id):
return jsonify({"paid": False}), HTTPStatus.OK return jsonify({"paid": False}), HTTPStatus.OK
@lnticket_ext.route("/api/v1/tickets/<ticket_id>", methods=["DELETE"]) @lnticket_ext.route("/api/v1/tickets/<ticket_id>", methods=["DELETE"])
@api_check_wallet_key("invoice") @api_check_wallet_key("invoice")
def api_ticket_delete(ticket_id): def api_ticket_delete(ticket_id):

16
lnbits/extensions/usermanager/crud.py

@ -13,11 +13,9 @@ from ...core.crud import (
) )
###Users ###Users
def create_usermanager_user(user_name: str, wallet_name: str, admin_id: str) -> Users: def create_usermanager_user(user_name: str, wallet_name: str, admin_id: str) -> Users:
user = get_user(create_account().id) user = get_user(create_account().id)
@ -37,7 +35,7 @@ def create_usermanager_user(user_name: str, wallet_name: str, admin_id: str) ->
INSERT INTO wallets (id, admin, name, user, adminkey, inkey) INSERT INTO wallets (id, admin, name, user, adminkey, inkey)
VALUES (?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?)
""", """,
(wallet.id, admin_id, wallet_name, user.id, wallet.adminkey, wallet.inkey) (wallet.id, admin_id, wallet_name, user.id, wallet.adminkey, wallet.inkey),
) )
return get_usermanager_user(user.id) return get_usermanager_user(user.id)
@ -48,7 +46,6 @@ def get_usermanager_user(user_id: str) -> Users:
row = db.fetchone("SELECT * FROM users WHERE id = ?", (user_id,)) row = db.fetchone("SELECT * FROM users WHERE id = ?", (user_id,))
return Users(**row) if row else None return Users(**row) if row else None
@ -71,8 +68,10 @@ def delete_usermanager_user(user_id: str) -> None:
with open_ext_db("usermanager") as dbb: with open_ext_db("usermanager") as dbb:
dbb.execute("DELETE FROM wallets WHERE user = ?", (user_id,)) dbb.execute("DELETE FROM wallets WHERE user = ?", (user_id,))
###Wallets ###Wallets
def create_usermanager_wallet(user_id: str, wallet_name: str, admin_id: str) -> Wallets: def create_usermanager_wallet(user_id: str, wallet_name: str, admin_id: str) -> Wallets:
wallet = create_wallet(user_id=user_id, wallet_name=wallet_name) wallet = create_wallet(user_id=user_id, wallet_name=wallet_name)
with open_ext_db("usermanager") as db: with open_ext_db("usermanager") as db:
@ -82,11 +81,12 @@ def create_usermanager_wallet(user_id: str, wallet_name: str, admin_id: str) ->
INSERT INTO wallets (id, admin, name, user, adminkey, inkey) INSERT INTO wallets (id, admin, name, user, adminkey, inkey)
VALUES (?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?)
""", """,
(wallet.id, admin_id, wallet_name, user_id, wallet.adminkey, wallet.inkey) (wallet.id, admin_id, wallet_name, user_id, wallet.adminkey, wallet.inkey),
) )
return get_usermanager_wallet(wallet.id) return get_usermanager_wallet(wallet.id)
def get_usermanager_wallet(wallet_id: str) -> Optional[Wallets]: def get_usermanager_wallet(wallet_id: str) -> Optional[Wallets]:
with open_ext_db("usermanager") as db: with open_ext_db("usermanager") as db:
row = db.fetchone("SELECT * FROM wallets WHERE id = ?", (wallet_id,)) row = db.fetchone("SELECT * FROM wallets WHERE id = ?", (wallet_id,))
@ -105,13 +105,13 @@ def get_usermanager_wallets(user_id: str) -> Wallets:
def get_usermanager_wallet_transactions(wallet_id: str) -> Users: def get_usermanager_wallet_transactions(wallet_id: str) -> Users:
return get_wallet_payments(wallet_id=wallet_id, include_all_pending=False) return get_wallet_payments(wallet_id=wallet_id, include_all_pending=False)
def get_usermanager_wallet_balances(user_id: str) -> Users: def get_usermanager_wallet_balances(user_id: str) -> Users:
user = get_user(user_id) user = get_user(user_id)
return (user.wallets) return user.wallets
def delete_usermanager_wallet(wallet_id: str, user_id: str) -> None: def delete_usermanager_wallet(wallet_id: str, user_id: str) -> None:
delete_wallet(user_id=user_id, wallet_id=wallet_id) delete_wallet(user_id=user_id, wallet_id=wallet_id)
with open_ext_db("usermanager") as db: with open_ext_db("usermanager") as db:
db.execute("DELETE FROM wallets WHERE id = ?", (wallet_id,)) db.execute("DELETE FROM wallets WHERE id = ?", (wallet_id,))

15
lnbits/extensions/usermanager/migrations.py

@ -5,7 +5,8 @@ def m001_initial(db):
""" """
Initial users table. Initial users table.
""" """
db.execute(""" db.execute(
"""
CREATE TABLE IF NOT EXISTS users ( CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY, id TEXT PRIMARY KEY,
name TEXT NOT NULL, name TEXT NOT NULL,
@ -13,13 +14,14 @@ def m001_initial(db):
email TEXT, email TEXT,
password TEXT password TEXT
); );
""") """
)
""" """
Initial wallets table. Initial wallets table.
""" """
db.execute(""" db.execute(
"""
CREATE TABLE IF NOT EXISTS wallets ( CREATE TABLE IF NOT EXISTS wallets (
id TEXT PRIMARY KEY, id TEXT PRIMARY KEY,
admin TEXT NOT NULL, admin TEXT NOT NULL,
@ -28,9 +30,10 @@ def m001_initial(db):
adminkey TEXT NOT NULL, adminkey TEXT NOT NULL,
inkey TEXT NOT NULL inkey TEXT NOT NULL
); );
""") """
)
def migrate(): def migrate():
with open_ext_db("usermanager") as db: with open_ext_db("usermanager") as db:
m001_initial(db) m001_initial(db)

4
lnbits/extensions/usermanager/models.py

@ -1,5 +1,6 @@
from typing import NamedTuple from typing import NamedTuple
class Users(NamedTuple): class Users(NamedTuple):
id: str id: str
name: str name: str
@ -7,6 +8,7 @@ class Users(NamedTuple):
email: str email: str
password: str password: str
class Wallets(NamedTuple): class Wallets(NamedTuple):
id: str id: str
admin: str admin: str
@ -14,5 +16,3 @@ class Wallets(NamedTuple):
user: str user: str
adminkey: str adminkey: str
inkey: str inkey: str

48
lnbits/extensions/usermanager/views_api.py

@ -5,19 +5,29 @@ from lnbits.core.crud import get_user
from lnbits.decorators import api_check_wallet_key, api_validate_post_request from lnbits.decorators import api_check_wallet_key, api_validate_post_request
from lnbits.extensions.usermanager import usermanager_ext from lnbits.extensions.usermanager import usermanager_ext
from .crud import create_usermanager_user, get_usermanager_user, get_usermanager_users, get_usermanager_wallet_transactions, get_usermanager_wallet_balances, delete_usermanager_user, create_usermanager_wallet, get_usermanager_wallet, get_usermanager_wallets, delete_usermanager_wallet from .crud import (
create_usermanager_user,
get_usermanager_user,
get_usermanager_users,
get_usermanager_wallet_transactions,
get_usermanager_wallet_balances,
delete_usermanager_user,
create_usermanager_wallet,
get_usermanager_wallet,
get_usermanager_wallets,
delete_usermanager_wallet,
)
from lnbits.core.services import create_invoice from lnbits.core.services import create_invoice
from base64 import urlsafe_b64encode from base64 import urlsafe_b64encode
from uuid import uuid4 from uuid import uuid4
from lnbits.db import open_ext_db from lnbits.db import open_ext_db
from ...core import ( from ...core import update_user_extension
update_user_extension,
)
###Users ###Users
@usermanager_ext.route("/api/v1/users", methods=["GET"]) @usermanager_ext.route("/api/v1/users", methods=["GET"])
@api_check_wallet_key(key_type="invoice") @api_check_wallet_key(key_type="invoice")
def api_usermanager_users(): def api_usermanager_users():
@ -27,11 +37,13 @@ def api_usermanager_users():
@usermanager_ext.route("/api/v1/users", methods=["POST"]) @usermanager_ext.route("/api/v1/users", methods=["POST"])
@api_check_wallet_key(key_type="invoice") @api_check_wallet_key(key_type="invoice")
@api_validate_post_request(schema={ @api_validate_post_request(
schema={
"admin_id": {"type": "string", "empty": False, "required": True}, "admin_id": {"type": "string", "empty": False, "required": True},
"user_name": {"type": "string", "empty": False, "required": True}, "user_name": {"type": "string", "empty": False, "required": True},
"wallet_name": {"type": "string", "empty": False, "required": True} "wallet_name": {"type": "string", "empty": False, "required": True},
}) }
)
def api_usermanager_users_create(): def api_usermanager_users_create():
user = create_usermanager_user(g.data["user_name"], g.data["wallet_name"], g.data["admin_id"]) user = create_usermanager_user(g.data["user_name"], g.data["wallet_name"], g.data["admin_id"])
return jsonify(user._asdict()), HTTPStatus.CREATED return jsonify(user._asdict()), HTTPStatus.CREATED
@ -46,15 +58,19 @@ def api_usermanager_users_delete(user_id):
delete_usermanager_user(user_id) delete_usermanager_user(user_id)
return "", HTTPStatus.NO_CONTENT return "", HTTPStatus.NO_CONTENT
###Activate Extension ###Activate Extension
@usermanager_ext.route("/api/v1/extensions", methods=["POST"]) @usermanager_ext.route("/api/v1/extensions", methods=["POST"])
@api_check_wallet_key(key_type="invoice") @api_check_wallet_key(key_type="invoice")
@api_validate_post_request(schema={ @api_validate_post_request(
schema={
"extension": {"type": "string", "empty": False, "required": True}, "extension": {"type": "string", "empty": False, "required": True},
"userid": {"type": "string", "empty": False, "required": True}, "userid": {"type": "string", "empty": False, "required": True},
"active": {"type": "boolean", "required": True} "active": {"type": "boolean", "required": True},
}) }
)
def api_usermanager_activate_extension(): def api_usermanager_activate_extension():
user = get_user(g.data["userid"]) user = get_user(g.data["userid"])
if not user: if not user:
@ -62,8 +78,10 @@ def api_usermanager_activate_extension():
update_user_extension(user_id=g.data["userid"], extension=g.data["extension"], active=g.data["active"]) update_user_extension(user_id=g.data["userid"], extension=g.data["extension"], active=g.data["active"])
return jsonify({"extension": "updated"}), HTTPStatus.CREATED return jsonify({"extension": "updated"}), HTTPStatus.CREATED
###Wallets ###Wallets
@usermanager_ext.route("/api/v1/wallets", methods=["GET"]) @usermanager_ext.route("/api/v1/wallets", methods=["GET"])
@api_check_wallet_key(key_type="invoice") @api_check_wallet_key(key_type="invoice")
def api_usermanager_wallets(): def api_usermanager_wallets():
@ -73,12 +91,13 @@ def api_usermanager_wallets():
@usermanager_ext.route("/api/v1/wallets", methods=["POST"]) @usermanager_ext.route("/api/v1/wallets", methods=["POST"])
@api_check_wallet_key(key_type="invoice") @api_check_wallet_key(key_type="invoice")
@api_validate_post_request(schema={ @api_validate_post_request(
schema={
"user_id": {"type": "string", "empty": False, "required": True}, "user_id": {"type": "string", "empty": False, "required": True},
"wallet_name": {"type": "string", "empty": False, "required": True}, "wallet_name": {"type": "string", "empty": False, "required": True},
"admin_id": {"type": "string", "empty": False, "required": True} "admin_id": {"type": "string", "empty": False, "required": True},
}
}) )
def api_usermanager_wallets_create(): def api_usermanager_wallets_create():
user = create_usermanager_wallet(g.data["user_id"], g.data["wallet_name"], g.data["admin_id"]) user = create_usermanager_wallet(g.data["user_id"], g.data["wallet_name"], g.data["admin_id"])
return jsonify(user._asdict()), HTTPStatus.CREATED return jsonify(user._asdict()), HTTPStatus.CREATED
@ -90,6 +109,7 @@ def api_usermanager_wallet_transactions(wallet_id):
return jsonify(get_usermanager_wallet_transactions(wallet_id)), HTTPStatus.OK return jsonify(get_usermanager_wallet_transactions(wallet_id)), HTTPStatus.OK
@usermanager_ext.route("/api/v1/wallets/<user_id>", methods=["GET"]) @usermanager_ext.route("/api/v1/wallets/<user_id>", methods=["GET"])
@api_check_wallet_key(key_type="invoice") @api_check_wallet_key(key_type="invoice")
def api_usermanager_wallet_balances(user_id): def api_usermanager_wallet_balances(user_id):

3
lnbits/extensions/withdraw/crud.py

@ -1,6 +1,5 @@
from datetime import datetime from datetime import datetime
from typing import List, Optional, Union from typing import List, Optional, Union
import shortuuid # type: ignore
from lnbits.db import open_ext_db from lnbits.db import open_ext_db
from lnbits.helpers import urlsafe_short_hash from lnbits.helpers import urlsafe_short_hash
@ -78,7 +77,6 @@ def get_withdraw_link_by_hash(unique_hash: str, num=0) -> Optional[WithdrawLink]
return WithdrawLink._make(link) return WithdrawLink._make(link)
def get_withdraw_links(wallet_ids: Union[str, List[str]]) -> List[WithdrawLink]: def get_withdraw_links(wallet_ids: Union[str, List[str]]) -> List[WithdrawLink]:
if isinstance(wallet_ids, str): if isinstance(wallet_ids, str):
wallet_ids = [wallet_ids] wallet_ids = [wallet_ids]
@ -103,6 +101,7 @@ def delete_withdraw_link(link_id: str) -> None:
with open_ext_db("withdraw") as db: with open_ext_db("withdraw") as db:
db.execute("DELETE FROM withdraw_link WHERE id = ?", (link_id,)) db.execute("DELETE FROM withdraw_link WHERE id = ?", (link_id,))
def chunks(lst, n): def chunks(lst, n):
for i in range(0, len(lst), n): for i in range(0, len(lst), n):
yield lst[i : i + n] yield lst[i : i + n]

13
lnbits/extensions/withdraw/migrations.py

@ -1,7 +1,4 @@
from datetime import datetime
from lnbits.db import open_ext_db from lnbits.db import open_ext_db
from lnbits.helpers import urlsafe_short_hash
def m001_initial(db): def m001_initial(db):
@ -25,7 +22,9 @@ def m001_initial(db):
used INTEGER DEFAULT 0, used INTEGER DEFAULT 0,
usescsv TEXT usescsv TEXT
); );
""") """
)
def m002_change_withdraw_table(db): def m002_change_withdraw_table(db):
""" """
@ -99,12 +98,8 @@ def m002_change_withdraw_table(db):
) )
db.execute("DROP TABLE withdraw_links") db.execute("DROP TABLE withdraw_links")
def migrate(): def migrate():
with open_ext_db("withdraw") as db: with open_ext_db("withdraw") as db:
m001_initial(db) m001_initial(db)
m002_change_withdraw_table(db) m002_change_withdraw_table(db)

8
lnbits/extensions/withdraw/models.py

@ -40,7 +40,13 @@ class WithdrawLink(NamedTuple):
usescssv = self.usescsv.split(",") usescssv = self.usescsv.split(",")
tohash = self.id + self.unique_hash + usescssv[self.number] tohash = self.id + self.unique_hash + usescssv[self.number]
multihash = shortuuid.uuid(name=tohash) multihash = shortuuid.uuid(name=tohash)
url = url_for("withdraw.api_lnurl_multi_response", unique_hash=self.unique_hash, id_unique_hash=multihash, _external=True, _scheme=scheme) url = url_for(
"withdraw.api_lnurl_multi_response",
unique_hash=self.unique_hash,
id_unique_hash=multihash,
_external=True,
_scheme=scheme,
)
else: else:
url = url_for("withdraw.api_lnurl_response", unique_hash=self.unique_hash, _external=True, _scheme=scheme) url = url_for("withdraw.api_lnurl_response", unique_hash=self.unique_hash, _external=True, _scheme=scheme)

14
lnbits/helpers.py

@ -34,14 +34,16 @@ class ExtensionManager:
config = {} config = {}
is_valid = False is_valid = False
output.append(Extension( output.append(
Extension(
extension, extension,
is_valid, is_valid,
config.get('name'), config.get("name"),
config.get('short_description'), config.get("short_description"),
config.get('icon'), config.get("icon"),
config.get('contributors') config.get("contributors"),
)) )
)
return output return output

Loading…
Cancel
Save