def get_account(user_id: str) -> Optional[User]: with open_db() as db: row = db.fetchone( "SELECT id, email, pass as password FROM accounts WHERE id = ?", (user_id, )) return User(**row) if row else None
def get_user(user_id: str) -> Optional[User]: with open_db() as db: user = db.fetchone("SELECT id, email FROM accounts WHERE id = ?", (user_id, )) if user: extensions = db.fetchall( "SELECT extension FROM extensions WHERE user = ? AND active = 1", (user_id, )) wallets = db.fetchall( """ SELECT *, COALESCE((SELECT balance FROM balances WHERE wallet = wallets.id), 0) AS balance_msat FROM wallets WHERE user = ? """, (user_id, ), ) return (User( **{ **user, **{ "extensions": [e[0] for e in extensions], "wallets": [Wallet(**w) for w in wallets] } }) if user else None)
def index(): """Main withdraw link page.""" usr = request.args.get("usr") if usr: if not len(usr) > 20: return redirect(url_for("home")) # Get all the data with open_db() as db: user_wallets = db.fetchall("SELECT * FROM wallets WHERE user = ?", (usr, )) user_ext = db.fetchall("SELECT * FROM extensions WHERE user = ?", (usr, )) user_ext = [v[0] for v in user_ext] with open_ext_db("withdraw") as withdraw_ext_db: user_fau = withdraw_ext_db.fetchall( "SELECT * FROM withdraws WHERE usr = ?", (usr, )) # If del is selected by user from withdraw page, the withdraw link is to be deleted faudel = request.args.get("del") if faudel: withdraw_ext_db.execute("DELETE FROM withdraws WHERE uni = ?", (faudel, )) user_fau = withdraw_ext_db.fetchall( "SELECT * FROM withdraws WHERE usr = ?", (usr, )) return render_template("withdraw/index.html", user_wallets=user_wallets, user=usr, user_ext=user_ext, user_fau=user_fau)
def create_account() -> User: with open_db() as db: user_id = uuid4().hex db.execute("INSERT INTO accounts (id) VALUES (?)", (user_id, )) new_account = get_account(user_id=user_id) assert new_account, "Newly created account couldn't be retrieved" return new_account
def update_user_extension(*, user_id: str, extension: str, active: int) -> None: with open_db() as db: db.execute( """ INSERT OR REPLACE INTO extensions (user, extension, active) VALUES (?, ?, ?) """, (user_id, extension, active), )
def delete_wallet_payments_expired(wallet_id: str, *, seconds: int = 86400) -> None: with open_db() as db: db.execute( """ DELETE FROM apipayments WHERE wallet = ? AND pending = 1 AND time < strftime('%s', 'now') - ? """, (wallet_id, seconds), )
def get_wallet_payment(wallet_id: str, checking_id: str) -> Optional[Payment]: with open_db() as db: row = db.fetchone( """ SELECT payhash as checking_id, amount, fee, pending, memo, time FROM apipayments WHERE wallet = ? AND payhash = ? """, (wallet_id, checking_id), ) return Payment(**row) if row else None
def get_wallet(wallet_id: str) -> Optional[Wallet]: with open_db() as db: row = db.fetchone( """ SELECT *, COALESCE((SELECT balance FROM balances WHERE wallet = wallets.id), 0) AS balance_msat FROM wallets WHERE id = ? """, (wallet_id, ), ) return Wallet(**row) if row else None
def delete_wallet(*, user_id: str, wallet_id: str) -> None: with open_db() as db: db.execute( """ UPDATE wallets AS w SET user = '******' || w.user, adminkey = 'del:' || w.adminkey, inkey = 'del:' || w.inkey WHERE id = ? AND user = ? """, (wallet_id, user_id), )
async def run(awaitable): fk = Request( "GET", "http", "/background/pseudo", b"", Headers([("host", "lnbits.background")]), "", "1.1", send_push_promise=lambda x, h: None, ) async with main_app.request_context(fk): g.db = open_db() await awaitable
def get_wallet_for_key(key: str, key_type: str = "invoice") -> Optional[Wallet]: with open_db() as db: check_field = "adminkey" if key_type == "admin" else "inkey" row = db.fetchone( f""" SELECT *, COALESCE((SELECT balance FROM balances WHERE wallet = wallets.id), 0) AS balance_msat FROM wallets WHERE {check_field} = ? """, (key, ), ) return Wallet(**row) if row else None
def create_wallet(*, user_id: str, wallet_name: Optional[str] = None) -> Wallet: with open_db() as db: wallet_id = uuid4().hex db.execute( """ INSERT INTO wallets (id, name, user, adminkey, inkey) VALUES (?, ?, ?, ?, ?) """, (wallet_id, wallet_name or DEFAULT_WALLET_NAME, user_id, uuid4().hex, uuid4().hex), ) return get_wallet(wallet_id=wallet_id)
def create_payment(*, wallet_id: str, checking_id: str, amount: str, memo: str, fee: int = 0, pending: bool = True) -> Payment: with open_db() as db: db.execute( """ INSERT INTO apipayments (wallet, payhash, amount, pending, memo, fee) VALUES (?, ?, ?, ?, ?, ?) """, (wallet_id, checking_id, amount, int(pending), memo, fee), ) return get_wallet_payment(wallet_id, checking_id)
def create_wallet(*, user_id: str, wallet_name: Optional[str] = None) -> Wallet: with open_db() as db: wallet_id = uuid4().hex db.execute( """ INSERT INTO wallets (id, name, user, adminkey, inkey) VALUES (?, ?, ?, ?, ?) """, (wallet_id, wallet_name or DEFAULT_WALLET_NAME, user_id, uuid4().hex, uuid4().hex), ) new_wallet = get_wallet(wallet_id=wallet_id) assert new_wallet, "Newly created wallet couldn't be retrieved" return new_wallet
def get_wallet_for_key(key: str, key_type: str = "invoice") -> Optional[Wallet]: with open_db() as db: row = db.fetchone( """ SELECT *, COALESCE((SELECT balance FROM balances WHERE wallet = wallets.id), 0) AS balance_msat FROM wallets WHERE adminkey = ? OR inkey = ? """, (key, key), ) if not row: return None if key_type == "admin" and row["adminkey"] != key: return None return Wallet(**row)
def create_payment(*, wallet_id: str, checking_id: str, amount: int, memo: str, fee: int = 0, pending: bool = True) -> Payment: with open_db() as db: db.execute( """ INSERT INTO apipayments (wallet, payhash, amount, pending, memo, fee) VALUES (?, ?, ?, ?, ?, ?) """, (wallet_id, checking_id, amount, int(pending), memo, fee), ) new_payment = get_wallet_payment(wallet_id, checking_id) assert new_payment, "Newly created payment couldn't be retrieved" return new_payment
def get_wallet_payments(wallet_id: str, *, include_all_pending: bool = False) -> List[Payment]: with open_db() as db: if include_all_pending: clause = "pending = 1" else: clause = "((amount > 0 AND pending = 0) OR amount < 0)" rows = db.fetchall( f""" SELECT payhash as checking_id, amount, fee, pending, memo, time FROM apipayments WHERE wallet = ? AND {clause} ORDER BY time DESC """, (wallet_id, ), ) return [Payment(**row) for row in rows]
def ticket(): """.""" thehash = request.args.get("hash") unireg = request.args.get("unireg") #Double check the payment has cleared with open_db() as db: payment = db.fetchall("SELECT * FROM apipayments WHERE payhash = ?", (thehash, )) if not payment: return jsonify({ "status": "ERROR", "reason": "NO RECORD OF PAYMENT" }), 400 if payment[0][4] == 1: return jsonify({"status": "ERROR", "reason": "NOT PAID"}), 400 #Update databases with open_ext_db("events") as events_ext_db: user_ev = events_ext_db.fetchall( "SELECT * FROM events WHERE unireg = ?", (unireg, )) updatesold = user_ev[0][9] + 1 events_ext_db.execute("UPDATE events SET sold = ? WHERE unireg = ?", ( updatesold, unireg, )) events_ext_db.execute("UPDATE eventssold SET paid = 1 WHERE hash = ?", (thehash, )) eventssold = events_ext_db.fetchall( "SELECT * FROM eventssold WHERE hash = ?", (thehash, )) if not eventssold: return jsonify({ "status": "ERROR", "reason": "NO TICKET RECORD" }), 200 return render_template("events/ticket.html", name=eventssold[0][3], ticket=thehash)
def get_wallet_payments(wallet_id: str, *, complete: bool = False, pending: bool = False, outgoing: bool = False, incoming: bool = False) -> List[Payment]: """ Filters payments to be returned by complete | pending | outgoing | incoming. """ clause = "" if complete and pending: clause += "" elif complete: clause += "AND ((amount > 0 AND pending = 0) OR amount < 0)" elif pending: clause += "AND pending = 1" else: raise TypeError("at least one of [complete, pending] must be True.") if outgoing and incoming: clause += "" elif outgoing: clause += "AND amount < 0" elif incoming: clause += "AND amount > 0" else: raise TypeError("at least one of [outgoing, incoming] must be True.") with open_db() as db: rows = db.fetchall( f""" SELECT payhash as checking_id, amount, fee, pending, memo, time FROM apipayments WHERE wallet = ? {clause} ORDER BY time DESC """, (wallet_id, ), ) return [Payment(**row) for row in rows]
def index(): """Main events link page.""" usr = request.args.get("usr") if usr: if not len(usr) > 20: return redirect(url_for("home")) # Get all the data with open_db() as db: user_wallets = db.fetchall("SELECT * FROM wallets WHERE user = ?", (usr, )) user_ext = db.fetchall( "SELECT extension FROM extensions WHERE user = ? AND active = 1", (usr, )) user_ext = [v[0] for v in user_ext] with open_ext_db("events") as events_ext_db: user_ev = events_ext_db.fetchall("SELECT * FROM events WHERE usr = ?", (usr, )) # If del is selected by user from events page, the event link is to be deleted evdel = request.args.get("del") if evdel: user_ev = events_ext_db.fetchall( "SELECT * FROM events WHERE uni = ?", (evdel, )) events_ext_db.execute("DELETE FROM events WHERE uni = ?", (evdel, )) if user_ev[0][9] > 0: events_ext_db.execute("DELETE FROM eventssold WHERE uni = ?", (user_ev[0][12], )) user_ev = events_ext_db.fetchall( "SELECT * FROM events WHERE usr = ?", (usr, )) print(user_ext) return render_template("events/index.html", user_wallets=user_wallets, user=usr, user_ext=user_ext, user_ev=user_ev)
def create(): """.""" data = request.json tit = data["tit"] wal = data["wal"] cldate = data["cldate"] notickets = data["notickets"] prtick = data["prtickets"] usr = data["usr"] descr = data["descr"] wall = wal.split("-") # Form validation if (not tit.replace(" ", "").isalnum() or wal == "" or int(notickets) < 0 or int(prtick) < 0): return jsonify({"ERROR": "FORM ERROR"}), 401 # If id that means its a link being edited, delete the record first if "id" in data: unid = data["id"].split("-") uni = unid[1] unireg = unid[2] with open_ext_db("events") as events_ext_db: events_ext_db.execute("DELETE FROM events WHERE uni = ?", (unid[1], )) else: uni = uuid.uuid4().hex unireg = uuid.uuid4().hex with open_db() as dbb: user_wallets = dbb.fetchall( "SELECT * FROM wallets WHERE user = ? AND id = ?", ( usr, wall[1], )) if not user_wallets: return jsonify({"ERROR": "NO WALLET USER"}), 401 with open_db() as db: user_ext = db.fetchall("SELECT * FROM extensions WHERE user = ?", (usr, )) user_ext = [v[0] for v in user_ext] # Add to DB with open_ext_db("events") as events_ext_db: events_ext_db.execute( """ INSERT OR IGNORE INTO events (usr, wal, walnme, walinvkey, uni, tit, cldate, notickets, prtick, descr, unireg) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( usr, wall[1], user_wallets[0][1], user_wallets[0][4], uni, tit, cldate, notickets, prtick, descr, unireg, ), ) user_ev = events_ext_db.fetchall("SELECT * FROM events WHERE usr = ?", (usr, )) if not user_ev: return jsonify({"ERROR": "NO WALLET USER"}), 401 return render_template("events/index.html", user_wallets=user_wallets, user=usr, user_ext=user_ext, user_ev=user_ev)
async def run(): async with main_app.request_context(fk): with open_db() as g.db: # type: ignore await func(*args)
def create_account() -> User: with open_db() as db: user_id = uuid4().hex db.execute("INSERT INTO accounts (id) VALUES (?)", (user_id, )) return get_account(user_id=user_id)
def create(): """.""" data = request.json amt = data["amt"] tit = data["tit"] wal = data["wal"] minamt = data["minamt"] maxamt = data["maxamt"] tme = data["tme"] uniq = data["uniq"] usr = data["usr"] wall = wal.split("-") # Form validation if (int(amt) < 0 or not tit.replace(" ", "").isalnum() or wal == "" or int(minamt) < 0 or int(maxamt) < 0 or int(minamt) > int(maxamt) or int(tme) < 0): return jsonify({"ERROR": "FORM ERROR"}), 401 # If id that means its a link being edited, delet the record first if "id" in data: unid = data["id"].split("-") uni = unid[1] with open_ext_db("withdraw") as withdraw_ext_db: withdraw_ext_db.execute("DELETE FROM withdraws WHERE uni = ?", (unid[1], )) else: uni = uuid.uuid4().hex # Randomiser for random QR option rand = "" if uniq > 0: for x in range(0, int(amt)): rand += uuid.uuid4().hex[0:5] + "," else: rand = uuid.uuid4().hex[0:5] + "," with open_db() as dbb: user_wallets = dbb.fetchall( "SELECT * FROM wallets WHERE user = ? AND id = ?", ( usr, wall[1], )) if not user_wallets: return jsonify({"ERROR": "NO WALLET USER"}), 401 # Get time dt = datetime.now() seconds = dt.timestamp() with open_db() as db: user_ext = db.fetchall("SELECT * FROM extensions WHERE user = ?", (usr, )) user_ext = [v[0] for v in user_ext] # Add to DB with open_ext_db("withdraw") as withdraw_ext_db: withdraw_ext_db.execute( """ INSERT OR IGNORE INTO withdraws (usr, wal, walnme, adm, uni, tit, maxamt, minamt, spent, inc, tme, uniq, withdrawals, tmestmp, rand) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( usr, wall[1], user_wallets[0][1], user_wallets[0][3], uni, tit, maxamt, minamt, 0, amt, tme, uniq, 0, seconds, rand, ), ) user_fau = withdraw_ext_db.fetchall( "SELECT * FROM withdraws WHERE usr = ?", (usr, )) if not user_fau: return jsonify({"ERROR": "NO WALLET USER"}), 401 return render_template("withdraw/index.html", user_wallets=user_wallets, user=usr, user_ext=user_ext, user_fau=user_fau)
def migrate(): with open_db() as db: m001_initial(db)
def delete_payment(checking_id: str) -> None: with open_db() as db: db.execute("DELETE FROM apipayments WHERE payhash = ?", (checking_id, ))
def update_payment_status(checking_id: str, pending: bool) -> None: with open_db() as db: db.execute("UPDATE apipayments SET pending = ? WHERE payhash = ?", ( int(pending), checking_id, ))