diff --git a/lnbits/core/crud/wallets.py b/lnbits/core/crud/wallets.py index 4f080b82a..a88259515 100644 --- a/lnbits/core/crud/wallets.py +++ b/lnbits/core/crud/wallets.py @@ -5,6 +5,7 @@ from uuid import uuid4 from lnbits.core.db import db from lnbits.core.models.wallets import BaseWallet, WalletsFilters, WalletType from lnbits.db import Connection, Filters, Page +from lnbits.helpers import generate_ln_address from lnbits.settings import settings from lnbits.utils.cache import cache @@ -30,6 +31,8 @@ async def create_wallet( inkey=uuid4().hex, currency=settings.lnbits_default_accounting_currency or "USD", ) + if settings.ln_address_creation_allowed and wallet.is_lightning_wallet: + wallet.lightning_address = await generate_lightning_address_local_part(conn) await (conn or db).insert("wallets", wallet) return wallet @@ -123,11 +126,21 @@ async def get_standalone_wallet( """ if deleted is not None: query += " AND deleted = :deleted " - return await (conn or db).fetchone( + wallet = await (conn or db).fetchone( query, {"wallet": wallet_id, "deleted": deleted}, Wallet, ) + if not wallet: + return None + if deleted is True: + return wallet + + if not wallet.lightning_address and settings.ln_address_creation_allowed: + wallet.lightning_address = await generate_lightning_address_local_part(conn) + await update_wallet(wallet, conn) + + return wallet async def get_wallet( @@ -220,6 +233,30 @@ async def get_wallets_count(): return row.get("count", 0) +async def generate_lightning_address_local_part( + conn: Connection | None = None, +) -> str: + for _ in range(100): + local_part = generate_ln_address() + if await get_wallet_id_by_ln_address(local_part, conn): + continue + return local_part + raise ValueError("Could not generate a unique wallet lightning address.") + + +async def get_wallet_id_by_ln_address( + local_part: str, conn: Connection | None = None +) -> str | None: + row: dict = await (conn or db).fetchone( + """ + SELECT id FROM wallets + WHERE lightning_address = :lightning_address + """, + {"lightning_address": local_part.lower()}, + ) + return row["id"] if row else None + + async def get_wallet_for_key( key: str, conn: Connection | None = None, diff --git a/lnbits/core/migrations.py b/lnbits/core/migrations.py index 2b084a35a..8796f2e86 100644 --- a/lnbits/core/migrations.py +++ b/lnbits/core/migrations.py @@ -890,3 +890,15 @@ async def m049_add_permissions_to_user_extensions(db: Connection): Adds user-level extension permission grants. """ await db.execute("ALTER TABLE extensions ADD COLUMN permissions TEXT DEFAULT '{}'") + + +async def m050_add_lightning_address_to_wallets(db: Connection): + """ + Adds a LUD-16 lightning address local-part to wallets. + """ + await db.execute("ALTER TABLE wallets ADD COLUMN lightning_address TEXT") + logger.debug("Creating index idx_wallets_lightning_address...") + await db.execute(""" + CREATE UNIQUE INDEX IF NOT EXISTS idx_wallets_lightning_address + ON wallets (lightning_address); + """) diff --git a/lnbits/core/models/wallets.py b/lnbits/core/models/wallets.py index 69cb61879..8e6241948 100644 --- a/lnbits/core/models/wallets.py +++ b/lnbits/core/models/wallets.py @@ -126,6 +126,7 @@ class Wallet(BaseWallet): created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc)) currency: str | None = None + lightning_address: str | None = None balance_msat: int = Field(default=0, no_database=True) extra: WalletExtra = WalletExtra() stored_paylinks: StoredPayLinks = StoredPayLinks() @@ -150,6 +151,7 @@ class Wallet(BaseWallet): if len(self.share_permissions): self.currency = shared_wallet.currency + self.lightning_address = shared_wallet.lightning_address self.balance_msat = shared_wallet.balance_msat self.stored_paylinks = shared_wallet.stored_paylinks @@ -240,10 +242,18 @@ class BaseWalletTypeInfo: class WalletsFilters(FilterModel): - __search_fields__ = ["id", "name", "currency"] + __search_fields__ = ["id", "name", "currency", "lightning_address"] - __sort_fields__ = ["id", "name", "currency", "created_at", "updated_at"] + __sort_fields__ = [ + "id", + "name", + "currency", + "lightning_address", + "created_at", + "updated_at", + ] id: str | None name: str | None currency: str | None + lightning_address: str | None diff --git a/lnbits/core/services/lightning_address.py b/lnbits/core/services/lightning_address.py new file mode 100644 index 000000000..421b33156 --- /dev/null +++ b/lnbits/core/services/lightning_address.py @@ -0,0 +1,242 @@ +import json +import re + +from fastapi import Query, Request +from lnurl import ( + CallbackUrl, + LightningInvoice, + LnurlErrorResponse, + LnurlPayActionResponse, + LnurlPayMetadata, + LnurlPayResponse, + MilliSatoshi, +) +from pydantic import parse_obj_as + +from lnbits.core.crud.wallets import ( + get_wallet, + get_wallet_id_by_ln_address, + update_wallet, +) +from lnbits.core.models.payments import CreateInvoice +from lnbits.core.models.wallets import Wallet +from lnbits.core.services.payments import ( + create_invoice, + create_wallet_invoice, + pay_invoice, +) +from lnbits.db import Connection +from lnbits.exceptions import PaymentError +from lnbits.settings import settings + +MAX_SENDABLE_MSAT = 2_100_000_000_000_000_000 +COMMENT_ALLOWED = 799 +LIGHTNING_ADDRESS_REGEX = re.compile(r"^[a-z0-9_.-]{1,210}$") + + +async def set_wallet_lightning_address( + *, + wallet: Wallet, + local_part: str, + allow_blacklisted: bool = False, + charge: bool = False, + conn: Connection | None = None, +) -> Wallet: + if not settings.ln_address_creation_allowed: + raise ValueError("Wallet Lightning Addresses are disabled.") + if not wallet.is_lightning_wallet or wallet.deleted: + raise ValueError("Lightning Address can only be set for active wallets.") + + local_part = await _validate_local_part( + local_part, wallet.id, allow_blacklisted, conn=conn + ) + if wallet.lightning_address == local_part: + return wallet + + if charge: + await _charge_for_lightning_address(wallet) + + wallet.lightning_address = local_part + return await update_wallet(wallet, conn=conn) + + +async def wallet_lightning_address_response( + username: str, request: Request +) -> LnurlPayResponse | LnurlErrorResponse: + local_part, tag = _split_tagged_local_part(username) + wallet_id = await get_wallet_id_by_ln_address(local_part) + if not wallet_id: + return LnurlErrorResponse(reason="Lightning address not found.") + + tagged_local_part = local_part + if tag: + tagged_local_part = f"{tagged_local_part}+{tag}" + + callback = request.url_for( + "lnurl.api_wallet_lightning_address_callback", + username=tagged_local_part, + ) + identifier = _lightning_address_for_request(request, tagged_local_part) + return LnurlPayResponse( + callback=parse_obj_as(CallbackUrl, str(callback)), + minSendable=MilliSatoshi(1000), + maxSendable=MilliSatoshi(MAX_SENDABLE_MSAT), + metadata=LnurlPayMetadata(json.dumps(_metadata(identifier, tag))), + commentAllowed=COMMENT_ALLOWED, + ) + + +async def wallet_lightning_address_callback( + username: str, + request: Request, + amount: int = Query(...), +) -> LnurlErrorResponse | LnurlPayActionResponse: + local_part, tag = _split_tagged_local_part(username) + wallet_id = await get_wallet_id_by_ln_address(local_part) + if not wallet_id: + return LnurlErrorResponse(reason="Lightning address not found.") + + if amount < 1000: + return LnurlErrorResponse(reason="Amount is smaller than minimum 1000.") + if amount > MAX_SENDABLE_MSAT: + return LnurlErrorResponse( + reason=f"Amount is greater than maximum {MAX_SENDABLE_MSAT}." + ) + + comment = request.query_params.get("comment") + if len(comment or "") > COMMENT_ALLOWED: + return LnurlErrorResponse( + reason=( + f"Got a comment with {len(comment or '')} characters, " + f"but can only accept {COMMENT_ALLOWED}" + ) + ) + + tagged_local_part = local_part + if tag: + tagged_local_part = f"{tagged_local_part}+{tag}" + identifier = _lightning_address_for_request(request, tagged_local_part) + extra = { + "tag": "wallet_lightning_address", + "lnaddress": identifier, + } + if tag: + extra["lnaddress_tag"] = tag + if comment: + extra["comment"] = comment + + metadata = LnurlPayMetadata(json.dumps(_metadata(identifier, tag))) + payment = await create_invoice( + wallet_id=wallet_id, + amount=int(amount / 1000), + memo=f"Payment to {identifier}", + unhashed_description=metadata.encode(), + extra=extra, + ) + invoice = parse_obj_as(LightningInvoice, LightningInvoice(payment.bolt11)) + return LnurlPayActionResponse(pr=invoice, disposable=False) + + +def _lightning_address_for_request(request: Request, local_part: str) -> str: + return f"{local_part}@{request.url.netloc}" + + +async def _validate_local_part( + local_part: str, + wallet_id: str, + allow_blacklisted: bool = False, + conn: Connection | None = None, +) -> str: + local_part = local_part.strip().lower() + if not local_part: + raise ValueError("Lightning Address is required.") + if "+" in local_part: + raise ValueError("Lightning Address cannot include tags.") + if "@" in local_part: + raise ValueError("Enter only the Lightning Address name before @.") + if not LIGHTNING_ADDRESS_REGEX.match(local_part): + raise ValueError( + "Lightning Address can only contain lowercase letters, numbers, " + "dash, underscore, and dot." + ) + if not allow_blacklisted and _uses_blacklisted_word(local_part): + raise ValueError("Lightning Address contains a reserved word.") + existing_wallet_id = await get_wallet_id_by_ln_address(local_part, conn=conn) + if existing_wallet_id and existing_wallet_id != wallet_id: + raise ValueError("Lightning Address is already taken.") + + return local_part + + +def _split_tagged_local_part(local_part: str) -> tuple[str, str | None]: + username, separator, tag = local_part.partition("+") + if not separator or not tag: + return username.lower(), None + return username.lower(), tag + + +def _metadata(identifier: str, tag: str | None = None) -> list[list[str]]: + metadata = [ + ["text/plain", f"Payment to {identifier}"], + ["text/identifier", identifier], + ] + if tag: + metadata.append(["text/tag", tag]) + return metadata + + +async def _charge_for_lightning_address(wallet: Wallet) -> None: + price_sats = settings.lnbits_wallet_lightning_address_price_sats + if not settings.lnbits_charge_wallet_lightning_addresses or price_sats <= 0: + return + if not settings.lnbits_service_fee_wallet: + raise ValueError("Lightning Address fee wallet is not configured.") + if settings.lnbits_service_fee_wallet == wallet.source_wallet_id: + raise ValueError("Lightning Address fee wallet cannot be the same wallet.") + + fee_wallet = await get_wallet(settings.lnbits_service_fee_wallet) + if not fee_wallet: + raise ValueError("Lightning Address fee wallet is not configured.") + + invoice = await create_wallet_invoice( + settings.lnbits_service_fee_wallet, + CreateInvoice( + out=False, + amount=price_sats, + memo="Lightning Address fee", + internal=True, + extra={ + "tag": "wallet_lightning_address_fee", + "wallet": wallet.source_wallet_id, + }, + ), + ) + try: + await pay_invoice( + wallet_id=wallet.source_wallet_id, + payment_request=invoice.bolt11, + description="Lightning Address fee", + tag="wallet_lightning_address_fee", + extra={ + "tag": "wallet_lightning_address_fee", + "fee_wallet": settings.lnbits_service_fee_wallet, + }, + ) + except PaymentError as exc: + raise ValueError(exc.message) from exc + + +def _blacklist_words() -> set[str]: + return { + word.strip().lower() + for word in settings.lnbits_wallet_lightning_address_blacklist + if word.strip() + } + + +def _uses_blacklisted_word(local_part: str) -> bool: + words = _blacklist_words() + if not words: + return False + segments = [segment for segment in re.split(r"[._-]+", local_part) if segment] + return local_part in words or any(segment in words for segment in segments) diff --git a/lnbits/core/views/lnurl_api.py b/lnbits/core/views/lnurl_api.py index 21d34abca..23ca95f68 100644 --- a/lnbits/core/views/lnurl_api.py +++ b/lnbits/core/views/lnurl_api.py @@ -1,10 +1,13 @@ from http import HTTPStatus from typing import Any +import httpx from fastapi import ( APIRouter, Depends, HTTPException, + Query, + Request, ) from lnurl import ( LnurlAuthResponse, @@ -18,6 +21,7 @@ from lnurl import execute_login as lnurlauth from lnurl import handle as lnurl_handle from lnurl.models import LnurlResponseModel from loguru import logger +from pydantic import ValidationError from lnbits.core.models import Payment from lnbits.core.models.lnurl import CreateLnurlPayment, LnurlScan @@ -27,13 +31,50 @@ from lnbits.decorators import ( require_base_invoice_key, ) from lnbits.helpers import check_callback_url -from lnbits.settings import settings +from lnbits.settings import RedirectPath, settings from ..services import fetch_lnurl_pay_request, pay_invoice +from ..services.lightning_address import ( + wallet_lightning_address_callback, + wallet_lightning_address_response, +) lnurl_router = APIRouter(tags=["LNURL"]) +@lnurl_router.get( + "/.well-known/lnurlp/{username}", + name="lnurl.api_wallet_lightning_address_response", +) +async def api_wallet_lightning_address_response( + username: str, request: Request +) -> LnurlPayResponse | LnurlErrorResponse: + if settings.lnbits_ln_address_mode in ["extension_first", "extension_only"]: + req_headers = request["headers"] if "headers" in request else [] + redirect = settings.find_extension_redirect(request.url.path, req_headers) + if redirect: + resp = await _check_extension_well_known(redirect, request) + if resp and resp.ok: + return resp + + if settings.lnbits_ln_address_mode == "extension_only": + return LnurlErrorResponse( + reason="Lightning addresses are not supported on this instance." + ) + + return await wallet_lightning_address_response(username, request) + + +@lnurl_router.get( + "/api/v1/lnurl/wallet/{username}/cb", + name="lnurl.api_wallet_lightning_address_callback", +) +async def api_wallet_lightning_address_callback( + username: str, request: Request, amount: int = Query(...) +) -> LnurlErrorResponse | Any: + return await wallet_lightning_address_callback(username, request, amount) + + async def _handle(lnurl: str) -> LnurlResponseModel: try: if "@" in lnurl: # lower case lightning addresses @@ -137,3 +178,32 @@ async def api_payments_pay_lnurl( ) return payment + + +async def _check_extension_well_known( + redirect: RedirectPath, request: Request +) -> LnurlPayResponse | LnurlErrorResponse | None: + target_path = redirect.new_path_from(request.url.path) + + transport = httpx.ASGITransport(app=request.app) + try: + async with httpx.AsyncClient( + transport=transport, + base_url=str(request.base_url), + ) as client: + response = await client.get( + target_path, + headers={"accept": "application/json"}, + ) + + response.raise_for_status() + response_data = response.json() + try: + return LnurlPayResponse.parse_obj(response_data) + except ValidationError: + return LnurlErrorResponse.parse_obj(response_data) + except Exception as exc: + logger.warning( + f"Failed to fetch LNURL response Extension redirect {target_path}: {exc}" + ) + return None diff --git a/lnbits/core/views/user_api.py b/lnbits/core/views/user_api.py index a9d614603..28ad4cddc 100644 --- a/lnbits/core/views/user_api.py +++ b/lnbits/core/views/user_api.py @@ -41,6 +41,7 @@ from lnbits.core.services import ( update_user_extensions, update_wallet_balance, ) +from lnbits.core.services.lightning_address import set_wallet_lightning_address from lnbits.db import Filters, Page from lnbits.decorators import check_admin, check_super_user, parse_filters from lnbits.helpers import ( @@ -280,6 +281,34 @@ async def api_users_create_user_wallet( return wallet +@users_router.put( + "/user/{user_id}/wallet/{wallet}/lightning-address", + name="Set wallet Lightning Address", +) +async def api_users_set_wallet_lightning_address( + user_id: str, + wallet: str, + lightning_address: str = Body(..., embed=True), +) -> Wallet: + wal = await get_wallet(wallet) + if not wal: + raise HTTPException( + status_code=HTTPStatus.NOT_FOUND, + detail="Wallet does not exist.", + ) + if user_id != wal.user: + raise HTTPException( + status_code=HTTPStatus.FORBIDDEN, + detail="Wallet does not belong to user.", + ) + return await set_wallet_lightning_address( + wallet=wal, + local_part=lightning_address, + allow_blacklisted=True, + charge=False, + ) + + @users_router.put( "/user/{user_id}/wallet/{wallet}/undelete", name="Reactivate deleted wallet" ) diff --git a/lnbits/core/views/wallet_api.py b/lnbits/core/views/wallet_api.py index 3aa7b9934..79636325a 100644 --- a/lnbits/core/views/wallet_api.py +++ b/lnbits/core/views/wallet_api.py @@ -22,6 +22,7 @@ from lnbits.core.models.wallets import ( WalletSharePermission, WalletType, ) +from lnbits.core.services.lightning_address import set_wallet_lightning_address from lnbits.core.services.wallets import ( create_lightning_shared_wallet, delete_wallet_share, @@ -38,6 +39,7 @@ from lnbits.decorators import ( require_invoice_key, ) from lnbits.helpers import generate_filter_params_openapi +from lnbits.settings import settings from ..crud import ( delete_wallet, @@ -164,6 +166,7 @@ async def api_update_wallet( color: str | None = Body(None), currency: str | None = Body(None), pinned: bool | None = Body(None), + lightning_address: str | None = Body(None), key_info: WalletTypeInfo = Depends(require_admin_key), ) -> Wallet: wallet = await get_wallet(key_info.wallet.id) @@ -175,6 +178,20 @@ async def api_update_wallet( wallet.extra.pinned = pinned if pinned is not None else wallet.extra.pinned wallet.currency = currency if currency is not None else wallet.currency + if lightning_address and lightning_address != wallet.lightning_address: + if not settings.lnbits_allow_custom_wallet_lightning_addresses: + raise HTTPException( + status_code=HTTPStatus.FORBIDDEN, + detail="Users cannot specify Lightning Addresses.", + ) + # too much logic here + wallet = await set_wallet_lightning_address( + wallet=wallet, + local_part=lightning_address, + charge=True, + ) + return wallet + await update_wallet(wallet) return wallet diff --git a/lnbits/helpers.py b/lnbits/helpers.py index c47c3a932..1dc5b7aa3 100644 --- a/lnbits/helpers.py +++ b/lnbits/helpers.py @@ -13,6 +13,7 @@ from fastapi.routing import APIRoute from loguru import logger from packaging import version from pydantic.schema import field_schema +from random_username.generate import generate_username # type: ignore[import-untyped] from starlette.templating import Jinja2Templates from lnbits.settings import settings @@ -22,6 +23,10 @@ from lnbits.utils.exchange_rates import currencies from .db import FilterModel +def generate_ln_address() -> str: + return generate_username(1)[0].lower() + + def get_db_vendor_name(): db_url = settings.lnbits_database_url return ( diff --git a/lnbits/middleware.py b/lnbits/middleware.py index b7b3c7d17..d216786ac 100644 --- a/lnbits/middleware.py +++ b/lnbits/middleware.py @@ -104,7 +104,7 @@ class ExtensionsRedirectMiddleware: req_headers = scope["headers"] if "headers" in scope else [] redirect = settings.find_extension_redirect(scope["path"], req_headers) - if redirect: + if redirect and not redirect.is_duplicate_well_known(): scope["path"] = redirect.new_path_from(scope["path"]) await self.app(scope, receive, send) diff --git a/lnbits/settings.py b/lnbits/settings.py index 21b861db8..4b89cb5e1 100644 --- a/lnbits/settings.py +++ b/lnbits/settings.py @@ -11,7 +11,7 @@ from enum import Enum from os import path from pathlib import Path from time import gmtime, strftime, time -from typing import Any +from typing import Any, Literal from uuid import uuid4 from loguru import logger @@ -45,6 +45,16 @@ class UsersSettings(LNbitsSettings): lnbits_admin_users: list[str] = Field(default=[]) lnbits_allowed_users: list[str] = Field(default=[]) lnbits_allow_new_accounts: bool = Field(default=True) + + lnbits_ln_address_mode: Literal[ + "core_first", "extension_first", "extension_only" + ] = Field(default="extension_first") + lnbits_allow_custom_wallet_lightning_addresses: bool = Field(default=False) + lnbits_charge_wallet_lightning_addresses: bool = Field(default=False) + lnbits_wallet_lightning_address_price_sats: int = Field(default=1000, ge=0) + lnbits_wallet_lightning_address_blacklist: list[str] = Field( + default=["admin", "info", "support", "help", "security"] + ) lnbits_require_user_activation: bool = Field(default=False) lnbits_user_activation_by_email: bool = Field(default=False) @@ -58,6 +68,10 @@ class UsersSettings(LNbitsSettings): def new_accounts_allowed(self) -> bool: return self.lnbits_allow_new_accounts and len(self.lnbits_allowed_users) == 0 + @property + def ln_address_creation_allowed(self) -> bool: + return self.lnbits_ln_address_mode != "extension_only" + class ExtensionsSettings(LNbitsSettings): lnbits_admin_extensions: list[str] = Field(default=[]) @@ -126,6 +140,9 @@ class RedirectPath(BaseModel): redirect_to_path: str header_filters: dict = {} + def is_duplicate_well_known(self) -> bool: + return self.from_path in ["/.well-known/lnurlp"] + def in_conflict(self, other: RedirectPath) -> bool: if self.ext_id == other.ext_id: return False @@ -1062,6 +1079,7 @@ class EditableSettings( @validator( "lnbits_admin_users", "lnbits_allowed_users", + "lnbits_wallet_lightning_address_blacklist", "lnbits_theme_options", "lnbits_admin_extensions", "lnbits_extensions_manifests", @@ -1362,6 +1380,18 @@ class PublicSettings(BaseModel): wallet_featured_button_label: str | None = Field(alias="walletFeaturedButtonLabel") wallet_featured_button_url: str | None = Field(alias="walletFeaturedButtonUrl") wallet_featured_button_icon: str | None = Field(alias="walletFeaturedButtonIcon") + enable_wallet_lightning_addresses: bool = Field( + alias="enableWalletLightningAddresses" + ) + allow_custom_wallet_lightning_addresses: bool = Field( + alias="allowCustomWalletLightningAddresses" + ) + charge_wallet_lightning_addresses: bool = Field( + alias="chargeWalletLightningAddresses" + ) + wallet_lightning_address_price_sats: int = Field( + alias="walletLightningAddressPriceSats" + ) lnbits_user_activation_by_email: bool = Field(alias="userActivationByEmail") lnbits_user_activation_by_payment: bool = Field(alias="userActivationByPayment") lnbits_user_activation_by_invitation_code: bool = Field( @@ -1427,6 +1457,16 @@ class PublicSettings(BaseModel): walletFeaturedButtonLabel=settings.lnbits_wallet_featured_button_label, walletFeaturedButtonUrl=settings.lnbits_wallet_featured_button_url, walletFeaturedButtonIcon=settings.lnbits_wallet_featured_button_icon, + enableWalletLightningAddresses=settings.ln_address_creation_allowed, + allowCustomWalletLightningAddresses=( + settings.lnbits_allow_custom_wallet_lightning_addresses + ), + chargeWalletLightningAddresses=( + settings.lnbits_charge_wallet_lightning_addresses + ), + walletLightningAddressPriceSats=( + settings.lnbits_wallet_lightning_address_price_sats + ), userActivationByEmail=settings.lnbits_user_activation_by_email, userActivationByPayment=settings.lnbits_user_activation_by_payment, userActivationByInvitationCode=settings.lnbits_user_activation_by_invitation_code, diff --git a/lnbits/static/bundle-components.min.js b/lnbits/static/bundle-components.min.js index 47516ee4b..9f951000a 100644 --- a/lnbits/static/bundle-components.min.js +++ b/lnbits/static/bundle-components.min.js @@ -1 +1 @@ -window.PageError={template:"#page-error"},window.PageHome={template:"#page-home",data:()=>({lnurl:"",authAction:"login",authMethod:"username-password",usr:"",username:"",reset_key:"",email:"",password:"",passwordRepeat:"",invitationCode:"",walletName:"",signup:!1}),computed:{showClaimLnurl(){return""!==this.lnurl&&this.g.settings.allowRegister&&this.g.settings.authMethods.includes("user-id-only")},formatDescription(){return LNbits.utils.convertMarkdown(this.g.settings.siteDescription)},isAccessTokenExpired(){return this.$q.cookies.get("is_access_token_expired")}},methods:{showLogin(e){this.authAction="login",this.authMethod=e},showRegister(e){this.user="",this.username=null,this.password=null,this.passwordRepeat=null,this.invitationCode=null,this.authAction="register",this.authMethod=e},async register(){try{await LNbits.api.register(this.username,this.email,this.password,this.passwordRepeat,this.invitationCode),this.refreshAuthUser()}catch(e){LNbits.utils.notifyApiError(e)}},async reset(){try{await LNbits.api.reset(this.reset_key,this.password,this.passwordRepeat),this.refreshAuthUser()}catch(e){LNbits.utils.notifyApiError(e)}},async login(){try{await LNbits.api.login(this.username,this.password),this.refreshAuthUser()}catch(e){LNbits.utils.notifyApiError(e)}},async loginUsr(){try{await LNbits.api.loginUsr(this.usr),this.refreshAuthUser()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}},async refreshAuthUser(){try{const e=await LNbits.api.getAuthUser();this.g.user=LNbits.map.user(e.data),this.g.isPublicPage=!1,this.$router.push(`/wallet/${this.g.user.wallets[0].id}`)}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}},createWallet(){LNbits.api.createAccount(this.walletName).then(e=>{this.$router.push(`/wallet/${e.data.id}`)})},processing(){Quasar.Notify.create({timeout:0,message:"Processing...",icon:null})}},created(){if(this.g.isUserAuthorized)return this.refreshAuthUser();const e=new URLSearchParams(window.location.search);this.reset_key=e.get("reset_key"),this.reset_key&&(this.authAction="reset"),e.has("lightning")&&(this.lnurl=e.get("lightning"))}},window.PageExtensionBuilder={template:"#page-extension-builder",data:()=>({step:1,previewStepNames:{2:"settings",3:"owner_data",4:"client_data",5:"public_page"},extensionDataCleanString:"",extensionData:{id:"",name:"",stub_version:"",short_description:"",description:"",public_page:{has_public_page:!0,owner_data_fields:{name:"",description:""},client_data_fields:{public_inputs:[]},action_fields:{generate_action:!0,generate_payment_logic:!1,wallet_id:"",currency:"",amount:"",paid_flag:""}},preview_action:{is_preview_mode:!1,is_settings_preview:!1,is_owner_data_preview:!1,is_client_data_preview:!1,is_public_page_preview:!1},settings_data:{name:"Settings",enabled:!0,type:"user",fields:[]},owner_data:{name:"OwnerData",fields:[]},client_data:{enabled:!0,name:"ClientData",fields:[]}},sampleField:{name:"name",type:"str",label:"Name",hint:"",optional:!0,editable:!0,searchable:!0,sortable:!0},settingsTypes:[{label:"User Settings",value:"user"},{label:"Admin Settings",value:"admin"}],amountSource:[{label:"Client Data",value:"client_data"},{label:"Owner Data",value:"owner_data"}],extensionStubVersions:[]}),watch:{"extensionData.public_page.action_fields.amount_source":function(e,t){t&&e!==t&&(this.extensionData.public_page.action_fields.amount="")}},computed:{paymentActionAmountFields(){const e=this.extensionData.public_page.action_fields.amount_source;return e?"owner_data"===e?[""].concat(this.extensionData.owner_data.fields.filter(e=>"int"===e.type||"float"===e.type).map(e=>e.name)):"client_data"===e?[""].concat(this.extensionData.client_data.fields.filter(e=>"int"===e.type||"float"===e.type).map(e=>e.name)):void 0:[""]}},methods:{saveState(){this.$q.localStorage.set("lnbits.extension.builder.data",JSON.stringify(this.extensionData)),this.$q.localStorage.set("lnbits.extension.builder.step",this.step)},nextStep(){this.saveState(),this.$refs.stepper.next(),this.refreshPreview()},previousStep(){this.saveState(),this.$refs.stepper.previous(),this.refreshPreview()},onStepChange(){this.saveState(),this.refreshPreview()},clearAllData(){LNbits.utils.confirmDialog("Are you sure you want to clear all data? This action cannot be undone.").onOk(()=>{this.extensionData=JSON.parse(this.extensionDataCleanString),this.$q.localStorage.remove("lnbits.extension.builder.data"),this.$refs.stepper.set(1)})},exportJsonData(){!0!==Quasar.exportFile(`${this.extensionData.id||"data-export"}.json`,JSON.stringify(this.extensionData,null,2),"text/json")?Quasar.Notify.create({message:"Browser denied file download...",color:"negative",icon:null}):Quasar.Notify.create({message:"File downloaded!",color:"positive",icon:"file_download"})},onJsonDataInput(e){const t=e.target.files[0],s=new FileReader;s.onload=e=>{this.extensionData={...this.extensionData,...JSON.parse(e.target.result)},this.$refs.extensionDataInput.value=null,Quasar.Notify.create({message:"File loaded!",color:"positive",icon:"file_upload"})},s.readAsText(t)},async buildExtension(){try{const e={responseType:"blob"},t=await LNbits.api.request("POST","/api/v1/extension/builder/zip",null,this.extensionData,e),s=window.URL.createObjectURL(new Blob([t.data])),a=document.createElement("a");a.href=s,a.download=`${this.extensionData.id||"lnbits-extension"}.zip`,document.body.appendChild(a),a.click(),a.remove(),window.URL.revokeObjectURL(s)}catch(e){LNbits.utils.notifyApiError(e)}},async buildExtensionAndDeploy(){try{const{data:e}=await LNbits.api.request("POST","/api/v1/extension/builder/deploy",null,this.extensionData);Quasar.Notify.create({message:e.message||"Extension deployed!",color:"positive"})}catch(e){LNbits.utils.notifyApiError(e)}},async cleanCacheData(){LNbits.utils.confirmDialog("Are you sure you want to clean the cache data? This action cannot be undone.","Clean Cache Data").onOk(async()=>{try{const{data:e}=await LNbits.api.request("DELETE","/api/v1/extension/builder",null,{});Quasar.Notify.create({message:e.message||"Cache data cleaned!",color:"positive"})}catch(e){LNbits.utils.notifyApiError(e)}})},async previewExtension(e){this.saveState();try{await LNbits.api.request("POST","/api/v1/extension/builder/preview",null,{...this.extensionData,preview_action:{is_preview_mode:!!e,is_settings_preview:"settings"===e,is_owner_data_preview:"owner_data"===e,is_client_data_preview:"client_data"===e,is_public_page_preview:"public_page"===e}}),this.refreshIframe(e)}catch(e){LNbits.utils.notifyApiError(e)}},async refreshPreview(){setTimeout(()=>{const e=this.previewStepNames[`${this.step}`]||"";e&&this.previewExtension(e)},100)},async getStubExtensionReleases(){try{const e="extension_builder_stub",{data:t}=await LNbits.api.request("GET",`/api/v1/extension/${e}/releases`);this.extensionStubVersions=t;const s=t.filter(e=>e.is_version_compatible);this.extensionData.stub_version=s[0]?s[0].version:""}catch(e){LNbits.utils.notifyApiError(e)}},refreshIframe(e=""){const t=this.$refs[`iframeStep${this.step}`];if(!t)return void console.warn("Extension Builder Preview iframe not loaded yet.");t.onload=()=>{const e=t.contentDocument||t.contentWindow.document;e.body.style.transform="scale(0.8)",e.body.style.transformOrigin="center top"};let s="Page"+this.extensionData.id.toLowerCase().split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("");"public_page"===e&&(s+="Public"),t.src=`/extensions/builder/preview?ext_id=${this.extensionData.id}&page=${e}&component=${s}`},initBasicData(){this.extensionData.owner_data.fields=[JSON.parse(JSON.stringify(this.sampleField))],this.extensionData.client_data.fields=[JSON.parse(JSON.stringify(this.sampleField))],this.extensionData.settings_data.fields=[JSON.parse(JSON.stringify(this.sampleField))],this.extensionDataCleanString=JSON.stringify(this.extensionData)}},created(){this.initBasicData();const e=this.$q.localStorage.getItem("lnbits.extension.builder.data");e&&(this.extensionData={...this.extensionData,...JSON.parse(e)});const t=+this.$q.localStorage.getItem("lnbits.extension.builder.step");t&&(this.step=t),this.g.user.admin&&this.getStubExtensionReleases(),setTimeout(()=>{this.refreshIframe()},1e3)}},window.PageExtensionBuilder={template:"#page-extension-builder",data:()=>({step:1,previewStepNames:{2:"settings",3:"owner_data",4:"client_data",5:"public_page"},extensionDataCleanString:"",extensionData:{id:"",name:"",stub_version:"",short_description:"",description:"",public_page:{has_public_page:!0,owner_data_fields:{name:"",description:""},client_data_fields:{public_inputs:[]},action_fields:{generate_action:!0,generate_payment_logic:!1,wallet_id:"",currency:"",amount:"",paid_flag:""}},preview_action:{is_preview_mode:!1,is_settings_preview:!1,is_owner_data_preview:!1,is_client_data_preview:!1,is_public_page_preview:!1},settings_data:{name:"Settings",enabled:!0,type:"user",fields:[]},owner_data:{name:"OwnerData",fields:[]},client_data:{enabled:!0,name:"ClientData",fields:[]}},sampleField:{name:"name",type:"str",label:"Name",hint:"",optional:!0,editable:!0,searchable:!0,sortable:!0},settingsTypes:[{label:"User Settings",value:"user"},{label:"Admin Settings",value:"admin"}],amountSource:[{label:"Client Data",value:"client_data"},{label:"Owner Data",value:"owner_data"}],extensionStubVersions:[]}),watch:{"extensionData.public_page.action_fields.amount_source":function(e,t){t&&e!==t&&(this.extensionData.public_page.action_fields.amount="")}},computed:{paymentActionAmountFields(){const e=this.extensionData.public_page.action_fields.amount_source;return e?"owner_data"===e?[""].concat(this.extensionData.owner_data.fields.filter(e=>"int"===e.type||"float"===e.type).map(e=>e.name)):"client_data"===e?[""].concat(this.extensionData.client_data.fields.filter(e=>"int"===e.type||"float"===e.type).map(e=>e.name)):void 0:[""]}},methods:{saveState(){this.$q.localStorage.set("lnbits.extension.builder.data",JSON.stringify(this.extensionData)),this.$q.localStorage.set("lnbits.extension.builder.step",this.step)},nextStep(){this.saveState(),this.$refs.stepper.next(),this.refreshPreview()},previousStep(){this.saveState(),this.$refs.stepper.previous(),this.refreshPreview()},onStepChange(){this.saveState(),this.refreshPreview()},clearAllData(){LNbits.utils.confirmDialog("Are you sure you want to clear all data? This action cannot be undone.").onOk(()=>{this.extensionData=JSON.parse(this.extensionDataCleanString),this.$q.localStorage.remove("lnbits.extension.builder.data"),this.$refs.stepper.set(1)})},exportJsonData(){!0!==Quasar.exportFile(`${this.extensionData.id||"data-export"}.json`,JSON.stringify(this.extensionData,null,2),"text/json")?Quasar.Notify.create({message:"Browser denied file download...",color:"negative",icon:null}):Quasar.Notify.create({message:"File downloaded!",color:"positive",icon:"file_download"})},onJsonDataInput(e){const t=e.target.files[0],s=new FileReader;s.onload=e=>{this.extensionData={...this.extensionData,...JSON.parse(e.target.result)},this.$refs.extensionDataInput.value=null,Quasar.Notify.create({message:"File loaded!",color:"positive",icon:"file_upload"})},s.readAsText(t)},async buildExtension(){try{const e={responseType:"blob"},t=await LNbits.api.request("POST","/api/v1/extension/builder/zip",null,this.extensionData,e),s=window.URL.createObjectURL(new Blob([t.data])),a=document.createElement("a");a.href=s,a.download=`${this.extensionData.id||"lnbits-extension"}.zip`,document.body.appendChild(a),a.click(),a.remove(),window.URL.revokeObjectURL(s)}catch(e){LNbits.utils.notifyApiError(e)}},async buildExtensionAndDeploy(){try{const{data:e}=await LNbits.api.request("POST","/api/v1/extension/builder/deploy",null,this.extensionData);Quasar.Notify.create({message:e.message||"Extension deployed!",color:"positive"})}catch(e){LNbits.utils.notifyApiError(e)}},async cleanCacheData(){LNbits.utils.confirmDialog("Are you sure you want to clean the cache data? This action cannot be undone.","Clean Cache Data").onOk(async()=>{try{const{data:e}=await LNbits.api.request("DELETE","/api/v1/extension/builder",null,{});Quasar.Notify.create({message:e.message||"Cache data cleaned!",color:"positive"})}catch(e){LNbits.utils.notifyApiError(e)}})},async previewExtension(e){this.saveState();try{await LNbits.api.request("POST","/api/v1/extension/builder/preview",null,{...this.extensionData,preview_action:{is_preview_mode:!!e,is_settings_preview:"settings"===e,is_owner_data_preview:"owner_data"===e,is_client_data_preview:"client_data"===e,is_public_page_preview:"public_page"===e}}),this.refreshIframe(e)}catch(e){LNbits.utils.notifyApiError(e)}},async refreshPreview(){setTimeout(()=>{const e=this.previewStepNames[`${this.step}`]||"";e&&this.previewExtension(e)},100)},async getStubExtensionReleases(){try{const e="extension_builder_stub",{data:t}=await LNbits.api.request("GET",`/api/v1/extension/${e}/releases`);this.extensionStubVersions=t;const s=t.filter(e=>e.is_version_compatible);this.extensionData.stub_version=s[0]?s[0].version:""}catch(e){LNbits.utils.notifyApiError(e)}},refreshIframe(e=""){const t=this.$refs[`iframeStep${this.step}`];if(!t)return void console.warn("Extension Builder Preview iframe not loaded yet.");t.onload=()=>{const e=t.contentDocument||t.contentWindow.document;e.body.style.transform="scale(0.8)",e.body.style.transformOrigin="center top"};let s="Page"+this.extensionData.id.toLowerCase().split("_").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("");"public_page"===e&&(s+="Public"),t.src=`/extensions/builder/preview?ext_id=${this.extensionData.id}&page=${e}&component=${s}`},initBasicData(){this.extensionData.owner_data.fields=[JSON.parse(JSON.stringify(this.sampleField))],this.extensionData.client_data.fields=[JSON.parse(JSON.stringify(this.sampleField))],this.extensionData.settings_data.fields=[JSON.parse(JSON.stringify(this.sampleField))],this.extensionDataCleanString=JSON.stringify(this.extensionData)}},created(){this.initBasicData();const e=this.$q.localStorage.getItem("lnbits.extension.builder.data");e&&(this.extensionData={...this.extensionData,...JSON.parse(e)});const t=+this.$q.localStorage.getItem("lnbits.extension.builder.step");t&&(this.step=t),this.g.user.admin&&this.getStubExtensionReleases(),setTimeout(()=>{this.refreshIframe()},1e3)}},window.PageExtensionBuilderPreview={template:"#page-extension-builder-preview",mixins:[windowMixin],watch:{name:"reload"},data:()=>({extId:"",pageName:"",componentName:null}),methods:{async reload(){await LNbits.utils.loadTemplate(`/extensions/builder/preview/${this.extId}/template?page_name=${this.pageName}`),await LNbits.utils.loadScript(`/extensions/builder/preview/${this.extId}/component?page_name=${this.pageName}`),this._component=window[this.componentName],console.log("LNbits preview reloaded componentName:",this.componentName,!!this._component),this.$forceUpdate()}},async created(){const e=new URLSearchParams(window.location.search);this.extId=e.get("ext_id")||"",this.pageName=e.get("page")||"",this.componentName=e.get("component")||"",await this.reload()},render(){return this._component?Vue.h(this._component):Vue.h("div","Loading...")}};const EXTENSION_PERMISSION_DEFAULT_MAX_ROWS_PER_SOURCE=1e4,EXTENSION_PERMISSION_MAX_ROWS_PER_SOURCE_LIMIT=1e6,EXTENSION_PERMISSION_MAX_MESSAGES_PER_SECOND_LIMIT=100;window.PageExtensions={template:"#page-extensions",data(){return{extbuilderEnabled:!1,slide:0,fullscreen:!1,autoplay:!0,searchTerm:"",tab:"installed",manageExtensionTab:"releases",filteredExtensions:[],categories:new Set,updatableExtensions:[],showUninstallDialog:!1,showManageExtensionDialog:!1,showExtensionDetailsDialog:!1,showDropDbDialog:!1,showPayToEnableDialog:!1,showUpdateAllDialog:!1,dropDbExtensionId:"",selectedExtension:null,selectedImage:null,selectedExtensionDetails:null,selectedExtensionDetailsDescription:"",selectedExtensionRepos:null,selectedRelease:null,permissionGrant:{show:!1,permissions:[],resolve:null},extensionPermissionMaxRowsPerSourceLimit:1e6,extensionPermissionMaxMessagesPerSecondLimit:100,managedExtensionPermissions:{loading:!1,extensionPermissions:[],userPermissions:{},savingExtensionPermissions:!1,savingKey:"",deletingKey:""},backgroundPaymentDestinationOptions:[{label:"Only transfers to my wallets",value:"own_wallets_only"},{label:"Allow external payments",value:"external_allowed"}],uninstallAndDropDb:!1,maxStars:5,paylinkWebsocket:null,searchToggle:!1,reviewsUrl:null,reviewsDialog:{show:!1,extension:null,loading:!1,submitting:!1,form:{name:"",rating:0,comment:""},error:null},reviews:[],reviewsTable:{loading:!1,columns:[{name:"name",align:"left",label:this.$t("Name"),field:"name",sortable:!0},{name:"comment",align:"left",label:this.$t("Comment"),field:"comment"},{name:"created_at",align:"left",label:this.$t("Date"),field:"created_at"},{name:"rating",align:"right",label:"Rating",field:"rating"}],pagination:{rowsPerPage:5,sortBy:"created_at",descending:!0,page:1}},paymentDialog:{show:!1,invoice:"",hash:""}}},watch:{searchTerm(e){this.filterExtensions(e,this.tab)},tab(e){this.filterExtensions(this.searchTerm,e)}},computed:{managedUserPermissionRows(){const e=[],t=this.managedExtensionPermissions.userPermissions||{};return Object.entries(t).forEach(([t,s])=>{Array.isArray(s)&&s.forEach(s=>{if(!s||"object"!=typeof s)return;const a=String(s.id||""),i=String(s.wallet_id||"");a&&i&&e.push({key:a,permissionId:t,label:this.permissionLabelById(t),grantId:a,walletId:i,walletName:this.walletName(i),grant:s})})}),e}},methods:{filterExtensions(e,t){const s=!["installed","all","featured"].includes(t);var a;this.filteredExtensions=this.extensions.filter(e=>"all"!==t||!e.isInstalled).filter(e=>"installed"!==t||e.isInstalled).filter(e=>"installed"!==t||(!!e.isActive||!!this.g.user.admin)).filter(e=>"featured"!==t||e.isFeatured).filter(e=>!s||(e=>e.categories?.includes(t)??!1)(e)).filter((a=e,function(e){return e.name.toLowerCase().includes(a.toLowerCase())||e.shortDescription?.toLowerCase().includes(a.toLowerCase())})).map(e=>({...e,details_link:e.installedRelease?.details_link||e.latestRelease?.details_link}))},async installExtension(e){this.unsubscribeFromPaylinkWs();const t=await this.resolveExtensionPermissionGrant(e);null!==t&&(this.selectedExtension.inProgress=!0,this.showManageExtensionDialog=!1,e.payment_hash=e.payment_hash||this.getPaylinkHash(e.pay_link),LNbits.api.request("POST","/api/v1/extension",this.g.user.wallets[0].adminkey,{ext_id:this.selectedExtension.id,archive:e.archive,source_repo:e.source_repo,payment_hash:e.payment_hash,version:e.version,permissions:t}).then(t=>{this.selectedExtension.inProgress=!1;const s=this.extensions.find(e=>e.id===this.selectedExtension.id);s.isAvailable=!0,s.isInstalled=!0,s.isWasm=!0===t.data.is_wasm||!0===t.data.isWasm||"wasm"===e.extension_type||!0===s.isWasm,s.icon=t.data.icon||s.icon,s.installedRelease=e,this.toggleExtension(s),s.inProgress=!1,this.selectedExtension=s,this.extensions=this.extensions.concat([]),this.tab="installed"}).catch(e=>{console.warn(e),this.selectedExtension.inProgress=!1,LNbits.utils.notifyApiError(e)}))},async uninstallExtension(){this.showManageExtensionDialog=!1,this.showUninstallDialog=!1,this.selectedExtension.inProgress=!0,LNbits.api.request("DELETE",`/api/v1/extension/${this.selectedExtension.id}`,this.g.user.wallets[0].adminkey).then(e=>{const t=this.extensions.find(e=>e.id===this.selectedExtension.id);t.isAvailable=!1,t.isInstalled=!1,t.inProgress=!1,t.installedRelease=null,this.filteredExtensions=this.filteredExtensions.filter(e=>e.id!==t.id),Quasar.Notify.create({type:"positive",message:"Extension uninstalled!"}),this.uninstallAndDropDb&&this.showDropDb()}).catch(e=>{LNbits.utils.notifyApiError(e),extension.inProgress=!1})},async dropExtensionDb(){const e=this.selectedExtension;this.showManageExtensionDialog=!1,this.showDropDbDialog=!1,this.dropDbExtensionId="",e.inProgress=!0,LNbits.api.request("DELETE",`/api/v1/extension/${e.id}/db`,this.g.user.wallets[0].adminkey).then(t=>{e.installedRelease=null,e.inProgress=!1,e.hasDatabaseTables=!1,Quasar.Notify.create({type:"positive",message:"Extension DB deleted!"})}).catch(t=>{LNbits.utils.notifyApiError(t),e.inProgress=!1})},toggleExtension(e){const t=e.isActive?"activate":"deactivate";LNbits.api.request("PUT",`/api/v1/extension/${e.id}/${t}`,this.g.user.wallets[0].adminkey).then(s=>{Quasar.Notify.create({timeout:2e3,type:"positive",message:`Extension '${e.id}' ${t}d!`})}).catch(t=>{LNbits.utils.notifyApiError(t),e.isActive=!1,e.inProgress=!1})},async enableExtensionForUser(e){e.isPaymentRequired?this.showPayToEnable(e):this.enableExtension(e)},async enableExtension(e){LNbits.api.request("PUT",`/api/v1/extension/${e.id}/enable`,this.g.user.wallets[0].adminkey).then(t=>{this.g.user.extensions=this.g.user.extensions.concat([e.id]),Quasar.Notify.create({type:"positive",message:"Extension enabled!"})}).catch(e=>{console.warn(e),LNbits.utils.notifyApiError(e)})},disableExtension(e){LNbits.api.request("PUT",`/api/v1/extension/${e.id}/disable`,this.g.user.wallets[0].adminkey).then(t=>{this.g.user.extensions=this.g.user.extensions.filter(t=>t!==e.id),Quasar.Notify.create({type:"positive",message:"Extension disabled!"})}).catch(e=>{console.warn(error),LNbits.utils.notifyApiError(e)})},showPayToEnable(e){this.selectedExtension=e,this.selectedExtension.payToEnable.paidAmount=e.payToEnable.amount,this.selectedExtension.payToEnable.showQRCode=!1,this.showPayToEnableDialog=!0},updatePayToInstallData(e){LNbits.api.request("PUT",`/api/v1/extension/${e.id}/sell`,this.g.user.wallets[0].adminkey,{required:e.payToEnable.required,amount:e.payToEnable.amount,wallet:e.payToEnable.wallet}).then(e=>{Quasar.Notify.create({type:"positive",message:"Payment info updated!"}),this.showManageExtensionDialog=!1}).catch(t=>{LNbits.utils.notifyApiError(t),e.inProgress=!1})},showUninstall(){this.showManageExtensionDialog=!1,this.showUninstallDialog=!0,this.uninstallAndDropDb=!1},showDropDb(){this.showDropDbDialog=!0},async showManageExtension(e){if(this.selectedExtension=e,this.selectedRelease=null,this.selectedExtensionRepos=null,this.resetManagedExtensionPermissions(),this.manageExtensionTab=this.g.user.admin?"releases":"extension-permissions",this.showManageExtensionDialog=!0,this.canManageExtensionPermissions(e)&&this.loadManagedExtensionPermissions(e),this.g.user.admin)try{const{data:t}=await LNbits.api.request("GET",`/api/v1/extension/${e.id}/releases`);this.selectedExtensionRepos=t.reduce((e,t)=>(e[t.source_repo]=e[t.source_repo]||{releases:[],isInstalled:!1,repo:t.repo},t.inProgress=!1,t.error=null,t.loaded=!1,t.isInstalled=this.isInstalledVersion(this.selectedExtension,t),t.isInstalled&&(e[t.source_repo].isInstalled=!0),t.pay_link&&(t.requiresPayment=!0,t.paidAmount=t.cost_sats,t.payment_hash=this.getPaylinkHash(t.pay_link)),e[t.source_repo].releases.push(t),e),{})}catch(t){LNbits.utils.notifyApiError(t),e.inProgress=!1}},canShowManageExtensionButton(e){return this.g.user.admin||!0===e?.isWasm&&!0===e?.isInstalled},canManageExtensionPermissions(e=this.selectedExtension){return!0===e?.isWasm&&!0===e?.isInstalled},canShowAdminManageTabs(){return!0===this.g.user.admin},resetManagedExtensionPermissions(){this.managedExtensionPermissions={loading:!1,extensionPermissions:[],userPermissions:{},savingExtensionPermissions:!1,savingKey:"",deletingKey:""}},async loadManagedExtensionPermissions(e=this.selectedExtension){if(this.canManageExtensionPermissions(e)){this.managedExtensionPermissions.loading=!0;try{const{data:t}=await LNbits.api.request("GET",`/api/v1/extension/${e.id}/permissions`);this.managedExtensionPermissions.extensionPermissions=this.cloneEditableExtensionPermissions(t.extension_permissions||[]),this.managedExtensionPermissions.userPermissions=this.cloneUserPermissions(t.user_permissions||{})}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}finally{this.managedExtensionPermissions.loading=!1}}},cloneEditableExtensionPermissions(e){return(e||[]).filter(e=>e&&"object"==typeof e).map(e=>({...e,policies:Array.isArray(e.policies)?e.policies.map(t=>this.cloneEditablePermissionPolicy(e.id,t)):e.policies}))},cloneEditablePermissionPolicy(e,t){if(!t||"object"!=typeof t||Array.isArray(t))return t;const s=Object.entries(t).reduce((e,[t,s])=>({...e,[t]:Array.isArray(s)?s.slice():s}),{});return"ext.storage.append_public"===e&&(s.max_rows_per_source=this.maxRowsPerSourceValue(s.max_rows_per_source,1e4)),"websocket.publish"===e&&(s.max_messages_per_second=Number(s.max_messages_per_second)),s},maxRowsPerSourceValue(e,t){const s=Number(e);return!Number.isInteger(s)||s<=0?t:Math.min(s,1e6)},extensionPermissionLimitError(e){const t=(e||[]).find(e=>"ext.storage.append_public"===e?.id);if(!t||!Array.isArray(t.policies))return this.websocketPublishLimitError(e);for(const e of t.policies){if(!e||"object"!=typeof e)continue;const t=Number(e.max_rows_per_source);if(!Number.isInteger(t)||t<=0)return"Max rows per source must be a positive integer.";if(t>1e6)return"Max rows per source cannot exceed 1000000."}return this.websocketPublishLimitError(e)},websocketPublishLimitError(e){const t=(e||[]).find(e=>"websocket.publish"===e?.id);if(!t)return"";if(!Array.isArray(t.policies)||1!==t.policies.length)return"Websocket publish requires a max messages per second policy.";const s=t.policies[0];if(!s||"object"!=typeof s)return"Websocket publish requires a max messages per second policy.";const a=Number(s.max_messages_per_second);return!Number.isInteger(a)||a<=0?"Max messages per second must be a positive integer.":a>100?"Max messages per second cannot exceed 100.":""},validateExtensionPermissionLimits(e){const t=this.extensionPermissionLimitError(e);return!t||(Quasar.Notify.create({type:"negative",message:t}),!1)},extensionPermissionsHaveEditableLimits:e=>(e||[]).some(e=>"ext.storage.append_public"===e?.id&&Array.isArray(e.policies)&&e.policies.length>0||"websocket.publish"===e?.id),async saveManagedExtensionPermissions(){const e=this.managedExtensionPermissions.extensionPermissions;if(this.validateExtensionPermissionLimits(e)){this.managedExtensionPermissions.savingExtensionPermissions=!0;try{const{data:t}=await LNbits.api.request("PUT",`/api/v1/extension/${this.selectedExtension.id}/permissions`,this.g.user.wallets[0].adminkey,{permissions:this.cloneEditableExtensionPermissions(e)});this.managedExtensionPermissions.extensionPermissions=this.cloneEditableExtensionPermissions(t.extension_permissions||[]),Quasar.Notify.create({type:"positive",message:"Permission updated."})}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}finally{this.managedExtensionPermissions.savingExtensionPermissions=!1}}},cloneUserPermissions(e){const t={};return Object.entries(e||{}).forEach(([e,s])=>{Array.isArray(s)&&(t[e]=s.filter(e=>e&&"object"==typeof e).map(e=>({...e,_original:{...e}})))}),t},async showExtensionDetails(e,t){if(t){this.selectedExtension=this.extensions.find(t=>t.id===e)||this.selectedExtension,this.selectedExtensionDetails=null,this.selectedExtensionDetailsDescription="",this.showExtensionDetailsDialog=!0,this.slide=0,this.fullscreen=!1;try{const{data:s}=await LNbits.api.request("GET",`/api/v1/extension/${e}/details?details_link=${t}`);this.selectedExtensionDetails=s,this.selectedExtensionDetailsDescription=this.extensionDescriptionDocument(s.description_md)}catch(e){console.warn(e)}}},extensionDescriptionDocument(e){const t="string"==typeof e?e:"",s=LNbits.utils.convertMarkdown(t),a=(new DOMParser).parseFromString(s,"text/html");a.body.querySelectorAll("applet, base, embed, form, frame, iframe, link, meta, object, portal, script").forEach(e=>e.remove()),a.body.querySelectorAll("*").forEach(e=>{for(const t of[...e.attributes]){const s=t.name.toLowerCase();(s.startsWith("on")||"srcdoc"===s||"xlink:href"===s)&&e.removeAttribute(t.name)}}),a.body.querySelectorAll("a[href], area[href]").forEach(e=>{try{const t=new URL(e.getAttribute("href"),window.location.origin);if(!["http:","https:"].includes(t.protocol)||t.username||t.password)return void e.removeAttribute("href");e.setAttribute("href",t.href),e.setAttribute("target","_blank"),e.setAttribute("rel","noopener noreferrer")}catch(t){e.removeAttribute("href")}});return`\n \n
\n \n \n \n \n \n \n \n ${a.body.innerHTML}\n \n `},async payAndInstall(e){try{if(null===await this.resolveExtensionPermissionGrant(e))return;this.selectedExtension.inProgress=!0,this.showManageExtensionDialog=!1;const t=await this.requestPaymentForInstall(this.selectedExtension.id,e);this.rememberPaylinkHash(e.pay_link,t.payment_hash);const s=this.g.user.wallets.find(t=>t.id===e.wallet),{data:a}=await LNbits.api.payInvoice(s,t.payment_request);e.payment_hash=a.payment_hash,await this.installExtension(e)}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}finally{this.selectedExtension.inProgress=!1}},async payAndEnable(e){try{const t=await this.requestPaymentForEnable(e.id,e.payToEnable.paidAmount),s=this.g.user.wallets.find(t=>t.id===e.payToEnable.paymentWallet),{data:a}=await LNbits.api.payInvoice(s,t.payment_request);this.enableExtension(e),this.showPayToEnableDialog=!1}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}},async showInstallQRCode(e){if(null!==await this.resolveExtensionPermissionGrant(e)){this.selectedRelease=e;try{const t=await this.requestPaymentForInstall(this.selectedExtension.id,e);this.selectedRelease.paymentRequest=t.payment_request,this.selectedRelease.payment_hash=t.payment_hash,this.selectedRelease=_.clone(this.selectedRelease),this.rememberPaylinkHash(this.selectedRelease.pay_link,this.selectedRelease.payment_hash),this.subscribeToPaylinkWs(this.selectedRelease.pay_link,t.payment_hash)}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}}},async showEnableQRCode(e){try{e.payToEnable.showQRCode=!0,this.selectedExtension=_.clone(e);const t=await this.requestPaymentForEnable(e.id,e.payToEnable.paidAmount);e.payToEnable.paymentRequest=t.payment_request,this.selectedExtension=_.clone(e);const s=new URL(window.location);s.protocol="https:"===s.protocol?"wss":"ws",s.pathname=`/api/v1/ws/${t.payment_hash}`;const a=new WebSocket(s);a.addEventListener("message",async({data:t})=>{!1===JSON.parse(t).pending&&(Quasar.Notify.create({type:"positive",message:"Invoice Paid!"}),this.enableExtension(e),a.close())})}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}},async requestPaymentForInstall(e,t){const{data:s}=await LNbits.api.request("PUT",`/api/v1/extension/${e}/invoice/install`,null,{ext_id:e,archive:t.archive,source_repo:t.source_repo,cost_sats:t.paidAmount,version:t.version});return s},async requestPaymentForEnable(e,t){const{data:s}=await LNbits.api.request("PUT",`/api/v1/extension/${e}/invoice/enable`,null,{amount:t});return s},clearHangingInvoice(e){this.forgetPaylinkHash(e.pay_link),e.payment_hash=null},rememberPaylinkHash(e,t){this.$q.localStorage.set(`lnbits.extensions.paylink.${e}`,t)},getPaylinkHash(e){return this.$q.localStorage.getItem(`lnbits.extensions.paylink.${e}`)},forgetPaylinkHash(e){this.$q.localStorage.remove(`lnbits.extensions.paylink.${e}`)},subscribeToPaylinkWs(e,t){const s=new URL(`${e}/${t}`);s.protocol="https:"===s.protocol?"wss":"ws",this.paylinkWebsocket=new WebSocket(s),this.paylinkWebsocket.addEventListener("message",async({data:e})=>{JSON.parse(e).paid?(Quasar.Notify.create({type:"positive",message:"Invoice Paid!"}),this.installExtension(this.selectedRelease)):Quasar.Notify.create({type:"warning",message:"Invoice tracking lost!"})})},unsubscribeFromPaylinkWs(){try{this.paylinkWebsocket&&this.paylinkWebsocket.close()}catch(e){console.warn(e)}},hasNewVersion(e){if(e.installedRelease&&e.latestRelease)return e.installedRelease.version!==e.latestRelease.version},isInstalledVersion(e,t){if(e.installedRelease)return e.installedRelease.source_repo===t.source_repo&&e.installedRelease.version===t.version},getReleaseIcon:e=>e.is_version_compatible?e.isInstalled?"download_done":"download":"block",getReleaseIconColor:e=>e.is_version_compatible?e.isInstalled?"text-green":"":"text-red",extensionOpenUrl:e=>e.isWasm?`/ext/${e.id}`:`/${e.id}`,permissionLabelById(e){const t=`extension_permission_${String(e).replace(/[^A-Za-z0-9]/g,"_")}`,s=this.$t(t);return s===t?e:s},walletName(e){const t=(this.g.user.wallets||[]).find(t=>t.id===e);return t?t.name||t.id:e},userPermissionRowCaption:e=>`${e.walletName} (${e.walletId.slice(0,8)}...)`,isBackgroundPaymentPermission:e=>"wallet.pay_invoice_background"===e.permissionId,userPermissionGrantPayload(e){return{wallet_id:e.walletId,max_amount:this.positiveInteger(e.grant.max_amount,0),destination_policy:this.backgroundPaymentDestinationPolicy(e.grant.destination_policy)}},positiveInteger(e,t){const s=Number(e);return!Number.isFinite(s)||s<=0?t:Math.floor(s)},backgroundPaymentDestinationPolicy:e=>"external_allowed"===e?"external_allowed":"own_wallets_only",backgroundPaymentGrantIncreased(e,t){const s=e.grant._original||{},a=this.positiveInteger(s.max_amount,0),i=this.backgroundPaymentDestinationPolicy(s.destination_policy);return t.max_amount>a||"own_wallets_only"===i&&"external_allowed"===t.destination_policy},confirmUserPermissionIncrease:()=>new Promise(e=>{let t=!1;const s=s=>{t||(t=!0,e(s))};LNbits.utils.confirmDialog("This increases what the extension can do with this wallet. Continue?").onOk(()=>s(!0)).onCancel(()=>s(!1)).onDismiss(()=>s(!1))}),async saveUserPermissionGrant(e){if(!this.isBackgroundPaymentPermission(e))return;const t=this.userPermissionGrantPayload(e);if(t.max_amount){if(!this.backgroundPaymentGrantIncreased(e,t)||await this.confirmUserPermissionIncrease()){this.managedExtensionPermissions.savingKey=e.key;try{await LNbits.api.request("POST",`/api/v1/extension/${this.selectedExtension.id}/permissions/background-payment`,null,t),Quasar.Notify.create({type:"positive",message:"Permission updated."}),await this.loadManagedExtensionPermissions()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}finally{this.managedExtensionPermissions.savingKey=""}}}else Quasar.Notify.create({type:"negative",message:"Max payment amount must be greater than zero."})},deleteUserPermissionGrant(e){LNbits.utils.confirmDialog("Remove this permission grant?").onOk(async()=>{this.managedExtensionPermissions.deletingKey=e.key;try{const t=encodeURIComponent(e.grantId);await LNbits.api.request("DELETE",`/api/v1/extension/${this.selectedExtension.id}/permissions/user/${t}`),Quasar.Notify.create({type:"positive",message:"Permission removed."}),await this.loadManagedExtensionPermissions()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}finally{this.managedExtensionPermissions.deletingKey=""}})},async getGitHubReleaseDetails(e){if(!e.is_github_release||e.loaded)return;const[t,s]=e.source_repo.split("/");e.inProgress=!0;try{const{data:a}=await LNbits.api.request("GET",`/api/v1/extension/release/${t}/${s}/${e.version}`);e.loaded=!0,e.is_version_compatible=a.is_version_compatible,e.min_lnbits_version=a.min_lnbits_version,e.warning=a.warning,e.extension_type=a.extension_type,e.permissions=a.permissions||[]}catch(t){console.warn(t),e.error=t,LNbits.utils.notifyApiError(t)}finally{e.inProgress=!1}},async resolveExtensionPermissionGrant(e){const t=this.extensionPermissionsForRelease(e);if(!this.releaseRequiresPermissionGrant(e)||!t.length)return[];if(e.grantedPermissions)return e.grantedPermissions;const s=await this.confirmExtensionPermissions(t);return s?(e.grantedPermissions=s,s):null},extensionPermissionsForRelease(e){return e.permissions||this.selectedExtension?.permissions||[]},releaseRequiresPermissionGrant(e){return"wasm"===e.extension_type||!0===this.selectedExtension?.isWasm},confirmExtensionPermissions(e){return new Promise(t=>{this.selectedRelease=null,this.permissionGrant={show:!0,permissions:this.cloneEditableExtensionPermissions(e),resolve:t},this.showManageExtensionDialog=!0})},grantExtensionPermissions(){this.validateExtensionPermissionLimits(this.permissionGrant.permissions)&&this.resolveExtensionPermissionDialog(this.cloneEditableExtensionPermissions(this.permissionGrant.permissions))},cancelExtensionPermissions(){this.resolveExtensionPermissionDialog(null)},onManageExtensionDialogHide(){this.permissionGrant.show&&this.resolveExtensionPermissionDialog(null)},resolveExtensionPermissionDialog(e){const t=this.permissionGrant.resolve;this.permissionGrant={show:!1,permissions:[],resolve:null},this.showManageExtensionDialog=!1,t&&t(e)},permissionGrantHasHighRisk(){return window.LNbitsExtensionPermissions.hasHighRisk({permissions:this.permissionGrant.permissions,extensions:this.extensions,translate:e=>this.$t(e)})},async selectAllUpdatableExtensionss(){this.updatableExtensions.forEach(e=>e.selectedForUpdate=!0)},async updateSelectedExtensions(){let e=0;for(const t of this.updatableExtensions)try{if(!t.selectedForUpdate)continue;if(t.isWasm){Quasar.Notify.create({type:"warning",message:`Skipping ${t.id}; this extension update requires permission approval.`});continue}t.inProgress=!0,await LNbits.api.request("POST","/api/v1/extension",null,{ext_id:t.id,archive:t.latestRelease.archive,source_repo:t.latestRelease.source_repo,payment_hash:t.latestRelease.payment_hash,version:t.latestRelease.version}),e++,t.isAvailable=!0,t.isInstalled=!0,t.isUpgraded=!0,t.inProgress=!1,t.installedRelease=t.latestRelease,t.isActive=!0,this.toggleExtension(t)}catch(e){console.warn(e),Quasar.Notify.create({type:"negative",message:`Failed to update ${t.id}!`})}finally{t.inProgress=!1}Quasar.Notify.create({type:e?"positive":"warning",message:`${e||"No"} extensions updated!`}),this.showUpdateAllDialog=!1},formatAvg(e){const t=Number(e||0);return Math.round(t/2/100*2)/2},async loadReviewStats(){if(this.reviewsUrl)try{const{data:e}=await LNbits.api.request("GET","/api/v1/extension/reviews/tags"),t={};e.forEach(e=>{t[e.tag]=e}),this.extensions.forEach(e=>{e.reviewStats=t[e.id]||null}),this.filterExtensions(this.searchTerm,this.tab)}catch(e){console.warn(e)}else console.info("Extension reviews are not configured")},async openReviews(e){const t=e||(this.selectedExtensionDetails?this.extensions.find(e=>e.id===this.selectedExtensionDetails.id):null);t&&(this.reviewsUrl?(this.reviewsDialog.extension=t,this.selectedExtension=e,this.reviewsDialog.show=!0,await this.getTagReviews()):Quasar.Notify.create({type:"warning",message:this.$t("reviews_url_not_configured")}))},async getTagReviews(e){if(this.reviewsUrl)try{this.reviewsTable.loading=!0;const t=LNbits.utils.prepareFilterQuery(this.reviewsTable,e),{data:s}=await LNbits.api.request("GET",`/api/v1/extension/reviews/${this.selectedExtension.id}?${t}`);this.reviews=s.data,this.reviewsTable.pagination.rowsNumber=s.total}catch(e){LNbits.utils.notifyApiError(e)}finally{this.reviewsTable.loading=!1}else Quasar.Notify.create({type:"warning",message:this.$t("reviews_url_not_configured")})},formatReviewDate(e){if(!e)return"";const t=Number(e);return Number.isNaN(t)?this.utils.formatDate(e):this.utils.formatTimestamp(t)},async submitReview(){if(this.reviewsDialog.extension&&this.reviewsUrl){this.reviewsDialog.submitting=!0;try{const e={tag:this.reviewsDialog.extension.id,name:this.reviewsDialog.form.name,rating:100*this.reviewsDialog.form.rating,comment:this.reviewsDialog.form.comment},{data:t}=await LNbits.api.request("PUT","/api/v1/extension/reviews",null,e);t.payment_request?this.openInvoiceDialog(t.payment_request,t.payment_hash):(Quasar.Notify.create({type:"positive",message:"Review submitted"}),this.resetReviewForm(),await this.getTagReviews(),await this.loadReviewStats())}catch(e){LNbits.utils.notifyApiError(e)}finally{this.reviewsDialog.submitting=!1}}},openInvoiceDialog(e,t){this.paymentDialog.invoice=e,this.paymentDialog.hash=t,this.paymentDialog.show=!0,this.listenForPayment(t)},resetReviewForm(){this.reviewsDialog.form={name:"",rating:0,comment:""},this.paymentDialog={show:!1,invoice:"",hash:""}},listenForPayment(e){try{const t=new URL(this.reviewsUrl);t.protocol="https:"===t.protocol?"wss:":"ws:",t.pathname=`/api/v1/ws/${e}`;const s=new WebSocket(t);s.addEventListener("message",async()=>{Quasar.Notify.create({type:"positive",message:this.$t("reviews_invoice_paid")}),this.paymentDialog.show=!1,this.resetReviewForm(),setTimeout(async()=>{await this.getTagReviews()},1e3),await this.loadReviewStats(),s.close()})}catch(e){console.warn(e)}},async fetchAllExtensions(){try{const{data:e}=await LNbits.api.request("GET","/api/v1/extension/all");return e.forEach(e=>{e.categories?.forEach(e=>this.categories.add(e))}),e}catch(e){return console.warn(e),LNbits.utils.notifyApiError(e),[]}}},async created(){this.extensions=await this.fetchAllExtensions(),this.extbuilderEnabled=this.g.user.admin||this.g.settings.extBuilder,this.reviewsUrl=this.g.settings.extensionsReviewsUrl,0===this.g.user.extensions.length&&(this.tab="all");const e=window.location.hash.replace("#",""),t=this.extensions.find(t=>t.id===e);t&&(this.searchTerm=t.id,t.isInstalled&&(this.tab="installed")),this.updatableExtensions=this.extensions.filter(e=>this.hasNewVersion(e)),await this.loadReviewStats(),this.filterExtensions(this.searchTerm,this.tab)}},window.PageFirstInstall={template:"#page-first-install",data:()=>({loginData:{isPwd:!0,isPwdRepeat:!0,username:"",password:"",passwordRepeat:"",firstInstallToken:""}}),computed:{checkPasswordsMatch(){return this.loginData.password!==this.loginData.passwordRepeat}},methods:{setPassword(){LNbits.api.request("PUT","/api/v1/auth/first_install",null,{username:this.loginData.username,password:this.loginData.password,password_repeat:this.loginData.passwordRepeat,first_install_token:this.loginData.firstInstallToken}).then(async()=>{const e=await LNbits.api.getAuthUser();this.g.user=LNbits.map.user(e.data),this.g.isPublicPage=!1,this.$router.push("/admin")}).catch(this.utils.notifyApiError)}},created(){const e=new URLSearchParams(window.location.search);this.loginData.firstInstallToken=e.get("token")||""}},window.PagePayments={template:"#page-payments",data:()=>({payments:[],dailyChartData:[],searchDate:{from:null,to:null},searchData:{wallet_id:null,payment_hash:null,memo:null,internal_memo:null},statusFilters:{success:!0,pending:!0,failed:!0,incoming:!0,outgoing:!0},chartData:{showPaymentStatus:!0,showPaymentTags:!0,showBalance:!0,showWalletsSize:!1,showBalanceInOut:!1,showPaymentCountInOut:!1},searchOptions:{status:[]},paymentsTable:{columns:[{name:"status",align:"left",label:"Status",field:"status",sortable:!1},{name:"created_at",align:"left",label:"Created At",field:"created_at",sortable:!0},{name:"amount",align:"right",label:"Amount",field:"amount",sortable:!0},{name:"amountFiat",align:"right",label:"Fiat",field:"amountFiat",sortable:!1},{name:"fee_sats",align:"left",label:"Fee",field:"fee_sats",sortable:!0},{name:"tag",align:"left",label:"Tag",field:"tag",sortable:!1},{name:"memo",align:"left",label:"Memo",field:"memo",sortable:!1,max_length:20},{name:"internal_memo",align:"left",label:"Internal Memo",field:"internal_memo",sortable:!1,max_length:20},{name:"wallet_id",align:"left",label:"Wallet (ID)",field:"wallet_id",sortable:!1},{name:"payment_hash",align:"left",label:"Payment Hash",field:"payment_hash",sortable:!1}],pagination:{sortBy:"created_at",rowsPerPage:25,page:1,descending:!0,rowsNumber:10},search:null,hideEmpty:!0,loading:!1},chartsReady:!1,showDetails:!1,paymentDetails:null,lnbitsBalance:0}),async mounted(){this.chartsReady=!0,await this.$nextTick(),this.initCharts(),await this.fetchPayments()},computed:{},methods:{async fetchPayments(e){const t=Object.entries(this.searchData).reduce((e,[t,s])=>s?(e[t]=s,e):e,{});delete t["time[ge]"],delete t["time[le]"],this.searchDate.from&&(t["time[ge]"]=this.searchDate.from+"T00:00:00"),this.searchDate.to&&(t["time[le]"]=this.searchDate.to+"T23:59:59"),this.paymentsTable.filter=t;try{const t=LNbits.utils.prepareFilterQuery(this.paymentsTable,e),{data:s}=await LNbits.api.request("GET",`/api/v1/payments/all/paginated?${t}`);this.paymentsTable.pagination.rowsNumber=s.total,this.payments=s.data.map(e=>(e.extra&&e.extra.tag&&(e.tag=e.extra.tag),e.timeFrom=moment.utc(e.created_at).local().fromNow(),e.outgoing=e.amount<0,e.amount=new Intl.NumberFormat(this.g.locale).format(e.amount/1e3)+" sats",e.extra?.wallet_fiat_amount&&(e.amountFiat=this.formatCurrency(e.extra.wallet_fiat_amount,e.extra.wallet_fiat_currency)),e.extra?.internal_memo&&(e.internal_memo=e.extra.internal_memo),e.fee_sats=new Intl.NumberFormat(this.g.locale).format(e.fee/1e3)+" sats",e))}catch(e){console.error(e),LNbits.utils.notifyApiError(e)}finally{this.updateCharts(e)}},async searchPaymentsBy(e,t){e&&(this.searchData[e]=t),await this.fetchPayments()},clearDateSeach(){this.searchDate={from:null,to:null},delete this.paymentsTable.filter["time[ge]"],delete this.paymentsTable.filter["time[le]"],this.fetchPayments()},searchByDate(){"string"==typeof this.searchDate&&(this.searchDate={from:this.searchDate,to:this.searchDate}),this.searchDate.from&&(this.paymentsTable.filter["time[ge]"]=this.searchDate.from+"T00:00:00"),this.searchDate.to&&(this.paymentsTable.filter["time[le]"]=this.searchDate.to+"T23:59:59"),this.fetchPayments()},handleFilterChanged(){const{success:e,pending:t,failed:s,incoming:a,outgoing:i}=this.statusFilters;delete this.searchData["status[ne]"],delete this.searchData["status[eq]"],e&&t&&s||(e&&t?this.searchData["status[ne]"]="failed":e&&s?this.searchData["status[ne]"]="pending":s&&t?this.searchData["status[ne]"]="success":e?this.searchData["status[eq]"]="success":t?this.searchData["status[eq]"]="pending":s&&(this.searchData["status[eq]"]="failed")),delete this.searchData["amount[ge]"],delete this.searchData["amount[le]"],a&&i||(a?this.searchData["amount[ge]"]="0":i&&(this.searchData["amount[le]"]="0")),this.fetchPayments()},showDetailsToggle(e){return this.paymentDetails=e,this.showDetails=!this.showDetails},formatCurrency(e,t){try{return LNbits.utils.formatCurrency(e,t)}catch(t){return console.error(t),`${e} ???`}},shortify:(e,t=10)=>(valueLength=(e||"").length,valueLength<=t?e:`${e.substring(0,5)}...${e.substring(valueLength-5,valueLength)}`),async updateCharts(e){let t=LNbits.utils.prepareFilterQuery(this.paymentsTable,e);try{const{data:e}=await LNbits.api.request("GET",`/api/v1/payments/stats/count?${t}&count_by=status`);e.sort((e,t)=>e.field-t.field).reverse(),this.searchOptions.status=e.map(e=>e.field),this.paymentsStatusChart.data.datasets[0].data=e.map(e=>e.total),this.paymentsStatusChart.data.labels=[...this.searchOptions.status],this.paymentsStatusChart.update()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}try{const{data:e}=await LNbits.api.request("GET",`/api/v1/payments/stats/wallets?${t}`),s=e.map(e=>e.balance/e.payments_count),a=Math.min(...s),i=Math.max(...s),n=e=>Math.floor(3+22*(e-a)/(i-a)),o=this.randomColors(20),r=e.map((e,t)=>({data:[{x:e.payments_count,y:e.balance,r:n(Math.max(e.balance/e.payments_count,5))}],label:e.wallet_name,wallet_id:e.wallet_id,backgroundColor:o[t%100],hoverOffset:4}));this.paymentsWalletsChart.data.datasets=r,this.paymentsWalletsChart.update()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}try{const{data:e}=await LNbits.api.request("GET",`/api/v1/payments/stats/count?${t}&count_by=tag`);this.searchOptions.tag=e.map(e=>e.field),this.searchOptions.status.sort(),this.paymentsTagsChart.data.datasets[0].data=e.map(e=>e.total),this.paymentsTagsChart.data.labels=e.map(e=>e.field||"core"),this.paymentsTagsChart.update()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}try{const t=Object.entries(this.searchData).reduce((e,[t,s])=>s?(e[t]=s,e):e,{}),s={...this.paymentsTable,filter:t},a=LNbits.utils.prepareFilterQuery(s,e);let{data:i}=await LNbits.api.request("GET",`/api/v1/payments/stats/daily?${a}`);const n=this.searchDate.from+"T00:00:00",o=this.searchDate.to+"T23:59:59";this.lnbitsBalance=i.length?i[i.length-1].balance:0,i=i.filter(e=>this.searchDate.from&&this.searchDate.to?e.date>=n&&e.date<=o:this.searchDate.from?e.date>=n:!this.searchDate.to||e.date<=o),this.paymentsDailyChart.data.datasets=[{label:"Balance",data:i.map(e=>e.balance),pointStyle:!1,borderWidth:2,tension:.7,fill:1},{label:"Fees",data:i.map(e=>e.fee),pointStyle:!1,borderWidth:1,tension:.4,fill:1}],this.paymentsDailyChart.data.labels=i.map(e=>e.date.substring(0,10)),this.paymentsDailyChart.update(),this.paymentsBalanceInOutChart.data.datasets=[{label:"Incoming Payments Balance",data:i.map(e=>e.balance_in)},{label:"Outgoing Payments Balance",data:i.map(e=>e.balance_out)}],this.paymentsBalanceInOutChart.data.labels=i.map(e=>e.date.substring(0,10)),this.paymentsBalanceInOutChart.update(),this.paymentsCountInOutChart.data.datasets=[{label:"Incoming Payments Count",data:i.map(e=>e.count_in)},{label:"Outgoing Payments Count",data:i.map(e=>-e.count_out)}],this.paymentsCountInOutChart.data.labels=i.map(e=>e.date.substring(0,10)),this.paymentsCountInOutChart.update()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}},async initCharts(){const e=this.$q.localStorage.getItem("lnbits.payments.chartData")||{};this.chartData={...this.chartData,...e},this.chartsReady?(this.paymentsStatusChart=new Chart(this.$refs.paymentsStatusChart.getContext("2d"),{type:"doughnut",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1}},onClick:(e,t,s)=>{if(t[0]){const e=t[0].index;this.searchPaymentsBy("status",s.data.labels[e])}}},data:{datasets:[{label:"",data:[],backgroundColor:["rgb(0, 205, 86)","rgb(64, 72, 78)","rgb(255, 99, 132)"],hoverOffset:4}]}}),this.paymentsWalletsChart=new Chart(this.$refs.paymentsWalletsChart.getContext("2d"),{type:"bubble",options:{responsive:!0,maintainAspectRatio:!1,plugins:{legend:{display:!1},title:{display:!1}},onClick:(e,t,s)=>{if(t[0]){const e=t[0].datasetIndex;this.searchPaymentsBy("wallet_id",s.data.datasets[e].wallet_id)}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(20),hoverOffset:4}]}}),this.paymentsTagsChart=new Chart(this.$refs.paymentsTagsChart.getContext("2d"),{type:"pie",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1},legend:{display:!1,title:{display:!1,text:"Tags"}}},onClick:(e,t,s)=>{if(t[0]){const e=t[0].index;this.searchPaymentsBy("tag",s.data.labels[e])}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(10),hoverOffset:4}]}}),this.paymentsDailyChart=new Chart(this.$refs.paymentsDailyChart.getContext("2d"),{type:"line",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1},legend:{display:!0,title:{display:!1,text:"Tags"}}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(10),hoverOffset:4}]}}),this.paymentsBalanceInOutChart=new Chart(this.$refs.paymentsBalanceInOutChart.getContext("2d"),{type:"bar",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1},legend:{display:!0,title:{display:!1,text:"Tags"}}},scales:{x:{stacked:!0},y:{stacked:!0}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(50),hoverOffset:4}]}}),this.paymentsCountInOutChart=new Chart(this.$refs.paymentsCountInOutChart.getContext("2d"),{type:"bar",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1},legend:{display:!0,title:{display:!1,text:""}}},scales:{x:{stacked:!0},y:{stacked:!0}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(80),hoverOffset:4}]}})):console.warn("Charts are not ready yet. Initialization delayed.")},saveChartsPreferences(){this.$q.localStorage.set("lnbits.payments.chartData",this.chartData)},randomColors(e=1){const t=[];for(let s=1;s<=10;s++)for(let a=1;a<=10;a++)t.push(`rgb(${a*e*33%200}, ${71*(s+a+e)%255}, ${(s+30*e)%255})`);return t}}},window.PageNode={template:"#page-node",config:{globalProperties:{LNbits:LNbits,msg:"hello"}},data(){return{isSuperUser:!1,wallet:{},tab:"dashboard",payments:1e3,info:{},channel_stats:{},channels:{data:[],filter:""},activeBalance:{},ranks:{},peers:{data:[],filter:""},connectPeerDialog:{show:!1,data:{}},setFeeDialog:{show:!1,data:{fee_ppm:0,fee_base_msat:0}},openChannelDialog:{show:!1,data:{}},closeChannelDialog:{show:!1,data:{}},nodeInfoDialog:{show:!1,data:{}},transactionDetailsDialog:{show:!1,data:{}},states:[{label:"Active",value:"active",color:"green"},{label:"Pending",value:"pending",color:"orange"},{label:"Inactive",value:"inactive",color:"grey"},{label:"Closed",value:"closed",color:"red"}],stateFilters:[{label:"Active",value:"active"},{label:"Pending",value:"pending"}],paymentsTable:{data:[],columns:[{name:"pending",label:""},{name:"date",align:"left",label:this.$t("date"),field:"date",sortable:!0},{name:"sat",align:"right",label:this.$t("amount"),field:e=>this.formatMsat(e.amount),sortable:!0},{name:"fee",align:"right",label:this.$t("fee"),field:"fee"},{name:"destination",align:"right",label:"Destination",field:"destination"},{name:"memo",align:"left",label:this.$t("memo"),field:"memo"}],pagination:{rowsPerPage:10,page:1,rowsNumber:10},filter:null},invoiceTable:{data:[],columns:[{name:"pending",label:""},{name:"paid_at",field:"paid_at",align:"left",label:"Paid at",sortable:!0},{name:"expiry",label:this.$t("expiry"),field:"expiry",align:"left",sortable:!0},{name:"amount",label:this.$t("amount"),field:e=>this.formatMsat(e.amount),sortable:!0},{name:"memo",align:"left",label:this.$t("memo"),field:"memo"}],pagination:{rowsPerPage:10,page:1,rowsNumber:10},filter:null}}},created(){this.getInfo(),this.get1MLStats()},watch:{tab(e){"transactions"!==e||this.paymentsTable.data.length?"channels"!==e||this.channels.data.length||(this.getChannels(),this.getPeers()):(this.getPayments(),this.getInvoices())}},computed:{checkChanges(){return!_.isEqual(this.settings,this.formData)},filteredChannels(){return this.stateFilters?this.channels.data.filter(e=>this.stateFilters.find(({value:t})=>t==e.state)):this.channels.data},totalBalance(){return this.filteredChannels.reduce((e,t)=>(e.local_msat+=t.balance.local_msat,e.remote_msat+=t.balance.remote_msat,e.total_msat+=t.balance.total_msat,e),{local_msat:0,remote_msat:0,total_msat:0})}},methods:{formatMsat:e=>LNbits.utils.formatMsat(e),nodeApi(e,t,s){const a=new URLSearchParams(s?.query);return LNbits.api.request(e,`/node/api/v1${t}?${a}`,{},s?.data).catch(e=>{LNbits.utils.notifyApiError(e)})},getChannel(e){return this.nodeApi("GET",`/channels/${e}`).then(e=>{this.setFeeDialog.data.fee_ppm=e.data.fee_ppm,this.setFeeDialog.data.fee_base_msat=e.data.fee_base_msat})},getChannels(){return this.nodeApi("GET","/channels").then(e=>{this.channels.data=e.data})},getInfo(){return this.nodeApi("GET","/info").then(e=>{this.info=e.data,this.channel_stats=e.data.channel_stats}).catch(()=>{this.info={},this.channel_stats={}})},get1MLStats(){return this.nodeApi("GET","/rank").then(e=>{this.ranks=e.data}).catch(()=>{this.ranks={}})},getPayments(e){e&&(this.paymentsTable.pagination=e.pagination);let t=this.paymentsTable.pagination;const s={limit:t.rowsPerPage,offset:(t.page-1)*t.rowsPerPage??0};return this.nodeApi("GET","/payments",{query:s}).then(e=>{this.paymentsTable.data=e.data.data,this.paymentsTable.pagination.rowsNumber=e.data.total})},getInvoices(e){e&&(this.invoiceTable.pagination=e.pagination);let t=this.invoiceTable.pagination;const s={limit:t.rowsPerPage,offset:(t.page-1)*t.rowsPerPage??0};return this.nodeApi("GET","/invoices",{query:s}).then(e=>{this.invoiceTable.data=e.data.data,this.invoiceTable.pagination.rowsNumber=e.data.total})},getPeers(){return this.nodeApi("GET","/peers").then(e=>{this.peers.data=e.data})},connectPeer(){this.nodeApi("POST","/peers",{data:this.connectPeerDialog.data}).then(()=>{this.connectPeerDialog.show=!1,this.getPeers()})},disconnectPeer(e){LNbits.utils.confirmDialog("Do you really wanna disconnect this peer?").onOk(()=>{this.nodeApi("DELETE",`/peers/${e}`).then(e=>{Quasar.Notify.create({message:"Disconnected",icon:null}),this.needsRestart=!0,this.getPeers()})})},setChannelFee(e){this.nodeApi("PUT",`/channels/${e}`,{data:this.setFeeDialog.data}).then(e=>{this.setFeeDialog.show=!1,this.getChannels()}).catch(LNbits.utils.notifyApiError)},openChannel(){this.nodeApi("POST","/channels",{data:this.openChannelDialog.data}).then(e=>{this.openChannelDialog.show=!1,this.getChannels()}).catch(e=>{console.log(e)})},showCloseChannelDialog(e){this.closeChannelDialog.show=!0,this.closeChannelDialog.data={force:!1,short_id:e.short_id,...e.point}},closeChannel(){this.nodeApi("DELETE","/channels",{query:this.closeChannelDialog.data}).then(e=>{this.closeChannelDialog.show=!1,this.getChannels()})},showSetFeeDialog(e){this.setFeeDialog.show=!0,this.setFeeDialog.channel_id=e,this.getChannel(e)},showOpenChannelDialog(e){this.openChannelDialog.show=!0,this.openChannelDialog.data={peer_id:e,funding_amount:0}},showNodeInfoDialog(e){this.nodeInfoDialog.show=!0,this.nodeInfoDialog.data=e},showTransactionDetailsDialog(e){this.transactionDetailsDialog.show=!0,this.transactionDetailsDialog.data=e},shortenNodeId:e=>e?e.substring(0,5)+"..."+e.substring(e.length-5):"..."}},window.PageNodePublic={template:"#page-node-public",data:()=>({enabled:!1,isSuperUser:!1,wallet:{},tab:"dashboard",payments:1e3,info:{},channel_stats:{},channels:[],activeBalance:{},ranks:{},peers:[],connectPeerDialog:{show:!1,data:{}},openChannelDialog:{show:!1,data:{}},closeChannelDialog:{show:!1,data:{}},nodeInfoDialog:{show:!1,data:{}},states:[{label:"Active",value:"active",color:"green"},{label:"Pending",value:"pending",color:"orange"},{label:"Inactive",value:"inactive",color:"grey"},{label:"Closed",value:"closed",color:"red"}]}),created(){this.getInfo(),this.get1MLStats()},methods:{formatMsat:e=>LNbits.utils.formatMsat(e),api:(e,t,s)=>LNbits.api.request(e,"/node/public/api/v1"+t,{},s),getInfo(){this.api("GET","/info",{}).then(e=>{this.info=e.data,this.channel_stats=e.data.channel_stats,this.enabled=!0}).catch(()=>{this.info={},this.channel_stats={}})},get1MLStats(){this.api("GET","/rank",{}).then(e=>{this.ranks=e.data}).catch(()=>{this.ranks={}})}}},window.PageAudit={template:"#page-audit",data:()=>({chartsReady:!1,auditEntries:[],searchData:{user_id:"",ip_address:"",request_type:"",component:"",request_method:"",response_code:"",path:""},searchOptions:{component:[],request_method:[],response_code:[]},auditTable:{columns:[{name:"created_at",align:"center",label:"Date",field:"created_at",sortable:!0},{name:"duration",align:"left",label:"Duration (sec)",field:"duration",sortable:!0},{name:"component",align:"left",label:"Component",field:"component",sortable:!1},{name:"request_method",align:"left",label:"Method",field:"request_method",sortable:!1},{name:"response_code",align:"left",label:"Code",field:"response_code",sortable:!1},{name:"user_id",align:"left",label:"User Id",field:"user_id",sortable:!1},{name:"ip_address",align:"left",label:"IP Address",field:"ip_address",sortable:!1},{name:"path",align:"left",label:"Path",field:"path",sortable:!1}],pagination:{sortBy:"created_at",rowsPerPage:10,page:1,descending:!0,rowsNumber:10},search:null,hideEmpty:!0,loading:!1},auditDetailsDialog:{data:null,show:!1}}),async created(){},async mounted(){this.chartsReady=!0,await this.$nextTick(),this.initCharts(),await this.fetchAudit()},methods:{async fetchAudit(e){try{const t=LNbits.utils.prepareFilterQuery(this.auditTable,e),{data:s}=await LNbits.api.request("GET",`/audit/api/v1?${t}`);this.auditTable.pagination.rowsNumber=s.total,this.auditEntries=s.data,await this.fetchAuditStats(e)}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}finally{this.auditTable.loading=!1}},async fetchAuditStats(e){try{const t=LNbits.utils.prepareFilterQuery(this.auditTable,e),{data:s}=await LNbits.api.request("GET",`/audit/api/v1/stats?${t}`),a=s.request_method.map(e=>e.field);this.searchOptions.request_method=[...new Set(this.searchOptions.request_method.concat(a))],this.requestMethodChart.data.labels=a,this.requestMethodChart.data.datasets[0].data=s.request_method.map(e=>e.total),this.requestMethodChart.update();const i=s.response_code.map(e=>e.field);this.searchOptions.response_code=[...new Set(this.searchOptions.response_code.concat(i))],this.responseCodeChart.data.labels=i,this.responseCodeChart.data.datasets[0].data=s.response_code.map(e=>e.total),this.responseCodeChart.update();const n=s.component.map(e=>e.field);this.searchOptions.component=[...new Set(this.searchOptions.component.concat(n))],this.componentUseChart.data.labels=n,this.componentUseChart.data.datasets[0].data=s.component.map(e=>e.total),this.componentUseChart.update(),this.longDurationChart.data.labels=s.long_duration.map(e=>e.field),this.longDurationChart.data.datasets[0].data=s.long_duration.map(e=>e.total),this.longDurationChart.update()}catch(e){console.warn(e),LNbits.utils.notifyApiError(e)}},async searchAuditBy(e,t){e&&(this.searchData[e]=t),this.auditTable.filter=Object.entries(this.searchData).reduce((e,[t,s])=>s?(e[t]=s,e):e,{}),await this.fetchAudit()},showDetailsDialog(e){const t=JSON.parse(e?.request_details||"");try{t.body&&(t.body=JSON.parse(t.body))}catch(e){}this.auditDetailsDialog.data=JSON.stringify(t,null,4),this.auditDetailsDialog.show=!0},shortify:e=>(valueLength=(e||"").length,valueLength<=10?e:`${e.substring(0,5)}...${e.substring(valueLength-5,valueLength)}`),async initCharts(){this.chartsReady?(this.responseCodeChart=new Chart(this.$refs.responseCodeChart.getContext("2d"),{type:"doughnut",options:{responsive:!0,plugins:{legend:{position:"bottom"},title:{display:!1,text:"HTTP Response Codes"}},onClick:(e,t,s)=>{if(t[0]){const e=t[0].index;this.searchAuditBy("response_code",s.data.labels[e])}}},data:{datasets:[{label:"",data:[20,10],backgroundColor:["rgb(100, 99, 200)","rgb(54, 162, 235)","rgb(255, 205, 86)","rgb(255, 5, 86)","rgb(25, 205, 86)","rgb(255, 205, 250)"]}],labels:[]}}),this.requestMethodChart=new Chart(this.$refs.requestMethodChart.getContext("2d"),{type:"bar",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1}},onClick:(e,t,s)=>{if(t[0]){const e=t[0].index;this.searchAuditBy("request_method",s.data.labels[e])}}},data:{datasets:[{label:"",data:[],backgroundColor:["rgb(255, 99, 132)","rgb(54, 162, 235)","rgb(255, 205, 86)","rgb(255, 5, 86)","rgb(25, 205, 86)","rgb(255, 205, 250)"],hoverOffset:4}]}}),this.componentUseChart=new Chart(this.$refs.componentUseChart.getContext("2d"),{type:"pie",options:{responsive:!0,plugins:{legend:{position:"xxx"},title:{display:!1,text:"Components"}},onClick:(e,t,s)=>{if(t[0]){const e=t[0].index;this.searchAuditBy("component",s.data.labels[e])}}},data:{datasets:[{data:[],backgroundColor:["rgb(255, 99, 132)","rgb(54, 162, 235)","rgb(255, 205, 86)","rgb(255, 5, 86)","rgb(25, 205, 86)","rgb(255, 205, 250)","rgb(100, 205, 250)","rgb(120, 205, 250)","rgb(140, 205, 250)","rgb(160, 205, 250)"],hoverOffset:4}]}}),this.longDurationChart=new Chart(this.$refs.longDurationChart.getContext("2d"),{type:"bar",options:{responsive:!0,indexAxis:"y",maintainAspectRatio:!1,plugins:{legend:{title:{display:!1,text:"Long Duration"}}},onClick:(e,t,s)=>{if(t[0]){const e=t[0].index;this.searchAuditBy("path",s.data.labels[e])}}},data:{datasets:[{label:"",data:[],backgroundColor:["rgb(255, 99, 132)","rgb(54, 162, 235)","rgb(255, 205, 86)","rgb(255, 5, 86)","rgb(25, 205, 86)","rgb(255, 205, 250)","rgb(100, 205, 250)","rgb(120, 205, 250)","rgb(140, 205, 250)","rgb(160, 205, 250)"],hoverOffset:4}]}})):console.warn("Charts are not ready yet. Initialization delayed.")}}},window.PageWallet={template:"#page-wallet",data:()=>({parse:{show:!1,invoice:null,lnurlpay:null,lnurlauth:null,sending:!1,data:{request:"",amount:0,comment:"",internalMemo:null,unit:"sat"},paymentChecker:null,copy:{show:!1},camera:{show:!1,camera:"auto"}},receive:{show:!1,status:"pending",paymentReq:null,paymentHash:null,amountMsat:null,minMax:[0,21e14],lnurl:null,units:[],unit:"sat",fiatProvider:"",data:{amount:null,memo:"",internalMemo:null,payment_hash:null}},update:{name:null,currency:null},hasNfc:!1,nfcReaderAbortController:null,formattedFiatAmount:0,totalBreakdown:{show:!1,loading:!1,rows:[],selectedTypes:["bitcoin","fiat"],selectedTags:[]},paymentFilter:{"status[ne]":"failed"},chartConfig:Quasar.LocalStorage.getItem("lnbits.wallets.chartConfig")||{showPaymentInOutChart:!0,showBalanceChart:!0,showBalanceInOutChart:!0}}),computed:{canPay(){return!!this.parse.invoice&&(this.parse.invoice.expired?(Quasar.Notify.create({message:"Invoice has expired",color:"negative"}),!1):this.parse.invoice.sat<=this.g.wallet.sat)},formattedAmount(){return"sat"==this.receive.unit&&this.g.isSatsDenomination?LNbits.utils.formatMsat(this.receive.amountMsat)+" sat":LNbits.utils.formatCurrency(Number(this.receive.data.amount).toFixed(2),this.g.isSatsDenomination?this.receive.unit:this.g.denomination)},formattedSatAmount(){return LNbits.utils.formatMsat(this.receive.amountMsat)+" sat"},totalBreakdownTags(){const e=this.totalBreakdown.rows.map(e=>e.tag||null);return[...new Set(e)].sort((e,t)=>this.totalBreakdownTagLabel(e).localeCompare(this.totalBreakdownTagLabel(t)))},hasFiatTotalBreakdown(){return this.totalBreakdown.rows.some(e=>e.is_fiat)},selectedTotalBreakdownRows(){return this.totalBreakdown.rows.filter(e=>{const t=e.is_fiat?"fiat":"bitcoin";return this.totalBreakdown.selectedTypes.includes(t)&&this.totalBreakdown.selectedTags.includes(this.totalBreakdownTagKey(e.tag))})},selectedTotalBreakdownMsat(){return this.selectedTotalBreakdownRows.reduce((e,t)=>e+t.total,0)},selectedTotalBreakdownSat(){return Math.round(this.selectedTotalBreakdownMsat/1e3)},selectedTotalBreakdownCount(){return this.selectedTotalBreakdownRows.reduce((e,t)=>e+t.payments_count,0)},formattedTotalBreakdown(){return this.utils.formatBalance(this.selectedTotalBreakdownSat,this.g.denomination)},formattedTotalBreakdownFiat(){if(!this.g.fiatTracking)return null;const e=this.selectedTotalBreakdownSat/1e8*this.g.exchangeRate;return LNbits.utils.formatCurrency(e,this.g.wallet.currency)},primaryTotalBreakdownValue(){return this.g.isFiatPriority&&this.g.fiatTracking&&this.formattedTotalBreakdownFiat||this.formattedTotalBreakdown},secondaryTotalBreakdownValue(){return this.g.fiatTracking?this.g.isFiatPriority?this.formattedTotalBreakdown:this.formattedTotalBreakdownFiat:null}},methods:{showWalletTotalBreakdown(){this.totalBreakdown.show=!0,this.totalBreakdown.rows.length||this.fetchTotalBreakdown()},fetchTotalBreakdown(){this.totalBreakdown.loading=!0,LNbits.api.getPaymentTotalBreakdown(this.g.wallet).then(e=>{this.totalBreakdown.rows=e.data,this.totalBreakdown.selectedTypes=["bitcoin","fiat"],this.totalBreakdown.selectedTags=this.totalBreakdownTags.map(this.totalBreakdownTagKey),this.totalBreakdown.loading=!1}).catch(e=>{this.totalBreakdown.loading=!1,LNbits.utils.notifyApiError(e)})},totalBreakdownTagLabel:e=>e||"No tag",totalBreakdownTagKey:e=>e||"__untagged__",totalBreakdownTagCount(e){return this.totalBreakdown.rows.filter(t=>(t.tag||null)===e).reduce((e,t)=>e+t.payments_count,0)},totalBreakdownTagMsat(e){return this.totalBreakdown.rows.filter(t=>(t.tag||null)===e).reduce((e,t)=>e+t.total,0)},formatTotalBreakdownMsat(e){return this.utils.formatBalance(Math.round(e/1e3),this.g.denomination)},handleSendLnurl(e){this.parse.data.request=e,this.parse.show=!0,this.lnurlScan()},msatoshiFormat:e=>LNbits.utils.formatSat(e/1e3),showReceiveDialog(){this.receive.show=!0,this.receive.status="pending",this.receive.paymentReq=null,this.receive.paymentHash=null,this.receive.data.amount=null,this.receive.data.memo=null,this.receive.data.internalMemo=null,this.receive.data.payment_hash=null,this.receive.units=["sat",...this.g.allowedCurrencies.length>0?this.g.allowedCurrencies:this.g.currencies],this.receive.unit=this.g.isFiatPriority&&this.g.wallet.currency||"sat",this.receive.minMax=[0,21e14],this.receive.lnurl=null},onReceiveDialogHide(){this.hasNfc&&this.nfcReaderAbortController.abort()},showParseDialog(){this.parse.show=!0,this.parse.invoice=null,this.parse.lnurlpay=null,this.parse.lnurlauth=null,this.parse.copy.show=window.isSecureContext&&void 0!==navigator.clipboard?.readText,this.parse.data.request="",this.parse.data.comment="",this.parse.data.internalMemo=null,this.parse.sending=!1,this.parse.data.paymentChecker=null,this.parse.camera.show=!1},closeParseDialog(){setTimeout(()=>{clearInterval(this.parse.paymentChecker)},1e4)},handleBalanceUpdate(e){this.g.wallet.sat=this.g.wallet.sat+e},createInvoice(){this.receive.status="loading",this.g.isSatsDenomination||(this.receive.data.amount=100*this.receive.data.amount),LNbits.api.createInvoice(this.g.wallet,this.receive.data.amount,this.receive.data.memo,this.receive.unit,this.receive.lnurlWithdraw,this.receive.fiatProvider,this.receive.data.internalMemo,this.receive.data.payment_hash).then(e=>{if(this.g.updatePayments=!this.g.updatePayments,this.receive.status="success",this.receive.paymentReq=e.data.bolt11,this.receive.fiatPaymentReq=e.data.extra?.fiat_payment_request,this.receive.amountMsat=e.data.amount,this.receive.paymentHash=e.data.payment_hash,this.receive.lnurl||this.readNfcTag(),this.receive.lnurl&&null!==e.data.extra?.lnurl_response){!1===e.data.extra.lnurl_response&&(e.data.extra.lnurl_response="Unable to connect");const t=this.receive.lnurl.callback.split("/")[2];if("string"==typeof e.data.extra.lnurl_response)return void Quasar.Notify.create({timeout:5e3,type:"warning",message:`${t} lnurl-withdraw call failed.`,caption:e.data.extra.lnurl_response});!0===e.data.extra.lnurl_response&&Quasar.Notify.create({timeout:3e3,message:`Invoice sent to ${t}!`,spinner:!0})}}).catch(e=>{LNbits.utils.notifyApiError(e),this.receive.status="pending"})},lnurlScan(){LNbits.api.request("POST","/api/v1/lnurlscan",this.g.wallet.adminkey,{lnurl:this.parse.data.request}).then(e=>{const t=e.data;if("ERROR"!==t.status){if("payRequest"===t.tag)this.parse.lnurlpay=Object.freeze(t),this.parse.data.amount=t.minSendable/1e3,this.receive.units=["sats",...this.g.allowedCurrencies.length>0?this.g.allowedCurrencies:this.g.currencies];else if("login"===t.tag)this.parse.lnurlauth=Object.freeze(t);else if("withdrawRequest"===t.tag){this.parse.show=!1,this.receive.show=!0,this.receive.lnurlWithdraw=Object.freeze(t),this.receive.status="pending",this.receive.paymentReq=null,this.receive.paymentHash=null,this.receive.data.amount=t.maxWithdrawable/1e3,this.receive.data.memo=t.defaultDescription,this.receive.minMax=[t.minWithdrawable/1e3,t.maxWithdrawable/1e3];const e=t.callback.split("/")[2];this.receive.lnurl={domain:e,callback:t.callback,fixed:t.fixed}}}else Quasar.Notify.create({timeout:5e3,type:"warning",message:"lnurl scan failed.",caption:t.reason})}).catch(e=>{LNbits.utils.notifyApiError(e)})},decodeQR(e){this.parse.data.request=e,this.decodeRequest(),this.parse.camera.show=!1},isLnurl:e=>e.toLowerCase().startsWith("lnurl1")||e.startsWith("lnurlp://")||e.startsWith("lnurlw://")||e.startsWith("lnurlauth://")||e.match(/[\w.+-~_]+@[\w.+-~_]/),decodeRequest(){this.parse.show=!0,this.parse.data.request=this.parse.data.request.trim();const e=this.parse.data.request.toLowerCase();if(e.startsWith("lightning:")?this.parse.data.request=this.parse.data.request.slice(10):e.startsWith("lnurl:")?this.parse.data.request=this.parse.data.request.slice(6):e.includes("lightning=lnurl1")&&(this.parse.data.request=this.parse.data.request.split("lightning=")[1].split("&")[0]),this.isLnurl(this.parse.data.request))return void this.lnurlScan();let t;this.parse.data.request.toLowerCase().includes("lightning")&&(this.parse.data.request=this.parse.data.request.split("lightning=")[1],this.parse.data.request.includes("&")&&(this.parse.data.request=this.parse.data.request.split("&")[0]));try{t=decode(this.parse.data.request)}catch(e){return Quasar.Notify.create({timeout:3e3,type:"warning",message:e+".",caption:"400 BAD REQUEST"}),void(this.parse.show=!1)}let s={msat:t.human_readable_part.amount,sat:t.human_readable_part.amount/1e3,fsat:LNbits.utils.formatSat(t.human_readable_part.amount/1e3),bolt11:this.parse.data.request};_.each(t.data.tags,e=>{if(_.isObject(e)&&_.has(e,"description"))if("payment_hash"===e.description)s.hash=e.value;else if("description"===e.description)s.description=e.value;else if("expiry"===e.description){const a=new Date(1e3*(t.data.time_stamp+e.value)),i=new Date(1e3*t.data.time_stamp);s.expireDate=Quasar.date.formatDate(a,"YYYY-MM-DDTHH:mm:ss.SSSZ"),s.createdDate=Quasar.date.formatDate(i,"YYYY-MM-DDTHH:mm:ss.SSSZ"),s.expireDateFrom=moment.utc(a).local().fromNow(),s.createdDateFrom=moment.utc(i).local().fromNow(),s.expired=!1}}),this.g.wallet.currency&&(s.fiatAmount=LNbits.utils.formatCurrency((s.sat/1e8*this.g.exchangeRate).toFixed(2),this.g.wallet.currency)),this.parse.invoice=Object.freeze(s)},payInvoice(){if(this.parse.sending)return;this.parse.sending=!0;const e=Quasar.Notify.create({timeout:0,message:this.$t("payment_processing")});LNbits.api.payInvoice(this.g.wallet,this.parse.data.request,this.parse.data.internalMemo).then(t=>{this.parse.sending=!1,e(),this.g.updatePayments=!this.g.updatePayments,this.parse.show=!1,"success"==t.data.status&&Quasar.Notify.create({type:"positive",message:this.$t("payment_successful")}),"pending"==t.data.status&&Quasar.Notify.create({type:"info",message:this.$t("payment_pending")})}).catch(t=>{this.parse.sending=!1,e(),LNbits.utils.notifyApiError(t),this.g.updatePayments=!this.g.updatePayments})},payLnurl(){this.parse.sending||(this.parse.sending=!0,LNbits.api.request("post","/api/v1/payments/lnurl",this.g.wallet.adminkey,{res:this.parse.lnurlpay,lnurl:this.parse.data.request,unit:this.parse.data.unit,amount:1e3*this.parse.data.amount,comment:this.parse.data.comment,internalMemo:this.parse.data.internalMemo}).then(e=>{if(this.parse.sending=!1,this.parse.show=!1,e.data.extra.success_action){const t=JSON.parse(e.data.extra.success_action);switch(t.tag){case"url":Quasar.Notify.create({message:t.url,caption:t.description,html:!1,type:"positive",timeout:0,closeBtn:!0,actions:[{label:"Open link",color:"white",handler:()=>this.utils.openUrlInNewTab(t.url)}]});break;case"message":Quasar.Notify.create({message:t.message,type:"positive",timeout:0,closeBtn:!0});break;case"aes":this.utils.decryptLnurlPayAES(t,e.data.preimage).then(e=>{Quasar.Notify.create({message:e,caption:t.description,html:!1,type:"positive",timeout:0,closeBtn:!0})}).catch(e=>{Quasar.Notify.create({message:t.description||"Payment successful.",caption:"Could not decrypt success action.",html:!1,type:"warning",timeout:0,closeBtn:!0})})}}}).catch(e=>{this.parse.sending=!1,LNbits.utils.notifyApiError(e)}))},authLnurl(){const e=Quasar.Notify.create({timeout:10,message:"Performing authentication..."});LNbits.api.request("post","/api/v1/lnurlauth",wallet.adminkey,this.parse.lnurlauth).then(t=>{e(),Quasar.Notify.create({message:"Authentication successful.",type:"positive",timeout:3500}),this.parse.show=!1}).catch(e=>{e.response.data.reason?Quasar.Notify.create({message:`Authentication failed. ${this.parse.lnurlauth.callback} says:`,caption:e.response.data.reason,type:"warning",timeout:5e3}):LNbits.utils.notifyApiError(e)})},updateWallet(e){LNbits.api.request("PATCH","/api/v1/wallet",this.g.wallet.adminkey,e).then(e=>{this.g.wallet={...this.g.wallet,...e.data};const t=this.g.user.wallets.findIndex(t=>t.id===e.data.id);-1!==t&&(this.g.user.wallets[t]={...this.g.user.wallets[t],...e.data}),Quasar.Notify.create({message:"Wallet updated.",type:"positive",timeout:3500})}).catch(e=>{LNbits.utils.notifyApiError(e)})},pasteToTextArea(){this.$refs.textArea.focus(),navigator.clipboard.readText().then(e=>{this.parse.data.request=e.trim()})},readNfcTag(){try{if("undefined"==typeof NDEFReader)return void console.debug("NFC not supported on this device or browser.");const e=new NDEFReader;this.nfcReaderAbortController=new AbortController,this.nfcReaderAbortController.signal.onabort=e=>{console.debug("All NFC Read operations have been aborted.")},this.hasNfc=!0;const t=Quasar.Notify.create({message:"Tap your NFC tag to pay this invoice with LNURLw."});return e.scan({signal:this.nfcReaderAbortController.signal}).then(()=>{e.onreadingerror=()=>{Quasar.Notify.create({type:"negative",message:"There was an error reading this NFC tag."})},e.onreading=({message:e})=>{const s=new TextDecoder("utf-8"),a=e.records.find(e=>-1!==s.decode(e.data).toUpperCase().indexOf("LNURLW"));if(a){t(),Quasar.Notify.create({type:"positive",message:"NFC tag read successfully."});const e=s.decode(a.data);this.payInvoiceWithNfc(e)}else Quasar.Notify.create({type:"warning",message:"NFC tag does not have LNURLw record."})}})}catch(e){Quasar.Notify.create({type:"negative",message:e?e.toString():"An unexpected error has occurred."})}},payInvoiceWithNfc(e){const t=Quasar.Notify.create({timeout:0,spinner:!0,message:this.$t("payment_processing")});LNbits.api.request("POST",`/api/v1/payments/${this.receive.paymentReq}/pay-with-nfc`,this.g.wallet.adminkey,{lnurl_w:e}).then(e=>{t(),e.data.success?Quasar.Notify.create({type:"positive",message:"Payment successful"}):Quasar.Notify.create({type:"negative",message:e.data.detail||"Payment failed"})}).catch(e=>{t(),LNbits.utils.notifyApiError(e)})}},created(){const e=new URLSearchParams(window.location.search);(e.has("lightning")||e.has("lnurl"))&&(this.parse.data.request=e.get("lightning")||e.get("lnurl"),this.decodeRequest(),this.parse.show=!0);const t=this.g.user.wallets.find(e=>e.id===this.$route.params.id);t?(this.g.wallet=t,this.g.lastActiveWallet=t.id,this.$q.localStorage.setItem("lnbits.lastActiveWallet",t.id),this.$router.replace(`/wallet/${t.id}`)):(this.g.errorCode=404,this.g.errorMessage="Wallet not found.",this.$router.push("/error"))},watch:{"g.updatePaymentsHash"(){this.receive.show=!1},"g.updatePayments"(){this.parse.show=!1,this.g.wallet.currency&&this.$q.localStorage.getItem("lnbits.exchangeRate."+this.g.wallet.currency)&&(this.g.exchangeRate=this.$q.localStorage.getItem("lnbits.exchangeRate."+this.g.wallet.currency),this.g.fiatBalance=this.g.exchangeRate/1e8*this.g.wallet.sat)},"g.wallet"(){this.g.wallet.currency?(this.g.fiatTracking=!0,this.g.fiatBalance=this.g.exchangeRate/1e8*this.g.wallet.sat):(this.g.fiatBalance=0,this.g.fiatTracking=!1)},"g.isFiatPriority"(){this.receive.unit=this.g.isFiatPriority?this.g.wallet.currency:"sat"},"g.fiatBalance"(){this.formattedFiatAmount=LNbits.utils.formatCurrency(this.g.fiatBalance.toFixed(2),this.g.wallet.currency)},"g.exchangeRate"(){this.g.fiatTracking&&this.g.wallet.currency&&(this.g.fiatBalance=this.g.exchangeRate/1e8*this.g.wallet.sat)}}},window.PageWallets={template:"#page-wallets",data:()=>({user:null,tab:"wallets",wallets:[],addWalletDialog:{show:!1},walletsTable:{columns:[{name:"name",align:"left",label:"Name",field:"name",sortable:!0},{name:"currency",align:"center",label:"Currency",field:"currency",sortable:!0},{name:"updated_at",align:"right",label:"Last Updated",field:"updated_at",sortable:!0}],pagination:{sortBy:"updated_at",rowsPerPage:12,page:1,descending:!0,rowsNumber:10},search:"",hideEmpty:!0,loading:!1}}),watch:{"walletsTable.search":{handler(){const e={};this.walletsTable.search&&(e.search=this.walletsTable.search),this.getUserWallets()}}},methods:{async getUserWallets(e){try{this.walletsTable.loading=!0;const t=LNbits.utils.prepareFilterQuery(this.walletsTable,e),{data:s}=await LNbits.api.request("GET",`/api/v1/wallet/paginated?${t}`,null);this.wallets=s.data,this.walletsTable.pagination.rowsNumber=s.total}catch(e){LNbits.utils.notifyApiError(e)}finally{this.walletsTable.loading=!1}},goToWallet(e){this.$router.push({path:"/wallet",query:{wal:e}})},formattedFiatAmount:(e,t)=>LNbits.utils.formatCurrency(Number(e).toFixed(2),t),formattedSatAmount:e=>LNbits.utils.formatMsat(e)+" sat"},async created(){await this.getUserWallets()}},window.PageUsers={template:"#page-users",data(){return{paymentsWallet:{},cancel:{},users:[],wallets:[],searchData:{user:"",username:"",email:"",pubkey:""},paymentPage:{show:!1},activeWallet:{userId:null,show:!1},activeUser:{data:null,showUserId:!1,show:!1},createWalletDialog:{data:{},show:!1},walletTable:{columns:[{name:"name",align:"left",label:"Name",field:"name"},{name:"id",align:"left",label:"Wallet Id",field:"id"},{name:"currency",align:"left",label:"Currency",field:"currency"},{name:"balance_msat",align:"left",label:"Balance",field:"balance_msat"}],pagination:{sortBy:"name",rowsPerPage:10,page:1,descending:!0,rowsNumber:10},search:null,hideEmpty:!0,loading:!1},usersTable:{columns:[{name:"activated",align:"left",label:this.$t("activated"),field:"activated",sortable:!1},{name:"wallet_id",align:"left",label:"Wallets",field:"wallet_id",sortable:!1},{name:"id",align:"left",label:"User Id",field:"id",sortable:!1},{name:"username",align:"left",label:"Username",field:"username",sortable:!1},{name:"email",align:"left",label:"Email",field:"email",sortable:!1},{name:"pubkey",align:"left",label:"Public Key",field:"pubkey",sortable:!1},{name:"balance_msat",align:"left",label:"Balance",field:"balance_msat",sortable:!1},{name:"transaction_count",align:"left",label:"Payments",field:"transaction_count",sortable:!1},{name:"last_payment",align:"left",label:"Last Payment",field:"last_payment",sortable:!1}],pagination:{sortBy:"created_at",rowsPerPage:10,page:1,descending:!0,rowsNumber:10},sortFields:[{name:"id",label:"User ID"},{name:"username",label:"Username"},{name:"email",label:"Email"},{name:"pubkey",label:"Public Key"},{name:"created_at",label:"Creation Date"},{name:"updated_at",label:"Last Updated"}],search:null,hideEmpty:!0,loading:!1}}},watch:{"usersTable.hideEmpty":function(e,t){this.usersTable.filter=e?{"transaction_count[gt]":0}:{},this.fetchUsers()}},created(){this.fetchUsers()},methods:{formatSat:e=>LNbits.utils.formatSat(Math.floor(e/1e3)),backToUsersPage(){this.activeUser.show=!1,this.paymentPage.show=!1,this.activeWallet.show=!1,this.fetchUsers()},handleBalanceUpdate(){this.fetchWallets(this.activeWallet.userId)},resetPassword(e){return LNbits.api.request("PUT",`/users/api/v1/user/${e}/reset_password`).then(e=>{LNbits.utils.confirmDialog(this.$t("reset_key_generated")+" "+this.$t("reset_key_copy")).onOk(()=>{const t=window.location.origin+"?reset_key="+e.data;this.utils.copyText(t)})}).catch(LNbits.utils.notifyApiError)},sortByColumn(e){this.usersTable.pagination.sortBy===e?this.usersTable.pagination.descending=!this.usersTable.pagination.descending:(this.usersTable.pagination.sortBy=e,this.usersTable.pagination.descending=!1),this.fetchUsers()},createUser(){LNbits.api.request("POST","/users/api/v1/user",null,this.activeUser.data).then(e=>{Quasar.Notify.create({type:"positive",message:"User created!",icon:null}),this.activeUser.setPassword=!0,this.activeUser.data=e.data,this.fetchUsers()}).catch(LNbits.utils.notifyApiError)},updateUser(){LNbits.api.request("PUT",`/users/api/v1/user/${this.activeUser.data.id}`,null,this.activeUser.data).then(()=>{Quasar.Notify.create({type:"positive",message:"User updated!",icon:null}),this.activeUser.data=null,this.activeUser.show=!1,this.fetchUsers()}).catch(LNbits.utils.notifyApiError)},createWallet(){const e=this.activeWallet.userId;e?LNbits.api.request("POST",`/users/api/v1/user/${e}/wallet`,null,this.createWalletDialog.data).then(()=>{this.fetchWallets(e),Quasar.Notify.create({type:"positive",message:"Wallet created!"})}).catch(LNbits.utils.notifyApiError):Quasar.Notify.create({type:"warning",message:"No user selected!",icon:null})},deleteUser(e){LNbits.utils.confirmDialog("Are you sure you want to delete this user?").onOk(()=>{LNbits.api.request("DELETE",`/users/api/v1/user/${e}`).then(()=>{this.fetchUsers(),Quasar.Notify.create({type:"positive",message:"User deleted!",icon:null}),this.activeUser.data=null,this.activeUser.show=!1}).catch(LNbits.utils.notifyApiError)})},undeleteUserWallet(e,t){LNbits.api.request("PUT",`/users/api/v1/user/${e}/wallet/${t}/undelete`).then(()=>{this.fetchWallets(e),Quasar.Notify.create({type:"positive",message:"Undeleted user wallet!",icon:null})}).catch(LNbits.utils.notifyApiError)},deleteUserWallet(e,t,s){const a=s?"Wallet is already deleted, are you sure you want to permanently delete this user wallet?":"Are you sure you want to delete this user wallet?";LNbits.utils.confirmDialog(a).onOk(()=>{LNbits.api.request("DELETE",`/users/api/v1/user/${e}/wallet/${t}`).then(()=>{this.fetchWallets(e),Quasar.Notify.create({type:"positive",message:"User wallet deleted!",icon:null})}).catch(LNbits.utils.notifyApiError)})},deleteAllUserWallets(e){LNbits.utils.confirmDialog(this.$t("confirm_delete_all_wallets")).onOk(()=>{LNbits.api.request("DELETE",`/users/api/v1/user/${e}/wallets`).then(t=>{Quasar.Notify.create({type:"positive",message:t.data.message,icon:null}),this.fetchWallets(e)}).catch(LNbits.utils.notifyApiError)})},copyWalletLink(e){const t=`${window.location.origin}/wallet?usr=${this.activeWallet.userId}&wal=${e}`;this.utils.copyText(t)},fetchUsers(e){this.relaxFilterForFields(["username","email"]);const t=LNbits.utils.prepareFilterQuery(this.usersTable,e);LNbits.api.request("GET",`/users/api/v1/user?${t}`).then(e=>{this.usersTable.loading=!1,this.usersTable.pagination.rowsNumber=e.data.total,this.users=e.data.data}).catch(LNbits.utils.notifyApiError)},fetchWallets(e){return LNbits.api.request("GET",`/users/api/v1/user/${e}/wallet`).then(t=>{this.wallets=t.data,this.activeWallet.userId=e,this.activeWallet.show=!0}).catch(LNbits.utils.notifyApiError)},relaxFilterForFields(e=[]){e.forEach(e=>{const t=this.usersTable?.filter?.[e];t&&this.usersTable.filter[e]&&(this.usersTable.filter[`${e}[like]`]=t,delete this.usersTable.filter[e])})},updateWallet(e){LNbits.api.request("PATCH","/api/v1/wallet",e.adminkey,{name:e.name}).then(()=>{e.editable=!1,Quasar.Notify.create({message:"Wallet name updated.",type:"positive",timeout:3500})}).catch(e=>{LNbits.utils.notifyApiError(e)})},toggleAdmin(e){LNbits.api.request("PUT",`/users/api/v1/user/${e}/admin`).then(()=>{this.fetchUsers(),Quasar.Notify.create({type:"positive",message:"Toggled admin!",icon:null})}).catch(LNbits.utils.notifyApiError)},toggleUserActivated(e){LNbits.api.request("PUT",`/users/api/v1/user/${e}/activate`).then(e=>{this.fetchUsers(),Quasar.Notify.create({type:"positive",message:e.data.message,icon:null})}).catch(LNbits.utils.notifyApiError)},async showAccountPage(e){if(this.activeUser.showPassword=!1,this.activeUser.showUserId=!1,this.activeUser.setPassword=!1,!e)return this.activeUser.data={extra:{}},void(this.activeUser.show=!0);try{const{data:t}=await LNbits.api.request("GET",`/users/api/v1/user/${e}`);this.activeUser.data=t,this.activeUser.show=!0}catch(e){console.warn(e),Quasar.Notify.create({type:"warning",message:"Failed to get user!"}),this.activeUser.show=!1}},async impersonateUser(e){try{await LNbits.api.impersonateUser(e),LNbits.utils.backupLocalStorage("impersonation",!0),this.$q.localStorage.setItem("lnbits.disclaimerShown",!0),window.location="/wallet"}catch(e){console.warn(e),Quasar.Notify.create({type:"warning",message:"Failed to impersonate user!"})}},async showWalletPayments(e){this.activeUser.show=!1,await this.fetchWallets(this.users[0].id),await this.showPayments(e)},showPayments(e){this.paymentsWallet=this.wallets.find(t=>t.id===e),this.paymentPage.show=!0},searchUserBy(e){const t=this.searchData[e];this.usersTable.filter={},t&&(this.usersTable.filter[e]=t),this.fetchUsers()},shortify:e=>(valueLength=(e||"").length,valueLength<=10?e:`${e.substring(0,5)}...${e.substring(valueLength-5,valueLength)}`)}},window.PageAccount={template:"#page-account",data(){return{untouchedUser:null,hasUsername:!1,showUserId:!1,themeOptions:[{name:"bitcoin",color:"deep-orange"},{name:"classic",color:"purple"},{name:"mint",color:"green"},{name:"autumn",color:"brown"},{name:"monochrome",color:"grey"},{name:"salvador",color:"blue-10"},{name:"freedom",color:"pink-13"},{name:"cyber",color:"light-green-9"},{name:"flamingo",color:"pink-3"}],defaultSiteCustomisation:{locale:"en"},reactionOptions:["None","confettiBothSides","confettiFireworks","confettiStars","confettiTop"],borderOptions:["retro-border","hard-border","neon-border","no-border"],tab:"user",credentialsData:{show:!1,oldPassword:null,newPassword:null,newPasswordRepeat:null,username:null,pubkey:null},apiAcl:{showNewAclDialog:!1,showPasswordDialog:!1,showNewTokenDialog:!1,data:[],passwordGuardedFunction:null,newAclName:"",newTokenName:"",password:"",apiToken:null,selectedTokenId:null,columns:[{name:"Name",align:"left",label:this.$t("Name"),field:"Name",sortable:!1},{name:"path",align:"left",label:this.$t("path"),field:"path",sortable:!1},{name:"read",align:"left",label:this.$t("read"),field:"read",sortable:!1},{name:"write",align:"left",label:this.$t("write"),field:"write",sortable:!1}],pagination:{rowsPerPage:100,page:1}},selectedApiAcl:{id:null,name:null,endpoints:[],token_id_list:[],allRead:!1,allWrite:!1},assets:[],assetsTable:{loading:!1,columns:[{name:"name",align:"left",label:this.$t("Name"),field:"name",sortable:!0},{name:"created_at",align:"left",label:this.$t("created_at"),field:"created_at",sortable:!0}],pagination:{rowsPerPage:6,page:1}},assetsUploadToPublic:!1,notifications:{nostr:{identifier:""}},labels:[],labelsDialog:{show:!1,data:{name:"",description:"",color:"#000000"}},labelsTable:{loading:!1,columns:[{name:"actions",align:"left"},{name:"name",align:"left",label:this.$t("Name"),field:"name",sortable:!0},{name:"description",align:"left",label:this.$t("description"),field:"description"},{name:"color",align:"left",label:this.$t("color"),field:"color"}],pagination:{rowsPerPage:6,page:1}}}},watch:{tab(e){this.$router.push(`/account#${e}`)},$route(e){e.hash.length>1&&(this.tab=e.hash.replace("#",""))},"assetsTable.search":{handler(){const e={};this.assetsTable.search&&(e.search=this.assetsTable.search),this.getUserAssets()}}},computed:{isUserTouched(){return!_.isEqual(this.g.user,this.untouchedUser)},selectedApiToken(){return this.selectedApiAcl.token_id_list.find(e=>e.id===this.apiAcl.selectedTokenId)},expiryAt(){return this.selectedApiToken.expires_at?`${this.$t("expiry")}: ${LNbits.utils.formatTimestamp(this.selectedApiToken.expires_at)}`:""},tokenStatus(){if(this.selectedApiToken.expires_at){const e=new Date;let t="",s="positive";return new Date(1e3*this.selectedApiToken.expires_at)