Compare commits

..
5 Commits
Author SHA1 Message Date
dni ⚡ 51c9d294cd chore: update to v0.12.12 2024-10-17 23:06:11 +02:00
dni ⚡ 4e342a7ab2 chore: bump to v0.12.12-rc1 2024-10-16 16:52:17 +02:00
dni ⚡ d7e180d855 chore: update to v0.12.12 2024-10-16 11:56:57 +02:00
Vlad Stananddni ⚡ af863b8c8f fix: await retry (#2739) 2024-10-16 11:56:17 +02:00
dni ⚡andarcbtc d8d898b20b feat: install lnbits.sh bash script (#2684)
Co-authored-by: arcbtc <ben@arc.wales>
2024-09-12 08:04:07 +02:00
75 changed files with 11140 additions and 19480 deletions
+1 -4
View File
@@ -46,10 +46,7 @@ runs:
- name: Install the project dependencies
shell: bash
run: |
poetry install
# needed for conv tests
poetry add psycopg2-binary
run: poetry install
- name: Use Node.js ${{ inputs.node-version }}
if: ${{ (inputs.npm == 'true') }}
+2 -3
View File
@@ -35,7 +35,6 @@ __bundle__
coverage.xml
node_modules
lnbits/static/bundle.js
lnbits/static/bundle-components.js
lnbits/static/bundle.css
lnbits/static/bundle.min.js.old
lnbits/static/bundle.min.css.old
@@ -50,8 +49,8 @@ fly.toml
lnbits-backup.zip
# Ignore extensions (post installable extension PR)
/lnbits/extensions
/upgrades/
extensions
upgrades/
# builded python package
dist
-1
View File
@@ -10,7 +10,6 @@
**/lnbits/static/vendor
**/lnbits/static/bundle.*
**/lnbits/static/bundle-components.*
**/lnbits/static/css/*
flake.lock
+7 -4
View File
@@ -103,21 +103,24 @@ sass:
bundle:
npm install
npm run bundle
npm run sass
npm run vendor_copy
npm run vendor_json
poetry run ./node_modules/.bin/prettier -w ./lnbits/static/vendor.json
npm run vendor_bundle_css
npm run vendor_minify_css
npm run vendor_bundle_js
npm run vendor_minify_js
checkbundle:
cp lnbits/static/bundle.min.js lnbits/static/bundle.min.js.old
cp lnbits/static/bundle.min.css lnbits/static/bundle.min.css.old
cp lnbits/static/bundle-components.min.js lnbits/static/bundle-components.min.js.old
make bundle
diff -q lnbits/static/bundle.min.js lnbits/static/bundle.min.js.old || exit 1
diff -q lnbits/static/bundle.min.css lnbits/static/bundle.min.css.old || exit 1
diff -q lnbits/static/bundle-components.min.js lnbits/static/bundle-components.min.js.old || exit 1
@echo "Bundle is OK"
rm lnbits/static/bundle.min.js.old
rm lnbits/static/bundle.min.css.old
rm lnbits/static/bundle-components.min.js.old
install-pre-commit-hook:
@echo "Installing pre-commit hook to git"
+1 -1
View File
@@ -70,7 +70,7 @@ chmod +x lnbits.sh &&
Now visit `0.0.0.0:5000` to make a super-user account.
`export PATH="/home/$USER/.local/bin:$PATH"` then `./lnbits.sh` can be used to run, but for more control `cd lnbits` and use `poetry run lnbits` (see previous option).
`./lnbits.sh` can be used to run, but for more control `cd lnbits` and use `poetry run lnbits` (see previous option).
## Option 3: Nix
-1
View File
@@ -30,7 +30,6 @@
meta.rev = self.dirtyRev or self.rev;
meta.mainProgram = projectName;
overrides = pkgs.poetry2nix.overrides.withDefaults (final: prev: {
coincurve = prev.coincurve.override { preferWheel = true; };
protobuf = prev.protobuf.override { preferWheel = true; };
ruff = prev.ruff.override { preferWheel = true; };
wallycore = prev.wallycore.override { preferWheel = true; };
-3
View File
@@ -42,9 +42,6 @@ elif [ ! -d lnbits/wallets ]; then
cd lnbits || { echo "Failed to cd into lnbits ... FAIL"; exit 1; }
fi
# Set path for running after install
export PATH="/home/$USER/.local/bin:$PATH"
# Install the dependencies using Poetry
poetry env use python3.9
poetry install --only main
+18 -13
View File
@@ -17,13 +17,10 @@ from slowapi.util import get_remote_address
from starlette.middleware.sessions import SessionMiddleware
from lnbits.core.crud import (
add_installed_extension,
get_dbversions,
get_installed_extensions,
update_installed_extension_state,
)
from lnbits.core.extensions.extension_manager import deactivate_extension
from lnbits.core.extensions.helpers import version_parse
from lnbits.core.helpers import migrate_extension_database
from lnbits.core.tasks import ( # watchdog_task
killswitch_task,
@@ -47,8 +44,14 @@ from lnbits.wallets import get_funding_source, set_funding_source
from .commands import migrate_databases
from .core import init_core_routers
from .core.db import core_app_extra
from .core.extensions.models import Extension, InstallableExtension
from .core.services import check_admin_settings, check_webpush_settings
from .core.views.extension_api import add_installed_extension
from .extension_manager import (
Extension,
InstallableExtension,
get_valid_extensions,
version_parse,
)
from .middleware import (
CustomGZipMiddleware,
ExtensionsRedirectMiddleware,
@@ -240,7 +243,6 @@ async def check_installed_extensions(app: FastAPI):
)
except Exception as e:
logger.warning(e)
await deactivate_extension(ext.id)
logger.warning(
f"Failed to re-install extension: {ext.id} ({ext.installed_version})"
)
@@ -315,6 +317,7 @@ async def restore_installed_extension(app: FastAPI, ext: InstallableExtension):
# mount routes for the new version
core_app_extra.register_new_ext_routes(extension)
ext.notify_upgrade(extension.upgrade_hash)
def register_custom_extensions_path():
@@ -377,22 +380,24 @@ def register_ext_routes(app: FastAPI, ext: Extension) -> None:
)
app.mount(s["path"], StaticFiles(directory=static_dir), s["name"])
ext_redirects = (
getattr(ext_module, f"{ext.code}_redirect_paths")
if hasattr(ext_module, f"{ext.code}_redirect_paths")
else []
)
if hasattr(ext_module, f"{ext.code}_redirect_paths"):
ext_redirects = getattr(ext_module, f"{ext.code}_redirect_paths")
settings.lnbits_extensions_redirects = [
r for r in settings.lnbits_extensions_redirects if r["ext_id"] != ext.code
]
for r in ext_redirects:
r["ext_id"] = ext.code
settings.lnbits_extensions_redirects.append(r)
settings.activate_extension_paths(ext.code, ext.upgrade_hash, ext_redirects)
logger.trace(f"adding route for extension {ext_module}")
logger.trace(f"Adding route for extension {ext_module}.")
prefix = f"/upgrades/{ext.upgrade_hash}" if ext.upgrade_hash != "" else ""
app.include_router(router=ext_route, prefix=prefix)
async def check_and_register_extensions(app: FastAPI):
await check_installed_extensions(app)
for ext in Extension.get_valid_extensions(False):
for ext in get_valid_extensions(False):
try:
register_ext_routes(app, ext)
except Exception as exc:
+8 -8
View File
@@ -25,18 +25,18 @@ from lnbits.core.crud import (
remove_deleted_wallets,
update_payment_status,
)
from lnbits.core.extensions.models import (
CreateExtension,
ExtensionRelease,
InstallableExtension,
)
from lnbits.core.helpers import migrate_databases
from lnbits.core.models import Payment, PaymentState
from lnbits.core.models import Payment, PaymentState, User
from lnbits.core.services import check_admin_settings
from lnbits.core.views.extension_api import (
api_install_extension,
api_uninstall_extension,
)
from lnbits.extension_manager import (
CreateExtension,
ExtensionRelease,
InstallableExtension,
)
from lnbits.settings import settings
from lnbits.wallets.base import Wallet
@@ -611,7 +611,7 @@ async def _call_install_extension(
)
resp.raise_for_status()
else:
await api_install_extension(data)
await api_install_extension(data, User(id="mock_id"))
async def _call_uninstall_extension(
@@ -625,7 +625,7 @@ async def _call_uninstall_extension(
)
resp.raise_for_status()
else:
await api_uninstall_extension(extension)
await api_uninstall_extension(extension, User(id="mock_id"))
async def _can_run_operation(url) -> bool:
+278 -279
View File
File diff suppressed because it is too large Load Diff
@@ -1,93 +0,0 @@
import asyncio
import importlib
from loguru import logger
from lnbits.core.crud import (
add_installed_extension,
delete_installed_extension,
get_dbversions,
get_installed_extension,
update_installed_extension_state,
)
from lnbits.core.db import core_app_extra
from lnbits.core.helpers import migrate_extension_database
from lnbits.settings import settings
from .models import Extension, InstallableExtension
async def install_extension(ext_info: InstallableExtension) -> Extension:
extension = Extension.from_installable_ext(ext_info)
installed_ext = await get_installed_extension(ext_info.id)
ext_info.payments = installed_ext.payments if installed_ext else []
await ext_info.download_archive()
ext_info.extract_archive()
db_version = (await get_dbversions()).get(ext_info.id, 0)
await migrate_extension_database(extension, db_version)
await add_installed_extension(ext_info)
if extension.is_upgrade_extension:
# call stop while the old routes are still active
await stop_extension_background_work(ext_info.id)
return extension
async def uninstall_extension(ext_id: str):
await stop_extension_background_work(ext_id)
settings.deactivate_extension_paths(ext_id)
extension = await get_installed_extension(ext_id)
if extension:
extension.clean_extension_files()
await delete_installed_extension(ext_id=ext_id)
async def activate_extension(ext: Extension):
core_app_extra.register_new_ext_routes(ext)
await update_installed_extension_state(ext_id=ext.code, active=True)
async def deactivate_extension(ext_id: str):
settings.deactivate_extension_paths(ext_id)
await update_installed_extension_state(ext_id=ext_id, active=False)
async def stop_extension_background_work(ext_id: str) -> bool:
"""
Stop background work for extension (like asyncio.Tasks, WebSockets, etc).
Extensions SHOULD expose a `api_stop()` function.
"""
upgrade_hash = settings.lnbits_upgraded_extensions.get(ext_id, "")
ext = Extension(ext_id, True, False, upgrade_hash=upgrade_hash)
try:
logger.info(f"Stopping background work for extension '{ext.module_name}'.")
old_module = importlib.import_module(ext.module_name)
# Extensions must expose an `{ext_id}_stop()` function at the module level
# The `api_stop()` function is for backwards compatibility (will be deprecated)
stop_fns = [f"{ext_id}_stop", "api_stop"]
stop_fn_name = next((fn for fn in stop_fns if hasattr(old_module, fn)), None)
assert stop_fn_name, "No stop function found for '{ext.module_name}'"
stop_fn = getattr(old_module, stop_fn_name)
if stop_fn:
if asyncio.iscoroutinefunction(stop_fn):
await stop_fn()
else:
stop_fn()
logger.info(f"Stopped background work for extension '{ext.module_name}'.")
except Exception as ex:
logger.warning(f"Failed to stop background work for '{ext.module_name}'.")
logger.warning(ex)
return False
return True
-56
View File
@@ -1,56 +0,0 @@
import hashlib
from typing import Any, Optional
from urllib import request
import httpx
from loguru import logger
from packaging import version
from lnbits.settings import settings
def version_parse(v: str):
"""
Wrapper for version.parse() that does not throw if the version is invalid.
Instead it return the lowest possible version ("0.0.0")
"""
try:
return version.parse(v)
except Exception:
return version.parse("0.0.0")
async def github_api_get(url: str, error_msg: Optional[str]) -> Any:
headers = {"User-Agent": settings.user_agent}
if settings.lnbits_ext_github_token:
headers["Authorization"] = f"Bearer {settings.lnbits_ext_github_token}"
async with httpx.AsyncClient(headers=headers) as client:
resp = await client.get(url)
if resp.status_code != 200:
logger.warning(f"{error_msg} ({url}): {resp.text}")
resp.raise_for_status()
return resp.json()
def download_url(url, save_path):
with request.urlopen(url, timeout=60) as dl_file:
with open(save_path, "wb") as out_file:
out_file.write(dl_file.read())
def file_hash(filename):
h = hashlib.sha256()
b = bytearray(128 * 1024)
mv = memoryview(b)
with open(filename, "rb", buffering=0) as f:
while n := f.readinto(mv):
h.update(mv[:n])
return h.hexdigest()
def icon_to_github_url(source_repo: str, path: Optional[str]) -> str:
if not path:
return ""
_, _, *rest = path.split("/")
tail = "/".join(rest)
return f"https://github.com/{source_repo}/raw/main/{tail}"
+69 -5
View File
@@ -1,8 +1,9 @@
import importlib
import re
from typing import Any
from typing import Any, Optional
from uuid import UUID
import httpx
from loguru import logger
from lnbits.core import migrations as core_migrations
@@ -12,10 +13,11 @@ from lnbits.core.crud import (
update_migration_version,
)
from lnbits.core.db import db as core_db
from lnbits.core.extensions.models import (
Extension,
)
from lnbits.db import COCKROACH, POSTGRES, SQLITE, Connection
from lnbits.extension_manager import (
Extension,
get_valid_extensions,
)
from lnbits.settings import settings
@@ -53,6 +55,68 @@ async def run_migration(
await update_migration_version(conn, db_name, version)
async def stop_extension_background_work(
ext_id: str, user: str, access_token: Optional[str] = None
):
"""
Stop background work for extension (like asyncio.Tasks, WebSockets, etc).
Extensions SHOULD expose a `api_stop()` function and/or a DELETE enpoint
at the root level of their API.
"""
stopped = await _stop_extension_background_work(ext_id)
if not stopped:
# fallback to REST API call
await _stop_extension_background_work_via_api(ext_id, user, access_token)
async def _stop_extension_background_work(ext_id) -> bool:
upgrade_hash = settings.extension_upgrade_hash(ext_id) or ""
ext = Extension(ext_id, True, False, upgrade_hash=upgrade_hash)
try:
logger.info(f"Stopping background work for extension '{ext.module_name}'.")
old_module = importlib.import_module(ext.module_name)
# Extensions must expose an `{ext_id}_stop()` function at the module level
# The `api_stop()` function is for backwards compatibility (will be deprecated)
stop_fns = [f"{ext_id}_stop", "api_stop"]
stop_fn_name = next((fn for fn in stop_fns if hasattr(old_module, fn)), None)
assert stop_fn_name, "No stop function found for '{ext.module_name}'"
stop_fn = getattr(old_module, stop_fn_name)
if stop_fn:
await stop_fn()
logger.info(f"Stopped background work for extension '{ext.module_name}'.")
except Exception as ex:
logger.warning(f"Failed to stop background work for '{ext.module_name}'.")
logger.warning(ex)
return False
return True
async def _stop_extension_background_work_via_api(ext_id, user, access_token):
logger.info(
f"Stopping background work for extension '{ext_id}' using the REST API."
)
async with httpx.AsyncClient() as client:
try:
url = f"http://{settings.host}:{settings.port}/{ext_id}/api/v1?usr={user}"
headers = (
{"Authorization": "Bearer " + access_token} if access_token else None
)
resp = await client.delete(url=url, headers=headers)
resp.raise_for_status()
logger.info(f"Stopped background work for extension '{ext_id}'.")
except Exception as ex:
logger.warning(
f"Failed to stop background work for '{ext_id}' using the REST API."
)
logger.warning(ex)
def to_valid_user_id(user_id: str) -> UUID:
if len(user_id) < 32:
raise ValueError("User ID must have at least 128 bits")
@@ -97,7 +161,7 @@ async def migrate_databases():
await load_disabled_extension_list()
# todo: revisit, use installed extensions
for ext in Extension.get_valid_extensions(False):
for ext in get_valid_extensions(False):
current_version = current_versions.get(ext.code, 0)
try:
await migrate_extension_database(ext, current_version)
+51 -46
View File
@@ -1,3 +1,4 @@
import datetime
from time import time
from loguru import logger
@@ -101,7 +102,7 @@ async def m002_add_fields_to_apipayments(db):
import json
rows = await db.fetchall("SELECT * FROM apipayments")
rows = await (await db.execute("SELECT * FROM apipayments")).fetchall()
for row in rows:
if not row["memo"] or not row["memo"].startswith("#"):
continue
@@ -112,15 +113,15 @@ async def m002_add_fields_to_apipayments(db):
new = row["memo"][len(prefix) :]
await db.execute(
"""
UPDATE apipayments SET extra = :extra, memo = :memo1
WHERE checking_id = :checking_id AND memo = :memo2
UPDATE apipayments SET extra = ?, memo = ?
WHERE checking_id = ? AND memo = ?
""",
{
"extra": json.dumps({"tag": ext}),
"memo1": new,
"checking_id": row["checking_id"],
"memo2": row["memo"],
},
(
json.dumps({"tag": ext}),
new,
row["checking_id"],
row["memo"],
),
)
break
except OperationalError:
@@ -211,17 +212,19 @@ async def m007_set_invoice_expiries(db):
Precomputes invoice expiry for existing pending incoming payments.
"""
try:
rows = await db.fetchall(
f"""
SELECT bolt11, checking_id
FROM apipayments
WHERE pending = true
AND amount > 0
AND bolt11 IS NOT NULL
AND expiry IS NULL
AND time < {db.timestamp_now}
"""
)
rows = await (
await db.execute(
f"""
SELECT bolt11, checking_id
FROM apipayments
WHERE pending = true
AND amount > 0
AND bolt11 IS NOT NULL
AND expiry IS NULL
AND time < {db.timestamp_now}
"""
)
).fetchall()
if len(rows):
logger.info(f"Migration: Checking expiry of {len(rows)} invoices")
for i, (
@@ -233,17 +236,22 @@ async def m007_set_invoice_expiries(db):
if invoice.expiry is None:
continue
expiration_date = invoice.date + invoice.expiry
expiration_date = datetime.datetime.fromtimestamp(
invoice.date + invoice.expiry
)
logger.info(
f"Migration: {i+1}/{len(rows)} setting expiry of invoice"
f" {invoice.payment_hash} to {expiration_date}"
)
await db.execute(
f"""
UPDATE apipayments SET expiry = {db.timestamp_placeholder('expiry')}
WHERE checking_id = :checking_id AND amount > 0
"""
UPDATE apipayments SET expiry = ?
WHERE checking_id = ? AND amount > 0
""",
{"expiry": expiration_date, "checking_id": checking_id},
(
db.datetime_to_timestamp(expiration_date),
checking_id,
),
)
except Exception:
continue
@@ -339,15 +347,17 @@ async def m014_set_deleted_wallets(db):
Sets deleted column to wallets.
"""
try:
rows = await db.fetchall(
"""
SELECT *
FROM wallets
WHERE user LIKE 'del:%'
AND adminkey LIKE 'del:%'
AND inkey LIKE 'del:%'
"""
)
rows = await (
await db.execute(
"""
SELECT *
FROM wallets
WHERE user LIKE 'del:%'
AND adminkey LIKE 'del:%'
AND inkey LIKE 'del:%'
"""
)
).fetchall()
for row in rows:
try:
@@ -357,15 +367,10 @@ async def m014_set_deleted_wallets(db):
await db.execute(
"""
UPDATE wallets SET
"user" = :user, adminkey = :adminkey, inkey = :inkey, deleted = true
WHERE id = :wallet
"user" = ?, adminkey = ?, inkey = ?, deleted = true
WHERE id = ?
""",
{
"user": user,
"adminkey": adminkey,
"inkey": inkey,
"wallet": row.get("id"),
},
(user, adminkey, inkey, row[0]),
)
except Exception:
continue
@@ -451,17 +456,17 @@ async def m017_add_timestamp_columns_to_accounts_and_wallets(db):
now = int(time())
await db.execute(
f"""
UPDATE wallets SET created_at = {db.timestamp_placeholder('now')}
UPDATE wallets SET created_at = {db.timestamp_placeholder}
WHERE created_at IS NULL
""",
{"now": now},
(now,),
)
await db.execute(
f"""
UPDATE accounts SET created_at = {db.timestamp_placeholder('now')}
UPDATE accounts SET created_at = {db.timestamp_placeholder}
WHERE created_at IS NULL
""",
{"now": now},
(now,),
)
except OperationalError as exc:
+6 -24
View File
@@ -7,6 +7,7 @@ import json
import time
from dataclasses import dataclass
from enum import Enum
from sqlite3 import Row
from typing import Callable, Optional
from ecdsa import SECP256k1, SigningKey
@@ -20,10 +21,8 @@ from lnbits.settings import settings
from lnbits.utils.exchange_rates import allowed_currencies
from lnbits.wallets import get_funding_source
from lnbits.wallets.base import (
PaymentFailedStatus,
PaymentPendingStatus,
PaymentStatus,
PaymentSuccessStatus,
)
@@ -212,19 +211,6 @@ class PaymentState(str, Enum):
return self.value
class CreatePayment(BaseModel):
wallet_id: str
payment_request: str
payment_hash: str
amount: int
memo: str
preimage: Optional[str] = None
expiry: Optional[datetime.datetime] = None
extra: Optional[dict] = None
webhook: Optional[str] = None
fee: int = 0
class Payment(FromRowModel):
status: str
# TODO should be removed in the future, backward compatibility
@@ -238,7 +224,7 @@ class Payment(FromRowModel):
preimage: str
payment_hash: str
expiry: Optional[float]
extra: Optional[dict]
extra: dict = {}
wallet_id: str
webhook: Optional[str]
webhook_status: Optional[int]
@@ -252,7 +238,7 @@ class Payment(FromRowModel):
return self.status == PaymentState.FAILED.value
@classmethod
def from_row(cls, row: dict):
def from_row(cls, row: Row):
return cls(
checking_id=row["checking_id"],
payment_hash=row["hash"] or "0" * 64,
@@ -299,15 +285,11 @@ class Payment(FromRowModel):
return self.expiry < time.time() if self.expiry else False
@property
def is_internal(self) -> bool:
def is_uncheckable(self) -> bool:
return self.checking_id.startswith("internal_")
async def check_status(self) -> PaymentStatus:
if self.is_internal:
if self.success:
return PaymentSuccessStatus()
if self.failed:
return PaymentFailedStatus()
if self.is_uncheckable:
return PaymentPendingStatus()
funding_source = get_funding_source()
if self.is_out:
@@ -359,7 +341,7 @@ class TinyURL(BaseModel):
time: float
@classmethod
def from_row(cls, row: dict):
def from_row(cls, row: Row):
return cls(**dict(row))
+39 -45
View File
@@ -1,9 +1,10 @@
import asyncio
import datetime
import json
import time
from io import BytesIO
from pathlib import Path
from typing import Optional
from typing import Dict, List, Optional, Tuple, TypedDict
from urllib.parse import parse_qs, urlparse
from uuid import UUID, uuid4
@@ -67,24 +68,16 @@ from .crud import (
update_user_extension,
)
from .helpers import to_valid_user_id
from .models import (
BalanceDelta,
CreatePayment,
Payment,
PaymentState,
User,
UserConfig,
Wallet,
)
from .models import BalanceDelta, Payment, PaymentState, User, UserConfig, Wallet
async def calculate_fiat_amounts(
amount: float,
wallet_id: str,
currency: Optional[str] = None,
extra: Optional[dict] = None,
extra: Optional[Dict] = None,
conn: Optional[Connection] = None,
) -> tuple[int, Optional[dict]]:
) -> Tuple[int, Optional[Dict]]:
wallet = await get_wallet(wallet_id, conn=conn)
assert wallet, "invalid wallet_id"
wallet_currency = wallet.currency or settings.lnbits_default_accounting_currency
@@ -125,11 +118,11 @@ async def create_invoice(
description_hash: Optional[bytes] = None,
unhashed_description: Optional[bytes] = None,
expiry: Optional[int] = None,
extra: Optional[dict] = None,
extra: Optional[Dict] = None,
webhook: Optional[str] = None,
internal: Optional[bool] = False,
conn: Optional[Connection] = None,
) -> tuple[str, str]:
) -> Tuple[str, str]:
if not amount > 0:
raise InvoiceError("Amountless invoices not supported.", status="failed")
@@ -174,20 +167,17 @@ async def create_invoice(
invoice = bolt11_decode(payment_request)
create_payment_model = CreatePayment(
amount_msat = 1000 * amount_sat
await create_payment(
wallet_id=wallet_id,
checking_id=checking_id,
payment_request=payment_request,
payment_hash=invoice.payment_hash,
amount=amount_sat * 1000,
amount=amount_msat,
expiry=invoice.expiry_date,
memo=memo,
extra=extra,
webhook=webhook,
)
await create_payment(
checking_id=checking_id,
data=create_payment_model,
conn=conn,
)
@@ -199,7 +189,7 @@ async def pay_invoice(
wallet_id: str,
payment_request: str,
max_sat: Optional[int] = None,
extra: Optional[dict] = None,
extra: Optional[Dict] = None,
description: str = "",
conn: Optional[Connection] = None,
) -> str:
@@ -233,7 +223,17 @@ async def pay_invoice(
invoice.amount_msat / 1000, wallet_id, extra=extra, conn=conn
)
create_payment_model = CreatePayment(
# put all parameters that don't change here
class PaymentKwargs(TypedDict):
wallet_id: str
payment_request: str
payment_hash: str
amount: int
memo: str
expiry: Optional[datetime.datetime]
extra: Optional[Dict]
payment_kwargs: PaymentKwargs = PaymentKwargs(
wallet_id=wallet_id,
payment_request=payment_request,
payment_hash=invoice.payment_hash,
@@ -252,6 +252,9 @@ async def pay_invoice(
# (pending only)
internal_checking_id = await check_internal(invoice.payment_hash, conn=conn)
if internal_checking_id:
fee_reserve_total_msat = fee_reserve_total(
invoice.amount_msat, internal=True
)
# perform additional checks on the internal payment
# the payment hash is not enough to make sure that this is the same invoice
internal_invoice = await get_standalone_payment(
@@ -266,23 +269,16 @@ async def pay_invoice(
logger.debug(f"creating temporary internal payment with id {internal_id}")
# create a new payment from this wallet
fee_reserve_total_msat = fee_reserve_total(
invoice.amount_msat, internal=True
)
create_payment_model.fee = abs(fee_reserve_total_msat)
new_payment = await create_payment(
checking_id=internal_id,
data=create_payment_model,
fee=0 + abs(fee_reserve_total_msat),
status=PaymentState.SUCCESS,
conn=conn,
**payment_kwargs,
)
else:
new_payment = await _create_external_payment(
temp_id=temp_id,
amount_msat=invoice.amount_msat,
data=create_payment_model,
conn=conn,
temp_id, invoice.amount_msat, conn=conn, **payment_kwargs
)
# do the balance check
@@ -381,16 +377,14 @@ async def pay_invoice(
# credit service fee wallet
if settings.lnbits_service_fee_wallet and service_fee_msat:
create_payment_model = CreatePayment(
new_payment = await create_payment(
wallet_id=settings.lnbits_service_fee_wallet,
payment_request=payment_request,
payment_hash=invoice.payment_hash,
fee=0,
amount=abs(service_fee_msat),
memo="Service fee",
)
new_payment = await create_payment(
checking_id=f"service_fee_{temp_id}",
data=create_payment_model,
checking_id="service_fee" + temp_id,
payment_request=payment_request,
payment_hash=invoice.payment_hash,
status=PaymentState.SUCCESS,
)
return invoice.payment_hash
@@ -399,8 +393,8 @@ async def pay_invoice(
async def _create_external_payment(
temp_id: str,
amount_msat: MilliSatoshi,
data: CreatePayment,
conn: Optional[Connection],
**payment_kwargs,
) -> Payment:
fee_reserve_total_msat = fee_reserve_total(amount_msat, internal=False)
@@ -434,11 +428,11 @@ async def _create_external_payment(
# create a temporary payment here so we can check if
# the balance is enough in the next step
try:
data.fee = -abs(fee_reserve_total_msat)
new_payment = await create_payment(
checking_id=temp_id,
data=data,
fee=-abs(fee_reserve_total_msat),
conn=conn,
**payment_kwargs,
)
return new_payment
except Exception as exc:
@@ -520,7 +514,7 @@ async def redeem_lnurl_withdraw(
wallet_id: str,
lnurl_request: str,
memo: Optional[str] = None,
extra: Optional[dict] = None,
extra: Optional[Dict] = None,
wait_seconds: int = 0,
conn: Optional[Connection] = None,
) -> None:
@@ -859,7 +853,7 @@ async def create_user_account(
class WebsocketConnectionManager:
def __init__(self) -> None:
self.active_connections: list[WebSocket] = []
self.active_connections: List[WebSocket] = []
async def connect(self, websocket: WebSocket, item_id: str):
logger.debug(f"Websocket connected to {item_id}")
+1 -1
View File
@@ -901,7 +901,7 @@
</q-dialog>
{% endblock %} {% block scripts %} {{ window_vars(user) }}
<script>
window.app = Vue.createApp({
new Vue({
el: '#vue',
data: function () {
+2 -2
View File
@@ -154,10 +154,10 @@
<q-card>
<q-card-section class="text-center">
<p v-text="$t('export_to_phone_desc')"></p>
<qrcode-vue
<qrcode
:value="'{{request.base_url}}wallet?usr={{user.id}}&wal={{wallet.id}}'"
:options="{ width: 256 }"
></qrcode-vue>
></qrcode>
</q-card-section>
<q-card-actions class="flex-center q-pb-md">
<q-btn
@@ -51,11 +51,11 @@
>
<a :href="'lightning:' + transactionDetailsDialog.data.bolt11">
<q-responsive :ratio="1" class="q-mx-xl">
<qrcode-vue
<qrcode
:value="'lightning:' + transactionDetailsDialog.data.bolt11.toUpperCase()"
:options="{width: 340}"
class="rounded-borders"
></qrcode-vue>
></qrcode>
</q-responsive>
</a>
<q-btn
@@ -138,11 +138,11 @@
>
<a :href="'lightning:' + props.row.bolt11">
<q-responsive :ratio="1" class="q-mx-xl">
<qrcode-vue
<qrcode
:value="'lightning:' + props.row.bolt11.toUpperCase()"
:options="{width: 340}"
class="rounded-borders"
></qrcode-vue>
></qrcode>
</q-responsive>
</a>
</div>
+4 -4
View File
@@ -7,7 +7,7 @@ include "users/_createWalletDialog.html" %}
<div class="row q-col-gutter-md justify-center">
<div class="col q-gutter-y-md" style="width: 300px">
<div style="width: 100%; max-width: 2000px">
<div style="width: 600px">
<canvas ref="chart1"></canvas>
</div>
</div>
@@ -24,8 +24,8 @@ include "users/_createWalletDialog.html" %}
</q-btn>
</div>
<q-table
row-key="id"
:rows="users"
:data="users"
:row-key="usersTableRowKey"
:columns="usersTable.columns"
:pagination.sync="usersTable.pagination"
:no-data-label="$t('no_users')"
@@ -70,7 +70,7 @@ include "users/_createWalletDialog.html" %}
v-if="!props.row.is_super_user"
icon="build"
size="sm"
:color="props.row.is_admin ? 'primary' : 'grey'"
:color="props.row.is_admin ? 'primary' : ''"
@click="toggleAdmin(props.row.id)"
>
<q-tooltip>Toggle Admin</q-tooltip>
+100 -59
View File
@@ -1,6 +1,8 @@
import sys
from http import HTTPStatus
from typing import (
List,
Optional,
)
from bolt11 import decode as bolt11_decode
@@ -11,21 +13,10 @@ from fastapi import (
)
from loguru import logger
from lnbits.core.extensions.extension_manager import (
activate_extension,
deactivate_extension,
install_extension,
uninstall_extension,
)
from lnbits.core.extensions.models import (
CreateExtension,
Extension,
ExtensionConfig,
ExtensionRelease,
InstallableExtension,
PayToEnableInfo,
ReleasePaymentInfo,
UserExtensionInfo,
from lnbits.core.db import core_app_extra
from lnbits.core.helpers import (
migrate_extension_database,
stop_extension_background_work,
)
from lnbits.core.models import (
SimpleStatus,
@@ -33,18 +24,36 @@ from lnbits.core.models import (
)
from lnbits.core.services import check_transaction_status, create_invoice
from lnbits.decorators import (
check_access_token,
check_admin,
check_user_exists,
)
from lnbits.extension_manager import (
CreateExtension,
Extension,
ExtensionRelease,
InstallableExtension,
PayToEnableInfo,
ReleasePaymentInfo,
UserExtensionInfo,
fetch_github_release_config,
fetch_release_details,
fetch_release_payment_info,
get_valid_extensions,
)
from lnbits.settings import settings
from ..crud import (
add_installed_extension,
delete_dbversion,
delete_installed_extension,
drop_extension_db,
get_dbversions,
get_installed_extension,
get_installed_extensions,
get_user_extension,
update_extension_pay_to_enable,
update_installed_extension_state,
update_user_extension,
update_user_extension_extra,
)
@@ -55,8 +64,12 @@ extension_router = APIRouter(
)
@extension_router.post("", dependencies=[Depends(check_admin)])
async def api_install_extension(data: CreateExtension):
@extension_router.post("")
async def api_install_extension(
data: CreateExtension,
user: User = Depends(check_admin),
access_token: Optional[str] = Depends(check_access_token),
):
release = await InstallableExtension.get_extension_release(
data.ext_id, data.source_repo, data.archive, data.version
)
@@ -76,36 +89,43 @@ async def api_install_extension(data: CreateExtension):
)
try:
extension = await install_extension(ext_info)
installed_ext = await get_installed_extension(data.ext_id)
ext_info.payments = installed_ext.payments if installed_ext else []
await ext_info.download_archive()
ext_info.extract_archive()
extension = Extension.from_installable_ext(ext_info)
db_version = (await get_dbversions()).get(data.ext_id, 0)
await migrate_extension_database(extension, db_version)
ext_info.active = True
await add_installed_extension(ext_info)
if extension.is_upgrade_extension:
# call stop while the old routes are still active
await stop_extension_background_work(data.ext_id, user.id, access_token)
# mount routes for the new version
core_app_extra.register_new_ext_routes(extension)
ext_info.notify_upgrade(extension.upgrade_hash)
settings.lnbits_deactivated_extensions.discard(data.ext_id)
return extension
except AssertionError as exc:
raise HTTPException(HTTPStatus.BAD_REQUEST, str(exc)) from exc
except Exception as exc:
logger.warning(exc)
ext_info.clean_extension_files()
detail = (
str(exc)
if isinstance(exc, AssertionError)
else f"Failed to install extension '{ext_info.id}'."
f"({ext_info.installed_version})."
)
raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
detail=detail,
) from exc
try:
await activate_extension(extension)
return extension
except Exception as exc:
logger.warning(exc)
await deactivate_extension(extension.code)
detail = (
str(exc)
if isinstance(exc, AssertionError)
else f"Extension `{extension.code}` installed, but activation failed."
)
raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
detail=detail,
detail=(
f"Failed to install extension {ext_info.id} "
f"({ext_info.installed_version})."
),
) from exc
@@ -123,7 +143,7 @@ async def api_extension_details(
)
assert release, "Details not found for release"
release_details = await ExtensionRelease.fetch_release_details(details_link)
release_details = await fetch_release_details(details_link)
assert release_details, "Cannot fetch details for release"
release_details["icon"] = release.icon
release_details["repo"] = release.repo
@@ -166,7 +186,7 @@ async def api_update_pay_to_enable(
async def api_enable_extension(
ext_id: str, user: User = Depends(check_user_exists)
) -> SimpleStatus:
if ext_id not in [e.code for e in Extension.get_valid_extensions()]:
if ext_id not in [e.code for e in get_valid_extensions()]:
raise HTTPException(
HTTPStatus.NOT_FOUND, f"Extension '{ext_id}' doesn't exist."
)
@@ -229,7 +249,7 @@ async def api_enable_extension(
async def api_disable_extension(
ext_id: str, user: User = Depends(check_user_exists)
) -> SimpleStatus:
if ext_id not in [e.code for e in Extension.get_valid_extensions()]:
if ext_id not in [e.code for e in get_valid_extensions()]:
raise HTTPException(
HTTPStatus.BAD_REQUEST, f"Extension '{ext_id}' doesn't exist."
)
@@ -250,14 +270,20 @@ async def api_activate_extension(ext_id: str) -> SimpleStatus:
try:
logger.info(f"Activating extension: '{ext_id}'.")
ext = Extension.get_valid_extension(ext_id)
all_extensions = get_valid_extensions()
ext = next((e for e in all_extensions if e.code == ext_id), None)
assert ext, f"Extension '{ext_id}' doesn't exist."
# if extension never loaded (was deactivated on server startup)
if ext_id not in sys.modules.keys():
# run extension start-up routine
core_app_extra.register_new_ext_routes(ext)
await activate_extension(ext)
settings.lnbits_deactivated_extensions.discard(ext_id)
await update_installed_extension_state(ext_id=ext_id, active=True)
return SimpleStatus(success=True, message=f"Extension '{ext_id}' activated.")
except Exception as exc:
logger.warning(exc)
await deactivate_extension(ext_id)
raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
detail=(f"Failed to activate '{ext_id}'."),
@@ -269,10 +295,13 @@ async def api_deactivate_extension(ext_id: str) -> SimpleStatus:
try:
logger.info(f"Deactivating extension: '{ext_id}'.")
ext = Extension.get_valid_extension(ext_id)
all_extensions = get_valid_extensions()
ext = next((e for e in all_extensions if e.code == ext_id), None)
assert ext, f"Extension '{ext_id}' doesn't exist."
await deactivate_extension(ext_id)
settings.lnbits_deactivated_extensions.add(ext_id)
await update_installed_extension_state(ext_id=ext_id, active=False)
return SimpleStatus(success=True, message=f"Extension '{ext_id}' deactivated.")
except Exception as exc:
logger.warning(exc)
@@ -282,19 +311,23 @@ async def api_deactivate_extension(ext_id: str) -> SimpleStatus:
) from exc
@extension_router.delete("/{ext_id}", dependencies=[Depends(check_admin)])
async def api_uninstall_extension(ext_id: str) -> SimpleStatus:
@extension_router.delete("/{ext_id}")
async def api_uninstall_extension(
ext_id: str,
user: User = Depends(check_admin),
access_token: Optional[str] = Depends(check_access_token),
) -> SimpleStatus:
installed_extensions = await get_installed_extensions()
extension = await get_installed_extension(ext_id)
if not extension:
extensions = [e for e in installed_extensions if e.id == ext_id]
if len(extensions) == 0:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail=f"Unknown extension id: {ext_id}",
)
installed_extensions = await get_installed_extensions()
# check that other extensions do not depend on this one
for valid_ext_id in [ext.code for ext in Extension.get_valid_extensions()]:
for valid_ext_id in [ext.code for ext in get_valid_extensions()]:
installed_ext = next(
(ext for ext in installed_extensions if ext.id == valid_ext_id), None
)
@@ -308,7 +341,14 @@ async def api_uninstall_extension(ext_id: str) -> SimpleStatus:
)
try:
await uninstall_extension(ext_id)
# call stop while the old routes are still active
await stop_extension_background_work(ext_id, user.id, access_token)
settings.lnbits_deactivated_extensions.add(ext_id)
for ext_info in extensions:
ext_info.clean_extension_files()
await delete_installed_extension(ext_id=ext_info.id)
logger.success(f"Extension '{ext_id}' uninstalled.")
return SimpleStatus(success=True, message=f"Extension '{ext_id}' uninstalled.")
@@ -357,8 +397,9 @@ async def get_pay_to_install_invoice(
assert release, "Release not found."
assert release.pay_link, "Pay link not found for release."
payment_info = await release.fetch_release_payment_info(data.cost_sats)
payment_info = await fetch_release_payment_info(
release.pay_link, data.cost_sats
)
assert payment_info and payment_info.payment_request, "Cannot request invoice."
invoice = bolt11_decode(payment_info.payment_request)
@@ -433,7 +474,7 @@ async def get_pay_to_enable_invoice(
)
async def get_extension_release(org: str, repo: str, tag_name: str):
try:
config = await ExtensionConfig.fetch_github_release_config(org, repo, tag_name)
config = await fetch_github_release_config(org, repo, tag_name)
if not config:
return {}
+2 -2
View File
@@ -12,7 +12,6 @@ from lnurl import decode as lnurl_decode
from loguru import logger
from pydantic.types import UUID4
from lnbits.core.extensions.models import Extension, InstallableExtension
from lnbits.core.helpers import to_valid_user_id
from lnbits.core.models import User
from lnbits.core.services import create_invoice
@@ -21,6 +20,7 @@ from lnbits.helpers import template_renderer
from lnbits.settings import settings
from lnbits.wallets import get_funding_source
from ...extension_manager import InstallableExtension, get_valid_extensions
from ...utils.exchange_rates import allowed_currencies, currencies
from ..crud import (
create_account,
@@ -104,7 +104,7 @@ async def extensions(request: Request, user: User = Depends(check_user_exists)):
installed_exts_ids = []
try:
all_ext_ids = [ext.code for ext in Extension.get_valid_extensions()]
all_ext_ids = [ext.code for ext in get_valid_extensions()]
inactive_extensions = [
e.id for e in await get_installed_extensions(active=False)
]
+12 -11
View File
@@ -35,6 +35,7 @@ from lnbits.core.models import (
from lnbits.db import Filters, Page
from lnbits.decorators import (
WalletTypeInfo,
get_key_type,
parse_filters,
require_admin_key,
require_invoice_key,
@@ -72,12 +73,12 @@ payment_router = APIRouter(prefix="/api/v1/payments", tags=["Payments"])
openapi_extra=generate_filter_params_openapi(PaymentFilters),
)
async def api_payments(
key_info: WalletTypeInfo = Depends(require_invoice_key),
wallet: WalletTypeInfo = Depends(get_key_type),
filters: Filters = Depends(parse_filters(PaymentFilters)),
):
await update_pending_payments(key_info.wallet.id)
await update_pending_payments(wallet.wallet.id)
return await get_payments(
wallet_id=key_info.wallet.id,
wallet_id=wallet.wallet.id,
pending=True,
complete=True,
filters=filters,
@@ -91,12 +92,12 @@ async def api_payments(
openapi_extra=generate_filter_params_openapi(PaymentFilters),
)
async def api_payments_history(
key_info: WalletTypeInfo = Depends(require_invoice_key),
wallet: WalletTypeInfo = Depends(get_key_type),
group: DateTrunc = Query("day"),
filters: Filters[PaymentFilters] = Depends(parse_filters(PaymentFilters)),
):
await update_pending_payments(key_info.wallet.id)
return await get_payments_history(key_info.wallet.id, group, filters)
await update_pending_payments(wallet.wallet.id)
return await get_payments_history(wallet.wallet.id, group, filters)
@payment_router.get(
@@ -108,12 +109,12 @@ async def api_payments_history(
openapi_extra=generate_filter_params_openapi(PaymentFilters),
)
async def api_payments_paginated(
key_info: WalletTypeInfo = Depends(require_invoice_key),
wallet: WalletTypeInfo = Depends(get_key_type),
filters: Filters = Depends(parse_filters(PaymentFilters)),
):
await update_pending_payments(key_info.wallet.id)
await update_pending_payments(wallet.wallet.id)
page = await get_payments_paginated(
wallet_id=key_info.wallet.id,
wallet_id=wallet.wallet.id,
pending=True,
complete=True,
filters=filters,
@@ -377,10 +378,10 @@ async def subscribe_wallet_invoices(request: Request, wallet: Wallet):
@payment_router.get("/sse")
async def api_payments_sse(
request: Request, key_info: WalletTypeInfo = Depends(require_invoice_key)
request: Request, wallet: WalletTypeInfo = Depends(get_key_type)
):
return EventSourceResponse(
subscribe_wallet_invoices(request, key_info.wallet),
subscribe_wallet_invoices(request, wallet.wallet),
ping=20,
media_type="text/event-stream",
)
+9 -8
View File
@@ -13,8 +13,8 @@ from lnbits.core.models import (
)
from lnbits.decorators import (
WalletTypeInfo,
get_key_type,
require_admin_key,
require_invoice_key,
)
from ..crud import (
@@ -27,14 +27,15 @@ wallet_router = APIRouter(prefix="/api/v1/wallet", tags=["Wallet"])
@wallet_router.get("")
async def api_wallet(wallet: WalletTypeInfo = Depends(require_invoice_key)):
res = {
"name": wallet.wallet.name,
"balance": wallet.wallet.balance_msat,
}
async def api_wallet(wallet: WalletTypeInfo = Depends(get_key_type)):
if wallet.key_type == KeyType.admin:
res["id"] = wallet.wallet.id
return res
return {
"id": wallet.wallet.id,
"name": wallet.wallet.name,
"balance": wallet.wallet.balance_msat,
}
else:
return {"name": wallet.wallet.name, "balance": wallet.wallet.balance_msat}
@wallet_router.put("/{new_name}")
+119 -124
View File
@@ -7,13 +7,14 @@ import re
import time
from contextlib import asynccontextmanager
from enum import Enum
from sqlite3 import Row
from typing import Any, Generic, Literal, Optional, TypeVar
from loguru import logger
from pydantic import BaseModel, ValidationError, root_validator
from sqlalchemy import event
from sqlalchemy.ext.asyncio import AsyncConnection, AsyncEngine, create_async_engine
from sqlalchemy.sql import text
from sqlalchemy import create_engine
from sqlalchemy_aio.base import AsyncConnection
from sqlalchemy_aio.strategy import ASYNCIO_STRATEGY
from lnbits.settings import settings
@@ -23,15 +24,31 @@ SQLITE = "SQLITE"
if settings.lnbits_database_url:
database_uri = settings.lnbits_database_url
if database_uri.startswith("cockroachdb://"):
DB_TYPE = COCKROACH
else:
if not database_uri.startswith("postgres://"):
raise ValueError(
"Please use the 'postgres://...' " "format for the database URL."
)
DB_TYPE = POSTGRES
from psycopg2.extensions import DECIMAL, new_type, register_type
def _parse_timestamp(value, _):
if value is None:
return None
f = "%Y-%m-%d %H:%M:%S.%f"
if "." not in value:
f = "%Y-%m-%d %H:%M:%S"
return time.mktime(datetime.datetime.strptime(value, f).timetuple())
register_type(
new_type(
DECIMAL.values,
"DEC2FLOAT",
lambda value, curs: float(value) if value is not None else None,
)
)
register_type(new_type((1184, 1114), "TIMESTAMP2INT", _parse_timestamp))
else:
if not os.path.isdir(settings.lnbits_data_folder):
os.mkdir(settings.lnbits_data_folder)
@@ -39,21 +56,21 @@ else:
DB_TYPE = SQLITE
def compat_timestamp_placeholder(key: str):
def compat_timestamp_placeholder():
if DB_TYPE == POSTGRES:
return f"to_timestamp(:{key})"
return "to_timestamp(?)"
elif DB_TYPE == COCKROACH:
return f"cast(:{key} AS timestamp)"
return "cast(? AS timestamp)"
else:
return f":{key}"
return "?"
def get_placeholder(model: Any, field: str) -> str:
type_ = model.__fields__[field].type_
if type_ == datetime.datetime:
return compat_timestamp_placeholder(field)
return compat_timestamp_placeholder()
else:
return f":{field}"
return "?"
class Compat:
@@ -110,13 +127,15 @@ class Compat:
return "BIGINT"
return "INT"
def timestamp_placeholder(self, key: str) -> str:
return compat_timestamp_placeholder(key)
@property
def timestamp_placeholder(self) -> str:
return compat_timestamp_placeholder()
class Connection(Compat):
def __init__(self, conn: AsyncConnection, typ, name, schema):
def __init__(self, conn: AsyncConnection, txn, typ, name, schema):
self.conn = conn
self.txn = txn
self.type = typ
self.name = name
self.schema = schema
@@ -127,42 +146,45 @@ class Connection(Compat):
query = query.replace("?", "%s")
return query
def rewrite_values(self, values: dict) -> dict:
def rewrite_values(self, values):
# strip html
clean_regex = re.compile("<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});")
clean_values: dict = {}
for key, raw_value in values.items():
# tuple to list and back to tuple
raw_values = [values] if isinstance(values, str) else list(values)
values = []
for raw_value in raw_values:
if isinstance(raw_value, str):
clean_values[key] = re.sub(clean_regex, "", raw_value)
values.append(re.sub(clean_regex, "", raw_value))
elif isinstance(raw_value, datetime.datetime):
ts = raw_value.timestamp()
if self.type == SQLITE:
clean_values[key] = int(ts)
values.append(int(ts))
else:
clean_values[key] = ts
values.append(ts)
else:
clean_values[key] = raw_value
return clean_values
values.append(raw_value)
return tuple(values)
async def fetchall(self, query: str, values: Optional[dict] = None) -> list[dict]:
params = self.rewrite_values(values) if values else {}
result = await self.conn.execute(text(self.rewrite_query(query)), params)
row = result.mappings().all()
result.close()
return row
async def fetchall(self, query: str, values: tuple = ()) -> list:
result = await self.conn.execute(
self.rewrite_query(query), self.rewrite_values(values)
)
return await result.fetchall()
async def fetchone(self, query: str, values: Optional[dict] = None) -> dict:
params = self.rewrite_values(values) if values else {}
result = await self.conn.execute(text(self.rewrite_query(query)), params)
row = result.mappings().first()
result.close()
async def fetchone(self, query: str, values: tuple = ()):
result = await self.conn.execute(
self.rewrite_query(query), self.rewrite_values(values)
)
row = await result.fetchone()
await result.close()
return row
async def fetch_page(
self,
query: str,
where: Optional[list[str]] = None,
values: Optional[dict] = None,
values: Optional[list[str]] = None,
filters: Optional[Filters] = None,
model: Optional[type[TRowModel]] = None,
group_by: Optional[list[str]] = None,
@@ -189,14 +211,14 @@ class Connection(Compat):
{filters.order_by()}
{filters.pagination()}
""",
self.rewrite_values(parsed_values),
parsed_values,
)
if rows:
# no need for extra query if no pagination is specified
if filters.offset or filters.limit:
result = await self.fetchone(
count = await self.fetchone(
f"""
SELECT COUNT(*) as count FROM (
SELECT COUNT(*) FROM (
{query}
{clause}
{group_by_string}
@@ -204,22 +226,21 @@ class Connection(Compat):
""",
parsed_values,
)
count = int(result.get("count", 0))
count = int(count[0])
else:
count = len(rows)
else:
count = 0
return Page(
data=[model.from_row(row) for row in rows] if model else [],
data=[model.from_row(row) for row in rows] if model else rows,
total=count,
)
async def execute(self, query: str, values: Optional[dict] = None):
params = self.rewrite_values(values) if values else {}
result = await self.conn.execute(text(self.rewrite_query(query)), params)
await self.conn.commit()
return result
async def execute(self, query: str, values: tuple = ()):
return await self.conn.execute(
self.rewrite_query(query), self.rewrite_values(values)
)
class Database(Compat):
@@ -232,44 +253,18 @@ class Database(Compat):
self.path = os.path.join(
settings.lnbits_data_folder, f"{self.name}.sqlite3"
)
database_uri = f"sqlite+aiosqlite:///{self.path}"
database_uri = f"sqlite:///{self.path}"
else:
database_uri = settings.lnbits_database_url.replace(
"postgres://", "postgresql+asyncpg://"
)
database_uri = settings.lnbits_database_url
if self.name.startswith("ext_"):
self.schema = self.name[4:]
else:
self.schema = None
self.engine: AsyncEngine = create_async_engine(
database_uri, echo=settings.debug_database
self.engine = create_engine(
database_uri, strategy=ASYNCIO_STRATEGY, echo=settings.debug_database
)
if self.type in {POSTGRES, COCKROACH}:
@event.listens_for(self.engine.sync_engine, "connect")
def register_custom_types(dbapi_connection, *_):
def _parse_timestamp(value):
if value is None:
return None
f = "%Y-%m-%d %H:%M:%S.%f"
if "." not in value:
f = "%Y-%m-%d %H:%M:%S"
return int(
time.mktime(datetime.datetime.strptime(value, f).timetuple())
)
dbapi_connection.run_async(
lambda connection: connection.set_type_codec(
"TIMESTAMP",
encoder=datetime.datetime,
decoder=_parse_timestamp,
schema="pg_catalog",
)
)
self.lock = asyncio.Lock()
logger.trace(f"database {self.type} added for {self.name}")
@@ -278,37 +273,41 @@ class Database(Compat):
async def connect(self):
await self.lock.acquire()
try:
async with self.engine.connect() as conn:
if not conn:
raise Exception("Could not connect to the database")
async with self.engine.connect() as conn: # type: ignore
async with conn.begin() as txn:
wconn = Connection(conn, txn, self.type, self.name, self.schema)
wconn = Connection(conn, self.type, self.name, self.schema)
if self.schema:
if self.type in {POSTGRES, COCKROACH}:
await wconn.execute(
f"CREATE SCHEMA IF NOT EXISTS {self.schema}"
)
elif self.type == SQLITE:
await wconn.execute(
f"ATTACH '{self.path}' AS {self.schema}"
)
if self.schema:
if self.type in {POSTGRES, COCKROACH}:
await wconn.execute(
f"CREATE SCHEMA IF NOT EXISTS {self.schema}"
)
elif self.type == SQLITE:
await wconn.execute(f"ATTACH '{self.path}' AS {self.schema}")
yield wconn
yield wconn
finally:
self.lock.release()
async def fetchall(self, query: str, values: Optional[dict] = None) -> list[dict]:
async def fetchall(self, query: str, values: tuple = ()) -> list:
async with self.connect() as conn:
return await conn.fetchall(query, values)
result = await conn.execute(query, values)
return await result.fetchall()
async def fetchone(self, query: str, values: Optional[dict] = None) -> dict:
async def fetchone(self, query: str, values: tuple = ()):
async with self.connect() as conn:
return await conn.fetchone(query, values)
result = await conn.execute(query, values)
row = await result.fetchone()
await result.close()
return row
async def fetch_page(
self,
query: str,
where: Optional[list[str]] = None,
values: Optional[dict] = None,
values: Optional[list[str]] = None,
filters: Optional[Filters] = None,
model: Optional[type[TRowModel]] = None,
group_by: Optional[list[str]] = None,
@@ -316,7 +315,7 @@ class Database(Compat):
async with self.connect() as conn:
return await conn.fetch_page(query, where, values, filters, model, group_by)
async def execute(self, query: str, values: Optional[dict] = None):
async def execute(self, query: str, values: tuple = ()):
async with self.connect() as conn:
return await conn.execute(query, values)
@@ -374,8 +373,8 @@ class Operator(Enum):
class FromRowModel(BaseModel):
@classmethod
def from_row(cls, row: dict):
return cls(**row)
def from_row(cls, row: Row):
return cls(**dict(row))
class FilterModel(BaseModel):
@@ -397,13 +396,12 @@ class Page(BaseModel, Generic[T]):
class Filter(BaseModel, Generic[TFilterModel]):
field: str
op: Operator = Operator.EQ
values: list[Any]
model: Optional[type[TFilterModel]]
values: Optional[dict] = None
@classmethod
def parse_query(
cls, key: str, raw_values: list[Any], model: type[TFilterModel], i: int = 0
):
def parse_query(cls, key: str, raw_values: list[Any], model: type[TFilterModel]):
# Key format:
# key[operator]
# e.g. name[eq]
@@ -419,12 +417,12 @@ class Filter(BaseModel, Generic[TFilterModel]):
if field in model.__fields__:
compare_field = model.__fields__[field]
values: dict = {}
values = []
for raw_value in raw_values:
validated, errors = compare_field.validate(raw_value, {}, loc="none")
if errors:
raise ValidationError(errors=[errors], model=model)
values[f"{field}__{i}"] = validated
values.append(validated)
else:
raise ValueError("Unknown filter field")
@@ -432,17 +430,13 @@ class Filter(BaseModel, Generic[TFilterModel]):
@property
def statement(self):
stmt = []
for key in self.values.keys() if self.values else []:
clean_key = key.split("__")[0]
if (
self.model
and self.model.__fields__[clean_key].type_ == datetime.datetime
):
placeholder = compat_timestamp_placeholder(key)
else:
placeholder = f":{key}"
stmt.append(f"{clean_key} {self.op.as_sql} {placeholder}")
assert self.model, "Model is required for statement generation"
placeholder = get_placeholder(self.model, self.field)
if self.op in (Operator.INCLUDE, Operator.EXCLUDE):
placeholders = ", ".join([placeholder] * len(self.values))
stmt = [f"{self.field} {self.op.as_sql} ({placeholders})"]
else:
stmt = [f"{self.field} {self.op.as_sql} {placeholder}"] * len(self.values)
return " OR ".join(stmt)
@@ -493,11 +487,14 @@ class Filters(BaseModel, Generic[TFilterModel]):
for page_filter in self.filters:
where_stmts.append(page_filter.statement)
if self.search and self.model:
fields = self.model.__search_fields__
if DB_TYPE == POSTGRES:
where_stmts.append(f"lower(concat({', '.join(fields)})) LIKE :search")
where_stmts.append(
f"lower(concat({', '.join(self.model.__search_fields__)})) LIKE ?"
)
elif DB_TYPE == SQLITE:
where_stmts.append(f"lower({'||'.join(fields)}) LIKE :search")
where_stmts.append(
f"lower({'||'.join(self.model.__search_fields__)}) LIKE ?"
)
if where_stmts:
return "WHERE " + " AND ".join(where_stmts)
return ""
@@ -507,14 +504,12 @@ class Filters(BaseModel, Generic[TFilterModel]):
return f"ORDER BY {self.sortby} {self.direction or 'asc'}"
return ""
def values(self, values: Optional[dict] = None) -> dict:
def values(self, values: Optional[list[str]] = None) -> tuple:
if not values:
values = {}
values = []
if self.filters:
for page_filter in self.filters:
if page_filter.values:
for key, value in page_filter.values.items():
values[key] = value
values.extend(page_filter.values)
if self.search and self.model:
values["search"] = f"%{self.search}%"
return values
values.append(f"%{self.search}%")
return tuple(values)
+11 -2
View File
@@ -95,6 +95,15 @@ class KeyChecker(SecurityBase):
return WalletTypeInfo(key_type, wallet)
async def get_key_type(
request: Request,
api_key_header: str = Security(api_key_header),
api_key_query: str = Security(api_key_query),
) -> WalletTypeInfo:
check: KeyChecker = KeyChecker(api_key=api_key_header or api_key_query)
return await check(request)
async def require_admin_key(
request: Request,
api_key_header: str = Security(api_key_header),
@@ -195,9 +204,9 @@ def parse_filters(model: Type[TFilterModel]):
):
params = request.query_params
filters = []
for i, key in enumerate(params.keys()):
for key in params.keys():
try:
filters.append(Filter.parse_query(key, params.getlist(key), model, i))
filters.append(Filter.parse_query(key, params.getlist(key), model))
except ValueError:
continue
@@ -1,5 +1,3 @@
from __future__ import annotations
import asyncio
import hashlib
import json
@@ -8,22 +6,16 @@ import shutil
import sys
import zipfile
from pathlib import Path
from typing import Any, NamedTuple, Optional
from typing import Any, List, NamedTuple, Optional, Tuple
from urllib import request
import httpx
from loguru import logger
from packaging import version
from pydantic import BaseModel
from lnbits.settings import settings
from .helpers import (
download_url,
file_hash,
github_api_get,
icon_to_github_url,
version_parse,
)
class ExplicitRelease(BaseModel):
id: str
@@ -31,7 +23,7 @@ class ExplicitRelease(BaseModel):
version: str
archive: str
hash: str
dependencies: list[str] = []
dependencies: List[str] = []
repo: Optional[str]
icon: Optional[str]
short_description: Optional[str]
@@ -56,9 +48,9 @@ class GitHubRelease(BaseModel):
class Manifest(BaseModel):
featured: list[str] = []
extensions: list[ExplicitRelease] = []
repos: list[GitHubRelease] = []
featured: List[str] = []
extensions: List["ExplicitRelease"] = []
repos: List["GitHubRelease"] = []
class GitHubRepoRelease(BaseModel):
@@ -89,17 +81,6 @@ class ExtensionConfig(BaseModel):
return True
return version_parse(self.min_lnbits_version) <= version_parse(settings.version)
@classmethod
async def fetch_github_release_config(
cls, org: str, repo: str, tag_name: str
) -> Optional[ExtensionConfig]:
config_url = (
f"https://raw.githubusercontent.com/{org}/{repo}/{tag_name}/config.json"
)
error_msg = "Cannot fetch GitHub extension config"
config = await github_api_get(config_url, error_msg)
return ExtensionConfig.parse_obj(config)
class ReleasePaymentInfo(BaseModel):
amount: Optional[int] = None
@@ -131,7 +112,7 @@ class UserExtension(BaseModel):
return self.extra.paid_to_enable is True
@classmethod
def from_row(cls, data: dict) -> UserExtension:
def from_row(cls, data: dict) -> "UserExtension":
ext = UserExtension(**data)
ext.extra = (
UserExtensionInfo(**json.loads(data["_extra"] or "{}"))
@@ -141,6 +122,124 @@ class UserExtension(BaseModel):
return ext
def download_url(url, save_path):
with request.urlopen(url, timeout=60) as dl_file:
with open(save_path, "wb") as out_file:
out_file.write(dl_file.read())
def file_hash(filename):
h = hashlib.sha256()
b = bytearray(128 * 1024)
mv = memoryview(b)
with open(filename, "rb", buffering=0) as f:
while n := f.readinto(mv):
h.update(mv[:n])
return h.hexdigest()
async def fetch_github_repo_info(
org: str, repository: str
) -> Tuple[GitHubRepo, GitHubRepoRelease, ExtensionConfig]:
repo_url = f"https://api.github.com/repos/{org}/{repository}"
error_msg = "Cannot fetch extension repo"
repo = await github_api_get(repo_url, error_msg)
github_repo = GitHubRepo.parse_obj(repo)
lates_release_url = (
f"https://api.github.com/repos/{org}/{repository}/releases/latest"
)
error_msg = "Cannot fetch extension releases"
latest_release: Any = await github_api_get(lates_release_url, error_msg)
config_url = f"https://raw.githubusercontent.com/{org}/{repository}/{github_repo.default_branch}/config.json"
error_msg = "Cannot fetch config for extension"
config = await github_api_get(config_url, error_msg)
return (
github_repo,
GitHubRepoRelease.parse_obj(latest_release),
ExtensionConfig.parse_obj(config),
)
async def fetch_manifest(url) -> Manifest:
error_msg = "Cannot fetch extensions manifest"
manifest = await github_api_get(url, error_msg)
return Manifest.parse_obj(manifest)
async def fetch_github_releases(org: str, repo: str) -> List[GitHubRepoRelease]:
releases_url = f"https://api.github.com/repos/{org}/{repo}/releases"
error_msg = "Cannot fetch extension releases"
releases = await github_api_get(releases_url, error_msg)
return [GitHubRepoRelease.parse_obj(r) for r in releases]
async def fetch_github_release_config(
org: str, repo: str, tag_name: str
) -> Optional[ExtensionConfig]:
config_url = (
f"https://raw.githubusercontent.com/{org}/{repo}/{tag_name}/config.json"
)
error_msg = "Cannot fetch GitHub extension config"
config = await github_api_get(config_url, error_msg)
return ExtensionConfig.parse_obj(config)
async def github_api_get(url: str, error_msg: Optional[str]) -> Any:
headers = {"User-Agent": settings.user_agent}
if settings.lnbits_ext_github_token:
headers["Authorization"] = f"Bearer {settings.lnbits_ext_github_token}"
async with httpx.AsyncClient(headers=headers) as client:
resp = await client.get(url)
if resp.status_code != 200:
logger.warning(f"{error_msg} ({url}): {resp.text}")
resp.raise_for_status()
return resp.json()
async def fetch_release_payment_info(
url: str, amount: Optional[int] = None
) -> Optional[ReleasePaymentInfo]:
if amount:
url = f"{url}?amount={amount}"
try:
async with httpx.AsyncClient() as client:
resp = await client.get(url)
resp.raise_for_status()
return ReleasePaymentInfo(**resp.json())
except Exception as e:
logger.warning(e)
return None
async def fetch_release_details(details_link: str) -> Optional[dict]:
try:
async with httpx.AsyncClient() as client:
resp = await client.get(details_link)
resp.raise_for_status()
data = resp.json()
if "description_md" in data:
resp = await client.get(data["description_md"])
if not resp.is_error:
data["description_md"] = resp.text
return data
except Exception as e:
logger.warning(e)
return None
def icon_to_github_url(source_repo: str, path: Optional[str]) -> str:
if not path:
return ""
_, _, *rest = path.split("/")
tail = "/".join(rest)
return f"https://github.com/{source_repo}/raw/main/{tail}"
class Extension(NamedTuple):
code: str
is_valid: bool
@@ -148,7 +247,7 @@ class Extension(NamedTuple):
name: Optional[str] = None
short_description: Optional[str] = None
tile: Optional[str] = None
contributors: Optional[list[str]] = None
contributors: Optional[List[str]] = None
hidden: bool = False
migration_module: Optional[str] = None
db_name: Optional[str] = None
@@ -170,7 +269,7 @@ class Extension(NamedTuple):
return self.upgrade_hash != ""
@classmethod
def from_installable_ext(cls, ext_info: InstallableExtension) -> Extension:
def from_installable_ext(cls, ext_info: "InstallableExtension") -> "Extension":
return Extension(
code=ext_info.id,
is_valid=True,
@@ -179,43 +278,22 @@ class Extension(NamedTuple):
upgrade_hash=ext_info.hash if ext_info.module_installed else "",
)
@classmethod
def get_valid_extensions(
cls, include_deactivated: Optional[bool] = True
) -> list[Extension]:
valid_extensions = [
extension for extension in cls._extensions() if extension.is_valid
]
if include_deactivated:
return valid_extensions
# All subdirectories in the current directory, not recursive.
if settings.lnbits_extensions_deactivate_all:
return []
return [
e
for e in valid_extensions
if e.code not in settings.lnbits_deactivated_extensions
]
@classmethod
def get_valid_extension(
cls, ext_id: str, include_deactivated: Optional[bool] = True
) -> Optional[Extension]:
all_extensions = cls.get_valid_extensions(include_deactivated)
return next((e for e in all_extensions if e.code == ext_id), None)
@classmethod
def _extensions(cls) -> list[Extension]:
class ExtensionManager:
def __init__(self) -> None:
p = Path(settings.lnbits_extensions_path, "extensions")
Path(p).mkdir(parents=True, exist_ok=True)
extension_folders: list[Path] = [f for f in p.iterdir() if f.is_dir()]
self._extension_folders: List[Path] = [f for f in p.iterdir() if f.is_dir()]
@property
def extensions(self) -> List[Extension]:
# todo: remove this property somehow, it is too expensive
output: list[Extension] = []
output: List[Extension] = []
for extension_folder in extension_folders:
for extension_folder in self._extension_folders:
extension_code = extension_folder.parts[-1]
try:
with open(extension_folder / "config.json") as json_file:
@@ -278,27 +356,13 @@ class ExtensionRelease(BaseModel):
if not self.pay_link:
return
payment_info = await self.fetch_release_payment_info()
payment_info = await fetch_release_payment_info(self.pay_link)
self.cost_sats = payment_info.amount if payment_info else None
async def fetch_release_payment_info(
self, amount: Optional[int] = None
) -> Optional[ReleasePaymentInfo]:
url = f"{self.pay_link}?amount={amount}" if amount else self.pay_link
assert url, "Missing URL for payment info."
try:
async with httpx.AsyncClient() as client:
resp = await client.get(url)
resp.raise_for_status()
return ReleasePaymentInfo(**resp.json())
except Exception as e:
logger.warning(e)
return None
@classmethod
def from_github_release(
cls, source_repo: str, r: GitHubRepoRelease
) -> ExtensionRelease:
cls, source_repo: str, r: "GitHubRepoRelease"
) -> "ExtensionRelease":
return ExtensionRelease(
name=r.name,
description=r.name,
@@ -313,8 +377,8 @@ class ExtensionRelease(BaseModel):
@classmethod
def from_explicit_release(
cls, source_repo: str, e: ExplicitRelease
) -> ExtensionRelease:
cls, source_repo: str, e: "ExplicitRelease"
) -> "ExtensionRelease":
return ExtensionRelease(
name=e.name,
version=e.version,
@@ -333,9 +397,9 @@ class ExtensionRelease(BaseModel):
)
@classmethod
async def get_github_releases(cls, org: str, repo: str) -> list[ExtensionRelease]:
async def get_github_releases(cls, org: str, repo: str) -> List["ExtensionRelease"]:
try:
github_releases = await cls.fetch_github_releases(org, repo)
github_releases = await fetch_github_releases(org, repo)
return [
ExtensionRelease.from_github_release(f"{org}/{repo}", r)
for r in github_releases
@@ -344,33 +408,6 @@ class ExtensionRelease(BaseModel):
logger.warning(e)
return []
@classmethod
async def fetch_github_releases(
cls, org: str, repo: str
) -> list[GitHubRepoRelease]:
releases_url = f"https://api.github.com/repos/{org}/{repo}/releases"
error_msg = "Cannot fetch extension releases"
releases = await github_api_get(releases_url, error_msg)
return [GitHubRepoRelease.parse_obj(r) for r in releases]
@classmethod
async def fetch_release_details(cls, details_link: str) -> Optional[dict]:
try:
async with httpx.AsyncClient() as client:
resp = await client.get(details_link)
resp.raise_for_status()
data = resp.json()
if "description_md" in data:
resp = await client.get(data["description_md"])
if not resp.is_error:
data["description_md"] = resp.text
return data
except Exception as e:
logger.warning(e)
return None
class InstallableExtension(BaseModel):
id: str
@@ -378,13 +415,13 @@ class InstallableExtension(BaseModel):
active: Optional[bool] = False
short_description: Optional[str] = None
icon: Optional[str] = None
dependencies: list[str] = []
dependencies: List[str] = []
is_admin_only: bool = False
stars: int = 0
featured = False
latest_release: Optional[ExtensionRelease] = None
installed_release: Optional[ExtensionRelease] = None
payments: list[ReleasePaymentInfo] = []
payments: List[ReleasePaymentInfo] = []
pay_to_enable: Optional[PayToEnableInfo] = None
archive: Optional[str] = None
@@ -509,6 +546,16 @@ class InstallableExtension(BaseModel):
shutil.copytree(Path(self.ext_upgrade_dir), Path(self.ext_dir))
logger.success(f"Extension {self.name} ({self.installed_version}) installed.")
def notify_upgrade(self, upgrade_hash: Optional[str]) -> None:
"""
Update the list of upgraded extensions. The middleware will perform
redirects based on this
"""
if upgrade_hash:
settings.lnbits_upgraded_extensions.add(f"{self.hash}/{self.id}")
settings.lnbits_all_extensions_ids.add(self.id)
def clean_extension_files(self):
# remove downloaded archive
if self.zip_path.is_file():
@@ -563,7 +610,7 @@ class InstallableExtension(BaseModel):
self.payments.append(payment_info)
@classmethod
def from_row(cls, data: dict) -> InstallableExtension:
def from_row(cls, data: dict) -> "InstallableExtension":
meta = json.loads(data["meta"])
ext = InstallableExtension(**data)
if "installed_release" in meta:
@@ -576,7 +623,9 @@ class InstallableExtension(BaseModel):
return ext
@classmethod
def from_rows(cls, rows: Optional[list[Any]] = None) -> list[InstallableExtension]:
def from_rows(
cls, rows: Optional[List[Any]] = None
) -> List["InstallableExtension"]:
if rows is None:
rows = []
return [InstallableExtension.from_row(row) for row in rows]
@@ -584,9 +633,9 @@ class InstallableExtension(BaseModel):
@classmethod
async def from_github_release(
cls, github_release: GitHubRelease
) -> Optional[InstallableExtension]:
) -> Optional["InstallableExtension"]:
try:
repo, latest_release, config = await cls.fetch_github_repo_info(
repo, latest_release, config = await fetch_github_repo_info(
github_release.organisation, github_release.repository
)
source_repo = f"{github_release.organisation}/{github_release.repository}"
@@ -608,7 +657,7 @@ class InstallableExtension(BaseModel):
return None
@classmethod
def from_explicit_release(cls, e: ExplicitRelease) -> InstallableExtension:
def from_explicit_release(cls, e: ExplicitRelease) -> "InstallableExtension":
return InstallableExtension(
id=e.id,
name=e.name,
@@ -621,13 +670,13 @@ class InstallableExtension(BaseModel):
@classmethod
async def get_installable_extensions(
cls,
) -> list[InstallableExtension]:
extension_list: list[InstallableExtension] = []
extension_id_list: list[str] = []
) -> List["InstallableExtension"]:
extension_list: List[InstallableExtension] = []
extension_id_list: List[str] = []
for url in settings.lnbits_extensions_manifests:
try:
manifest = await cls.fetch_manifest(url)
manifest = await fetch_manifest(url)
for r in manifest.repos:
ext = await InstallableExtension.from_github_release(r)
@@ -663,12 +712,12 @@ class InstallableExtension(BaseModel):
return extension_list
@classmethod
async def get_extension_releases(cls, ext_id: str) -> list[ExtensionRelease]:
extension_releases: list[ExtensionRelease] = []
async def get_extension_releases(cls, ext_id: str) -> List["ExtensionRelease"]:
extension_releases: List[ExtensionRelease] = []
for url in settings.lnbits_extensions_manifests:
try:
manifest = await cls.fetch_manifest(url)
manifest = await fetch_manifest(url)
for r in manifest.repos:
if r.id != ext_id:
continue
@@ -692,8 +741,8 @@ class InstallableExtension(BaseModel):
@classmethod
async def get_extension_release(
cls, ext_id: str, source_repo: str, archive: str, version: str
) -> Optional[ExtensionRelease]:
all_releases: list[ExtensionRelease] = (
) -> Optional["ExtensionRelease"]:
all_releases: List[ExtensionRelease] = (
await InstallableExtension.get_extension_releases(ext_id)
)
selected_release = [
@@ -706,37 +755,6 @@ class InstallableExtension(BaseModel):
return selected_release[0] if len(selected_release) != 0 else None
@classmethod
async def fetch_github_repo_info(
cls, org: str, repository: str
) -> tuple[GitHubRepo, GitHubRepoRelease, ExtensionConfig]:
repo_url = f"https://api.github.com/repos/{org}/{repository}"
error_msg = "Cannot fetch extension repo"
repo = await github_api_get(repo_url, error_msg)
github_repo = GitHubRepo.parse_obj(repo)
lates_release_url = (
f"https://api.github.com/repos/{org}/{repository}/releases/latest"
)
error_msg = "Cannot fetch extension releases"
latest_release: Any = await github_api_get(lates_release_url, error_msg)
config_url = f"https://raw.githubusercontent.com/{org}/{repository}/{github_repo.default_branch}/config.json"
error_msg = "Cannot fetch config for extension"
config = await github_api_get(config_url, error_msg)
return (
github_repo,
GitHubRepoRelease.parse_obj(latest_release),
ExtensionConfig.parse_obj(config),
)
@classmethod
async def fetch_manifest(cls, url) -> Manifest:
error_msg = "Cannot fetch extensions manifest"
manifest = await github_api_get(url, error_msg)
return Manifest.parse_obj(manifest)
class CreateExtension(BaseModel):
ext_id: str
@@ -751,3 +769,32 @@ class ExtensionDetailsRequest(BaseModel):
ext_id: str
source_repo: str
version: str
def get_valid_extensions(include_deactivated: Optional[bool] = True) -> List[Extension]:
valid_extensions = [
extension for extension in ExtensionManager().extensions if extension.is_valid
]
if include_deactivated:
return valid_extensions
if settings.lnbits_extensions_deactivate_all:
return []
return [
e
for e in valid_extensions
if e.code not in settings.lnbits_deactivated_extensions
]
def version_parse(v: str):
"""
Wrapper for version.parse() that does not throw if the version is invalid.
Instead it return the lowest possible version ("0.0.0")
"""
try:
return version.parse(v)
except Exception:
return version.parse("0.0.0")
+4 -8
View File
@@ -10,7 +10,6 @@ import shortuuid
from pydantic import BaseModel
from pydantic.schema import field_schema
from lnbits.core.extensions.models import Extension
from lnbits.db import get_placeholder
from lnbits.jinja2_templating import Jinja2Templates
from lnbits.nodes import get_node_class
@@ -19,6 +18,7 @@ from lnbits.settings import settings
from lnbits.utils.crypto import AESCipher
from .db import FilterModel
from .extension_manager import get_valid_extensions
def get_db_vendor_name():
@@ -93,21 +93,19 @@ def template_renderer(additional_folders: Optional[List] = None) -> Jinja2Templa
settings.lnbits_node_ui and get_node_class() is not None
)
t.env.globals["LNBITS_NODE_UI_AVAILABLE"] = get_node_class() is not None
t.env.globals["EXTENSIONS"] = Extension.get_valid_extensions(False)
t.env.globals["EXTENSIONS"] = get_valid_extensions(False)
if settings.lnbits_custom_logo:
t.env.globals["USE_CUSTOM_LOGO"] = settings.lnbits_custom_logo
if settings.bundle_assets:
t.env.globals["INCLUDED_JS"] = ["bundle.min.js"]
t.env.globals["INCLUDED_CSS"] = ["bundle.min.css"]
t.env.globals["INCLUDED_COMPONENTS"] = ["bundle-components.min.js"]
else:
vendor_filepath = Path(settings.lnbits_path, "static", "vendor.json")
with open(vendor_filepath) as vendor_file:
vendor_files = json.loads(vendor_file.read())
t.env.globals["INCLUDED_JS"] = vendor_files["js"]
t.env.globals["INCLUDED_CSS"] = vendor_files["css"]
t.env.globals["INCLUDED_COMPONENTS"] = vendor_files["components"]
t.env.globals["WEBPUSH_PUBKEY"] = settings.lnbits_webpush_pubkey
@@ -189,14 +187,12 @@ def insert_query(table_name: str, model: BaseModel) -> str:
return f"INSERT INTO {table_name} ({fields}) VALUES ({values})"
def update_query(
table_name: str, model: BaseModel, where: str = "WHERE id = :id"
) -> str:
def update_query(table_name: str, model: BaseModel, where: str = "WHERE id = ?") -> str:
"""
Generate an update query with placeholders for a given table and model
:param table_name: Name of the table
:param model: Pydantic model
:param where: Where string, default to `WHERE id = :id`
:param where: Where string, default to `WHERE id = ?`
"""
fields = []
for field in model.dict().keys():
+72 -7
View File
@@ -1,5 +1,5 @@
from http import HTTPStatus
from typing import Any, List, Union
from typing import Any, List, Tuple, Union
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
@@ -45,11 +45,16 @@ class InstalledExtensionMiddleware:
await self.app(scope, receive, send)
return
upgrade_path = next(
(
e
for e in settings.lnbits_upgraded_extensions
if e.endswith(f"/{top_path}")
),
None,
)
# re-route all trafic if the extension has been upgraded
if top_path in settings.lnbits_upgraded_extensions:
upgrade_path = (
f"""{settings.lnbits_upgraded_extensions[top_path]}/{top_path}"""
)
if upgrade_path:
tail = "/".join(rest)
scope["path"] = f"/upgrades/{upgrade_path}/{tail}"
@@ -113,12 +118,72 @@ class ExtensionsRedirectMiddleware:
return
req_headers = scope["headers"] if "headers" in scope else []
redirect = settings.find_extension_redirect(scope["path"], req_headers)
redirect = self._find_redirect(scope["path"], req_headers)
if redirect:
scope["path"] = redirect.new_path_from(scope["path"])
scope["path"] = self._new_path(redirect, scope["path"])
await self.app(scope, receive, send)
def _find_redirect(self, path: str, req_headers: List[Tuple[bytes, bytes]]):
return next(
(
r
for r in settings.lnbits_extensions_redirects
if self._redirect_matches(r, path, req_headers)
),
None,
)
def _redirect_matches(
self, redirect: dict, path: str, req_headers: List[Tuple[bytes, bytes]]
) -> bool:
if "from_path" not in redirect:
return False
header_filters = (
redirect["header_filters"] if "header_filters" in redirect else {}
)
return self._has_common_path(redirect["from_path"], path) and self._has_headers(
header_filters, req_headers
)
def _has_headers(
self, filter_headers: dict, req_headers: List[Tuple[bytes, bytes]]
) -> bool:
for h in filter_headers:
if not self._has_header(req_headers, (str(h), str(filter_headers[h]))):
return False
return True
def _has_header(
self, req_headers: List[Tuple[bytes, bytes]], header: Tuple[str, str]
) -> bool:
for h in req_headers:
if (
h[0].decode().lower() == header[0].lower()
and h[1].decode() == header[1]
):
return True
return False
def _has_common_path(self, redirect_path: str, req_path: str) -> bool:
redirect_path_elements = redirect_path.split("/")
req_path_elements = req_path.split("/")
if len(redirect_path) > len(req_path):
return False
sub_path = req_path_elements[: len(redirect_path_elements)]
return redirect_path == "/".join(sub_path)
def _new_path(self, redirect: dict, req_path: str) -> str:
from_path = redirect["from_path"].split("/")
redirect_to = redirect["redirect_to_path"].split("/")
req_tail_path = req_path.split("/")[len(from_path) :]
elements = [
e for e in ([redirect["ext_id"], *redirect_to, *req_tail_path]) if e != ""
]
return "/" + "/".join(elements)
def add_ratelimit_middleware(app: FastAPI):
core_app_extra.register_new_ratelimiter()
+7 -113
View File
@@ -62,132 +62,26 @@ class ExtensionsInstallSettings(LNbitsSettings):
lnbits_ext_github_token: str = Field(default="")
class RedirectPath(BaseModel):
ext_id: str
from_path: str
redirect_to_path: str
header_filters: dict = {}
def in_conflict(self, other: RedirectPath) -> bool:
if self.ext_id == other.ext_id:
return False
return self.redirect_matches(
other.from_path, list(other.header_filters.items())
) or other.redirect_matches(self.from_path, list(self.header_filters.items()))
def find_in_conflict(self, others: list[RedirectPath]) -> Optional[RedirectPath]:
for other in others:
if self.in_conflict(other):
return other
return None
def new_path_from(self, req_path: str) -> str:
from_path = self.from_path.split("/")
redirect_to = self.redirect_to_path.split("/")
req_tail_path = req_path.split("/")[len(from_path) :]
elements = [e for e in ([self.ext_id, *redirect_to, *req_tail_path]) if e != ""]
return "/" + "/".join(elements)
def redirect_matches(self, path: str, req_headers: list[tuple[str, str]]) -> bool:
return self._has_common_path(path) and self._has_headers(req_headers)
def _has_common_path(self, req_path: str) -> bool:
if len(self.from_path) > len(req_path):
return False
redirect_path_elements = self.from_path.split("/")
req_path_elements = req_path.split("/")
sub_path = req_path_elements[: len(redirect_path_elements)]
return self.from_path == "/".join(sub_path)
def _has_headers(self, req_headers: list[tuple[str, str]]) -> bool:
for h in self.header_filters:
if not self._has_header(req_headers, (str(h), str(self.header_filters[h]))):
return False
return True
def _has_header(
self, req_headers: list[tuple[str, str]], header: tuple[str, str]
) -> bool:
for h in req_headers:
if h[0].lower() == header[0].lower() and h[1].lower() == header[1].lower():
return True
return False
class InstalledExtensionsSettings(LNbitsSettings):
# installed extensions that have been deactivated
lnbits_deactivated_extensions: set[str] = Field(default=[])
# upgraded extensions that require API redirects
lnbits_upgraded_extensions: dict[str, str] = Field(default={})
lnbits_upgraded_extensions: set[str] = Field(default=[])
# list of redirects that extensions want to perform
lnbits_extensions_redirects: list[RedirectPath] = Field(default=[])
lnbits_extensions_redirects: list[Any] = Field(default=[])
# list of all extension ids
lnbits_all_extensions_ids: set[Any] = Field(default=[])
def find_extension_redirect(
self, path: str, req_headers: list[tuple[bytes, bytes]]
) -> Optional[RedirectPath]:
headers = [(k.decode(), v.decode()) for k, v in req_headers]
def extension_upgrade_path(self, ext_id: str) -> Optional[str]:
return next(
(
r
for r in self.lnbits_extensions_redirects
if r.redirect_matches(path, headers)
),
(e for e in self.lnbits_upgraded_extensions if e.endswith(f"/{ext_id}")),
None,
)
def activate_extension_paths(
self,
ext_id: str,
upgrade_hash: Optional[str] = None,
ext_redirects: Optional[list[dict]] = None,
):
self.lnbits_deactivated_extensions.discard(ext_id)
"""
Update the list of upgraded extensions. The middleware will perform
redirects based on this
"""
if upgrade_hash:
self.lnbits_upgraded_extensions[ext_id] = upgrade_hash
if ext_redirects:
self._activate_extension_redirects(ext_id, ext_redirects)
self.lnbits_all_extensions_ids.add(ext_id)
def deactivate_extension_paths(self, ext_id: str):
self.lnbits_deactivated_extensions.add(ext_id)
self._remove_extension_redirects(ext_id)
def _activate_extension_redirects(self, ext_id: str, ext_redirects: list[dict]):
ext_redirect_paths = [
RedirectPath(**{"ext_id": ext_id, **er}) for er in ext_redirects
]
existing_redirects = {
r.ext_id
for r in self.lnbits_extensions_redirects
if r.find_in_conflict(ext_redirect_paths)
}
assert len(existing_redirects) == 0, (
f"Cannot redirect for extension '{ext_id}'."
f" Already mapped by {existing_redirects}."
)
self._remove_extension_redirects(ext_id)
self.lnbits_extensions_redirects += ext_redirect_paths
def _remove_extension_redirects(self, ext_id: str):
self.lnbits_extensions_redirects = [
er for er in self.lnbits_extensions_redirects if er.ext_id != ext_id
]
def extension_upgrade_hash(self, ext_id: str) -> Optional[str]:
path = settings.extension_upgrade_path(ext_id)
return path.split("/")[0] if path else None
class ThemesSettings(LNbitsSettings):
File diff suppressed because one or more lines are too long
+1 -1
View File
File diff suppressed because one or more lines are too long
+41 -29
View File
File diff suppressed because one or more lines are too long
+16 -2
View File
@@ -1,6 +1,6 @@
window.app = Vue.createApp({
new Vue({
el: '#vue',
mixins: [window.windowMixin],
mixins: [windowMixin],
data: function () {
return {
user: null,
@@ -80,6 +80,20 @@ window.app = Vue.createApp({
this.applyGradient()
}
},
setColors: function () {
this.$q.localStorage.set(
'lnbits.primaryColor',
LNbits.utils.getPaletteColor('primary')
)
this.$q.localStorage.set(
'lnbits.secondaryColor',
LNbits.utils.getPaletteColor('secondary')
)
this.$q.localStorage.set(
'lnbits.darkBgColor',
LNbits.utils.getPaletteColor('dark')
)
},
updateAccount: async function () {
try {
const {data} = await LNbits.api.request(
+1 -1
View File
@@ -1,4 +1,4 @@
window.app = Vue.createApp({
new Vue({
el: '#vue',
mixins: [windowMixin],
data: function () {
+18 -75
View File
@@ -1,10 +1,15 @@
/* globals crypto, moment, Vue, axios, Quasar, _ */
Vue.use(VueI18n)
window.LOCALE = 'en'
window.i18n = new VueI18n.createI18n({
window.i18n = new VueI18n({
locale: window.LOCALE,
fallbackLocale: window.LOCALE,
messages: window.localisation
})
window.EventHub = new Vue()
window.LNbits = {
api: {
request: function (method, url, apiKey, data) {
@@ -259,12 +264,12 @@ window.LNbits = {
fiat_currency: data.fiat_currency
}
obj.date = Quasar.date.formatDate(
obj.date = Quasar.utils.date.formatDate(
new Date(obj.time * 1000),
'YYYY-MM-DD HH:mm'
)
obj.dateFrom = moment(obj.date).fromNow()
obj.expirydate = Quasar.date.formatDate(
obj.expirydate = Quasar.utils.date.formatDate(
new Date(obj.expiry * 1000),
'YYYY-MM-DD HH:mm'
)
@@ -289,7 +294,7 @@ window.LNbits = {
},
utils: {
confirmDialog: function (msg) {
return Quasar.Dialog.create({
return Quasar.plugins.Dialog.create({
message: msg,
ok: {
flat: true,
@@ -406,14 +411,14 @@ window.LNbits = {
)
.join('\r\n')
var status = Quasar.exportFile(
var status = Quasar.utils.exportFile(
`${fileName || 'table-export'}.csv`,
content,
'text/csv'
)
if (status !== true) {
Quasar.Notify.create({
Quasar.plugins.Notify.create({
message: 'Browser denied file download...',
color: 'negative',
icon: null
@@ -427,16 +432,16 @@ window.LNbits = {
return converter.makeHtml(text)
},
hexToRgb: function (hex) {
return Quasar.colors.hexToRgb(hex)
return Quasar.utils.colors.hexToRgb(hex)
},
hexDarken: function (hex, percent) {
return Quasar.colors.lighten(hex, percent)
return Quasar.utils.colors.lighten(hex, percent)
},
hexAlpha: function (hex, alpha) {
return Quasar.colors.changeAlpha(hex, alpha)
return Quasar.utils.colors.changeAlpha(hex, alpha)
},
getPaletteColor: function (color) {
return Quasar.colors.getPaletteColor(color)
return Quasar.utils.colors.getPaletteColor(color)
}
}
}
@@ -470,7 +475,6 @@ window.windowMixin = {
},
applyGradient: function () {
if (this.$q.localStorage.getItem('lnbits.gradientBg')) {
this.setColors()
darkBgColor = this.$q.localStorage.getItem('lnbits.darkBgColor')
primaryColor = this.$q.localStorage.getItem('lnbits.primaryColor')
const gradientStyle = `linear-gradient(to bottom right, ${LNbits.utils.hexDarken(String(primaryColor), -70)}, #0a0a0a)`
@@ -488,23 +492,9 @@ window.windowMixin = {
document.head.appendChild(style)
}
},
setColors: function () {
this.$q.localStorage.set(
'lnbits.primaryColor',
LNbits.utils.getPaletteColor('primary')
)
this.$q.localStorage.set(
'lnbits.secondaryColor',
LNbits.utils.getPaletteColor('secondary')
)
this.$q.localStorage.set(
'lnbits.darkBgColor',
LNbits.utils.getPaletteColor('dark')
)
},
copyText: function (text, message, position) {
var notify = this.$q.notify
Quasar.copyToClipboard(text).then(function () {
Quasar.utils.copyToClipboard(text).then(function () {
notify({
message: message || 'Copied to clipboard!',
position: position || 'bottom'
@@ -551,52 +541,6 @@ window.windowMixin = {
LNbits.utils.notifyApiError(e)
}
})
},
themeParams() {
const url = new URL(window.location.href)
const params = new URLSearchParams(window.location.search)
const fields = ['theme', 'dark', 'gradient']
const toBoolean = value =>
value.trim().toLowerCase() === 'true' || value === '1'
// Check if any of the relevant parameters ('theme', 'dark', 'gradient') are present in the URL.
if (fields.some(param => params.has(param))) {
const theme = params.get('theme')
const darkMode = params.get('dark')
const gradient = params.get('gradient')
if (
theme &&
this.g.allowedThemes.includes(theme.trim().toLowerCase())
) {
const normalizedTheme = theme.trim().toLowerCase()
document.body.setAttribute('data-theme', normalizedTheme)
this.$q.localStorage.set('lnbits.theme', normalizedTheme)
}
if (darkMode) {
const isDark = toBoolean(darkMode)
this.$q.localStorage.set('lnbits.darkMode', isDark)
if (!isDark) {
this.$q.localStorage.set('lnbits.gradientBg', false)
}
}
if (gradient) {
const isGradient = toBoolean(gradient)
this.$q.localStorage.set('lnbits.gradientBg', isGradient)
if (isGradient) {
this.$q.localStorage.set('lnbits.darkMode', true)
}
}
// Remove processed parameters
fields.forEach(param => params.delete(param))
window.history.replaceState(null, null, url.pathname)
}
this.setColors()
}
},
created: async function () {
@@ -611,6 +555,8 @@ window.windowMixin = {
this.reactionChoice =
this.$q.localStorage.getItem('lnbits.reactions') || 'confettiBothSides'
this.applyGradient()
this.g.allowedThemes = window.allowedThemes ?? ['bitcoin']
let locale = this.$q.localStorage.getItem('lnbits.lang')
@@ -649,8 +595,6 @@ window.windowMixin = {
)
}
this.applyGradient()
if (window.user) {
this.g.user = Object.freeze(window.LNbits.map.user(window.user))
}
@@ -689,7 +633,6 @@ window.windowMixin = {
this.g.extensions = extensions
}
await this.checkUsrInUrl()
this.themeParams()
}
}
+25 -24
View File
@@ -1,6 +1,6 @@
window.app.component(QrcodeVue)
/* global _, Vue, moment, LNbits, EventHub, decryptLnurlPayAES */
window.app.component('lnbits-fsat', {
Vue.component('lnbits-fsat', {
props: {
amount: {
type: Number,
@@ -15,13 +15,12 @@ window.app.component('lnbits-fsat', {
}
})
window.app.component('lnbits-wallet-list', {
props: ['balance'],
Vue.component('lnbits-wallet-list', {
data: function () {
return {
user: null,
activeWallet: null,
balance: 0,
activeBalance: [],
showForm: false,
walletName: '',
LNBITS_DENOMINATION: LNBITS_DENOMINATION
@@ -75,7 +74,7 @@ window.app.component('lnbits-wallet-list', {
`,
computed: {
wallets: function () {
var bal = this.balance
var bal = this.activeBalance
return this.user.wallets.map(function (obj) {
obj.live_fsat =
bal.length && bal[0] === obj.id
@@ -88,6 +87,9 @@ window.app.component('lnbits-wallet-list', {
methods: {
createWallet: function () {
LNbits.api.createWallet(this.user.wallets[0], this.walletName)
},
updateWalletBalance: function (payload) {
this.activeBalance = payload
}
},
created: function () {
@@ -97,11 +99,11 @@ window.app.component('lnbits-wallet-list', {
if (window.wallet) {
this.activeWallet = LNbits.map.wallet(window.wallet)
}
document.addEventListener('updateWalletBalance', this.updateWalletBalance)
EventHub.$on('update-wallet-balance', this.updateWalletBalance)
}
})
window.app.component('lnbits-extension-list', {
Vue.component('lnbits-extension-list', {
data: function () {
return {
extensions: [],
@@ -167,7 +169,7 @@ window.app.component('lnbits-extension-list', {
}
})
window.app.component('lnbits-manage', {
Vue.component('lnbits-manage', {
props: ['showAdmin', 'showNode', 'showExtensions', 'showUsers'],
methods: {
isActive: function (path) {
@@ -227,9 +229,9 @@ window.app.component('lnbits-manage', {
}
})
window.app.component('lnbits-payment-details', {
Vue.component('lnbits-payment-details', {
props: ['payment'],
mixins: [window.windowMixin],
mixins: [windowMixin],
data: function () {
return {
LNBITS_DENOMINATION: LNBITS_DENOMINATION
@@ -343,7 +345,7 @@ window.app.component('lnbits-payment-details', {
}
})
window.app.component('lnbits-lnurlpay-success-action', {
Vue.component('lnbits-lnurlpay-success-action', {
props: ['payment', 'success_action'],
data() {
return {
@@ -372,12 +374,10 @@ window.app.component('lnbits-lnurlpay-success-action', {
}
})
window.app.component('lnbits-qrcode', {
mixins: [window.windowMixin],
components: {
QrcodeVue
},
Vue.component('lnbits-qrcode', {
mixins: [windowMixin],
props: ['value'],
components: {[VueQrcode.name]: VueQrcode},
data() {
return {
logo: LNBITS_QR_LOGO
@@ -385,14 +385,15 @@ window.app.component('lnbits-qrcode', {
},
template: `
<div class="qrcode__wrapper">
<qrcode-vue :value="value" size="350" class="rounded-borders"></qrcode-vue>
<qrcode :value="value"
:options="{errorCorrectionLevel: 'Q', width: 800}" class="rounded-borders"></qrcode>
<img class="qrcode__image" :src="logo" alt="..." />
</div>
`
})
window.app.component('lnbits-notifications-btn', {
mixins: [window.windowMixin],
Vue.component('lnbits-notifications-btn', {
mixins: [windowMixin],
props: ['pubkey'],
data() {
return {
@@ -604,8 +605,8 @@ window.app.component('lnbits-notifications-btn', {
}
})
window.app.component('lnbits-dynamic-fields', {
mixins: [window.windowMixin],
Vue.component('lnbits-dynamic-fields', {
mixins: [windowMixin],
props: ['options', 'value'],
data() {
return {
@@ -741,8 +742,8 @@ window.app.component('lnbits-dynamic-fields', {
}
})
window.app.component('lnbits-update-balance', {
mixins: [window.windowMixin],
Vue.component('lnbits-update-balance', {
mixins: [windowMixin],
props: ['wallet_id', 'callback'],
computed: {
denomination() {
@@ -1,4 +1,4 @@
window.app.component('lnbits-extension-rating', {
Vue.component('lnbits-extension-rating', {
name: 'lnbits-extension-rating',
props: ['rating'],
template: `
@@ -1,10 +1,10 @@
window.app.component('lnbits-extension-settings-form', {
Vue.component('lnbits-extension-settings-form', {
name: 'lnbits-extension-settings-form',
props: ['options', 'adminkey', 'endpoint'],
methods: {
async updateSettings() {
updateSettings: async function () {
if (!this.settings) {
return this.$q.notify({
return Quasar.plugins.Notify.create({
message: 'No settings to update',
type: 'negative'
})
@@ -66,7 +66,7 @@ window.app.component('lnbits-extension-settings-form', {
}
})
window.app.component('lnbits-extension-settings-btn-dialog', {
Vue.component('lnbits-extension-settings-btn-dialog', {
name: 'lnbits-extension-settings-btn-dialog',
props: ['options', 'adminkey', 'endpoint'],
template: `
@@ -1,5 +1,5 @@
window.app.component('lnbits-funding-sources', {
mixins: [window.windowMixin],
Vue.component('lnbits-funding-sources', {
mixins: [windowMixin],
props: ['form-data', 'allowed-funding-sources'],
methods: {
getFundingSourceLabel(item) {
+2 -2
View File
@@ -80,10 +80,10 @@ function generateChart(canvas, rawData) {
})
}
window.app.component('payment-chart', {
Vue.component('payment-chart', {
name: 'payment-chart',
props: ['wallet'],
mixins: [window.windowMixin],
mixins: [windowMixin],
data: function () {
return {
paymentsChart: {
+3 -3
View File
@@ -1,7 +1,7 @@
window.app.component('payment-list', {
Vue.component('payment-list', {
name: 'payment-list',
props: ['update', 'wallet', 'mobileSimple', 'lazy'],
mixins: [window.windowMixin],
mixins: [windowMixin],
data: function () {
return {
denomination: LNBITS_DENOMINATION,
@@ -313,7 +313,7 @@ window.app.component('payment-list', {
<q-table
dense
flat
:rows="paymentsOmitter"
:data="paymentsOmitter"
:row-key="paymentTableRowKey"
:columns="paymentsTable.columns"
:pagination.sync="paymentsTable.pagination"
+3 -2
View File
@@ -1,6 +1,6 @@
window.app = Vue.createApp({
new Vue({
el: '#vue',
mixins: [window.windowMixin],
mixins: [windowMixin],
data: function () {
return {
disclaimerDialog: {
@@ -93,6 +93,7 @@ window.app = Vue.createApp({
},
created() {
this.description = SITE_DESCRIPTION
this.isUserAuthorized = !!this.$q.cookies.get('is_lnbits_user_authorized')
if (this.isUserAuthorized) {
window.location.href = '/wallet'
-4
View File
@@ -1,4 +0,0 @@
window.app.use(VueQrcodeReader)
window.app.use(Quasar)
window.app.use(window.i18n)
window.app.mount('#vue')
+12 -12
View File
@@ -4,7 +4,7 @@ function shortenNodeId(nodeId) {
: '...'
}
window.app.component('lnbits-node-ranks', {
Vue.component('lnbits-node-ranks', {
props: ['ranks'],
data: function () {
return {
@@ -35,7 +35,7 @@ window.app.component('lnbits-node-ranks', {
`
})
window.app.component('lnbits-channel-stats', {
Vue.component('lnbits-channel-stats', {
props: ['stats'],
data: function () {
return {
@@ -71,7 +71,7 @@ window.app.component('lnbits-channel-stats', {
}
})
window.app.component('lnbits-stat', {
Vue.component('lnbits-stat', {
props: ['title', 'amount', 'msat', 'btc'],
computed: {
value: function () {
@@ -99,20 +99,20 @@ window.app.component('lnbits-stat', {
`
})
window.app.component('lnbits-node-qrcode', {
Vue.component('lnbits-node-qrcode', {
props: ['info'],
mixins: [window.windowMixin],
mixins: [windowMixin],
template: `
<q-card class="my-card">
<q-card-section>
<div class="text-h6">
<div style="text-align: center">
<vue-qrcode
<qrcode
:value="info.addresses[0]"
:options="{width: 250}"
v-if='info.addresses[0]'
class="rounded-borders"
></vue-qrcode>
></qrcode>
<div v-else class='text-subtitle1'>
No addresses available
</div>
@@ -132,14 +132,14 @@ window.app.component('lnbits-node-qrcode', {
`
})
window.app.component('lnbits-node-info', {
Vue.component('lnbits-node-info', {
props: ['info'],
data() {
return {
showDialog: false
}
},
mixins: [window.windowMixin],
mixins: [windowMixin],
methods: {
shortenNodeId
},
@@ -177,7 +177,7 @@ window.app.component('lnbits-node-info', {
`
})
window.app.component('lnbits-stat', {
Vue.component('lnbits-stat', {
props: ['title', 'amount', 'msat', 'btc'],
computed: {
value: function () {
@@ -205,7 +205,7 @@ window.app.component('lnbits-stat', {
`
})
window.app.component('lnbits-channel-balance', {
Vue.component('lnbits-channel-balance', {
props: ['balance', 'color'],
methods: {
formatMsat: function (msat) {
@@ -246,7 +246,7 @@ window.app.component('lnbits-channel-balance', {
`
})
window.app.component('lnbits-date', {
Vue.component('lnbits-date', {
props: ['ts'],
computed: {
date: function () {
+7 -49
View File
@@ -1,6 +1,6 @@
window.app = Vue.createApp({
new Vue({
el: '#vue',
mixins: [window.windowMixin],
mixins: [windowMixin],
data: function () {
return {
isSuperUser: false,
@@ -164,41 +164,6 @@ window.app = Vue.createApp({
this.chart1 = new Chart(this.$refs.chart1.getContext('2d'), {
type: 'bubble',
options: {
scales: {
xAxes: [
{
type: 'linear',
ticks: {
beginAtZero: true
},
scaleLabel: {
display: true,
labelString: 'Tx count'
}
}
],
yAxes: [
{
type: 'linear',
ticks: {
beginAtZero: true
},
scaleLabel: {
display: true,
labelString: 'User balance in million sats'
}
}
]
},
tooltips: {
callbacks: {
label: function (tooltipItem, data) {
const dataset = data.datasets[tooltipItem.datasetIndex]
const dataPoint = dataset.data[tooltipItem.index]
return dataPoint.customLabel || ''
}
}
},
layout: {
padding: 10
}
@@ -206,7 +171,7 @@ window.app = Vue.createApp({
data: {
datasets: [
{
label: 'Wallet balance vs transaction count',
label: 'Balance - TX Count in million sats',
backgroundColor: 'rgb(255, 99, 132)',
data: []
}
@@ -218,6 +183,9 @@ window.app = Vue.createApp({
formatSat: function (value) {
return LNbits.utils.formatSat(Math.floor(value / 1000))
},
usersTableRowKey: function (row) {
return row.id
},
createUser() {
LNbits.api
.request('POST', '/users/api/v1/user', null, this.createUserDialog.data)
@@ -323,20 +291,10 @@ window.app = Vue.createApp({
})
const data = filtered.map(user => {
const labelUsername = `${user.username ? 'User: ' + user.username + '. ' : ''}`
const userBalanceSats = Math.floor(
user.balance_msat / 1000
).toLocaleString()
return {
x: user.transaction_count,
y: user.balance_msat / 1000000000,
r: 4,
customLabel:
labelUsername +
'Balance: ' +
userBalanceSats +
' sats. Tx count: ' +
user.transaction_count
r: 3
}
})
this.chart1.data.datasets[0].data = data
+12 -8
View File
@@ -1,6 +1,11 @@
window.app = Vue.createApp({
/* globals windowMixin, decode, Vue, VueQrcodeReader, VueQrcode, Quasar, LNbits, _, EventHub, decryptLnurlPayAES */
Vue.component(VueQrcode.name, VueQrcode)
Vue.use(VueQrcodeReader)
new Vue({
el: '#vue',
mixins: [window.windowMixin],
mixins: [windowMixin],
data: function () {
return {
updatePayments: false,
@@ -316,7 +321,7 @@ window.app = Vue.createApp({
var expireDate = new Date(
(invoice.data.time_stamp + tag.value) * 1000
)
cleanInvoice.expireDate = this.$q.utils.date.formatDate(
cleanInvoice.expireDate = Quasar.utils.date.formatDate(
expireDate,
'YYYY-MM-DDTHH:mm:ss.SSSZ'
)
@@ -509,11 +514,10 @@ window.app = Vue.createApp({
fetchBalance: function () {
LNbits.api.getWallet(this.g.wallet).then(response => {
this.balance = Math.floor(response.data.balance / 1000)
document.dispatchEvent(
new CustomEvent('updateWalletBalance', {
detail: [this.g.wallet.id, this.balance]
})
)
EventHub.$emit('update-wallet-balance', [
this.g.wallet.id,
this.balance
])
})
if (this.g.wallet.currency) {
this.updateFiatBalance()
+13 -15
View File
@@ -3,14 +3,15 @@
"vendor/moment.js",
"vendor/underscore.js",
"vendor/axios.js",
"vendor/vue.global.prod.js",
"vendor/quasar.umd.prod.js",
"vendor/vuex.global.js",
"vendor/vue-i18n.global.prod.js",
"vendor/vue-router.global.js",
"vendor/vue-qrcode-reader.umd.js",
"vendor/qrcode.vue.browser.js",
"vendor/chart.umd.js",
"vendor/vue.js",
"vendor/vue-router.js",
"vendor/VueQrcodeReader.umd.js",
"vendor/vue-qrcode.js",
"vendor/vuex.js",
"vendor/quasar.ie.polyfills.umd.min.js",
"vendor/quasar.umd.js",
"vendor/Chart.bundle.js",
"vendor/vue-i18n.js",
"vendor/showdown.js",
"i18n/i18n.js",
"i18n/de.js",
@@ -33,17 +34,14 @@
"i18n/kr.js",
"i18n/fi.js",
"js/base.js",
"js/event-reactions.js",
"js/bolt11-decoder.js"
],
"components": [
"js/components.js",
"js/components/lnbits-funding-sources.js",
"js/components/extension-settings.js",
"js/components/extension-rating.js",
"js/components/payment-list.js",
"js/components/payment-chart.js",
"js/components.js",
"js/init-app.js"
"js/event-reactions.js",
"js/bolt11-decoder.js"
],
"css": ["vendor/quasar.css", "css/base.css"]
"css": ["vendor/quasar.css", "vendor/Chart.css", "css/base.css"]
}
+131 -179
View File
@@ -1,4 +1,4 @@
// Axios v1.7.7 Copyright (c) 2024 Matt Zabriskie and contributors
// Axios v1.7.5 Copyright (c) 2024 Matt Zabriskie and contributors
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
@@ -3093,42 +3093,38 @@
};
var composeSignals = function composeSignals(signals, timeout) {
var _signals = signals = signals ? signals.filter(Boolean) : [],
length = _signals.length;
if (timeout || length) {
var controller = new AbortController();
var aborted;
var onabort = function onabort(reason) {
if (!aborted) {
aborted = true;
unsubscribe();
var err = reason instanceof Error ? reason : this.reason;
controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));
}
};
var timer = timeout && setTimeout(function () {
var controller = new AbortController();
var aborted;
var onabort = function onabort(cancel) {
if (!aborted) {
aborted = true;
unsubscribe();
var err = cancel instanceof Error ? cancel : this.reason;
controller.abort(err instanceof AxiosError ? err : new CanceledError(err instanceof Error ? err.message : err));
}
};
var timer = timeout && setTimeout(function () {
onabort(new AxiosError("timeout ".concat(timeout, " of ms exceeded"), AxiosError.ETIMEDOUT));
}, timeout);
var unsubscribe = function unsubscribe() {
if (signals) {
timer && clearTimeout(timer);
timer = null;
onabort(new AxiosError("timeout ".concat(timeout, " of ms exceeded"), AxiosError.ETIMEDOUT));
}, timeout);
var unsubscribe = function unsubscribe() {
if (signals) {
timer && clearTimeout(timer);
timer = null;
signals.forEach(function (signal) {
signal.unsubscribe ? signal.unsubscribe(onabort) : signal.removeEventListener('abort', onabort);
});
signals = null;
}
};
signals.forEach(function (signal) {
return signal.addEventListener('abort', onabort);
});
var signal = controller.signal;
signal.unsubscribe = function () {
return utils$1.asap(unsubscribe);
};
return signal;
}
signals.forEach(function (signal) {
signal && (signal.removeEventListener ? signal.removeEventListener('abort', onabort) : signal.unsubscribe(onabort));
});
signals = null;
}
};
signals.forEach(function (signal) {
return signal && signal.addEventListener && signal.addEventListener('abort', onabort);
});
var signal = controller.signal;
signal.unsubscribe = unsubscribe;
return [signal, function () {
timer && clearTimeout(timer);
timer = null;
}];
};
var composeSignals$1 = composeSignals;
@@ -3167,7 +3163,7 @@
}, streamChunk);
});
var readBytes = /*#__PURE__*/function () {
var _ref = _wrapAsyncGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(iterable, chunkSize) {
var _ref = _wrapAsyncGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(iterable, chunkSize, encode) {
var _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, chunk;
return _regeneratorRuntime().wrap(function _callee$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
@@ -3175,111 +3171,82 @@
_iteratorAbruptCompletion = false;
_didIteratorError = false;
_context2.prev = 2;
_iterator = _asyncIterator(readStream(iterable));
_iterator = _asyncIterator(iterable);
case 4:
_context2.next = 6;
return _awaitAsyncGenerator(_iterator.next());
case 6:
if (!(_iteratorAbruptCompletion = !(_step = _context2.sent).done)) {
_context2.next = 12;
_context2.next = 27;
break;
}
chunk = _step.value;
return _context2.delegateYield(_asyncGeneratorDelegate(_asyncIterator(streamChunk(chunk, chunkSize))), "t0", 9);
case 9:
_context2.t0 = _asyncGeneratorDelegate;
_context2.t1 = _asyncIterator;
_context2.t2 = streamChunk;
if (!ArrayBuffer.isView(chunk)) {
_context2.next = 15;
break;
}
_context2.t3 = chunk;
_context2.next = 18;
break;
case 15:
_context2.next = 17;
return _awaitAsyncGenerator(encode(String(chunk)));
case 17:
_context2.t3 = _context2.sent;
case 18:
_context2.t4 = _context2.t3;
_context2.t5 = chunkSize;
_context2.t6 = (0, _context2.t2)(_context2.t4, _context2.t5);
_context2.t7 = (0, _context2.t1)(_context2.t6);
_context2.t8 = _awaitAsyncGenerator;
return _context2.delegateYield((0, _context2.t0)(_context2.t7, _context2.t8), "t9", 24);
case 24:
_iteratorAbruptCompletion = false;
_context2.next = 4;
break;
case 12:
_context2.next = 18;
case 27:
_context2.next = 33;
break;
case 14:
_context2.prev = 14;
_context2.t1 = _context2["catch"](2);
case 29:
_context2.prev = 29;
_context2.t10 = _context2["catch"](2);
_didIteratorError = true;
_iteratorError = _context2.t1;
case 18:
_context2.prev = 18;
_context2.prev = 19;
_iteratorError = _context2.t10;
case 33:
_context2.prev = 33;
_context2.prev = 34;
if (!(_iteratorAbruptCompletion && _iterator["return"] != null)) {
_context2.next = 23;
_context2.next = 38;
break;
}
_context2.next = 23;
_context2.next = 38;
return _awaitAsyncGenerator(_iterator["return"]());
case 23:
_context2.prev = 23;
case 38:
_context2.prev = 38;
if (!_didIteratorError) {
_context2.next = 26;
_context2.next = 41;
break;
}
throw _iteratorError;
case 26:
return _context2.finish(23);
case 27:
return _context2.finish(18);
case 28:
case 41:
return _context2.finish(38);
case 42:
return _context2.finish(33);
case 43:
case "end":
return _context2.stop();
}
}, _callee, null, [[2, 14, 18, 28], [19,, 23, 27]]);
}, _callee, null, [[2, 29, 33, 43], [34,, 38, 42]]);
}));
return function readBytes(_x, _x2) {
return function readBytes(_x, _x2, _x3) {
return _ref.apply(this, arguments);
};
}();
var readStream = /*#__PURE__*/function () {
var _ref2 = _wrapAsyncGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(stream) {
var reader, _yield$_awaitAsyncGen, done, value;
return _regeneratorRuntime().wrap(function _callee2$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
if (!stream[Symbol.asyncIterator]) {
_context3.next = 3;
break;
}
return _context3.delegateYield(_asyncGeneratorDelegate(_asyncIterator(stream)), "t0", 2);
case 2:
return _context3.abrupt("return");
case 3:
reader = stream.getReader();
_context3.prev = 4;
case 5:
_context3.next = 7;
return _awaitAsyncGenerator(reader.read());
case 7:
_yield$_awaitAsyncGen = _context3.sent;
done = _yield$_awaitAsyncGen.done;
value = _yield$_awaitAsyncGen.value;
if (!done) {
_context3.next = 12;
break;
}
return _context3.abrupt("break", 16);
case 12:
_context3.next = 14;
return value;
case 14:
_context3.next = 5;
break;
case 16:
_context3.prev = 16;
_context3.next = 19;
return _awaitAsyncGenerator(reader.cancel());
case 19:
return _context3.finish(16);
case 20:
case "end":
return _context3.stop();
}
}, _callee2, null, [[4,, 16, 20]]);
}));
return function readStream(_x3) {
return _ref2.apply(this, arguments);
};
}();
var trackStream = function trackStream(stream, chunkSize, onProgress, onFinish) {
var iterator = readBytes(stream, chunkSize);
var trackStream = function trackStream(stream, chunkSize, onProgress, onFinish, encode) {
var iterator = readBytes(stream, chunkSize, encode);
var bytes = 0;
var done;
var _onFinish = function _onFinish(e) {
@@ -3290,25 +3257,25 @@
};
return new ReadableStream({
pull: function pull(controller) {
return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
var _yield$iterator$next, _done, value, len, loadedBytes;
return _regeneratorRuntime().wrap(function _callee3$(_context4) {
while (1) switch (_context4.prev = _context4.next) {
return _regeneratorRuntime().wrap(function _callee2$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
_context4.prev = 0;
_context4.next = 3;
_context3.prev = 0;
_context3.next = 3;
return iterator.next();
case 3:
_yield$iterator$next = _context4.sent;
_yield$iterator$next = _context3.sent;
_done = _yield$iterator$next.done;
value = _yield$iterator$next.value;
if (!_done) {
_context4.next = 10;
_context3.next = 10;
break;
}
_onFinish();
controller.close();
return _context4.abrupt("return");
return _context3.abrupt("return");
case 10:
len = value.byteLength;
if (onProgress) {
@@ -3316,18 +3283,18 @@
onProgress(loadedBytes);
}
controller.enqueue(new Uint8Array(value));
_context4.next = 19;
_context3.next = 19;
break;
case 15:
_context4.prev = 15;
_context4.t0 = _context4["catch"](0);
_onFinish(_context4.t0);
throw _context4.t0;
_context3.prev = 15;
_context3.t0 = _context3["catch"](0);
_onFinish(_context3.t0);
throw _context3.t0;
case 19:
case "end":
return _context4.stop();
return _context3.stop();
}
}, _callee3, null, [[0, 15]]);
}, _callee2, null, [[0, 15]]);
}))();
},
cancel: function cancel(reason) {
@@ -3410,7 +3377,6 @@
}(new Response());
var getBodyLength = /*#__PURE__*/function () {
var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(body) {
var _request;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
@@ -3427,36 +3393,32 @@
return _context2.abrupt("return", body.size);
case 4:
if (!utils$1.isSpecCompliantForm(body)) {
_context2.next = 9;
_context2.next = 8;
break;
}
_request = new Request(platform.origin, {
method: 'POST',
body: body
});
_context2.next = 8;
return _request.arrayBuffer();
case 8:
_context2.next = 7;
return new Request(body).arrayBuffer();
case 7:
return _context2.abrupt("return", _context2.sent.byteLength);
case 9:
case 8:
if (!(utils$1.isArrayBufferView(body) || utils$1.isArrayBuffer(body))) {
_context2.next = 11;
_context2.next = 10;
break;
}
return _context2.abrupt("return", body.byteLength);
case 11:
case 10:
if (utils$1.isURLSearchParams(body)) {
body = body + '';
}
if (!utils$1.isString(body)) {
_context2.next = 16;
_context2.next = 15;
break;
}
_context2.next = 15;
_context2.next = 14;
return encodeText(body);
case 15:
case 14:
return _context2.abrupt("return", _context2.sent.byteLength);
case 16:
case 15:
case "end":
return _context2.stop();
}
@@ -3486,15 +3448,18 @@
}();
var fetchAdapter = isFetchSupported && ( /*#__PURE__*/function () {
var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(config) {
var _resolveConfig, url, method, data, signal, cancelToken, timeout, onDownloadProgress, onUploadProgress, responseType, headers, _resolveConfig$withCr, withCredentials, fetchOptions, composedSignal, request, unsubscribe, requestContentLength, _request, contentTypeHeader, _progressEventDecorat, _progressEventDecorat2, onProgress, flush, isCredentialsSupported, response, isStreamResponse, options, responseContentLength, _ref5, _ref6, _onProgress, _flush, responseData;
var _resolveConfig, url, method, data, signal, cancelToken, timeout, onDownloadProgress, onUploadProgress, responseType, headers, _resolveConfig$withCr, withCredentials, fetchOptions, _ref5, _ref6, composedSignal, stopTimeout, finished, request, onFinish, requestContentLength, _request, contentTypeHeader, _progressEventDecorat, _progressEventDecorat2, onProgress, flush, isCredentialsSupported, response, isStreamResponse, options, responseContentLength, _ref7, _ref8, _onProgress, _flush, responseData;
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) switch (_context4.prev = _context4.next) {
case 0:
_resolveConfig = resolveConfig(config), url = _resolveConfig.url, method = _resolveConfig.method, data = _resolveConfig.data, signal = _resolveConfig.signal, cancelToken = _resolveConfig.cancelToken, timeout = _resolveConfig.timeout, onDownloadProgress = _resolveConfig.onDownloadProgress, onUploadProgress = _resolveConfig.onUploadProgress, responseType = _resolveConfig.responseType, headers = _resolveConfig.headers, _resolveConfig$withCr = _resolveConfig.withCredentials, withCredentials = _resolveConfig$withCr === void 0 ? 'same-origin' : _resolveConfig$withCr, fetchOptions = _resolveConfig.fetchOptions;
responseType = responseType ? (responseType + '').toLowerCase() : 'text';
composedSignal = composeSignals$1([signal, cancelToken && cancelToken.toAbortSignal()], timeout);
unsubscribe = composedSignal && composedSignal.unsubscribe && function () {
composedSignal.unsubscribe();
_ref5 = signal || cancelToken || timeout ? composeSignals$1([signal, cancelToken], timeout) : [], _ref6 = _slicedToArray(_ref5, 2), composedSignal = _ref6[0], stopTimeout = _ref6[1];
onFinish = function onFinish() {
!finished && setTimeout(function () {
composedSignal && composedSignal.unsubscribe();
});
finished = true;
};
_context4.prev = 4;
_context4.t0 = onUploadProgress && supportsRequestStream && method !== 'get' && method !== 'head';
@@ -3522,7 +3487,7 @@
}
if (_request.body) {
_progressEventDecorat = progressEventDecorator(requestContentLength, progressEventReducer(asyncDecorator(onUploadProgress))), _progressEventDecorat2 = _slicedToArray(_progressEventDecorat, 2), onProgress = _progressEventDecorat2[0], flush = _progressEventDecorat2[1];
data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush);
data = trackStream(_request.body, DEFAULT_CHUNK_SIZE, onProgress, flush, encodeText);
}
case 15:
if (!utils$1.isString(withCredentials)) {
@@ -3545,25 +3510,26 @@
case 20:
response = _context4.sent;
isStreamResponse = supportsResponseStream && (responseType === 'stream' || responseType === 'response');
if (supportsResponseStream && (onDownloadProgress || isStreamResponse && unsubscribe)) {
if (supportsResponseStream && (onDownloadProgress || isStreamResponse)) {
options = {};
['status', 'statusText', 'headers'].forEach(function (prop) {
options[prop] = response[prop];
});
responseContentLength = utils$1.toFiniteNumber(response.headers.get('content-length'));
_ref5 = onDownloadProgress && progressEventDecorator(responseContentLength, progressEventReducer(asyncDecorator(onDownloadProgress), true)) || [], _ref6 = _slicedToArray(_ref5, 2), _onProgress = _ref6[0], _flush = _ref6[1];
_ref7 = onDownloadProgress && progressEventDecorator(responseContentLength, progressEventReducer(asyncDecorator(onDownloadProgress), true)) || [], _ref8 = _slicedToArray(_ref7, 2), _onProgress = _ref8[0], _flush = _ref8[1];
response = new Response(trackStream(response.body, DEFAULT_CHUNK_SIZE, _onProgress, function () {
_flush && _flush();
unsubscribe && unsubscribe();
}), options);
isStreamResponse && onFinish();
}, encodeText), options);
}
responseType = responseType || 'text';
_context4.next = 26;
return resolvers[utils$1.findKey(resolvers, responseType) || 'text'](response, config);
case 26:
responseData = _context4.sent;
!isStreamResponse && unsubscribe && unsubscribe();
_context4.next = 30;
!isStreamResponse && onFinish();
stopTimeout && stopTimeout();
_context4.next = 31;
return new Promise(function (resolve, reject) {
settle(resolve, reject, {
data: responseData,
@@ -3574,26 +3540,26 @@
request: request
});
});
case 30:
case 31:
return _context4.abrupt("return", _context4.sent);
case 33:
_context4.prev = 33;
case 34:
_context4.prev = 34;
_context4.t2 = _context4["catch"](4);
unsubscribe && unsubscribe();
onFinish();
if (!(_context4.t2 && _context4.t2.name === 'TypeError' && /fetch/i.test(_context4.t2.message))) {
_context4.next = 38;
_context4.next = 39;
break;
}
throw Object.assign(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request), {
cause: _context4.t2.cause || _context4.t2
});
case 38:
throw AxiosError.from(_context4.t2, _context4.t2 && _context4.t2.code, config, request);
case 39:
throw AxiosError.from(_context4.t2, _context4.t2 && _context4.t2.code, config, request);
case 40:
case "end":
return _context4.stop();
}
}, _callee4, null, [[4, 33]]);
}, _callee4, null, [[4, 34]]);
}));
return function (_x5) {
return _ref4.apply(this, arguments);
@@ -3717,7 +3683,7 @@
});
}
var VERSION = "1.7.7";
var VERSION = "1.7.5";
var validators$1 = {};
@@ -4098,20 +4064,6 @@
this._listeners.splice(index, 1);
}
}
}, {
key: "toAbortSignal",
value: function toAbortSignal() {
var _this = this;
var controller = new AbortController();
var abort = function abort(err) {
controller.abort(err);
};
this.subscribe(abort);
controller.signal.unsubscribe = function () {
return _this.unsubscribe(abort);
};
return controller.signal;
}
/**
* Returns an object that contains a new `CancelToken` and a function that, when called,
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
+3146 -3105
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+8 -13
View File
@@ -7,13 +7,13 @@
exports.noConflict = function () { global._ = current; return exports; };
}()));
}(this, (function () {
// Underscore.js 1.13.7
// Underscore.js 1.13.6
// https://underscorejs.org
// (c) 2009-2024 Jeremy Ashkenas, Julian Gonggrijp, and DocumentCloud and Investigative Reporters & Editors
// (c) 2009-2022 Jeremy Ashkenas, Julian Gonggrijp, and DocumentCloud and Investigative Reporters & Editors
// Underscore may be freely distributed under the MIT license.
// Current version.
var VERSION = '1.13.7';
var VERSION = '1.13.6';
// Establish the root object, `window` (`self`) in the browser, `global`
// on the server, or `this` in some virtual machines. We use `self`
@@ -150,11 +150,8 @@
// In IE 10 - Edge 13, `DataView` has string tag `'[object Object]'`.
// In IE 11, the most common among them, this problem also applies to
// `Map`, `WeakMap` and `Set`.
// Also, there are cases where an application can override the native
// `DataView` object, in cases like that we can't use the constructor
// safely and should just rely on alternate `DataView` checks
var hasDataViewBug = (
supportsDataView && (!/\[native code\]/.test(String(DataView)) || hasObjectTag(new DataView(new ArrayBuffer(8))))
var hasStringTagBug = (
supportsDataView && hasObjectTag(new DataView(new ArrayBuffer(8)))
),
isIE11 = (typeof Map !== 'undefined' && hasObjectTag(new Map));
@@ -162,13 +159,11 @@
// In IE 10 - Edge 13, we need a different heuristic
// to determine whether an object is a `DataView`.
// Also, in cases where the native `DataView` is
// overridden we can't rely on the tag itself.
function alternateIsDataView(obj) {
function ie10IsDataView(obj) {
return obj != null && isFunction$1(obj.getInt8) && isArrayBuffer(obj.buffer);
}
var isDataView$1 = (hasDataViewBug ? alternateIsDataView : isDataView);
var isDataView$1 = (hasStringTagBug ? ie10IsDataView : isDataView);
// Is a given value an array?
// Delegates to ECMA5's native `Array.isArray`.
@@ -381,7 +376,7 @@
var className = toString.call(a);
if (className !== toString.call(b)) return false;
// Work around a bug in IE 10 - Edge 13.
if (hasDataViewBug && className == '[object Object]' && isDataView$1(a)) {
if (hasStringTagBug && className == '[object Object]' && isDataView$1(a)) {
if (!isDataView$1(b)) return false;
className = tagDataView;
}
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+5505 -109
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -85,7 +85,7 @@ async def catch_everything_and_restart(
logger.error(traceback.format_exc())
logger.error("will restart the task in 5 seconds.")
await asyncio.sleep(5)
return catch_everything_and_restart(func, name)
return await catch_everything_and_restart(func, name)
invoice_listeners: Dict[str, asyncio.Queue] = {}
+184 -188
View File
@@ -32,198 +32,196 @@
</head>
<body data-theme="bitcoin">
<div id="vue">
<q-layout view="hHh lpR lfr" v-cloak>
<q-header bordered class="bg-marginal-bg">
<q-toolbar>
{% block drawer_toggle %}
<q-btn
dense
flat
round
icon="menu"
@click="g.visibleDrawer = !g.visibleDrawer"
></q-btn>
{% endblock %}
<q-toolbar-title>
{% block toolbar_title %}
<q-btn flat no-caps dense size="lg" type="a" href="/"
>{% if USE_CUSTOM_LOGO %}
<img height="30px" alt="Logo" src="{{ USE_CUSTOM_LOGO }}" />
{%else%} {% if SITE_TITLE != 'LNbits' %} {{ SITE_TITLE }} {%
else %}
<span><strong>LN</strong>bits</span> {% endif %} {%endif%} </q-btn
>{% endblock %} {% block toolbar_subtitle %}{%if user and
user.super_user%}
<q-badge align="middle">Super User</q-badge>
{% elif user and user.admin %}
<q-badge align="middle">Admin User</q-badge>
{%endif%}{% endblock %}
</q-toolbar-title>
{% block beta %} {% if VOIDWALLET %}
<q-badge
v-text="$t('voidwallet_active')"
color="red"
class="q-mr-md gt-md"
>
</q-badge>
<q-layout id="vue" view="hHh lpR lfr" v-cloak>
<q-header bordered class="bg-marginal-bg">
<q-toolbar>
{% block drawer_toggle %}
<q-btn
dense
flat
round
icon="menu"
@click="g.visibleDrawer = !g.visibleDrawer"
></q-btn>
{% endblock %}
<q-toolbar-title>
{% block toolbar_title %}
<q-btn flat no-caps dense size="lg" type="a" href="/"
>{% if USE_CUSTOM_LOGO %}
<img height="30px" alt="Logo" src="{{ USE_CUSTOM_LOGO }}" />
{%else%} {% if SITE_TITLE != 'LNbits' %} {{ SITE_TITLE }} {% else
%}
<span><strong>LN</strong>bits</span> {% endif %} {%endif%} </q-btn
>{% endblock %} {% block toolbar_subtitle %}{%if user and
user.super_user%}
<q-badge align="middle">Super User</q-badge>
{% elif user and user.admin %}
<q-badge align="middle">Admin User</q-badge>
{%endif%}{% endblock %}
</q-toolbar-title>
{% block beta %} {% if VOIDWALLET %}
<q-badge
v-text="$t('voidwallet_active')"
color="red"
class="q-mr-md gt-md"
>
</q-badge>
{%endif%}
<q-badge
v-if="'{{LNBITS_CUSTOM_BADGE}}' && '{{LNBITS_CUSTOM_BADGE}}' != 'None'"
v-show="$q.screen.gt.sm"
color="{{ LNBITS_CUSTOM_BADGE_COLOR }}"
class="q-mr-md"
label="{{LNBITS_CUSTOM_BADGE}}"
>
</q-badge>
{% if LNBITS_SERVICE_FEE > 0 %}
<q-badge
v-show="$q.screen.gt.sm"
v-if="g.user"
color="green"
class="q-mr-md"
>
{% if LNBITS_SERVICE_FEE_MAX > 0 %}
<span
v-text='$t("service_fee_max", { amount: "{{ LNBITS_SERVICE_FEE }}", max: "{{ LNBITS_SERVICE_FEE_MAX }}"})'
></span>
{%else%}
<span
v-text='$t("service_fee", { amount: "{{ LNBITS_SERVICE_FEE }}" })'
></span>
{%endif%}
<q-badge
v-if="'{{LNBITS_CUSTOM_BADGE}}' && '{{LNBITS_CUSTOM_BADGE}}' != 'None'"
v-show="$q.screen.gt.sm"
color="{{ LNBITS_CUSTOM_BADGE_COLOR }}"
class="q-mr-md"
label="{{LNBITS_CUSTOM_BADGE}}"
>
</q-badge>
{% if LNBITS_SERVICE_FEE > 0 %}
<q-badge
v-show="$q.screen.gt.sm"
v-if="g.user"
color="green"
class="q-mr-md"
>
{% if LNBITS_SERVICE_FEE_MAX > 0 %}
<span
v-text='$t("service_fee_max", { amount: "{{ LNBITS_SERVICE_FEE }}", max: "{{ LNBITS_SERVICE_FEE_MAX }}"})'
></span>
{%else%}
<span
v-text='$t("service_fee", { amount: "{{ LNBITS_SERVICE_FEE }}" })'
></span>
{%endif%}
<q-tooltip
><span v-text='$t("service_fee_tooltip")'></span
></q-tooltip>
</q-badge>
<q-tooltip
><span v-text='$t("service_fee_tooltip")'></span
></q-tooltip>
</q-badge>
{%endif%} {% endblock %}
<q-badge v-if="g.offline" color="red" class="q-mr-md">
<span>OFFLINE</span>
</q-badge>
{%endif%} {% endblock %}
<q-badge v-if="g.offline" color="red" class="q-mr-md">
<span>OFFLINE</span>
</q-badge>
<q-btn-dropdown
v-if="isUserAuthorized"
dense
flat
round
size="sm"
class="q-pl-sm"
>
<template v-slot:label>
<div>
{%if user and user.config and user.config.picture%}
<img src="{{user.config.picture}}" style="max-width: 32px" />
{%else%}
<q-icon name="account_circle" />
{%endif%}
</div>
</template>
<q-list>
<q-item tag="a" href="/account" clickable v-close-popup
><q-item-section>
<q-icon name="person" />
</q-item-section>
<q-item-section>
<q-item-label>
<span v-text="$t('my_account')"></span>
</q-item-label>
</q-item-section>
<q-item-section>
<q-item-label> </q-item-label>
</q-item-section>
</q-item>
<q-separator></q-separator>
<q-item clickable v-close-popup @click="logout"
><q-item-section>
<q-icon name="logout" />
</q-item-section>
<q-item-section>
<q-item-label>
<span v-text="$t('logout')"></span>
</q-item-label>
</q-item-section>
<q-item-section>
<q-item-label> </q-item-label>
</q-item-section>
</q-item>
</q-list>
</q-btn-dropdown>
</q-toolbar>
</q-header>
<q-btn-dropdown
v-if="isUserAuthorized"
dense
flat
round
size="sm"
class="q-pl-sm"
>
<template v-slot:label>
<div>
{%if user and user.config and user.config.picture%}
<img src="{{user.config.picture}}" style="max-width: 32px" />
{%else%}
<q-icon name="account_circle" />
{%endif%}
</div>
</template>
<q-list>
<q-item tag="a" href="/account" clickable v-close-popup
><q-item-section>
<q-icon name="person" />
</q-item-section>
<q-item-section>
<q-item-label>
<span v-text="$t('my_account')"></span>
</q-item-label>
</q-item-section>
<q-item-section>
<q-item-label> </q-item-label>
</q-item-section>
</q-item>
<q-separator></q-separator>
<q-item clickable v-close-popup @click="logout"
><q-item-section>
<q-icon name="logout" />
</q-item-section>
<q-item-section>
<q-item-label>
<span v-text="$t('logout')"></span>
</q-item-label>
</q-item-section>
<q-item-section>
<q-item-label> </q-item-label>
</q-item-section>
</q-item>
</q-list>
</q-btn-dropdown>
</q-toolbar>
</q-header>
{% block drawer %}
<q-drawer
v-model="g.visibleDrawer"
side="left"
:width="($q.screen.lt.md) ? 260 : 230"
show-if-above
:elevated="$q.screen.lt.md"
>
<lnbits-wallet-list :balance="balance"></lnbits-wallet-list>
{% block drawer %}
<q-drawer
v-model="g.visibleDrawer"
side="left"
:width="($q.screen.lt.md) ? 260 : 230"
show-if-above
:elevated="$q.screen.lt.md"
>
<lnbits-wallet-list></lnbits-wallet-list>
<lnbits-manage
:show-admin="'{{LNBITS_ADMIN_UI}}' == 'True'"
:show-users="'{{LNBITS_ADMIN_UI}}' == 'True'"
:show-node="'{{LNBITS_NODE_UI}}' == 'True'"
:show-extensions="'{{LNBITS_EXTENSIONS_DEACTIVATE_ALL}}' == 'False'"
></lnbits-manage>
<lnbits-extension-list class="q-pb-xl"></lnbits-extension-list>
</q-drawer>
{% endblock %} {% block page_container %}
<q-page-container>
<q-page class="q-px-md q-py-lg" :class="{'q-px-lg': $q.screen.gt.xs}">
{% block page %}{% endblock %}
</q-page>
</q-page-container>
{% endblock %} {% block footer %}
<lnbits-manage
:show-admin="'{{LNBITS_ADMIN_UI}}' == 'True'"
:show-users="'{{LNBITS_ADMIN_UI}}' == 'True'"
:show-node="'{{LNBITS_NODE_UI}}' == 'True'"
:show-extensions="'{{LNBITS_EXTENSIONS_DEACTIVATE_ALL}}' == 'False'"
></lnbits-manage>
<lnbits-extension-list class="q-pb-xl"></lnbits-extension-list>
</q-drawer>
{% endblock %} {% block page_container %}
<q-page-container>
<q-page class="q-px-md q-py-lg" :class="{'q-px-lg': $q.screen.gt.xs}">
{% block page %}{% endblock %}
</q-page>
</q-page-container>
{% endblock %} {% block footer %}
<q-footer
class="bg-transparent q-px-lg q-py-md"
:class="{'text-dark': !$q.dark.isActive}"
>
<q-space class="q-py-lg lt-md"></q-space>
<q-toolbar class="gt-sm">
<q-toolbar-title class="text-caption">
{{ SITE_TITLE }}, {{SITE_TAGLINE}}
<br />
<small
v-text="$t('lnbits_version') + ': {{LNBITS_VERSION}}'"
></small>
</q-toolbar-title>
<q-space></q-space>
<q-btn
flat
dense
:color="($q.dark.isActive) ? 'white' : 'primary'"
type="a"
href="/docs"
target="_blank"
rel="noopener noreferrer"
>
<span v-text="$t('api_docs')"></span>
<q-tooltip
><span v-text="$t('view_swagger_docs')"></span
></q-tooltip>
</q-btn>
<q-btn
flat
dense
:color="($q.dark.isActive) ? 'white' : 'primary'"
icon="code"
type="a"
href="https://github.com/lnbits/lnbits"
target="_blank"
rel="noopener noreferrer"
>
<q-tooltip><span v-text="$t('view_github')"></span></q-tooltip>
</q-btn>
</q-toolbar>
</q-footer>
<q-footer
class="bg-transparent q-px-lg q-py-md"
:class="{'text-dark': !$q.dark.isActive}"
>
<q-space class="q-py-lg lt-md"></q-space>
<q-toolbar class="gt-sm">
<q-toolbar-title class="text-caption">
{{ SITE_TITLE }}, {{SITE_TAGLINE}}
<br />
<small
v-text="$t('lnbits_version') + ': {{LNBITS_VERSION}}'"
></small>
</q-toolbar-title>
<q-space></q-space>
<q-btn
flat
dense
:color="($q.dark.isActive) ? 'white' : 'primary'"
type="a"
href="/docs"
target="_blank"
rel="noopener noreferrer"
>
<span v-text="$t('api_docs')"></span>
<q-tooltip
><span v-text="$t('view_swagger_docs')"></span
></q-tooltip>
</q-btn>
<q-btn
flat
dense
:color="($q.dark.isActive) ? 'white' : 'primary'"
icon="code"
type="a"
href="https://github.com/lnbits/lnbits"
target="_blank"
rel="noopener noreferrer"
>
<q-tooltip><span v-text="$t('view_github')"></span></q-tooltip>
</q-btn>
</q-toolbar>
</q-footer>
{% endblock %}
</q-layout>
</div>
{% endblock %}
</q-layout>
{% block vue_templates %}{% endblock %}
<!---->
@@ -260,8 +258,6 @@
{ value: 'fi', label: 'Suomi', display: '🇫🇮 FI' }
]
</script>
{% block scripts %}{% endblock %} {% for url in INCLUDED_COMPONENTS %}
<script src="{{ static_url_for('static', url) }}"></script>
{% endfor %}
{% block scripts %}{% endblock %}
</body>
</html>
+4 -4
View File
@@ -74,10 +74,10 @@ def configure_logger() -> None:
logging.getLogger("uvicorn.error").propagate = False
logging.getLogger("sqlalchemy").handlers = [InterceptHandler()]
logging.getLogger("sqlalchemy.engine").handlers = [InterceptHandler()]
logging.getLogger("sqlalchemy.engine").propagate = False
logging.getLogger("sqlalchemy.engine.Engine").handlers = [InterceptHandler()]
logging.getLogger("sqlalchemy.engine.Engine").propagate = False
logging.getLogger("sqlalchemy.engine.base").handlers = [InterceptHandler()]
logging.getLogger("sqlalchemy.engine.base").propagate = False
logging.getLogger("sqlalchemy.engine.base.Engine").handlers = [InterceptHandler()]
logging.getLogger("sqlalchemy.engine.base.Engine").propagate = False
class Formatter:
+418 -409
View File
File diff suppressed because it is too large Load Diff
+35 -37
View File
@@ -6,46 +6,45 @@
"vendor_json": "node -e \"require('fs').writeFileSync('./lnbits/static/vendor.json', JSON.stringify(require('./package.json').bundle))\"",
"vendor_bundle_css": "node -e \"require('concat')(require('./package.json').bundle.css.map(a => 'lnbits/static/'+a), './lnbits/static/bundle.css')\"",
"vendor_bundle_js": "node -e \"require('concat')(require('./package.json').bundle.js.map(a => 'lnbits/static/'+a),'./lnbits/static/bundle.js')\"",
"vendor_bundle_components": "node -e \"require('concat')(require('./package.json').bundle.components.map(a => 'lnbits/static/'+a), './lnbits/static/bundle-components.js')\"",
"vendor_minify_css": "./node_modules/.bin/minify ./lnbits/static/bundle.css > ./lnbits/static/bundle.min.css",
"vendor_minify_js": "./node_modules/.bin/minify ./lnbits/static/bundle.js > ./lnbits/static/bundle.min.js",
"vendor_minify_components": "./node_modules/.bin/minify ./lnbits/static/bundle-components.js > ./lnbits/static/bundle-components.min.js",
"bundle": "npm run sass && npm run vendor_copy && npm run vendor_json && npm run vendor_bundle_css && npm run vendor_bundle_js && npm run vendor_bundle_components && npm run vendor_minify_css && npm run vendor_minify_js && npm run vendor_minify_components"
"vendor_minify_js": "./node_modules/.bin/minify ./lnbits/static/bundle.js > ./lnbits/static/bundle.min.js"
},
"devDependencies": {
"concat": "^1.0.3",
"minify": "^9.2.0",
"prettier": "^3.3.3",
"pyright": "1.1.289",
"sass": "^1.78.0"
"sass": "^1.60.0"
},
"dependencies": {
"axios": "^1.7.7",
"chart.js": "^4.4.4",
"@chenfengyuan/vue-qrcode": "1.0.2",
"axios": "^1.7.5",
"chart.js": "^2.9.4",
"moment": "^2.30.1",
"qrcode.vue": "^3.4.1",
"quasar": "2.16.10",
"quasar": "1.13.2",
"showdown": "^2.1.0",
"underscore": "^1.13.7",
"vue": "3.5.2",
"vue-i18n": "^9.14.0",
"vue-qrcode-reader": "^5.5.7",
"vue-router": "4.4.3",
"vuex": "4.1.0"
"underscore": "^1.13.6",
"vue": "2.6.12",
"vue-i18n": "^8.28.2",
"vue-qrcode-reader": "^2.3.18",
"vue-router": "3.4.3",
"vuex": "3.5.1"
},
"vendor": [
"./node_modules/moment/moment.js",
"./node_modules/underscore/underscore.js",
"./node_modules/axios/dist/axios.js",
"./node_modules/vue/dist/vue.global.prod.js",
"./node_modules/quasar/dist/quasar.umd.prod.js",
"./node_modules/vuex/dist/vuex.global.js",
"./node_modules/vue-i18n/dist/vue-i18n.global.prod.js",
"./node_modules/vue-router/dist/vue-router.global.js",
"./node_modules/vue-qrcode-reader/dist/vue-qrcode-reader.umd.js",
"./node_modules/qrcode.vue/dist/qrcode.vue.browser.js",
"./node_modules/chart.js/dist/chart.umd.js",
"./node_modules/vue/dist/vue.js",
"./node_modules/vue-router/dist/vue-router.js",
"./node_modules/vue-qrcode-reader/dist/VueQrcodeReader.umd.js",
"./node_modules/@chenfengyuan/vue-qrcode/dist/vue-qrcode.js",
"./node_modules/vuex/dist/vuex.js",
"./node_modules/quasar/dist/quasar.ie.polyfills.umd.min.js",
"./node_modules/quasar/dist/quasar.umd.js",
"./node_modules/chart.js/dist/Chart.bundle.js",
"./node_modules/quasar/dist/quasar.css",
"./node_modules/chart.js/dist/Chart.css",
"./node_modules/vue-i18n/dist/vue-i18n.js",
"./node_modules/showdown/dist/showdown.js"
],
"bundle": {
@@ -53,14 +52,15 @@
"vendor/moment.js",
"vendor/underscore.js",
"vendor/axios.js",
"vendor/vue.global.prod.js",
"vendor/quasar.umd.prod.js",
"vendor/vuex.global.js",
"vendor/vue-i18n.global.prod.js",
"vendor/vue-router.global.js",
"vendor/vue-qrcode-reader.umd.js",
"vendor/qrcode.vue.browser.js",
"vendor/chart.umd.js",
"vendor/vue.js",
"vendor/vue-router.js",
"vendor/VueQrcodeReader.umd.js",
"vendor/vue-qrcode.js",
"vendor/vuex.js",
"vendor/quasar.ie.polyfills.umd.min.js",
"vendor/quasar.umd.js",
"vendor/Chart.bundle.js",
"vendor/vue-i18n.js",
"vendor/showdown.js",
"i18n/i18n.js",
"i18n/de.js",
@@ -83,20 +83,18 @@
"i18n/kr.js",
"i18n/fi.js",
"js/base.js",
"js/event-reactions.js",
"js/bolt11-decoder.js"
],
"components": [
"js/components.js",
"js/components/lnbits-funding-sources.js",
"js/components/extension-settings.js",
"js/components/extension-rating.js",
"js/components/payment-list.js",
"js/components/payment-chart.js",
"js/components.js",
"js/init-app.js"
"js/event-reactions.js",
"js/bolt11-decoder.js"
],
"css": [
"vendor/quasar.css",
"vendor/Chart.css",
"css/base.css"
]
}
Generated
+464 -529
View File
File diff suppressed because it is too large Load Diff
+15 -13
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "lnbits"
version = "1.0.0-rc2"
version = "0.12.12"
description = "LNbits, free and open-source Lightning wallet and accounts system."
authors = ["Alan Bits <alan@lnbits.com>"]
readme = "README.md"
@@ -16,25 +16,25 @@ python = "^3.12 | ^3.11 | ^3.10 | ^3.9"
bech32 = "1.2.0"
click = "8.1.7"
ecdsa = "0.19.0"
fastapi = "0.113.0"
fastapi = "0.112.0"
httpx = "0.27.0"
jinja2 = "3.1.4"
lnurl = "0.5.3"
pydantic = "1.10.18"
psycopg2-binary = "2.9.9"
pydantic = "1.10.17"
pyqrcode = "1.2.1"
shortuuid = "1.0.13"
sqlalchemy = "1.3.24"
sqlalchemy-aio = "0.17.0"
sse-starlette = "1.8.2"
typing-extensions = "4.12.2"
uvicorn = "0.30.6"
sqlalchemy = "1.4.54"
aiosqlite = "0.20.0"
asyncpg = "0.29.0"
uvicorn = "0.30.5"
uvloop = "0.19.0"
websockets = "11.0.3"
loguru = "0.7.2"
grpcio = "1.66.1"
protobuf = "5.28.0"
pyln-client = "24.8.1"
grpcio = "1.65.5"
protobuf = "5.27.3"
pyln-client = "24.5"
pywebpush = "1.14.1"
slowapi = "0.1.9"
websocket-client = "1.8.0"
@@ -70,11 +70,11 @@ black = "^24.8.0"
pytest-asyncio = "^0.21.2"
pytest = "^8.3.2"
pytest-cov = "^4.1.0"
mypy = "^1.11.2"
mypy = "^1.11.1"
types-protobuf = "^5.27.0.20240626"
pre-commit = "^3.8.0"
openapi-spec-validator = "^0.7.1"
ruff = "^0.6.4"
ruff = "^0.5.7"
types-passlib = "^1.7.7.20240327"
openai = "^1.39.0"
json5 = "^0.9.25"
@@ -84,7 +84,7 @@ pytest-httpserver = "^1.1.0"
pytest-mock = "^3.14.0"
types-mock = "^5.1.0.20240425"
mock = "^5.1.0"
grpcio-tools = "^1.66.1"
grpcio-tools = "^1.65.5"
[build-system]
requires = ["poetry-core>=1.0.0"]
@@ -126,6 +126,7 @@ module = [
"secp256k1.*",
"uvicorn.*",
"sqlalchemy.*",
"sqlalchemy_aio.*",
"websocket.*",
"websockets.*",
"pyqrcode.*",
@@ -135,6 +136,7 @@ module = [
"bolt11.*",
"bitstring.*",
"ecdsa.*",
"psycopg2.*",
"pyngrok.*",
"pyln.client.*",
"py_vapid.*",
+4 -4
View File
@@ -367,11 +367,11 @@ async def test_get_payments_history(client, adminkey_headers_from, fake_payments
assert response.status_code == 200
data = response.json()
assert len(data) == 1
assert data[0]["income"] == sum(
[int(payment.amount * 1000) for payment in fake_data if not payment.out]
)
assert data[0]["spending"] == sum(
[int(payment.amount * 1000) for payment in fake_data if payment.out]
payment.amount * 1000 for payment in fake_data if payment.out
)
assert data[0]["income"] == sum(
payment.amount * 1000 for payment in fake_data if not payment.out
)
response = await client.get(
+5 -3
View File
@@ -25,6 +25,7 @@ from lnbits.core.views.payment_api import api_payments_create_invoice
from lnbits.db import DB_TYPE, SQLITE, Database
from lnbits.settings import settings
from tests.helpers import (
clean_database,
get_random_invoice_data,
)
@@ -46,6 +47,7 @@ def event_loop():
# use session scope to run once before and once after all tests
@pytest_asyncio.fixture(scope="session")
async def app():
clean_database(settings)
app = create_app()
async with LifespanManager(app) as manager:
settings.first_install = False
@@ -197,9 +199,9 @@ async def fake_payments(client, adminkey_headers_from):
"/api/v1/payments", headers=adminkey_headers_from, json=invoice.dict()
)
assert response.is_success
data = response.json()
assert data["checking_id"]
await update_payment_status(data["checking_id"], status=PaymentState.SUCCESS)
await update_payment_status(
response.json()["checking_id"], status=PaymentState.SUCCESS
)
params = {"time[ge]": ts, "time[le]": time()}
return fake_data, params
+23 -1
View File
@@ -2,7 +2,11 @@ import random
import string
from typing import Optional
from lnbits.db import FromRowModel
from psycopg2 import connect
from psycopg2.errors import InvalidCatalogName
from lnbits import core
from lnbits.db import DB_TYPE, POSTGRES, FromRowModel
from lnbits.wallets import get_funding_source, set_funding_source
@@ -31,3 +35,21 @@ set_funding_source()
funding_source = get_funding_source()
is_fake: bool = funding_source.__class__.__name__ == "FakeWallet"
is_regtest: bool = not is_fake
def clean_database(settings):
if DB_TYPE == POSTGRES:
conn = connect(settings.lnbits_database_url)
conn.autocommit = True
with conn.cursor() as cur:
try:
cur.execute("DROP DATABASE lnbits_test")
except InvalidCatalogName:
pass
cur.execute("CREATE DATABASE lnbits_test")
core.db.__init__("database")
conn.close()
else:
# TODO: do this once mock data is removed from test data folder
# os.remove(settings.lnbits_data_folder + "/database.sqlite3")
pass
+2 -2
View File
@@ -14,8 +14,8 @@ from lnbits.db import POSTGRES
@pytest.mark.asyncio
async def test_date_conversion(db):
if db.type == POSTGRES:
row = await db.fetchone("SELECT now()::date as now")
assert row and isinstance(row.get("now"), date)
row = await db.fetchone("SELECT now()::date")
assert row and isinstance(row[0], date)
# make test to create wallet and delete wallet
+2 -9
View File
@@ -12,17 +12,10 @@ test = DbTestModel(id=1, name="test", value="yes")
@pytest.mark.asyncio
async def test_helpers_insert_query():
q = insert_query("test_helpers_query", test)
assert (
q == "INSERT INTO test_helpers_query (id, name, value) "
"VALUES (:id, :name, :value)"
)
assert q == "INSERT INTO test_helpers_query (id, name, value) VALUES (?, ?, ?)"
@pytest.mark.asyncio
async def test_helpers_update_query():
q = update_query("test_helpers_query", test)
assert (
q == "UPDATE test_helpers_query "
"SET id = :id, name = :name, value = :value "
"WHERE id = :id"
)
assert q == "UPDATE test_helpers_query SET id = ?, name = ?, value = ? WHERE id = ?"
-168
View File
@@ -1,168 +0,0 @@
import pytest
from lnbits.settings import RedirectPath
lnurlp_redirect_path = {
"from_path": "/.well-known/lnurlp",
"redirect_to_path": "/api/v1/well-known",
}
lnurlp_redirect_path_with_headers = {
"from_path": "/.well-known/lnurlp",
"redirect_to_path": "/api/v1/well-known",
"header_filters": {"accept": "application/nostr+json"},
}
lnaddress_redirect_path = {
"from_path": "/.well-known/lnurlp",
"redirect_to_path": "/api/v1/well-known",
}
nostrrelay_redirect_path = {
"from_path": "/",
"redirect_to_path": "/api/v1/relay-info",
"header_filters": {"accept": "application/nostr+json"},
}
@pytest.fixture()
def lnurlp():
return RedirectPath(ext_id="lnurlp", **lnurlp_redirect_path)
@pytest.fixture()
def lnurlp_with_headers():
return RedirectPath(
ext_id="lnurlp_with_headers", **lnurlp_redirect_path_with_headers
)
@pytest.fixture()
def lnaddress():
return RedirectPath(ext_id="lnaddress", **lnaddress_redirect_path)
@pytest.fixture()
def nostrrelay():
return RedirectPath(ext_id="nostrrelay", **nostrrelay_redirect_path)
def test_redirect_path_self_not_in_conflict(
lnurlp: RedirectPath, lnaddress: RedirectPath, nostrrelay: RedirectPath
):
assert not lnurlp.in_conflict(lnurlp), "Path is not in conflict with itself."
assert not lnaddress.in_conflict(lnaddress), "Path is not in conflict with itself."
assert not nostrrelay.in_conflict(
nostrrelay
), "Path is not in conflict with itself."
assert not lnurlp.in_conflict(nostrrelay)
assert not nostrrelay.in_conflict(lnurlp)
def test_redirect_path_not_in_conflict(
lnurlp: RedirectPath, lnaddress: RedirectPath, nostrrelay: RedirectPath
):
assert not lnurlp.in_conflict(nostrrelay)
assert not nostrrelay.in_conflict(lnurlp)
assert not lnaddress.in_conflict(nostrrelay)
assert not nostrrelay.in_conflict(lnaddress)
def test_redirect_path_in_conflict(lnurlp: RedirectPath, lnaddress: RedirectPath):
assert lnurlp.in_conflict(lnaddress)
assert lnaddress.in_conflict(lnurlp)
def test_redirect_path_find_conflict(
lnurlp: RedirectPath, lnaddress: RedirectPath, nostrrelay: RedirectPath
):
assert lnurlp.find_in_conflict([nostrrelay, lnaddress])
assert lnurlp.find_in_conflict([lnaddress, nostrrelay])
assert lnaddress.find_in_conflict([nostrrelay, lnurlp])
assert lnaddress.find_in_conflict([lnurlp, nostrrelay])
def test_redirect_path_find_no_conflict(
lnurlp: RedirectPath, lnaddress: RedirectPath, nostrrelay: RedirectPath
):
assert not nostrrelay.find_in_conflict([lnurlp, lnaddress])
assert not lnurlp.find_in_conflict([nostrrelay])
assert not lnaddress.find_in_conflict([nostrrelay])
def test_redirect_path_in_conflict_with_headers(
lnurlp: RedirectPath, lnurlp_with_headers: RedirectPath
):
assert lnurlp.in_conflict(lnurlp_with_headers)
assert lnurlp_with_headers.in_conflict(lnurlp)
def test_redirect_path_matches_with_headers(
lnurlp: RedirectPath, lnurlp_with_headers: RedirectPath
):
headers_list = list(lnurlp_with_headers.header_filters.items())
assert lnurlp.redirect_matches(
path=lnurlp_with_headers.from_path,
req_headers=headers_list,
)
assert lnurlp_with_headers.redirect_matches(
path=lnurlp_redirect_path["from_path"],
req_headers=[("ACCEPT", "APPlication/nostr+json")],
)
assert lnurlp_with_headers.redirect_matches(
path=lnurlp_redirect_path["from_path"],
req_headers=[("accept", "application/nostr+json"), ("my_header", "my_value")],
)
assert not lnurlp_with_headers.redirect_matches(
path=lnurlp_redirect_path["from_path"], req_headers=[]
)
assert not lnurlp_with_headers.redirect_matches(
path=lnurlp_redirect_path["from_path"],
req_headers=[("accept", "application/json")],
)
assert not lnurlp_with_headers.redirect_matches(path="/random/path", req_headers=[])
assert not lnurlp_with_headers.redirect_matches(path="/random_path", req_headers=[])
assert not lnurlp_with_headers.redirect_matches(
path="/.well-known/lnurlp", req_headers=[]
)
assert lnurlp.redirect_matches(path="/.well-known/lnurlp", req_headers=[])
assert lnurlp.redirect_matches(
path="/.well-known/lnurlp/some/other/path", req_headers=[]
)
assert lnurlp.redirect_matches(
path="/.well-known/lnurlp/some/other/path",
req_headers=headers_list,
)
assert not lnurlp_with_headers.redirect_matches(
path="/.well-known/lnurlp", req_headers=[]
)
assert not lnurlp_with_headers.redirect_matches(
path="/.well-known/lnurlp/some/other/path", req_headers=[]
)
assert lnurlp_with_headers.redirect_matches(
path="/.well-known/lnurlp/some/other/path",
req_headers=headers_list,
)
def test_redirect_path_new_path_from(lnurlp: RedirectPath):
assert lnurlp.new_path_from("") == "/lnurlp/api/v1/well-known"
assert lnurlp.new_path_from("/") == "/lnurlp/api/v1/well-known"
assert lnurlp.new_path_from("/path") == "/lnurlp/api/v1/well-known"
assert lnurlp.new_path_from("/path/more") == "/lnurlp/api/v1/well-known"
assert lnurlp.new_path_from("/.well-known/lnurlp") == "/lnurlp/api/v1/well-known"
assert (
lnurlp.new_path_from("/.well-known/lnurlp/path")
== "/lnurlp/api/v1/well-known/path"
)
assert (
lnurlp.new_path_from("/.well-known/lnurlp/path/more")
== "/lnurlp/api/v1/well-known/path/more"
)
+5 -9
View File
@@ -1,5 +1,5 @@
# Python script to migrate an LNbits SQLite DB to Postgres
# credits to @Fritz446 for the awesome work
# All credits to @Fritz446 for the awesome work
# pip install psycopg2 OR psycopg2-binary
@@ -9,13 +9,9 @@ import sqlite3
import sys
from typing import List, Optional
from lnbits.settings import settings
import psycopg2
try:
import psycopg2 # type: ignore
except ImportError:
print("Please install psycopg2")
sys.exit(1)
from lnbits.settings import settings
sqfolder = settings.lnbits_data_folder
db_url = settings.lnbits_database_url
@@ -59,8 +55,8 @@ def check_db_versions(sqdb):
version = dbpost[key]
if value != version:
raise Exception(
f"sqlite database version ({value}) of {key} doesn't match "
f"postgres database version {version}"
f"sqlite database version ({value}) of {key} doesn't match postgres"
f" database version {version}"
)
connection = postgres.connection