Compare commits
27
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1161fab805 | ||
|
|
dfdce54e57 | ||
|
|
1367480ec6 | ||
|
|
e2d83b516a | ||
|
|
83699289fc | ||
|
|
f04e88d8bf | ||
|
|
564edfc447 | ||
|
|
b98515df14 | ||
|
|
1e0fc84586 | ||
|
|
a1d94834ae | ||
|
|
5de4239f3c | ||
|
|
c404666d7f | ||
|
|
190a466c0a | ||
|
|
d01e3523d8 | ||
|
|
88672501d8 | ||
|
|
ce57d08163 | ||
|
|
52304e0730 | ||
|
|
6664eebf5a | ||
|
|
2a2af81827 | ||
|
|
9b47f6323f | ||
|
|
a61807a257 | ||
|
|
30e0522419 | ||
|
|
8f033a6047 | ||
|
|
a2c817a56b | ||
|
|
555350085e | ||
|
|
fc5061a67f | ||
|
|
c9c68bd8d7 |
@@ -119,6 +119,8 @@ LNBITS_SITE_TAGLINE="Open Source Lightning Payments Platform"
|
|||||||
LNBITS_SITE_DESCRIPTION="The world's most powerful suite of bitcoin tools. Run for yourself, for others, or as part of a stack."
|
LNBITS_SITE_DESCRIPTION="The world's most powerful suite of bitcoin tools. Run for yourself, for others, or as part of a stack."
|
||||||
# Choose from bitcoin, mint, flamingo, freedom, salvador, autumn, monochrome, classic, cyber
|
# Choose from bitcoin, mint, flamingo, freedom, salvador, autumn, monochrome, classic, cyber
|
||||||
LNBITS_THEME_OPTIONS="classic, bitcoin, flamingo, freedom, mint, autumn, monochrome, salvador, cyber"
|
LNBITS_THEME_OPTIONS="classic, bitcoin, flamingo, freedom, mint, autumn, monochrome, salvador, cyber"
|
||||||
|
# Toggle the background styling on burger menus / drawers
|
||||||
|
# LNBITS_DEFAULT_BURGER_MENU_BACKGROUND=true
|
||||||
# LNBITS_CUSTOM_LOGO="https://lnbits.com/assets/images/logo/logo.svg"
|
# LNBITS_CUSTOM_LOGO="https://lnbits.com/assets/images/logo/logo.svg"
|
||||||
|
|
||||||
######################################
|
######################################
|
||||||
|
|||||||
@@ -306,7 +306,7 @@ async def update_payment_checking_id(
|
|||||||
await (conn or db).execute(
|
await (conn or db).execute(
|
||||||
f"""
|
f"""
|
||||||
UPDATE apipayments
|
UPDATE apipayments
|
||||||
SET checking_id = :new_id, updated_at = {db.timestamp_placeholder('now')}
|
SET checking_id = :new_id, updated_at = {db.timestamp_placeholder("now")}
|
||||||
WHERE checking_id = :old_id
|
WHERE checking_id = :old_id
|
||||||
""", # noqa: S608
|
""", # noqa: S608
|
||||||
{
|
{
|
||||||
@@ -321,13 +321,15 @@ async def update_payment(
|
|||||||
payment: Payment,
|
payment: Payment,
|
||||||
new_checking_id: str | None = None,
|
new_checking_id: str | None = None,
|
||||||
conn: Connection | None = None,
|
conn: Connection | None = None,
|
||||||
) -> None:
|
) -> Payment:
|
||||||
payment.updated_at = datetime.now(timezone.utc)
|
payment.updated_at = datetime.now(timezone.utc)
|
||||||
await (conn or db).update(
|
await (conn or db).update(
|
||||||
"apipayments", payment, "WHERE checking_id = :checking_id"
|
"apipayments", payment, "WHERE checking_id = :checking_id"
|
||||||
)
|
)
|
||||||
if new_checking_id and new_checking_id != payment.checking_id:
|
if new_checking_id and new_checking_id != payment.checking_id:
|
||||||
await update_payment_checking_id(payment.checking_id, new_checking_id, conn)
|
await update_payment_checking_id(payment.checking_id, new_checking_id, conn)
|
||||||
|
payment.checking_id = new_checking_id
|
||||||
|
return payment
|
||||||
|
|
||||||
|
|
||||||
async def get_payments_history(
|
async def get_payments_history(
|
||||||
@@ -399,7 +401,6 @@ async def get_payment_count_stats(
|
|||||||
user_id: str | None = None,
|
user_id: str | None = None,
|
||||||
conn: Connection | None = None,
|
conn: Connection | None = None,
|
||||||
) -> list[PaymentCountStat]:
|
) -> list[PaymentCountStat]:
|
||||||
|
|
||||||
if not filters:
|
if not filters:
|
||||||
filters = Filters()
|
filters = Filters()
|
||||||
extra_stmts = []
|
extra_stmts = []
|
||||||
@@ -432,7 +433,6 @@ async def get_daily_stats(
|
|||||||
user_id: str | None = None,
|
user_id: str | None = None,
|
||||||
conn: Connection | None = None,
|
conn: Connection | None = None,
|
||||||
) -> tuple[list[PaymentDailyStats], list[PaymentDailyStats]]:
|
) -> tuple[list[PaymentDailyStats], list[PaymentDailyStats]]:
|
||||||
|
|
||||||
if not filters:
|
if not filters:
|
||||||
filters = Filters()
|
filters = Filters()
|
||||||
|
|
||||||
@@ -482,7 +482,6 @@ async def get_wallets_stats(
|
|||||||
user_id: str | None = None,
|
user_id: str | None = None,
|
||||||
conn: Connection | None = None,
|
conn: Connection | None = None,
|
||||||
) -> list[PaymentWalletStats]:
|
) -> list[PaymentWalletStats]:
|
||||||
|
|
||||||
if not filters:
|
if not filters:
|
||||||
filters = Filters()
|
filters = Filters()
|
||||||
|
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ from .payments import (
|
|||||||
PaymentState,
|
PaymentState,
|
||||||
PaymentWalletStats,
|
PaymentWalletStats,
|
||||||
SettleInvoice,
|
SettleInvoice,
|
||||||
|
UpdatePaymentExtra,
|
||||||
)
|
)
|
||||||
from .tinyurl import TinyURL
|
from .tinyurl import TinyURL
|
||||||
from .users import (
|
from .users import (
|
||||||
@@ -90,6 +91,7 @@ __all__ = [
|
|||||||
"SimpleStatus",
|
"SimpleStatus",
|
||||||
"TinyURL",
|
"TinyURL",
|
||||||
"UpdateBalance",
|
"UpdateBalance",
|
||||||
|
"UpdatePaymentExtra",
|
||||||
"UpdateSuperuserPassword",
|
"UpdateSuperuserPassword",
|
||||||
"UpdateUser",
|
"UpdateUser",
|
||||||
"UpdateUserPassword",
|
"UpdateUserPassword",
|
||||||
|
|||||||
@@ -35,6 +35,11 @@ class PaymentExtra(BaseModel):
|
|||||||
lnurl_response: str | None = None
|
lnurl_response: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class UpdatePaymentExtra(BaseModel):
|
||||||
|
payment_hash: str
|
||||||
|
extra: dict = Field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
class PayInvoice(BaseModel):
|
class PayInvoice(BaseModel):
|
||||||
payment_request: str
|
payment_request: str
|
||||||
description: str | None = None
|
description: str | None = None
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
import base64
|
import base64
|
||||||
import io
|
import io
|
||||||
|
from urllib.parse import quote
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
|
import filetype
|
||||||
from fastapi import UploadFile
|
from fastapi import UploadFile
|
||||||
from loguru import logger
|
from loguru import logger
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
@@ -10,11 +12,48 @@ from lnbits.core.crud.assets import create_asset, get_user_assets_count
|
|||||||
from lnbits.core.models.assets import Asset
|
from lnbits.core.models.assets import Asset
|
||||||
from lnbits.settings import settings
|
from lnbits.settings import settings
|
||||||
|
|
||||||
|
IMAGE_MIME_TYPE_ALIASES = {
|
||||||
|
"heic": "image/heic",
|
||||||
|
"heics": "image/heics",
|
||||||
|
"heif": "image/heif",
|
||||||
|
"image/jpg": "image/jpeg",
|
||||||
|
"jpeg": "image/jpeg",
|
||||||
|
"jpg": "image/jpeg",
|
||||||
|
"png": "image/png",
|
||||||
|
}
|
||||||
|
PIL_IMAGE_FORMAT_MIME_TYPES = {
|
||||||
|
"JPEG": "image/jpeg",
|
||||||
|
"PNG": "image/png",
|
||||||
|
}
|
||||||
|
INLINE_ASSET_MIME_TYPES = {
|
||||||
|
"image/heic",
|
||||||
|
"image/heics",
|
||||||
|
"image/heif",
|
||||||
|
"image/jpeg",
|
||||||
|
"image/png",
|
||||||
|
}
|
||||||
|
ASSET_SECURITY_HEADERS = {
|
||||||
|
"X-Content-Type-Options": "nosniff",
|
||||||
|
"Content-Security-Policy": (
|
||||||
|
"sandbox; default-src 'none'; script-src 'none'; "
|
||||||
|
"object-src 'none'; base-uri 'none'"
|
||||||
|
),
|
||||||
|
}
|
||||||
|
THUMBNAIL_FORMAT_MIME_TYPES = {
|
||||||
|
"jpg": "image/jpeg",
|
||||||
|
"jpeg": "image/jpeg",
|
||||||
|
"png": "image/png",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
async def create_user_asset(user_id: str, file: UploadFile, is_public: bool) -> Asset:
|
async def create_user_asset(user_id: str, file: UploadFile, is_public: bool) -> Asset:
|
||||||
if not file.content_type:
|
if not file.content_type:
|
||||||
raise ValueError("File must have a content type.")
|
raise ValueError("File must have a content type.")
|
||||||
if file.content_type.lower() not in settings.lnbits_assets_allowed_mime_types:
|
|
||||||
|
content_type = normalize_asset_mime_type(file.content_type)
|
||||||
|
filename = file.filename or "unnamed"
|
||||||
|
|
||||||
|
if content_type not in allowed_asset_mime_types():
|
||||||
raise ValueError(f"File type '{file.content_type}' not allowed.")
|
raise ValueError(f"File type '{file.content_type}' not allowed.")
|
||||||
|
|
||||||
if not settings.is_unlimited_assets_user(user_id):
|
if not settings.is_unlimited_assets_user(user_id):
|
||||||
@@ -30,14 +69,26 @@ async def create_user_asset(user_id: str, file: UploadFile, is_public: bool) ->
|
|||||||
f"File limit of {settings.lnbits_max_asset_size_mb}MB exceeded."
|
f"File limit of {settings.lnbits_max_asset_size_mb}MB exceeded."
|
||||||
)
|
)
|
||||||
|
|
||||||
|
stored_mime_type = detect_image_mime_type(contents)
|
||||||
|
if stored_mime_type != content_type:
|
||||||
|
logger.warning(
|
||||||
|
"Image MIME type mismatch: declared={}, detected={}",
|
||||||
|
content_type,
|
||||||
|
stored_mime_type,
|
||||||
|
)
|
||||||
|
raise ValueError(
|
||||||
|
"Image file content does not match declared file type. "
|
||||||
|
f"Declared: '{content_type}', detected: '{stored_mime_type}'."
|
||||||
|
)
|
||||||
|
|
||||||
thumb_buffer = thumbnail_from_bytes(contents)
|
thumb_buffer = thumbnail_from_bytes(contents)
|
||||||
|
|
||||||
asset = Asset(
|
asset = Asset(
|
||||||
id=uuid4().hex,
|
id=uuid4().hex,
|
||||||
user_id=user_id,
|
user_id=user_id,
|
||||||
mime_type=file.content_type,
|
mime_type=stored_mime_type,
|
||||||
is_public=is_public,
|
is_public=is_public,
|
||||||
name=file.filename or "unnamed",
|
name=filename,
|
||||||
size_bytes=len(contents),
|
size_bytes=len(contents),
|
||||||
thumbnail_base64=(
|
thumbnail_base64=(
|
||||||
base64.b64encode(thumb_buffer.getvalue()).decode("utf-8")
|
base64.b64encode(thumb_buffer.getvalue()).decode("utf-8")
|
||||||
@@ -51,6 +102,79 @@ async def create_user_asset(user_id: str, file: UploadFile, is_public: bool) ->
|
|||||||
return asset
|
return asset
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_asset_mime_type(content_type: str) -> str:
|
||||||
|
content_type = content_type.split(";", 1)[0].strip().lower()
|
||||||
|
return IMAGE_MIME_TYPE_ALIASES.get(content_type, content_type)
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_media_type(media_type: str) -> str:
|
||||||
|
return media_type.split(";", 1)[0].strip().lower() or "application/octet-stream"
|
||||||
|
|
||||||
|
|
||||||
|
def thumbnail_media_type() -> str:
|
||||||
|
thumbnail_format = (settings.lnbits_asset_thumbnail_format or "png").strip().lower()
|
||||||
|
return THUMBNAIL_FORMAT_MIME_TYPES.get(thumbnail_format, "application/octet-stream")
|
||||||
|
|
||||||
|
|
||||||
|
def content_disposition(disposition: str, filename: str) -> str:
|
||||||
|
safe_filename = filename or "unnamed"
|
||||||
|
quoted_filename = quote(safe_filename, safe="")
|
||||||
|
if quoted_filename == safe_filename:
|
||||||
|
return f'{disposition}; filename="{safe_filename}"'
|
||||||
|
return f"{disposition}; filename*=utf-8''{quoted_filename}"
|
||||||
|
|
||||||
|
|
||||||
|
def allowed_asset_mime_types() -> set[str]:
|
||||||
|
return {
|
||||||
|
mime_type
|
||||||
|
for mime_type in (
|
||||||
|
normalize_asset_mime_type(mime_type)
|
||||||
|
for mime_type in settings.lnbits_assets_allowed_mime_types
|
||||||
|
)
|
||||||
|
if mime_type.startswith("image/")
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def detect_image_mime_type(contents: bytes) -> str:
|
||||||
|
kind = filetype.guess(contents)
|
||||||
|
mime_type = normalize_asset_mime_type(kind.mime) if kind else None
|
||||||
|
|
||||||
|
if mime_type and mime_type in PIL_IMAGE_FORMAT_MIME_TYPES.values():
|
||||||
|
verify_pil_image(contents, mime_type)
|
||||||
|
return mime_type
|
||||||
|
|
||||||
|
if mime_type and mime_type.startswith("image/"):
|
||||||
|
return mime_type
|
||||||
|
|
||||||
|
try:
|
||||||
|
with Image.open(io.BytesIO(contents)) as image:
|
||||||
|
image.verify()
|
||||||
|
mime_type = PIL_IMAGE_FORMAT_MIME_TYPES.get(image.format or "")
|
||||||
|
except Exception as exc:
|
||||||
|
raise ValueError(
|
||||||
|
"Image file content does not match declared file type."
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
if not mime_type:
|
||||||
|
raise ValueError("Image file content does not match declared file type.")
|
||||||
|
|
||||||
|
return mime_type
|
||||||
|
|
||||||
|
|
||||||
|
def verify_pil_image(contents: bytes, mime_type: str) -> None:
|
||||||
|
try:
|
||||||
|
with Image.open(io.BytesIO(contents)) as image:
|
||||||
|
image.verify()
|
||||||
|
detected_mime_type = PIL_IMAGE_FORMAT_MIME_TYPES.get(image.format or "")
|
||||||
|
except Exception as exc:
|
||||||
|
raise ValueError(
|
||||||
|
"Image file content does not match declared file type."
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
if detected_mime_type != mime_type:
|
||||||
|
raise ValueError("Image file content does not match declared file type.")
|
||||||
|
|
||||||
|
|
||||||
def thumbnail_from_bytes(contents: bytes) -> io.BytesIO | None:
|
def thumbnail_from_bytes(contents: bytes) -> io.BytesIO | None:
|
||||||
try:
|
try:
|
||||||
image = Image.open(io.BytesIO(contents))
|
image = Image.open(io.BytesIO(contents))
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import hashlib
|
import hashlib
|
||||||
import hmac
|
import hmac
|
||||||
import json
|
import json
|
||||||
import math
|
|
||||||
import time
|
import time
|
||||||
from base64 import b64encode
|
from base64 import b64encode
|
||||||
|
|
||||||
@@ -220,35 +219,27 @@ def check_revolut_signature(
|
|||||||
logger.warning("Revolut webhook signing secret is not set.")
|
logger.warning("Revolut webhook signing secret is not set.")
|
||||||
raise ValueError("Revolut webhook cannot be verified.")
|
raise ValueError("Revolut webhook cannot be verified.")
|
||||||
|
|
||||||
timestamp = int(timestamp_header)
|
try:
|
||||||
timestamp_seconds = timestamp / 1000 if timestamp > 9999999999 else timestamp
|
timestamp = int(timestamp_header)
|
||||||
if not math.isfinite(timestamp_seconds):
|
except ValueError as exc:
|
||||||
logger.warning("Invalid Revolut timestamp.")
|
logger.warning("Invalid Revolut timestamp.")
|
||||||
raise ValueError("Invalid Revolut timestamp.")
|
raise ValueError("Invalid Revolut timestamp.") from exc
|
||||||
|
|
||||||
|
timestamp_seconds = timestamp / 1000 if timestamp > 9999999999 else timestamp
|
||||||
|
|
||||||
if abs(time.time() - timestamp_seconds) > tolerance_seconds:
|
if abs(time.time() - timestamp_seconds) > tolerance_seconds:
|
||||||
logger.warning("Timestamp outside tolerance.")
|
logger.warning("Timestamp outside tolerance.")
|
||||||
raise ValueError("Timestamp outside tolerance." f"Timestamp: {timestamp}")
|
raise ValueError("Timestamp outside tolerance." f"Timestamp: {timestamp}")
|
||||||
|
|
||||||
candidates = [
|
signed_payload = b"v1." + timestamp_header.encode() + b"." + payload
|
||||||
b"v1." + timestamp_header.encode() + b"." + payload,
|
digest = hmac.new(
|
||||||
payload,
|
key=secret.encode(), msg=signed_payload, digestmod=hashlib.sha256
|
||||||
f"{timestamp_header}.{payload.decode()}".encode(),
|
).hexdigest()
|
||||||
timestamp_header.encode() + b"." + payload,
|
expected_signature = f"v1={digest}"
|
||||||
]
|
|
||||||
signatures = []
|
|
||||||
for candidate in candidates:
|
|
||||||
digest = hmac.new(
|
|
||||||
key=secret.encode(), msg=candidate, digestmod=hashlib.sha256
|
|
||||||
).digest()
|
|
||||||
signatures.extend(
|
|
||||||
[digest.hex(), f"v1={digest.hex()}", b64encode(digest).decode()]
|
|
||||||
)
|
|
||||||
|
|
||||||
provided_signatures = [sig.strip() for sig in sig_header.split(",") if sig.strip()]
|
provided_signatures = [sig.strip() for sig in sig_header.split(",") if sig.strip()]
|
||||||
if not any(
|
if not any(
|
||||||
hmac.compare_digest(expected, provided)
|
hmac.compare_digest(expected_signature, provided)
|
||||||
for expected in signatures
|
|
||||||
for provided in provided_signatures
|
for provided in provided_signatures
|
||||||
):
|
):
|
||||||
logger.warning("Revolut signature verification failed.")
|
logger.warning("Revolut signature verification failed.")
|
||||||
|
|||||||
@@ -171,15 +171,15 @@ async def create_fiat_invoice(
|
|||||||
|
|
||||||
internal_payment.fiat_provider = fiat_provider_name
|
internal_payment.fiat_provider = fiat_provider_name
|
||||||
internal_payment.extra["fiat_checking_id"] = fiat_invoice.checking_id
|
internal_payment.extra["fiat_checking_id"] = fiat_invoice.checking_id
|
||||||
# todo: move to payent
|
# TODO: move to payment
|
||||||
internal_payment.extra["fiat_payment_request"] = fiat_invoice.payment_request
|
internal_payment.extra["fiat_payment_request"] = fiat_invoice.payment_request
|
||||||
new_checking_id = (
|
new_checking_id = (
|
||||||
f"fiat_{fiat_provider_name}_"
|
f"fiat_{fiat_provider_name}_"
|
||||||
f"{fiat_invoice.checking_id or internal_payment.checking_id}"
|
f"{fiat_invoice.checking_id or internal_payment.checking_id}"
|
||||||
)
|
)
|
||||||
await update_payment(internal_payment, new_checking_id, conn=conn)
|
internal_payment = await update_payment(
|
||||||
internal_payment.checking_id = new_checking_id
|
internal_payment, new_checking_id, conn=conn
|
||||||
|
)
|
||||||
return internal_payment
|
return internal_payment
|
||||||
|
|
||||||
|
|
||||||
@@ -374,7 +374,7 @@ async def update_pending_payment(
|
|||||||
status = await check_payment_status(payment)
|
status = await check_payment_status(payment)
|
||||||
if status.failed:
|
if status.failed:
|
||||||
payment.status = PaymentState.FAILED
|
payment.status = PaymentState.FAILED
|
||||||
await update_payment(payment, conn=conn)
|
payment = await update_payment(payment, conn=conn)
|
||||||
elif status.success:
|
elif status.success:
|
||||||
payment = await update_payment_success_status(payment, status, conn=conn)
|
payment = await update_payment_success_status(payment, status, conn=conn)
|
||||||
return payment
|
return payment
|
||||||
@@ -876,7 +876,7 @@ async def update_payment_success_status(
|
|||||||
payment.status = PaymentState.SUCCESS
|
payment.status = PaymentState.SUCCESS
|
||||||
payment.fee = -(abs(status.fee_msat or 0) + abs(service_fee_msat))
|
payment.fee = -(abs(status.fee_msat or 0) + abs(service_fee_msat))
|
||||||
payment.preimage = payment.preimage or status.preimage
|
payment.preimage = payment.preimage or status.preimage
|
||||||
await update_payment(payment, conn=conn)
|
payment = await update_payment(payment, conn=conn)
|
||||||
return payment
|
return payment
|
||||||
|
|
||||||
|
|
||||||
@@ -1099,8 +1099,9 @@ async def update_invoice_callback(checking_id: str) -> Payment | None:
|
|||||||
payment.fee = status.fee_msat or payment.fee
|
payment.fee = status.fee_msat or payment.fee
|
||||||
# only overwrite preimage if status.preimage provides it
|
# only overwrite preimage if status.preimage provides it
|
||||||
payment.preimage = status.preimage or payment.preimage
|
payment.preimage = status.preimage or payment.preimage
|
||||||
|
|
||||||
payment.status = PaymentState.SUCCESS
|
payment.status = PaymentState.SUCCESS
|
||||||
await update_payment(payment)
|
payment = await update_payment(payment)
|
||||||
if payment.fiat_provider:
|
if payment.fiat_provider:
|
||||||
await handle_fiat_payment_confirmation(payment)
|
await handle_fiat_payment_confirmation(payment)
|
||||||
return payment
|
return payment
|
||||||
|
|||||||
@@ -16,7 +16,14 @@ from lnbits.core.crud.assets import (
|
|||||||
from lnbits.core.models.assets import AssetFilters, AssetInfo, AssetUpdate
|
from lnbits.core.models.assets import AssetFilters, AssetInfo, AssetUpdate
|
||||||
from lnbits.core.models.misc import SimpleStatus
|
from lnbits.core.models.misc import SimpleStatus
|
||||||
from lnbits.core.models.users import AccountId
|
from lnbits.core.models.users import AccountId
|
||||||
from lnbits.core.services.assets import create_user_asset
|
from lnbits.core.services.assets import (
|
||||||
|
ASSET_SECURITY_HEADERS,
|
||||||
|
INLINE_ASSET_MIME_TYPES,
|
||||||
|
content_disposition,
|
||||||
|
create_user_asset,
|
||||||
|
normalize_media_type,
|
||||||
|
thumbnail_media_type,
|
||||||
|
)
|
||||||
from lnbits.db import Filters, Page
|
from lnbits.db import Filters, Page
|
||||||
from lnbits.decorators import (
|
from lnbits.decorators import (
|
||||||
check_account_id_exists,
|
check_account_id_exists,
|
||||||
@@ -75,11 +82,7 @@ async def api_get_asset_data(
|
|||||||
if not asset:
|
if not asset:
|
||||||
raise HTTPException(HTTPStatus.NOT_FOUND, "Asset not found.")
|
raise HTTPException(HTTPStatus.NOT_FOUND, "Asset not found.")
|
||||||
|
|
||||||
return Response(
|
return asset_response(asset.data, asset.mime_type, asset.name)
|
||||||
content=asset.data,
|
|
||||||
media_type=asset.mime_type,
|
|
||||||
headers={"Content-Disposition": f'inline; filename="{asset.name}"'},
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@asset_router.get(
|
@asset_router.get(
|
||||||
@@ -101,14 +104,14 @@ async def api_get_asset_thumbnail(
|
|||||||
if not asset_info:
|
if not asset_info:
|
||||||
raise HTTPException(HTTPStatus.NOT_FOUND, "Asset not found.")
|
raise HTTPException(HTTPStatus.NOT_FOUND, "Asset not found.")
|
||||||
|
|
||||||
return Response(
|
return asset_response(
|
||||||
content=(
|
content=(
|
||||||
base64.b64decode(asset_info.thumbnail_base64)
|
base64.b64decode(asset_info.thumbnail_base64)
|
||||||
if asset_info.thumbnail_base64
|
if asset_info.thumbnail_base64
|
||||||
else b""
|
else b""
|
||||||
),
|
),
|
||||||
media_type=asset_info.mime_type,
|
media_type=thumbnail_media_type(),
|
||||||
headers={"Content-Disposition": f'inline; filename="{asset_info.name}"'},
|
filename=asset_info.name,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -172,3 +175,16 @@ async def api_delete_asset(
|
|||||||
|
|
||||||
await delete_user_asset(account_id.id, asset_id)
|
await delete_user_asset(account_id.id, asset_id)
|
||||||
return SimpleStatus(success=True, message="Asset deleted successfully.")
|
return SimpleStatus(success=True, message="Asset deleted successfully.")
|
||||||
|
|
||||||
|
|
||||||
|
def asset_response(content: bytes, media_type: str, filename: str) -> Response:
|
||||||
|
media_type = normalize_media_type(media_type)
|
||||||
|
disposition = "inline" if media_type in INLINE_ASSET_MIME_TYPES else "attachment"
|
||||||
|
return Response(
|
||||||
|
content=content,
|
||||||
|
media_type=media_type,
|
||||||
|
headers={
|
||||||
|
**ASSET_SECURITY_HEADERS,
|
||||||
|
"Content-Disposition": content_disposition(disposition, filename),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ from lnbits.decorators import (
|
|||||||
check_account_exists,
|
check_account_exists,
|
||||||
check_admin,
|
check_admin,
|
||||||
check_user_exists,
|
check_user_exists,
|
||||||
|
optional_user_id,
|
||||||
)
|
)
|
||||||
from lnbits.helpers import (
|
from lnbits.helpers import (
|
||||||
create_access_token,
|
create_access_token,
|
||||||
@@ -320,7 +321,10 @@ async def api_delete_user_api_token(
|
|||||||
|
|
||||||
@auth_router.get("/{provider}", description="SSO Provider")
|
@auth_router.get("/{provider}", description="SSO Provider")
|
||||||
async def login_with_sso_provider(
|
async def login_with_sso_provider(
|
||||||
request: Request, provider: str, user_id: str | None = None
|
request: Request,
|
||||||
|
provider: str,
|
||||||
|
user_id: str | None,
|
||||||
|
auth_user_id: str | None = Depends(optional_user_id),
|
||||||
):
|
):
|
||||||
provider_sso = _new_sso(provider)
|
provider_sso = _new_sso(provider)
|
||||||
if not provider_sso:
|
if not provider_sso:
|
||||||
@@ -328,6 +332,8 @@ async def login_with_sso_provider(
|
|||||||
HTTPStatus.FORBIDDEN,
|
HTTPStatus.FORBIDDEN,
|
||||||
f"Login by '{provider}' not allowed.",
|
f"Login by '{provider}' not allowed.",
|
||||||
)
|
)
|
||||||
|
if user_id and user_id != auth_user_id:
|
||||||
|
raise HTTPException(HTTPStatus.FORBIDDEN, "User ID mismatch.")
|
||||||
|
|
||||||
provider_sso.redirect_uri = str(request.base_url) + f"api/v1/auth/{provider}/token"
|
provider_sso.redirect_uri = str(request.base_url) + f"api/v1/auth/{provider}/token"
|
||||||
with provider_sso:
|
with provider_sso:
|
||||||
@@ -348,7 +354,11 @@ async def handle_oauth_token(request: Request, provider: str) -> RedirectRespons
|
|||||||
userinfo = await provider_sso.verify_and_process(request)
|
userinfo = await provider_sso.verify_and_process(request)
|
||||||
if not userinfo:
|
if not userinfo:
|
||||||
raise HTTPException(HTTPStatus.UNAUTHORIZED, "Invalid user info.")
|
raise HTTPException(HTTPStatus.UNAUTHORIZED, "Invalid user info.")
|
||||||
user_id = decrypt_internal_message(provider_sso.state)
|
if provider_sso.state is None or provider_sso.state == "null":
|
||||||
|
user_id = None
|
||||||
|
else:
|
||||||
|
user_id = decrypt_internal_message(provider_sso.state)
|
||||||
|
|
||||||
request.session.pop("user", None)
|
request.session.pop("user", None)
|
||||||
return await _handle_sso_login(userinfo, user_id)
|
return await _handle_sso_login(userinfo, user_id)
|
||||||
|
|
||||||
|
|||||||
@@ -18,7 +18,11 @@ from lnbits.core.services.fiat_providers import (
|
|||||||
check_stripe_signature,
|
check_stripe_signature,
|
||||||
verify_paypal_webhook,
|
verify_paypal_webhook,
|
||||||
)
|
)
|
||||||
from lnbits.core.services.payments import create_fiat_invoice
|
from lnbits.core.services.payments import (
|
||||||
|
create_fiat_invoice,
|
||||||
|
create_wallet_invoice,
|
||||||
|
service_fee_fiat,
|
||||||
|
)
|
||||||
from lnbits.db import Filter, Filters
|
from lnbits.db import Filter, Filters
|
||||||
from lnbits.fiat import get_fiat_provider
|
from lnbits.fiat import get_fiat_provider
|
||||||
from lnbits.fiat.base import FiatSubscriptionPaymentOptions
|
from lnbits.fiat.base import FiatSubscriptionPaymentOptions
|
||||||
@@ -353,15 +357,20 @@ async def handle_revolut_event(event: dict):
|
|||||||
return
|
return
|
||||||
|
|
||||||
payment = await get_standalone_payment(f"fiat_revolut_order_{order_id}")
|
payment = await get_standalone_payment(f"fiat_revolut_order_{order_id}")
|
||||||
if not payment:
|
if payment:
|
||||||
logger.warning(f"No payment found for Revolut order: '{order_id}'.")
|
await check_fiat_status(payment)
|
||||||
return
|
return
|
||||||
|
|
||||||
await check_fiat_status(payment)
|
if event_type == "ORDER_COMPLETED":
|
||||||
|
logger.warning(f"No payment found for Revolut order: '{order_id}'.")
|
||||||
|
await _handle_revolut_subscription_order_paid(order_id)
|
||||||
|
return
|
||||||
|
|
||||||
|
logger.info(f"Ignoring Revolut authorised order without payment: '{order_id}'.")
|
||||||
return
|
return
|
||||||
|
|
||||||
if event_type == "SUBSCRIPTION_INITIATED":
|
if event_type == "SUBSCRIPTION_INITIATED":
|
||||||
await _handle_revolut_subscription_initiated(event)
|
logger.info("Revolut subscription initiated event received.")
|
||||||
return
|
return
|
||||||
|
|
||||||
if event_type in [
|
if event_type in [
|
||||||
@@ -375,18 +384,25 @@ async def handle_revolut_event(event: dict):
|
|||||||
logger.warning(f"Unhandled Revolut event type: '{event_type}'.")
|
logger.warning(f"Unhandled Revolut event type: '{event_type}'.")
|
||||||
|
|
||||||
|
|
||||||
async def _handle_revolut_subscription_initiated(event: dict):
|
async def _get_revolut_provider() -> RevolutWallet | None:
|
||||||
subscription_id = event.get("subscription_id")
|
|
||||||
if not subscription_id:
|
|
||||||
logger.warning("Revolut subscription event missing subscription_id.")
|
|
||||||
return
|
|
||||||
|
|
||||||
fiat_provider = await get_fiat_provider("revolut")
|
fiat_provider = await get_fiat_provider("revolut")
|
||||||
if not isinstance(fiat_provider, RevolutWallet):
|
if not isinstance(fiat_provider, RevolutWallet):
|
||||||
logger.warning("Revolut fiat provider is not configured.")
|
logger.warning("Revolut fiat provider is not configured.")
|
||||||
|
return None
|
||||||
|
return fiat_provider
|
||||||
|
|
||||||
|
|
||||||
|
async def _handle_revolut_subscription(
|
||||||
|
subscription: dict,
|
||||||
|
fiat_provider: RevolutWallet,
|
||||||
|
order_id: str | None = None,
|
||||||
|
order: dict | None = None,
|
||||||
|
):
|
||||||
|
subscription_id = subscription.get("id")
|
||||||
|
if not subscription_id:
|
||||||
|
logger.warning("Revolut subscription missing id.")
|
||||||
return
|
return
|
||||||
|
|
||||||
subscription = await fiat_provider.get_subscription(subscription_id)
|
|
||||||
reference = fiat_provider.deserialize_subscription_reference(
|
reference = fiat_provider.deserialize_subscription_reference(
|
||||||
subscription.get("external_reference")
|
subscription.get("external_reference")
|
||||||
)
|
)
|
||||||
@@ -394,16 +410,17 @@ async def _handle_revolut_subscription_initiated(event: dict):
|
|||||||
logger.warning("Revolut subscription event missing LNbits metadata.")
|
logger.warning("Revolut subscription event missing LNbits metadata.")
|
||||||
return
|
return
|
||||||
|
|
||||||
cycle_id = subscription.get("current_cycle_id")
|
|
||||||
if not cycle_id:
|
|
||||||
logger.warning("Revolut subscription missing current_cycle_id.")
|
|
||||||
return
|
|
||||||
|
|
||||||
cycle = await fiat_provider.get_subscription_cycle(subscription_id, cycle_id)
|
|
||||||
order_id = cycle.get("order_id")
|
|
||||||
if not order_id:
|
if not order_id:
|
||||||
logger.warning("Revolut subscription cycle missing order_id.")
|
cycle_id = subscription.get("current_cycle_id")
|
||||||
return
|
if not cycle_id:
|
||||||
|
logger.warning("Revolut subscription missing current_cycle_id.")
|
||||||
|
return
|
||||||
|
|
||||||
|
cycle = await fiat_provider.get_subscription_cycle(subscription_id, cycle_id)
|
||||||
|
order_id = cycle.get("order_id")
|
||||||
|
if not order_id:
|
||||||
|
logger.warning("Revolut subscription cycle missing order_id.")
|
||||||
|
return
|
||||||
|
|
||||||
existing_payment = await get_standalone_payment(f"fiat_revolut_order_{order_id}")
|
existing_payment = await get_standalone_payment(f"fiat_revolut_order_{order_id}")
|
||||||
if existing_payment:
|
if existing_payment:
|
||||||
@@ -413,7 +430,8 @@ async def _handle_revolut_subscription_initiated(event: dict):
|
|||||||
await check_fiat_status(existing_payment)
|
await check_fiat_status(existing_payment)
|
||||||
return
|
return
|
||||||
|
|
||||||
order = await fiat_provider.get_order(order_id)
|
if not order:
|
||||||
|
order = await fiat_provider.get_order(order_id)
|
||||||
amount_minor = order.get("amount")
|
amount_minor = order.get("amount")
|
||||||
currency = (order.get("currency") or "").upper()
|
currency = (order.get("currency") or "").upper()
|
||||||
if amount_minor is None or not currency:
|
if amount_minor is None or not currency:
|
||||||
@@ -429,21 +447,80 @@ async def _handle_revolut_subscription_initiated(event: dict):
|
|||||||
"payment_request": order.get("checkout_url") or "",
|
"payment_request": order.get("checkout_url") or "",
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
lnbits_payment = await create_fiat_invoice(
|
lnbits_payment = await _create_revolut_subscription_payment(
|
||||||
wallet_id=reference.wallet_id,
|
wallet_id=reference.wallet_id,
|
||||||
invoice_data=CreateInvoice(
|
amount_minor=amount_minor,
|
||||||
unit=currency,
|
currency=currency,
|
||||||
amount=amount_minor / 100,
|
memo=reference.memo or "",
|
||||||
memo=reference.memo or "",
|
extra=extra,
|
||||||
extra=extra,
|
order_id=order_id,
|
||||||
fiat_provider="revolut",
|
payment_request=order.get("checkout_url") or "",
|
||||||
external_id=subscription_id,
|
subscription_id=subscription_id,
|
||||||
),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
await check_fiat_status(lnbits_payment)
|
await check_fiat_status(lnbits_payment)
|
||||||
|
|
||||||
|
|
||||||
|
async def _handle_revolut_subscription_order_paid(order_id: str):
|
||||||
|
fiat_provider = await _get_revolut_provider()
|
||||||
|
if not fiat_provider:
|
||||||
|
return
|
||||||
|
|
||||||
|
order = await fiat_provider.get_order(order_id)
|
||||||
|
order_type = (order.get("type") or "").lower()
|
||||||
|
order_state = (order.get("state") or "").upper()
|
||||||
|
if order_type != "payment" or order_state != "COMPLETED":
|
||||||
|
logger.warning(f"Revolut order is not a completed payment: '{order_id}'.")
|
||||||
|
return
|
||||||
|
|
||||||
|
channel_data = order.get("channel_data") or {}
|
||||||
|
subscription_id = channel_data.get("subscription_id")
|
||||||
|
if not subscription_id:
|
||||||
|
logger.warning(f"Revolut order missing subscription_id: '{order_id}'.")
|
||||||
|
return
|
||||||
|
|
||||||
|
subscription = await fiat_provider.get_subscription(subscription_id)
|
||||||
|
if subscription.get("state") != "active":
|
||||||
|
logger.warning(f"Revolut subscription is not active: '{subscription_id}'.")
|
||||||
|
return
|
||||||
|
|
||||||
|
await _handle_revolut_subscription(
|
||||||
|
subscription, fiat_provider, order_id=order_id, order=order
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def _create_revolut_subscription_payment(
|
||||||
|
wallet_id: str,
|
||||||
|
amount_minor: int,
|
||||||
|
currency: str,
|
||||||
|
memo: str,
|
||||||
|
extra: dict,
|
||||||
|
order_id: str,
|
||||||
|
payment_request: str,
|
||||||
|
subscription_id: str,
|
||||||
|
) -> Payment:
|
||||||
|
amount = RevolutWallet.minor_units_to_amount(amount_minor, currency)
|
||||||
|
payment = await create_wallet_invoice(
|
||||||
|
wallet_id,
|
||||||
|
CreateInvoice(
|
||||||
|
unit=currency,
|
||||||
|
amount=amount,
|
||||||
|
memo=memo,
|
||||||
|
extra=extra,
|
||||||
|
internal=True,
|
||||||
|
external_id=subscription_id,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
payment.fee = -abs(service_fee_fiat(payment.msat, "revolut"))
|
||||||
|
payment.fiat_provider = "revolut"
|
||||||
|
payment.extra["fiat_checking_id"] = f"order_{order_id}"
|
||||||
|
payment.extra["fiat_payment_request"] = payment_request
|
||||||
|
checking_id = f"fiat_revolut_order_{order_id}"
|
||||||
|
await update_payment(payment, checking_id)
|
||||||
|
payment.checking_id = checking_id
|
||||||
|
return payment
|
||||||
|
|
||||||
|
|
||||||
async def _handle_square_payment_event(event: dict):
|
async def _handle_square_payment_event(event: dict):
|
||||||
payment = _square_extract_payment(event)
|
payment = _square_extract_payment(event)
|
||||||
payment_options = _deserialize_square_metadata(_square_payment_note(payment))
|
payment_options = _deserialize_square_metadata(_square_payment_note(payment))
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ generic_router = APIRouter(
|
|||||||
|
|
||||||
@generic_router.get("/favicon.ico", response_class=FileResponse)
|
@generic_router.get("/favicon.ico", response_class=FileResponse)
|
||||||
async def favicon():
|
async def favicon():
|
||||||
return RedirectResponse(settings.lnbits_qr_logo)
|
return RedirectResponse(settings.root_path + settings.lnbits_qr_logo)
|
||||||
|
|
||||||
|
|
||||||
@generic_router.get("/robots.txt", response_class=HTMLResponse)
|
@generic_router.get("/robots.txt", response_class=HTMLResponse)
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ from lnbits.core.models import (
|
|||||||
PaymentWalletStats,
|
PaymentWalletStats,
|
||||||
SettleInvoice,
|
SettleInvoice,
|
||||||
SimpleStatus,
|
SimpleStatus,
|
||||||
|
UpdatePaymentExtra,
|
||||||
)
|
)
|
||||||
from lnbits.core.models.payments import UpdatePaymentLabels
|
from lnbits.core.models.payments import UpdatePaymentLabels
|
||||||
from lnbits.core.models.users import AccountId
|
from lnbits.core.models.users import AccountId
|
||||||
@@ -297,6 +298,38 @@ async def api_update_payment_labels(
|
|||||||
return SimpleStatus(success=True, message="Payment labels updated.")
|
return SimpleStatus(success=True, message="Payment labels updated.")
|
||||||
|
|
||||||
|
|
||||||
|
@payment_router.patch(
|
||||||
|
"/extra",
|
||||||
|
name="Update payment extra",
|
||||||
|
description="Append new extra metadata to a payment.",
|
||||||
|
response_model=Payment,
|
||||||
|
)
|
||||||
|
async def api_update_payment_extra(
|
||||||
|
data: UpdatePaymentExtra,
|
||||||
|
key_type: WalletTypeInfo = Depends(require_admin_key),
|
||||||
|
) -> Payment:
|
||||||
|
payment = await get_standalone_payment(
|
||||||
|
data.payment_hash, wallet_id=key_type.wallet.id
|
||||||
|
)
|
||||||
|
if payment is None:
|
||||||
|
raise HTTPException(HTTPStatus.NOT_FOUND, "Payment does not exist.")
|
||||||
|
if not payment.success:
|
||||||
|
raise HTTPException(
|
||||||
|
HTTPStatus.BAD_REQUEST, "Payment extra can only be updated after success."
|
||||||
|
)
|
||||||
|
|
||||||
|
duplicate_keys = sorted(set(payment.extra).intersection(data.extra))
|
||||||
|
if duplicate_keys:
|
||||||
|
raise HTTPException(
|
||||||
|
HTTPStatus.BAD_REQUEST,
|
||||||
|
f"Extra keys already exist: {', '.join(duplicate_keys)}.",
|
||||||
|
)
|
||||||
|
|
||||||
|
payment.extra.update(data.extra)
|
||||||
|
await update_payment(payment)
|
||||||
|
return payment
|
||||||
|
|
||||||
|
|
||||||
@payment_router.get("/fee-reserve")
|
@payment_router.get("/fee-reserve")
|
||||||
async def api_payments_fee_reserve(invoice: str = Query("invoice")) -> JSONResponse:
|
async def api_payments_fee_reserve(invoice: str = Query("invoice")) -> JSONResponse:
|
||||||
invoice_obj = bolt11.decode(invoice)
|
invoice_obj = bolt11.decode(invoice)
|
||||||
|
|||||||
@@ -517,6 +517,7 @@ async def _check_account_api_access(
|
|||||||
raise HTTPException(HTTPStatus.FORBIDDEN, "Method not allowed.")
|
raise HTTPException(HTTPStatus.FORBIDDEN, "Method not allowed.")
|
||||||
|
|
||||||
|
|
||||||
|
# TODO: this messes up my extension urls
|
||||||
def url_for_interceptor(original_method):
|
def url_for_interceptor(original_method):
|
||||||
def normalize_url(self, *args, **kwargs):
|
def normalize_url(self, *args, **kwargs):
|
||||||
url = original_method(self, *args, **kwargs)
|
url = original_method(self, *args, **kwargs)
|
||||||
@@ -527,6 +528,7 @@ def url_for_interceptor(original_method):
|
|||||||
|
|
||||||
# Upgraded extensions modify the path.
|
# Upgraded extensions modify the path.
|
||||||
# This interceptor ensures that the path is normalized.
|
# This interceptor ensures that the path is normalized.
|
||||||
|
# TODO: this messes up my extension urls
|
||||||
Request.url_for = url_for_interceptor(Request.url_for) # type: ignore[method-assign]
|
Request.url_for = url_for_interceptor(Request.url_for) # type: ignore[method-assign]
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+7
-3
@@ -95,6 +95,10 @@ class FiatSubscriptionPaymentOptions(BaseModel):
|
|||||||
description="Unique ID that can be used to identify the subscription request."
|
description="Unique ID that can be used to identify the subscription request."
|
||||||
"If not provided, one will be generated.",
|
"If not provided, one will be generated.",
|
||||||
)
|
)
|
||||||
|
customer_email: str | None = Field(
|
||||||
|
default=None,
|
||||||
|
description="The customer email to use for the subscription.",
|
||||||
|
)
|
||||||
tag: str | None = Field(
|
tag: str | None = Field(
|
||||||
default=None,
|
default=None,
|
||||||
description="Payments created by the recurring subscription"
|
description="Payments created by the recurring subscription"
|
||||||
@@ -127,15 +131,15 @@ class FiatSubscriptionResponse(BaseModel):
|
|||||||
|
|
||||||
|
|
||||||
class FiatPaymentSuccessStatus(FiatPaymentStatus):
|
class FiatPaymentSuccessStatus(FiatPaymentStatus):
|
||||||
paid = True
|
paid = True # type: ignore[reportIncompatibleVariableOverride]
|
||||||
|
|
||||||
|
|
||||||
class FiatPaymentFailedStatus(FiatPaymentStatus):
|
class FiatPaymentFailedStatus(FiatPaymentStatus):
|
||||||
paid = False
|
paid = False # type: ignore[reportIncompatibleVariableOverride]
|
||||||
|
|
||||||
|
|
||||||
class FiatPaymentPendingStatus(FiatPaymentStatus):
|
class FiatPaymentPendingStatus(FiatPaymentStatus):
|
||||||
paid = None
|
paid = None # type: ignore[reportIncompatibleVariableOverride]
|
||||||
|
|
||||||
|
|
||||||
class FiatProvider(ABC):
|
class FiatProvider(ABC):
|
||||||
|
|||||||
+170
-20
@@ -2,6 +2,7 @@ import asyncio
|
|||||||
import ipaddress
|
import ipaddress
|
||||||
import json
|
import json
|
||||||
from collections.abc import AsyncGenerator
|
from collections.abc import AsyncGenerator
|
||||||
|
from decimal import ROUND_HALF_UP, Decimal
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from urllib.parse import urlparse
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
@@ -56,6 +57,37 @@ REVOLUT_WEBHOOK_EVENTS = [
|
|||||||
"SUBSCRIPTION_INITIATED",
|
"SUBSCRIPTION_INITIATED",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
ZERO_DECIMAL_CURRENCIES = {
|
||||||
|
"BIF",
|
||||||
|
"CLP",
|
||||||
|
"DJF",
|
||||||
|
"GNF",
|
||||||
|
"ISK",
|
||||||
|
"JPY",
|
||||||
|
"KMF",
|
||||||
|
"KRW",
|
||||||
|
"PYG",
|
||||||
|
"RWF",
|
||||||
|
"UGX",
|
||||||
|
"VND",
|
||||||
|
"VUV",
|
||||||
|
"XAF",
|
||||||
|
"XOF",
|
||||||
|
"XPF",
|
||||||
|
}
|
||||||
|
THREE_DECIMAL_CURRENCIES = {
|
||||||
|
"BHD",
|
||||||
|
"IQD",
|
||||||
|
"JOD",
|
||||||
|
"KWD",
|
||||||
|
"LYD",
|
||||||
|
"OMR",
|
||||||
|
"TND",
|
||||||
|
}
|
||||||
|
REVOLUT_CUSTOMER_LIST_LIMIT = 500
|
||||||
|
REVOLUT_CUSTOMER_LIST_MAX_PAGES = 20
|
||||||
|
REVOLUT_REQUEST_TIMEOUT = 30
|
||||||
|
|
||||||
|
|
||||||
class RevolutWallet(FiatProvider):
|
class RevolutWallet(FiatProvider):
|
||||||
"""https://developer.revolut.com/docs/merchant"""
|
"""https://developer.revolut.com/docs/merchant"""
|
||||||
@@ -93,7 +125,11 @@ class RevolutWallet(FiatProvider):
|
|||||||
return FiatStatusResponse(balance=0)
|
return FiatStatusResponse(balance=0)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
r = await self.client.get("/api/orders", params={"limit": 1}, timeout=15)
|
r = await self.client.get(
|
||||||
|
"/api/orders",
|
||||||
|
params={"limit": 1},
|
||||||
|
timeout=REVOLUT_REQUEST_TIMEOUT,
|
||||||
|
)
|
||||||
r.raise_for_status()
|
r.raise_for_status()
|
||||||
_ = r.json()
|
_ = r.json()
|
||||||
return FiatStatusResponse(balance=0)
|
return FiatStatusResponse(balance=0)
|
||||||
@@ -118,7 +154,7 @@ class RevolutWallet(FiatProvider):
|
|||||||
ok=False, error_message="Invalid Revolut options"
|
ok=False, error_message="Invalid Revolut options"
|
||||||
)
|
)
|
||||||
|
|
||||||
amount_minor = int(amount * 100)
|
amount_minor = self.amount_to_minor_units(amount, currency)
|
||||||
checkout = opts.checkout or RevolutCheckoutOptions()
|
checkout = opts.checkout or RevolutCheckoutOptions()
|
||||||
success_url = (
|
success_url = (
|
||||||
checkout.success_url
|
checkout.success_url
|
||||||
@@ -139,7 +175,9 @@ class RevolutWallet(FiatProvider):
|
|||||||
}
|
}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
r = await self.client.post("/api/orders", json=payload)
|
r = await self.client.post(
|
||||||
|
"/api/orders", json=payload, timeout=REVOLUT_REQUEST_TIMEOUT
|
||||||
|
)
|
||||||
r.raise_for_status()
|
r.raise_for_status()
|
||||||
data = r.json()
|
data = r.json()
|
||||||
order_id = data.get("id")
|
order_id = data.get("id")
|
||||||
@@ -183,13 +221,6 @@ class RevolutWallet(FiatProvider):
|
|||||||
)
|
)
|
||||||
|
|
||||||
extra = payment_options.extra or {}
|
extra = payment_options.extra or {}
|
||||||
customer_id = extra.get("customer_id")
|
|
||||||
if not customer_id:
|
|
||||||
return FiatSubscriptionResponse(
|
|
||||||
ok=False,
|
|
||||||
error_message="Revolut subscriptions require extra.customer_id.",
|
|
||||||
)
|
|
||||||
|
|
||||||
if not payment_options.subscription_request_id:
|
if not payment_options.subscription_request_id:
|
||||||
payment_options.subscription_request_id = urlsafe_short_hash()
|
payment_options.subscription_request_id = urlsafe_short_hash()
|
||||||
|
|
||||||
@@ -202,7 +233,6 @@ class RevolutWallet(FiatProvider):
|
|||||||
)
|
)
|
||||||
payload: dict[str, Any] = {
|
payload: dict[str, Any] = {
|
||||||
"plan_variation_id": subscription_id,
|
"plan_variation_id": subscription_id,
|
||||||
"customer_id": customer_id,
|
|
||||||
"external_reference": self._serialize_subscription_reference(reference),
|
"external_reference": self._serialize_subscription_reference(reference),
|
||||||
"setup_order_redirect_url": (
|
"setup_order_redirect_url": (
|
||||||
payment_options.success_url
|
payment_options.success_url
|
||||||
@@ -219,8 +249,17 @@ class RevolutWallet(FiatProvider):
|
|||||||
}
|
}
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
customer_id, customer_error = await self._get_subscription_customer_id(
|
||||||
|
payment_options
|
||||||
|
)
|
||||||
|
if not customer_id:
|
||||||
|
return FiatSubscriptionResponse(ok=False, error_message=customer_error)
|
||||||
|
payload["customer_id"] = customer_id
|
||||||
r = await self.client.post(
|
r = await self.client.post(
|
||||||
"/api/subscriptions", json=payload, headers=headers
|
"/api/subscriptions",
|
||||||
|
json=payload,
|
||||||
|
headers=headers,
|
||||||
|
timeout=REVOLUT_REQUEST_TIMEOUT,
|
||||||
)
|
)
|
||||||
r.raise_for_status()
|
r.raise_for_status()
|
||||||
data = r.json()
|
data = r.json()
|
||||||
@@ -244,7 +283,7 @@ class RevolutWallet(FiatProvider):
|
|||||||
return FiatSubscriptionResponse(
|
return FiatSubscriptionResponse(
|
||||||
ok=True,
|
ok=True,
|
||||||
checkout_session_url=checkout_url,
|
checkout_session_url=checkout_url,
|
||||||
subscription_request_id=revolut_subscription_id,
|
subscription_request_id=payment_options.subscription_request_id,
|
||||||
)
|
)
|
||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
return FiatSubscriptionResponse(
|
return FiatSubscriptionResponse(
|
||||||
@@ -263,7 +302,10 @@ class RevolutWallet(FiatProvider):
|
|||||||
**kwargs,
|
**kwargs,
|
||||||
) -> FiatSubscriptionResponse:
|
) -> FiatSubscriptionResponse:
|
||||||
try:
|
try:
|
||||||
r = await self.client.post(f"/api/subscriptions/{subscription_id}/cancel")
|
r = await self.client.post(
|
||||||
|
f"/api/subscriptions/{subscription_id}/cancel",
|
||||||
|
timeout=REVOLUT_REQUEST_TIMEOUT,
|
||||||
|
)
|
||||||
r.raise_for_status()
|
r.raise_for_status()
|
||||||
return FiatSubscriptionResponse(ok=True)
|
return FiatSubscriptionResponse(ok=True)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
@@ -304,12 +346,16 @@ class RevolutWallet(FiatProvider):
|
|||||||
return value.replace("order_", "", 1) if value.startswith("order_") else value
|
return value.replace("order_", "", 1) if value.startswith("order_") else value
|
||||||
|
|
||||||
async def get_order(self, order_id: str) -> dict[str, Any]:
|
async def get_order(self, order_id: str) -> dict[str, Any]:
|
||||||
r = await self.client.get(f"/api/orders/{order_id}")
|
r = await self.client.get(
|
||||||
|
f"/api/orders/{order_id}", timeout=REVOLUT_REQUEST_TIMEOUT
|
||||||
|
)
|
||||||
r.raise_for_status()
|
r.raise_for_status()
|
||||||
return r.json()
|
return r.json()
|
||||||
|
|
||||||
async def get_subscription(self, subscription_id: str) -> dict[str, Any]:
|
async def get_subscription(self, subscription_id: str) -> dict[str, Any]:
|
||||||
r = await self.client.get(f"/api/subscriptions/{subscription_id}")
|
r = await self.client.get(
|
||||||
|
f"/api/subscriptions/{subscription_id}", timeout=REVOLUT_REQUEST_TIMEOUT
|
||||||
|
)
|
||||||
r.raise_for_status()
|
r.raise_for_status()
|
||||||
return r.json()
|
return r.json()
|
||||||
|
|
||||||
@@ -317,7 +363,60 @@ class RevolutWallet(FiatProvider):
|
|||||||
self, subscription_id: str, cycle_id: str
|
self, subscription_id: str, cycle_id: str
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
r = await self.client.get(
|
r = await self.client.get(
|
||||||
f"/api/subscriptions/{subscription_id}/cycles/{cycle_id}"
|
f"/api/subscriptions/{subscription_id}/cycles/{cycle_id}",
|
||||||
|
timeout=REVOLUT_REQUEST_TIMEOUT,
|
||||||
|
)
|
||||||
|
r.raise_for_status()
|
||||||
|
return r.json()
|
||||||
|
|
||||||
|
async def _get_subscription_customer_id(
|
||||||
|
self, payment_options: FiatSubscriptionPaymentOptions
|
||||||
|
) -> tuple[str | None, str | None]:
|
||||||
|
if not payment_options.customer_email:
|
||||||
|
return (
|
||||||
|
None,
|
||||||
|
"Revolut subscriptions require customer_email.",
|
||||||
|
)
|
||||||
|
|
||||||
|
customer = await self._get_customer_by_email(payment_options.customer_email)
|
||||||
|
customer_id = customer.get("id") if customer else None
|
||||||
|
if customer_id:
|
||||||
|
return customer_id, None
|
||||||
|
|
||||||
|
customer = await self._create_customer(payment_options.customer_email)
|
||||||
|
customer_id = customer.get("id")
|
||||||
|
if not customer_id:
|
||||||
|
return None, "Server error: missing customer id"
|
||||||
|
return customer_id, None
|
||||||
|
|
||||||
|
async def _get_customer_by_email(self, email: str) -> dict[str, Any] | None:
|
||||||
|
page_token = None
|
||||||
|
for _ in range(REVOLUT_CUSTOMER_LIST_MAX_PAGES):
|
||||||
|
customer_page = await self._list_customers(page_token=page_token)
|
||||||
|
customer = _find_customer_by_email(customer_page["customers"], email)
|
||||||
|
if customer:
|
||||||
|
return customer
|
||||||
|
|
||||||
|
page_token = customer_page.get("next_page_token")
|
||||||
|
if not page_token:
|
||||||
|
return None
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def _list_customers(self, page_token: str | None = None) -> dict[str, Any]:
|
||||||
|
params: dict[str, Any] = {"limit": REVOLUT_CUSTOMER_LIST_LIMIT}
|
||||||
|
if page_token:
|
||||||
|
params["page_token"] = page_token
|
||||||
|
r = await self.client.get(
|
||||||
|
"/api/customers", params=params, timeout=REVOLUT_REQUEST_TIMEOUT
|
||||||
|
)
|
||||||
|
r.raise_for_status()
|
||||||
|
return _extract_customer_page(r.json())
|
||||||
|
|
||||||
|
async def _create_customer(self, email: str) -> dict[str, Any]:
|
||||||
|
r = await self.client.post(
|
||||||
|
"/api/customers",
|
||||||
|
json={"email": email},
|
||||||
|
timeout=REVOLUT_REQUEST_TIMEOUT,
|
||||||
)
|
)
|
||||||
r.raise_for_status()
|
r.raise_for_status()
|
||||||
return r.json()
|
return r.json()
|
||||||
@@ -354,13 +453,15 @@ class RevolutWallet(FiatProvider):
|
|||||||
existing["already_exists"] = True
|
existing["already_exists"] = True
|
||||||
return existing
|
return existing
|
||||||
|
|
||||||
response = await client.post("/api/webhooks", json=payload, timeout=15)
|
response = await client.post(
|
||||||
|
"/api/webhooks", json=payload, timeout=REVOLUT_REQUEST_TIMEOUT
|
||||||
|
)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
return response.json()
|
return response.json()
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
async def _list_webhooks(cls, client: httpx.AsyncClient) -> list[dict[str, Any]]:
|
async def _list_webhooks(cls, client: httpx.AsyncClient) -> list[dict[str, Any]]:
|
||||||
response = await client.get("/api/webhooks", timeout=15)
|
response = await client.get("/api/webhooks", timeout=REVOLUT_REQUEST_TIMEOUT)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
data = response.json()
|
data = response.json()
|
||||||
if isinstance(data, list):
|
if isinstance(data, list):
|
||||||
@@ -385,7 +486,9 @@ class RevolutWallet(FiatProvider):
|
|||||||
if webhook_id and (
|
if webhook_id and (
|
||||||
not webhook.get("events") or not webhook.get("signing_secret")
|
not webhook.get("events") or not webhook.get("signing_secret")
|
||||||
):
|
):
|
||||||
response = await client.get(f"/api/webhooks/{webhook_id}", timeout=15)
|
response = await client.get(
|
||||||
|
f"/api/webhooks/{webhook_id}", timeout=REVOLUT_REQUEST_TIMEOUT
|
||||||
|
)
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
webhook = response.json()
|
webhook = response.json()
|
||||||
|
|
||||||
@@ -445,6 +548,25 @@ class RevolutWallet(FiatProvider):
|
|||||||
return FiatPaymentFailedStatus()
|
return FiatPaymentFailedStatus()
|
||||||
return FiatPaymentPendingStatus()
|
return FiatPaymentPendingStatus()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def amount_to_minor_units(cls, amount: float | Decimal, currency: str) -> int:
|
||||||
|
scale = Decimal(10) ** cls.currency_exponent(currency)
|
||||||
|
return int((Decimal(str(amount)) * scale).quantize(Decimal("1"), ROUND_HALF_UP))
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def minor_units_to_amount(cls, amount: int, currency: str) -> float:
|
||||||
|
scale = Decimal(10) ** cls.currency_exponent(currency)
|
||||||
|
return float(Decimal(amount) / scale)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def currency_exponent(cls, currency: str) -> int:
|
||||||
|
normalized = currency.upper()
|
||||||
|
if normalized in ZERO_DECIMAL_CURRENCIES:
|
||||||
|
return 0
|
||||||
|
if normalized in THREE_DECIMAL_CURRENCIES:
|
||||||
|
return 3
|
||||||
|
return 2
|
||||||
|
|
||||||
def _parse_create_opts(
|
def _parse_create_opts(
|
||||||
self, raw_opts: dict[str, Any]
|
self, raw_opts: dict[str, Any]
|
||||||
) -> RevolutCreateInvoiceOptions | None:
|
) -> RevolutCreateInvoiceOptions | None:
|
||||||
@@ -485,3 +607,31 @@ class RevolutWallet(FiatProvider):
|
|||||||
str(settings.revolut_webhook_signing_secret),
|
str(settings.revolut_webhook_signing_secret),
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_customer_page(data: Any) -> dict[str, Any]:
|
||||||
|
if isinstance(data, list):
|
||||||
|
return {"customers": _filter_customer_list(data)}
|
||||||
|
if isinstance(data, dict):
|
||||||
|
for field in ["customers", "data", "items"]:
|
||||||
|
customers = data.get(field)
|
||||||
|
if isinstance(customers, list):
|
||||||
|
return {
|
||||||
|
"customers": _filter_customer_list(customers),
|
||||||
|
"next_page_token": data.get("next_page_token"),
|
||||||
|
}
|
||||||
|
return {"customers": []}
|
||||||
|
|
||||||
|
|
||||||
|
def _filter_customer_list(customers: list[Any]) -> list[dict[str, Any]]:
|
||||||
|
return [customer for customer in customers if isinstance(customer, dict)]
|
||||||
|
|
||||||
|
|
||||||
|
def _find_customer_by_email(
|
||||||
|
customers: list[dict[str, Any]], email: str
|
||||||
|
) -> dict[str, Any] | None:
|
||||||
|
normalized_email = email.casefold()
|
||||||
|
for customer in customers:
|
||||||
|
if str(customer.get("email") or "").casefold() == normalized_email:
|
||||||
|
return customer
|
||||||
|
return None
|
||||||
|
|||||||
@@ -137,6 +137,10 @@ class SquareWallet(FiatProvider):
|
|||||||
payment_options: FiatSubscriptionPaymentOptions,
|
payment_options: FiatSubscriptionPaymentOptions,
|
||||||
**kwargs,
|
**kwargs,
|
||||||
) -> FiatSubscriptionResponse:
|
) -> FiatSubscriptionResponse:
|
||||||
|
if settings.lnbits_running:
|
||||||
|
return FiatSubscriptionResponse(
|
||||||
|
ok=False, error_message="Subscription not supported for Square."
|
||||||
|
)
|
||||||
success_url = (
|
success_url = (
|
||||||
payment_options.success_url
|
payment_options.success_url
|
||||||
or settings.square_payment_success_url
|
or settings.square_payment_success_url
|
||||||
|
|||||||
+17
-4
@@ -48,8 +48,11 @@ def url_for(endpoint: str, external: bool | None = False, **params: Any) -> str:
|
|||||||
return url
|
return url
|
||||||
|
|
||||||
|
|
||||||
def static_url_for(static: str, path: str) -> str:
|
def static_url_for(static: str, path: str, no_cache: bool = False) -> str:
|
||||||
return f"/{static}/{path}?v={settings.server_startup_time}"
|
url = f"{settings.root_path}{static}/{path}"
|
||||||
|
if no_cache:
|
||||||
|
url += f"?v={settings.server_startup_time}"
|
||||||
|
return url
|
||||||
|
|
||||||
|
|
||||||
def template_renderer(additional_folders: list | None = None) -> Jinja2Templates:
|
def template_renderer(additional_folders: list | None = None) -> Jinja2Templates:
|
||||||
@@ -57,7 +60,6 @@ def template_renderer(additional_folders: list | None = None) -> Jinja2Templates
|
|||||||
"lnbits/templates",
|
"lnbits/templates",
|
||||||
settings.extension_builder_working_dir_path.as_posix(),
|
settings.extension_builder_working_dir_path.as_posix(),
|
||||||
]
|
]
|
||||||
|
|
||||||
if additional_folders:
|
if additional_folders:
|
||||||
additional_folders += [
|
additional_folders += [
|
||||||
Path(settings.lnbits_extensions_path, "extensions", f)
|
Path(settings.lnbits_extensions_path, "extensions", f)
|
||||||
@@ -69,6 +71,7 @@ def template_renderer(additional_folders: list | None = None) -> Jinja2Templates
|
|||||||
t.env.globals["normalize_path"] = normalize_path
|
t.env.globals["normalize_path"] = normalize_path
|
||||||
|
|
||||||
# used in base.html
|
# used in base.html
|
||||||
|
t.env.globals["ROOT_PATH"] = settings.root_path
|
||||||
t.env.globals["SITE_TITLE"] = settings.lnbits_site_title
|
t.env.globals["SITE_TITLE"] = settings.lnbits_site_title
|
||||||
t.env.globals["LNBITS_APPLE_TOUCH_ICON"] = settings.lnbits_apple_touch_icon
|
t.env.globals["LNBITS_APPLE_TOUCH_ICON"] = settings.lnbits_apple_touch_icon
|
||||||
t.env.globals["SETTINGS"] = settings.to_public().dict(by_alias=True)
|
t.env.globals["SETTINGS"] = settings.to_public().dict(by_alias=True)
|
||||||
@@ -310,6 +313,8 @@ def get_api_routes(routes: list) -> dict[str, str]:
|
|||||||
|
|
||||||
def path_segments(path: str) -> list[str]:
|
def path_segments(path: str) -> list[str]:
|
||||||
path = path.strip("/")
|
path = path.strip("/")
|
||||||
|
# Remove empty segments caused by '//' in the path
|
||||||
|
# segments = [s for s in path.split("/") if s]
|
||||||
segments = path.split("/")
|
segments = path.split("/")
|
||||||
if len(segments) < 2:
|
if len(segments) < 2:
|
||||||
return segments
|
return segments
|
||||||
@@ -319,8 +324,16 @@ def path_segments(path: str) -> list[str]:
|
|||||||
|
|
||||||
|
|
||||||
def normalize_path(path: str | None) -> str:
|
def normalize_path(path: str | None) -> str:
|
||||||
|
print(path)
|
||||||
path = path or ""
|
path = path or ""
|
||||||
return "/" + "/".join(path_segments(path))
|
segments = path_segments(path)
|
||||||
|
print(segments)
|
||||||
|
joined = "/".join(segments)
|
||||||
|
print("!!!!!!!!!!")
|
||||||
|
print(joined)
|
||||||
|
return joined
|
||||||
|
|
||||||
|
# return "/" + "/".join(path_segments(path))
|
||||||
|
|
||||||
|
|
||||||
def normalize_endpoint(endpoint: str, add_proto=True) -> str:
|
def normalize_endpoint(endpoint: str, add_proto=True) -> str:
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ from lnbits.helpers import normalize_path, template_renderer
|
|||||||
from lnbits.settings import settings
|
from lnbits.settings import settings
|
||||||
|
|
||||||
|
|
||||||
|
# TODO: root path should be considered here?
|
||||||
class InstalledExtensionMiddleware:
|
class InstalledExtensionMiddleware:
|
||||||
# This middleware class intercepts calls made to the extensions API and:
|
# This middleware class intercepts calls made to the extensions API and:
|
||||||
# - it blocks the calls if the extension has been disabled or uninstalled.
|
# - it blocks the calls if the extension has been disabled or uninstalled.
|
||||||
@@ -51,7 +52,7 @@ class InstalledExtensionMiddleware:
|
|||||||
await self.app(scope, receive, send)
|
await self.app(scope, receive, send)
|
||||||
return
|
return
|
||||||
|
|
||||||
# re-route all trafic if the extension has been upgraded
|
# re-route all traffic if the extension has been upgraded
|
||||||
if top_path in settings.lnbits_upgraded_extensions:
|
if top_path in settings.lnbits_upgraded_extensions:
|
||||||
upgrade_path = (
|
upgrade_path = (
|
||||||
f"""{settings.lnbits_upgraded_extensions[top_path]}/{top_path}"""
|
f"""{settings.lnbits_upgraded_extensions[top_path]}/{top_path}"""
|
||||||
@@ -241,6 +242,7 @@ def add_first_install_middleware(app: FastAPI):
|
|||||||
async def first_install_middleware(request: Request, call_next):
|
async def first_install_middleware(request: Request, call_next):
|
||||||
if (
|
if (
|
||||||
settings.first_install
|
settings.first_install
|
||||||
|
# TODO: root path should be considered here?
|
||||||
and request.url.path != "/api/v1/auth/first_install"
|
and request.url.path != "/api/v1/auth/first_install"
|
||||||
and request.url.path != "/first_install"
|
and request.url.path != "/first_install"
|
||||||
and not request.url.path.startswith("/static")
|
and not request.url.path.startswith("/static")
|
||||||
|
|||||||
+13
-1
@@ -17,6 +17,11 @@ from lnbits.settings import set_cli_settings, settings
|
|||||||
)
|
)
|
||||||
@click.option("--port", default=settings.port, help="Port to listen on")
|
@click.option("--port", default=settings.port, help="Port to listen on")
|
||||||
@click.option("--host", default=settings.host, help="Host to run LNbits on")
|
@click.option("--host", default=settings.host, help="Host to run LNbits on")
|
||||||
|
@click.option(
|
||||||
|
"--root-path",
|
||||||
|
default=settings.root_path,
|
||||||
|
help="Root path of proxy, my.lnbits.com/rootpath ",
|
||||||
|
)
|
||||||
@click.option(
|
@click.option(
|
||||||
"--forwarded-allow-ips",
|
"--forwarded-allow-ips",
|
||||||
default=settings.forwarded_allow_ips,
|
default=settings.forwarded_allow_ips,
|
||||||
@@ -30,6 +35,7 @@ from lnbits.settings import set_cli_settings, settings
|
|||||||
def main(
|
def main(
|
||||||
port: int,
|
port: int,
|
||||||
host: str,
|
host: str,
|
||||||
|
root_path: str,
|
||||||
forwarded_allow_ips: str,
|
forwarded_allow_ips: str,
|
||||||
ssl_keyfile: str,
|
ssl_keyfile: str,
|
||||||
ssl_certfile: str,
|
ssl_certfile: str,
|
||||||
@@ -46,7 +52,12 @@ def main(
|
|||||||
parents=True, exist_ok=True
|
parents=True, exist_ok=True
|
||||||
)
|
)
|
||||||
|
|
||||||
set_cli_settings(host=host, port=port, forwarded_allow_ips=forwarded_allow_ips)
|
set_cli_settings(
|
||||||
|
host=host,
|
||||||
|
port=port,
|
||||||
|
forwarded_allow_ips=forwarded_allow_ips,
|
||||||
|
root_path=root_path,
|
||||||
|
)
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
config = uvicorn.Config(
|
config = uvicorn.Config(
|
||||||
@@ -54,6 +65,7 @@ def main(
|
|||||||
loop="uvloop",
|
loop="uvloop",
|
||||||
port=port,
|
port=port,
|
||||||
host=host,
|
host=host,
|
||||||
|
root_path=root_path,
|
||||||
forwarded_allow_ips=forwarded_allow_ips,
|
forwarded_allow_ips=forwarded_allow_ips,
|
||||||
ssl_keyfile=ssl_keyfile,
|
ssl_keyfile=ssl_keyfile,
|
||||||
ssl_certfile=ssl_certfile,
|
ssl_certfile=ssl_certfile,
|
||||||
|
|||||||
+7
-8
@@ -300,6 +300,7 @@ class ThemesSettings(LNbitsSettings):
|
|||||||
lnbits_default_card_rounded: bool = Field(default=True)
|
lnbits_default_card_rounded: bool = Field(default=True)
|
||||||
lnbits_default_card_gradient: bool = Field(default=True)
|
lnbits_default_card_gradient: bool = Field(default=True)
|
||||||
lnbits_default_card_shadow: bool = Field(default=False)
|
lnbits_default_card_shadow: bool = Field(default=False)
|
||||||
|
lnbits_default_burger_menu_background: bool = Field(default=True)
|
||||||
|
|
||||||
|
|
||||||
class OpsSettings(LNbitsSettings):
|
class OpsSettings(LNbitsSettings):
|
||||||
@@ -323,11 +324,6 @@ class AssetSettings(LNbitsSettings):
|
|||||||
"heic",
|
"heic",
|
||||||
"heif",
|
"heif",
|
||||||
"heics",
|
"heics",
|
||||||
"text/plain",
|
|
||||||
"text/json",
|
|
||||||
"text/xml",
|
|
||||||
"application/json",
|
|
||||||
"application/pdf",
|
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
lnbits_asset_thumbnail_width: int = Field(default=128, ge=0)
|
lnbits_asset_thumbnail_width: int = Field(default=128, ge=0)
|
||||||
@@ -1051,7 +1047,7 @@ class EditableSettings(
|
|||||||
|
|
||||||
|
|
||||||
class UpdateSettings(EditableSettings):
|
class UpdateSettings(EditableSettings):
|
||||||
class Config:
|
class Config(EditableSettings.Config):
|
||||||
extra = Extra.forbid
|
extra = Extra.forbid
|
||||||
|
|
||||||
|
|
||||||
@@ -1064,6 +1060,7 @@ class EnvSettings(LNbitsSettings):
|
|||||||
auth_https_only: bool = Field(default=True)
|
auth_https_only: bool = Field(default=True)
|
||||||
host: str = Field(default="127.0.0.1")
|
host: str = Field(default="127.0.0.1")
|
||||||
port: int = Field(default=5000, gt=0)
|
port: int = Field(default=5000, gt=0)
|
||||||
|
root_path: str = Field(default="/")
|
||||||
forwarded_allow_ips: str = Field(default="*")
|
forwarded_allow_ips: str = Field(default="*")
|
||||||
lnbits_title: str = Field(default="LNbits API")
|
lnbits_title: str = Field(default="LNbits API")
|
||||||
lnbits_path: str = Field(default=".")
|
lnbits_path: str = Field(default=".")
|
||||||
@@ -1202,11 +1199,11 @@ class ReadOnlySettings(
|
|||||||
|
|
||||||
|
|
||||||
class Settings(EditableSettings, ReadOnlySettings, TransientSettings, BaseSettings):
|
class Settings(EditableSettings, ReadOnlySettings, TransientSettings, BaseSettings):
|
||||||
class Config:
|
class Config(EditableSettings.Config, BaseSettings.Config): # type: ignore[misc]
|
||||||
env_file = ".env"
|
env_file = ".env"
|
||||||
env_file_encoding = "utf-8"
|
env_file_encoding = "utf-8"
|
||||||
case_sensitive = False
|
case_sensitive = False
|
||||||
json_loads = list_parse_fallback
|
json_loads = list_parse_fallback # type: ignore[assignment]
|
||||||
|
|
||||||
def is_user_allowed(self, user_id: str) -> bool:
|
def is_user_allowed(self, user_id: str) -> bool:
|
||||||
return (
|
return (
|
||||||
@@ -1286,6 +1283,7 @@ class PublicSettings(BaseModel):
|
|||||||
default_card_rounded: bool = Field(alias="defaultCardRounded")
|
default_card_rounded: bool = Field(alias="defaultCardRounded")
|
||||||
default_card_gradient: bool = Field(alias="defaultCardGradient")
|
default_card_gradient: bool = Field(alias="defaultCardGradient")
|
||||||
default_card_shadow: bool = Field(alias="defaultCardShadow")
|
default_card_shadow: bool = Field(alias="defaultCardShadow")
|
||||||
|
default_burger_menu_background: bool = Field(alias="defaultBurgerMenuBackground")
|
||||||
denomination: str | None = Field()
|
denomination: str | None = Field()
|
||||||
extensions: list[str] = Field()
|
extensions: list[str] = Field()
|
||||||
allowed_currencies: list[str] = Field(alias="allowedCurrencies")
|
allowed_currencies: list[str] = Field(alias="allowedCurrencies")
|
||||||
@@ -1349,6 +1347,7 @@ class PublicSettings(BaseModel):
|
|||||||
defaultCardRounded=settings.lnbits_default_card_rounded,
|
defaultCardRounded=settings.lnbits_default_card_rounded,
|
||||||
defaultCardGradient=settings.lnbits_default_card_gradient,
|
defaultCardGradient=settings.lnbits_default_card_gradient,
|
||||||
defaultCardShadow=settings.lnbits_default_card_shadow,
|
defaultCardShadow=settings.lnbits_default_card_shadow,
|
||||||
|
defaultBurgerMenuBackground=settings.lnbits_default_burger_menu_background,
|
||||||
denomination=settings.lnbits_denomination,
|
denomination=settings.lnbits_denomination,
|
||||||
extensions=list(settings.lnbits_installed_extensions_ids),
|
extensions=list(settings.lnbits_installed_extensions_ids),
|
||||||
allowedCurrencies=settings.lnbits_allowed_currencies,
|
allowedCurrencies=settings.lnbits_allowed_currencies,
|
||||||
|
|||||||
+1
-1
File diff suppressed because one or more lines are too long
Vendored
+1
-1
File diff suppressed because one or more lines are too long
Vendored
+18
-18
File diff suppressed because one or more lines are too long
@@ -212,12 +212,15 @@ body.bg-image .q-page-container {
|
|||||||
backdrop-filter: none; /* Ensure the page content is not affected */
|
backdrop-filter: none; /* Ensure the page content is not affected */
|
||||||
}
|
}
|
||||||
|
|
||||||
body.body--dark .q-card:not(.q-dialog .q-card, .lnbits__dialog-card, .q-dialog-plugin--dark),
|
body.body--dark .q-card:not(.q-dialog .q-card, .lnbits__dialog-card, .q-dialog-plugin--dark) {
|
||||||
|
--q-dark: rgba(29, 29, 29, 0.3);
|
||||||
|
background-color: var(--q-dark);
|
||||||
|
}
|
||||||
body.body--dark .q-header,
|
body.body--dark .q-header,
|
||||||
body.body--dark .q-drawer {
|
body.body--dark .q-drawer {
|
||||||
--q-dark: rgba(29, 29, 29, 0.3);
|
--q-dark: rgba(29, 29, 29, 0.3);
|
||||||
background-color: var(--q-dark);
|
background-color: var(--q-dark);
|
||||||
backdrop-filter: blur(6px) brightness(0.8);
|
backdrop-filter: brightness(0.8);
|
||||||
}
|
}
|
||||||
|
|
||||||
body.rounded-ui .q-card,
|
body.rounded-ui .q-card,
|
||||||
@@ -388,11 +391,18 @@ body[data-theme=salvador].card-gradient.body--dark .q-drawer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
body.card-shadow .q-card:not(.q-dialog .q-card, .lnbits__dialog-card, .q-dialog-plugin--dark) {
|
body.card-shadow .q-card:not(.q-dialog .q-card, .lnbits__dialog-card, .q-dialog-plugin--dark) {
|
||||||
filter: drop-shadow(0 10px 24px rgba(0, 0, 0, 0.18));
|
box-shadow: 0 10px 24px rgba(0, 0, 0, 0.18);
|
||||||
}
|
}
|
||||||
|
|
||||||
body.card-shadow.body--dark .q-card:not(.q-dialog .q-card, .lnbits__dialog-card, .q-dialog-plugin--dark) {
|
body.card-shadow.body--dark .q-card:not(.q-dialog .q-card, .lnbits__dialog-card, .q-dialog-plugin--dark) {
|
||||||
filter: drop-shadow(0 12px 28px rgba(0, 0, 0, 0.45));
|
box-shadow: 0 12px 28px rgba(0, 0, 0, 0.45);
|
||||||
|
}
|
||||||
|
|
||||||
|
body.no-burger-background .q-drawer {
|
||||||
|
background-color: transparent !important;
|
||||||
|
background-image: none !important;
|
||||||
|
backdrop-filter: none !important;
|
||||||
|
box-shadow: none !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
:root {
|
:root {
|
||||||
|
|||||||
@@ -490,6 +490,8 @@ window.localisation.en = {
|
|||||||
toggle_card_gradient: 'Toggle gradient on cards',
|
toggle_card_gradient: 'Toggle gradient on cards',
|
||||||
card_shadow: 'Card Shadow',
|
card_shadow: 'Card Shadow',
|
||||||
toggle_card_shadow: 'Toggle shadow on cards',
|
toggle_card_shadow: 'Toggle shadow on cards',
|
||||||
|
burger_menu_background: 'Burger Menu Background',
|
||||||
|
toggle_burger_menu_background: 'Toggle burger menu background',
|
||||||
language: 'Language',
|
language: 'Language',
|
||||||
assets: 'Assets',
|
assets: 'Assets',
|
||||||
max_asset_size_mb: 'Max Asset Size (MB)',
|
max_asset_size_mb: 'Max Asset Size (MB)',
|
||||||
|
|||||||
+19
-51
@@ -1,5 +1,7 @@
|
|||||||
window._lnbitsApi = {
|
window._lnbitsApi = {
|
||||||
request(method, url, apiKey, data, options = {}) {
|
request(method, url, apiKey, data, options = {}) {
|
||||||
|
url = ROOT_PATH + url.replace(/^\/+/, '') // Ensure single slash after rootPath
|
||||||
|
console.log(`API Request: ${method.toUpperCase()} ${url}`)
|
||||||
return axios({
|
return axios({
|
||||||
method: method,
|
method: method,
|
||||||
url: url,
|
url: url,
|
||||||
@@ -67,75 +69,41 @@ window._lnbitsApi = {
|
|||||||
})
|
})
|
||||||
},
|
},
|
||||||
register(username, email, password, password_repeat, invitation_code) {
|
register(username, email, password, password_repeat, invitation_code) {
|
||||||
return axios({
|
return this.request('post', '/api/v1/auth/register', null, {
|
||||||
method: 'POST',
|
username,
|
||||||
url: '/api/v1/auth/register',
|
email,
|
||||||
data: {
|
password,
|
||||||
username,
|
password_repeat,
|
||||||
email,
|
invitation_code
|
||||||
password,
|
|
||||||
password_repeat,
|
|
||||||
invitation_code
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
reset(reset_key, password, password_repeat) {
|
reset(reset_key, password, password_repeat) {
|
||||||
return axios({
|
return this.request('put', '/api/v1/auth/reset', null, {
|
||||||
method: 'PUT',
|
reset_key,
|
||||||
url: '/api/v1/auth/reset',
|
password,
|
||||||
data: {
|
password_repeat
|
||||||
reset_key,
|
|
||||||
password,
|
|
||||||
password_repeat
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
getAuthUser() {
|
getAuthUser() {
|
||||||
return axios({
|
return this.request('get', '/api/v1/auth')
|
||||||
method: 'GET',
|
|
||||||
url: '/api/v1/auth'
|
|
||||||
})
|
|
||||||
},
|
},
|
||||||
login(username, password) {
|
login(username, password) {
|
||||||
return axios({
|
return this.request('post', '/api/v1/auth', null, {username, password})
|
||||||
method: 'POST',
|
|
||||||
url: '/api/v1/auth',
|
|
||||||
data: {username, password}
|
|
||||||
})
|
|
||||||
},
|
},
|
||||||
loginByProvider(provider, headers, data) {
|
loginByProvider(provider, headers, data) {
|
||||||
return axios({
|
return this.request('post', `/api/v1/auth/${provider}`, null, data)
|
||||||
method: 'POST',
|
|
||||||
url: `/api/v1/auth/${provider}`,
|
|
||||||
headers: headers,
|
|
||||||
data
|
|
||||||
})
|
|
||||||
},
|
},
|
||||||
loginUsr(usr) {
|
loginUsr(usr) {
|
||||||
return axios({
|
return this.request('post', '/api/v1/auth/usr', null, {usr})
|
||||||
method: 'POST',
|
|
||||||
url: '/api/v1/auth/usr',
|
|
||||||
data: {usr}
|
|
||||||
})
|
|
||||||
},
|
},
|
||||||
logout() {
|
logout() {
|
||||||
return axios({
|
return this.request('post', '/api/v1/auth/logout')
|
||||||
method: 'POST',
|
|
||||||
url: '/api/v1/auth/logout'
|
|
||||||
})
|
|
||||||
},
|
},
|
||||||
impersonateUser(usr) {
|
impersonateUser(usr) {
|
||||||
return axios({
|
return this.request('POST', '/api/v1/auth/impersonate', null, {usr})
|
||||||
method: 'POST',
|
|
||||||
url: '/api/v1/auth/impersonate',
|
|
||||||
data: {usr}
|
|
||||||
})
|
|
||||||
},
|
},
|
||||||
stopImpersonation() {
|
stopImpersonation() {
|
||||||
return axios({
|
return this.request('DELETE', '/api/v1/auth/impersonate')
|
||||||
method: 'DELETE',
|
|
||||||
url: '/api/v1/auth/impersonate'
|
|
||||||
})
|
|
||||||
},
|
},
|
||||||
getAuthenticatedUser() {
|
getAuthenticatedUser() {
|
||||||
return this.request('get', '/api/v1/auth')
|
return this.request('get', '/api/v1/auth')
|
||||||
|
|||||||
@@ -452,7 +452,9 @@ window.app.component('username-password', {
|
|||||||
confirmationMethod: 'code',
|
confirmationMethod: 'code',
|
||||||
confirmationEmail: '',
|
confirmationEmail: '',
|
||||||
confirmationCode: this.invitationCode || '',
|
confirmationCode: this.invitationCode || '',
|
||||||
showConfirmationCode: false
|
showConfirmationCode: false,
|
||||||
|
showPwd: false,
|
||||||
|
showPwdRepeat: false
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
methods: {
|
methods: {
|
||||||
|
|||||||
@@ -360,18 +360,37 @@ window.app.component('lnbits-payment-list', {
|
|||||||
paymentTableRowKey(row) {
|
paymentTableRowKey(row) {
|
||||||
return row.payment_hash + row.amount
|
return row.payment_hash + row.amount
|
||||||
},
|
},
|
||||||
exportCSV(detailed = false) {
|
async exportCSV(detailed = false) {
|
||||||
// status is important for export but it is not in paymentsTable
|
// status is important for export but it is not in paymentsTable
|
||||||
// because it is manually added with payment detail link and icons
|
// because it is manually added with payment detail link and icons
|
||||||
// and would cause duplication in the list
|
// and would cause duplication in the list
|
||||||
const pagination = this.paymentsTable.pagination
|
const pagination = this.paymentsTable.pagination
|
||||||
const query = {
|
const maxPages = 100
|
||||||
sortby: pagination.sortBy ?? 'time',
|
const limit = 1000
|
||||||
direction: pagination.descending ? 'desc' : 'asc'
|
let payments = []
|
||||||
}
|
|
||||||
const params = new URLSearchParams(query)
|
this.paymentsCSV.loading = true
|
||||||
LNbits.api.getPayments(this.wallet, params).then(response => {
|
try {
|
||||||
let payments = response.data.data.map(this.mapPayment)
|
for (let page = 0; page < maxPages; page++) {
|
||||||
|
const query = {
|
||||||
|
sortby: pagination.sortBy ?? 'time',
|
||||||
|
direction: pagination.descending ? 'desc' : 'asc',
|
||||||
|
limit,
|
||||||
|
offset: page * limit
|
||||||
|
}
|
||||||
|
const params = new URLSearchParams(query)
|
||||||
|
const response = await LNbits.api.getPayments(this.wallet, params)
|
||||||
|
const pagePayments = response.data.data || []
|
||||||
|
payments = payments.concat(pagePayments.map(this.mapPayment))
|
||||||
|
|
||||||
|
if (
|
||||||
|
pagePayments.length < limit ||
|
||||||
|
payments.length >= response.data.total
|
||||||
|
) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let columns = this.paymentsCSV.columns
|
let columns = this.paymentsCSV.columns
|
||||||
|
|
||||||
if (detailed) {
|
if (detailed) {
|
||||||
@@ -400,7 +419,11 @@ window.app.component('lnbits-payment-list', {
|
|||||||
payments,
|
payments,
|
||||||
this.wallet.name + '-payments'
|
this.wallet.name + '-payments'
|
||||||
)
|
)
|
||||||
})
|
} catch (err) {
|
||||||
|
LNbits.utils.notifyApiError(err)
|
||||||
|
} finally {
|
||||||
|
this.paymentsCSV.loading = false
|
||||||
|
}
|
||||||
},
|
},
|
||||||
addFilterTag() {
|
addFilterTag() {
|
||||||
if (!this.exportTagName) return
|
if (!this.exportTagName) return
|
||||||
|
|||||||
@@ -8,6 +8,10 @@ window.app.component('lnbits-qrcode-lnurl', {
|
|||||||
prefix: {
|
prefix: {
|
||||||
type: String,
|
type: String,
|
||||||
default: 'lnurlp'
|
default: 'lnurlp'
|
||||||
|
},
|
||||||
|
href: {
|
||||||
|
type: String,
|
||||||
|
default: ''
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
data() {
|
data() {
|
||||||
@@ -21,7 +25,10 @@ window.app.component('lnbits-qrcode-lnurl', {
|
|||||||
if (this.tab == 'bech32') {
|
if (this.tab == 'bech32') {
|
||||||
const bytes = new TextEncoder().encode(this.url)
|
const bytes = new TextEncoder().encode(this.url)
|
||||||
const bech32 = NostrTools.nip19.encodeBytes('lnurl', bytes)
|
const bech32 = NostrTools.nip19.encodeBytes('lnurl', bytes)
|
||||||
this.lnurl = `lightning:${bech32.toUpperCase()}`
|
this.lnurl =
|
||||||
|
this.href && this.href.trim() !== ''
|
||||||
|
? `${this.href}?lightning=${bech32.toUpperCase()}`
|
||||||
|
: `lightning:${bech32.toUpperCase()}`
|
||||||
} else if (this.tab == 'lud17') {
|
} else if (this.tab == 'lud17') {
|
||||||
if (this.url.startsWith('http://')) {
|
if (this.url.startsWith('http://')) {
|
||||||
this.lnurl = this.url.replace('http://', this.prefix + '://')
|
this.lnurl = this.url.replace('http://', this.prefix + '://')
|
||||||
|
|||||||
@@ -85,6 +85,9 @@ window.app.component('lnbits-qrcode', {
|
|||||||
event.preventDefault()
|
event.preventDefault()
|
||||||
event.stopPropagation()
|
event.stopPropagation()
|
||||||
return false
|
return false
|
||||||
|
} else if (this.href && this.href.startsWith('http')) {
|
||||||
|
window.open(this.href, '_blank')
|
||||||
|
event.preventDefault()
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
async writeNfcTag() {
|
async writeNfcTag() {
|
||||||
|
|||||||
@@ -69,6 +69,14 @@ window.app.component('lnbits-theme', {
|
|||||||
document.body.classList.remove('card-shadow')
|
document.body.classList.remove('card-shadow')
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
'g.burgerMenuChoice'(val) {
|
||||||
|
this.$q.localStorage.set('lnbits.burgerMenu', val)
|
||||||
|
if (val === true) {
|
||||||
|
document.body.classList.remove('no-burger-background')
|
||||||
|
} else {
|
||||||
|
document.body.classList.add('no-burger-background')
|
||||||
|
}
|
||||||
|
},
|
||||||
'g.mobileSimple'(val) {
|
'g.mobileSimple'(val) {
|
||||||
this.$q.localStorage.set('lnbits.mobileSimple', val)
|
this.$q.localStorage.set('lnbits.mobileSimple', val)
|
||||||
if (val === true) {
|
if (val === true) {
|
||||||
@@ -150,6 +158,9 @@ window.app.component('lnbits-theme', {
|
|||||||
if (this.g.cardShadowChoice === true) {
|
if (this.g.cardShadowChoice === true) {
|
||||||
document.body.classList.add('card-shadow')
|
document.body.classList.add('card-shadow')
|
||||||
}
|
}
|
||||||
|
if (this.g.burgerMenuChoice !== true) {
|
||||||
|
document.body.classList.add('no-burger-background')
|
||||||
|
}
|
||||||
if (this.g.bgimageChoice !== '') {
|
if (this.g.bgimageChoice !== '') {
|
||||||
document.body.classList.add('bg-image')
|
document.body.classList.add('bg-image')
|
||||||
document.body.style.setProperty(
|
document.body.style.setProperty(
|
||||||
|
|||||||
@@ -1,16 +1,17 @@
|
|||||||
function eventReaction(amount) {
|
function eventReaction(amount) {
|
||||||
localUrl = ''
|
localUrl = ''
|
||||||
reaction = localStorage.getItem('lnbits.reactions')
|
const reaction =
|
||||||
if (!reaction || reaction === 'None') {
|
Quasar.LocalStorage.getItem('lnbits.reactions') || SETTINGS.defaultReaction
|
||||||
|
if (!reaction || reaction.toLowerCase() === 'none') {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (amount < 0) {
|
if (amount < 0) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
reaction = localStorage.getItem('lnbits.reactions')
|
if (typeof window[reaction] === 'function') {
|
||||||
if (reaction) {
|
window[reaction]()
|
||||||
window[reaction.split('|')[1]]()
|
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.log(e)
|
console.log(e)
|
||||||
|
|||||||
@@ -29,6 +29,10 @@ window.g = Vue.reactive({
|
|||||||
SETTINGS.defaultCardGradient
|
SETTINGS.defaultCardGradient
|
||||||
),
|
),
|
||||||
cardShadowChoice: localStore('lnbits.cardShadow', SETTINGS.defaultCardShadow),
|
cardShadowChoice: localStore('lnbits.cardShadow', SETTINGS.defaultCardShadow),
|
||||||
|
burgerMenuChoice: localStore(
|
||||||
|
'lnbits.burgerMenu',
|
||||||
|
SETTINGS.defaultBurgerMenuBackground
|
||||||
|
),
|
||||||
reactionChoice: localStore('lnbits.reactions', SETTINGS.defaultReaction),
|
reactionChoice: localStore('lnbits.reactions', SETTINGS.defaultReaction),
|
||||||
bgimageChoice: localStore(
|
bgimageChoice: localStore(
|
||||||
'lnbits.backgroundImage',
|
'lnbits.backgroundImage',
|
||||||
@@ -68,7 +72,7 @@ window.dateFormat = 'YYYY-MM-DD HH:mm'
|
|||||||
|
|
||||||
const websocketPrefix =
|
const websocketPrefix =
|
||||||
window.location.protocol === 'http:' ? 'ws://' : 'wss://'
|
window.location.protocol === 'http:' ? 'ws://' : 'wss://'
|
||||||
const websocketUrl = `${websocketPrefix}${window.location.host}/api/v1/ws`
|
const websocketUrl = `${websocketPrefix}${window.location.host}${ROOT_PATH}api/v1/ws`
|
||||||
|
|
||||||
const _access_cookies_for_safari_refresh_do_not_delete = document.cookie
|
const _access_cookies_for_safari_refresh_do_not_delete = document.cookie
|
||||||
|
|
||||||
@@ -83,9 +87,11 @@ addEventListener('online', event => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
if (navigator.serviceWorker != null) {
|
if (navigator.serviceWorker != null) {
|
||||||
navigator.serviceWorker.register('/service-worker.js').then(registration => {
|
navigator.serviceWorker
|
||||||
console.log('Registered events at scope: ', registration.scope)
|
.register(ROOT_PATH + 'service-worker.js')
|
||||||
})
|
.then(registration => {
|
||||||
|
console.log('Registered events at scope: ', registration.scope)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
if (navigator.mediaDevices && navigator.mediaDevices.enumerateDevices) {
|
if (navigator.mediaDevices && navigator.mediaDevices.enumerateDevices) {
|
||||||
|
|||||||
@@ -11,11 +11,16 @@ const quasarConfig = {
|
|||||||
|
|
||||||
const DynamicComponent = {
|
const DynamicComponent = {
|
||||||
async created() {
|
async created() {
|
||||||
|
// no trailing /
|
||||||
|
const rootPath = ROOT_PATH.replace(/\/+$/, '')
|
||||||
const name = this.$route.path.split('/')[1]
|
const name = this.$route.path.split('/')[1]
|
||||||
const path = `/${name}/`
|
const path = `${rootPath}/${name}/`
|
||||||
const routesPath = `/${name}/static/routes.json`
|
const routesPath = `${rootPath}/${name}/static/routes.json`
|
||||||
if (this.$router.getRoutes().some(r => r.path === path)) return
|
if (this.$router.getRoutes().some(r => r.path === path)) return
|
||||||
if (this.$route.fullPath.startsWith('/extensions/builder/preview')) return
|
if (
|
||||||
|
this.$route.fullPath.startsWith(rootPath + '/extensions/builder/preview')
|
||||||
|
)
|
||||||
|
return
|
||||||
fetch(routesPath)
|
fetch(routesPath)
|
||||||
.then(async res => {
|
.then(async res => {
|
||||||
if (!res.ok) throw new Error('No dynamic routes found')
|
if (!res.ok) throw new Error('No dynamic routes found')
|
||||||
@@ -38,9 +43,17 @@ const DynamicComponent = {
|
|||||||
let route = RENDERED_ROUTE
|
let route = RENDERED_ROUTE
|
||||||
// append trailing slash only on the root path `/path` -> `/path/`
|
// append trailing slash only on the root path `/path` -> `/path/`
|
||||||
if (route.split('/').length === 2) route += '/'
|
if (route.split('/').length === 2) route += '/'
|
||||||
|
console.log('ROUTE', route)
|
||||||
|
|
||||||
|
console.log('path / fullpath', this.$route.path, this.$route.fullPath)
|
||||||
|
|
||||||
if (route !== this.$route.path) {
|
if (route !== this.$route.path) {
|
||||||
console.log('Redirecting to non-vue route:', this.$route.fullPath)
|
const rootPath = ROOT_PATH.replace(/\/+$/, '')
|
||||||
window.location = this.$route.fullPath
|
console.log(
|
||||||
|
'Redirecting to non-vue route:',
|
||||||
|
rootPath + this.$route.fullPath
|
||||||
|
)
|
||||||
|
// window.location = rootPath + this.$route.fullPath
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -139,7 +152,7 @@ const routes = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
window.router = VueRouter.createRouter({
|
window.router = VueRouter.createRouter({
|
||||||
history: VueRouter.createWebHistory(),
|
history: VueRouter.createWebHistory(ROOT_PATH),
|
||||||
routes
|
routes
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -732,7 +732,8 @@ window.PageAccount = {
|
|||||||
darkChoice: this.g.settings.defaultDark,
|
darkChoice: this.g.settings.defaultDark,
|
||||||
cardRoundedChoice: this.g.settings.defaultCardRounded,
|
cardRoundedChoice: this.g.settings.defaultCardRounded,
|
||||||
cardGradientChoice: this.g.settings.defaultCardGradient,
|
cardGradientChoice: this.g.settings.defaultCardGradient,
|
||||||
cardShadowChoice: this.g.settings.defaultCardShadow
|
cardShadowChoice: this.g.settings.defaultCardShadow,
|
||||||
|
burgerMenuChoice: this.g.settings.defaultBurgerMenuBackground
|
||||||
}
|
}
|
||||||
this.siteCustomisationChanged(defaults)
|
this.siteCustomisationChanged(defaults)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,17 @@
|
|||||||
window._lnbitsUtils = {
|
window._lnbitsUtils = {
|
||||||
url_for(url) {
|
urlFor(url, noCache = false) {
|
||||||
const _url = new URL(url, window.location.origin)
|
if (url.startsWith('http://') || url.startsWith('https://')) {
|
||||||
_url.searchParams.set('v', window.g.settings.cacheKey)
|
return url
|
||||||
|
}
|
||||||
|
const rootPath = ROOT_PATH.replace(/\/+$/, '')
|
||||||
|
const _url = new URL(rootPath + url, window.location.origin)
|
||||||
|
if (!noCache) _url.searchParams.set('v', window.g.settings.cacheKey)
|
||||||
return _url.toString()
|
return _url.toString()
|
||||||
},
|
},
|
||||||
loadScript(src) {
|
loadScript(src) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const script = document.createElement('script')
|
const script = document.createElement('script')
|
||||||
script.src = this.url_for(src)
|
script.src = this.urlFor(src)
|
||||||
script.onload = () => {
|
script.onload = () => {
|
||||||
resolve()
|
resolve()
|
||||||
}
|
}
|
||||||
@@ -18,7 +22,7 @@ window._lnbitsUtils = {
|
|||||||
})
|
})
|
||||||
},
|
},
|
||||||
async loadTemplate(url) {
|
async loadTemplate(url) {
|
||||||
return fetch(this.url_for(url))
|
return fetch(this.urlFor(url))
|
||||||
.then(response => {
|
.then(response => {
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error(`Failed to load template from ${url}`)
|
throw new Error(`Failed to load template from ${url}`)
|
||||||
|
|||||||
@@ -58,11 +58,15 @@ body.bg-image {
|
|||||||
}
|
}
|
||||||
// transparent background for specific elements
|
// transparent background for specific elements
|
||||||
body.body--dark {
|
body.body--dark {
|
||||||
.q-card:not(.q-dialog .q-card, .lnbits__dialog-card, .q-dialog-plugin--dark),
|
.q-card:not(.q-dialog .q-card, .lnbits__dialog-card, .q-dialog-plugin--dark) {
|
||||||
|
--q-dark: #{color.adjust(#1d1d1d, $alpha: -0.7)};
|
||||||
|
background-color: var(--q-dark);
|
||||||
|
}
|
||||||
|
|
||||||
.q-header,
|
.q-header,
|
||||||
.q-drawer {
|
.q-drawer {
|
||||||
--q-dark: #{color.adjust(#1d1d1d, $alpha: -0.7)};
|
--q-dark: #{color.adjust(#1d1d1d, $alpha: -0.7)};
|
||||||
background-color: var(--q-dark);
|
background-color: var(--q-dark);
|
||||||
backdrop-filter: blur(6px) brightness(0.8);
|
backdrop-filter: brightness(0.8);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -61,12 +61,21 @@ body.rounded-ui {
|
|||||||
|
|
||||||
body.card-shadow {
|
body.card-shadow {
|
||||||
.q-card:not(.q-dialog .q-card, .lnbits__dialog-card, .q-dialog-plugin--dark) {
|
.q-card:not(.q-dialog .q-card, .lnbits__dialog-card, .q-dialog-plugin--dark) {
|
||||||
filter: drop-shadow(0 10px 24px rgba(0, 0, 0, 0.18));
|
box-shadow: 0 10px 24px rgba(0, 0, 0, 0.18);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
body.card-shadow.body--dark {
|
body.card-shadow.body--dark {
|
||||||
.q-card:not(.q-dialog .q-card, .lnbits__dialog-card, .q-dialog-plugin--dark) {
|
.q-card:not(.q-dialog .q-card, .lnbits__dialog-card, .q-dialog-plugin--dark) {
|
||||||
filter: drop-shadow(0 12px 28px rgba(0, 0, 0, 0.45));
|
box-shadow: 0 12px 28px rgba(0, 0, 0, 0.45);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
body.no-burger-background {
|
||||||
|
.q-drawer {
|
||||||
|
background-color: transparent !important;
|
||||||
|
background-image: none !important;
|
||||||
|
backdrop-filter: none !important;
|
||||||
|
box-shadow: none !important;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
-20776
File diff suppressed because it is too large
Load Diff
Vendored
-47
@@ -1,47 +0,0 @@
|
|||||||
/*
|
|
||||||
* DOM element rendering detection
|
|
||||||
* https://davidwalsh.name/detect-node-insertion
|
|
||||||
*/
|
|
||||||
@keyframes chartjs-render-animation {
|
|
||||||
from { opacity: 0.99; }
|
|
||||||
to { opacity: 1; }
|
|
||||||
}
|
|
||||||
|
|
||||||
.chartjs-render-monitor {
|
|
||||||
animation: chartjs-render-animation 0.001s;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* DOM element resizing detection
|
|
||||||
* https://github.com/marcj/css-element-queries
|
|
||||||
*/
|
|
||||||
.chartjs-size-monitor,
|
|
||||||
.chartjs-size-monitor-expand,
|
|
||||||
.chartjs-size-monitor-shrink {
|
|
||||||
position: absolute;
|
|
||||||
direction: ltr;
|
|
||||||
left: 0;
|
|
||||||
top: 0;
|
|
||||||
right: 0;
|
|
||||||
bottom: 0;
|
|
||||||
overflow: hidden;
|
|
||||||
pointer-events: none;
|
|
||||||
visibility: hidden;
|
|
||||||
z-index: -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
.chartjs-size-monitor-expand > div {
|
|
||||||
position: absolute;
|
|
||||||
width: 1000000px;
|
|
||||||
height: 1000000px;
|
|
||||||
left: 0;
|
|
||||||
top: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.chartjs-size-monitor-shrink > div {
|
|
||||||
position: absolute;
|
|
||||||
width: 200%;
|
|
||||||
height: 200%;
|
|
||||||
left: 0;
|
|
||||||
top: 0;
|
|
||||||
}
|
|
||||||
Vendored
+867
-497
File diff suppressed because it is too large
Load Diff
Vendored
+2773
-3121
File diff suppressed because it is too large
Load Diff
+222
-132
@@ -1,5 +1,5 @@
|
|||||||
/*!
|
/*!
|
||||||
* qrcode.vue v3.6.0
|
* qrcode.vue v3.9.0
|
||||||
* A Vue.js component to generate QRCode. Both support Vue 2 and Vue 3
|
* A Vue.js component to generate QRCode. Both support Vue 2 and Vue 3
|
||||||
* © 2017-PRESENT @scopewu(https://github.com/scopewu)
|
* © 2017-PRESENT @scopewu(https://github.com/scopewu)
|
||||||
* MIT License.
|
* MIT License.
|
||||||
@@ -909,7 +909,18 @@ var qrcodegen;
|
|||||||
})(qrcodegen || (qrcodegen = {}));
|
})(qrcodegen || (qrcodegen = {}));
|
||||||
var QR = qrcodegen;
|
var QR = qrcodegen;
|
||||||
|
|
||||||
|
var _uid = 0;
|
||||||
|
function getUid() {
|
||||||
|
if (typeof vue.useId === 'function') {
|
||||||
|
return "".concat(vue.useId(), "-").concat(_uid++);
|
||||||
|
}
|
||||||
|
return "vue-".concat(Math.random().toString(36).slice(2), "-").concat(_uid++);
|
||||||
|
}
|
||||||
var defaultErrorCorrectLevel = 'L';
|
var defaultErrorCorrectLevel = 'L';
|
||||||
|
var DEFAULT_QR_SIZE = 100;
|
||||||
|
var DEFAULT_MARGIN = 0;
|
||||||
|
var DEFAULT_IMAGE_SIZE_RATIO = 0.1;
|
||||||
|
var IMAGE_EXCAVATE_THICKNESS = 2;
|
||||||
var ErrorCorrectLevelMap = {
|
var ErrorCorrectLevelMap = {
|
||||||
L: QR.QrCode.Ecc.LOW,
|
L: QR.QrCode.Ecc.LOW,
|
||||||
M: QR.QrCode.Ecc.MEDIUM,
|
M: QR.QrCode.Ecc.MEDIUM,
|
||||||
@@ -929,74 +940,139 @@ var SUPPORTS_PATH2D = (function () {
|
|||||||
function validErrorCorrectLevel(level) {
|
function validErrorCorrectLevel(level) {
|
||||||
return level in ErrorCorrectLevelMap;
|
return level in ErrorCorrectLevelMap;
|
||||||
}
|
}
|
||||||
|
function getNeighborFlags(modules, row, col) {
|
||||||
|
var north = row > 0 ? modules[row - 1][col] : false;
|
||||||
|
var south = row < modules.length - 1 ? modules[row + 1][col] : false;
|
||||||
|
var west = col > 0 ? modules[row][col - 1] : false;
|
||||||
|
var east = col < modules[row].length - 1 ? modules[row][col + 1] : false;
|
||||||
|
return {
|
||||||
|
nw: !north && !west,
|
||||||
|
ne: !north && !east,
|
||||||
|
se: !south && !east,
|
||||||
|
sw: !south && !west,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
function generateRoundedPath(modules, margin, radius) {
|
||||||
|
if (margin === void 0) { margin = 0; }
|
||||||
|
if (radius === void 0) { radius = 0; }
|
||||||
|
var pathSegments = [];
|
||||||
|
var r = Math.min(radius, 0.5);
|
||||||
|
for (var row = 0; row < modules.length; row++) {
|
||||||
|
for (var col = 0; col < modules[row].length; col++) {
|
||||||
|
if (!modules[row][col])
|
||||||
|
continue;
|
||||||
|
var _a = getNeighborFlags(modules, row, col), nw = _a.nw, ne = _a.ne, se = _a.se, sw = _a.sw;
|
||||||
|
var x = col + margin;
|
||||||
|
var y = row + margin;
|
||||||
|
pathSegments.push("M".concat(x + (nw ? r : 0), " ").concat(y), "L".concat(x + 1 - (ne ? r : 0), " ").concat(y));
|
||||||
|
if (ne) {
|
||||||
|
pathSegments.push("A".concat(r, " ").concat(r, " 0 0 1 ").concat(x + 1, " ").concat(y + r));
|
||||||
|
}
|
||||||
|
pathSegments.push("L".concat(x + 1, " ").concat(y + 1 - (se ? r : 0)));
|
||||||
|
if (se) {
|
||||||
|
pathSegments.push("A".concat(r, " ").concat(r, " 0 0 1 ").concat(x + 1 - r, " ").concat(y + 1));
|
||||||
|
}
|
||||||
|
pathSegments.push("L".concat(x + (sw ? r : 0), " ").concat(y + 1));
|
||||||
|
if (sw) {
|
||||||
|
pathSegments.push("A".concat(r, " ").concat(r, " 0 0 1 ").concat(x, " ").concat(y + 1 - r));
|
||||||
|
}
|
||||||
|
pathSegments.push("L".concat(x, " ").concat(y + (nw ? r : 0)));
|
||||||
|
if (nw) {
|
||||||
|
pathSegments.push("A".concat(r, " ").concat(r, " 0 0 1 ").concat(x + r, " ").concat(y));
|
||||||
|
}
|
||||||
|
pathSegments.push('z');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return pathSegments.join('');
|
||||||
|
}
|
||||||
function generatePath(modules, margin) {
|
function generatePath(modules, margin) {
|
||||||
if (margin === void 0) { margin = 0; }
|
if (margin === void 0) { margin = 0; }
|
||||||
var ops = [];
|
var pathSegments = [];
|
||||||
modules.forEach(function (row, y) {
|
for (var y = 0; y < modules.length; y++) {
|
||||||
|
var row = modules[y];
|
||||||
var start = null;
|
var start = null;
|
||||||
row.forEach(function (cell, x) {
|
for (var x = 0; x < row.length; x++) {
|
||||||
|
var cell = row[x];
|
||||||
if (!cell && start !== null) {
|
if (!cell && start !== null) {
|
||||||
// M0 0h7v1H0z injects the space with the move and drops the comma,
|
// M0 0h7v1H0z injects the space with the move and drops the comma,
|
||||||
// saving a char per operation
|
pathSegments.push("M".concat(start + margin, " ").concat(y + margin, "h").concat(x - start, "v1H").concat(start + margin, "z"));
|
||||||
ops.push("M".concat(start + margin, " ").concat(y + margin, "h").concat(x - start, "v1H").concat(start + margin, "z"));
|
|
||||||
start = null;
|
start = null;
|
||||||
return;
|
continue;
|
||||||
}
|
}
|
||||||
// end of row, clean up or skip
|
// end of row, clean up or skip
|
||||||
if (x === row.length - 1) {
|
if (x === row.length - 1) {
|
||||||
if (!cell) {
|
if (!cell) {
|
||||||
// We would have closed the op above already so this can only mean
|
// We would have closed the op above already so this can only mean
|
||||||
// 2+ light modules in a row.
|
// 2+ light modules in a row.
|
||||||
return;
|
continue;
|
||||||
}
|
}
|
||||||
if (start === null) {
|
if (start === null) {
|
||||||
// Just a single dark module.
|
// Just a single dark module.
|
||||||
ops.push("M".concat(x + margin, ",").concat(y + margin, " h1v1H").concat(x + margin, "z"));
|
pathSegments.push("M".concat(x + margin, ",").concat(y + margin, " h1v1H").concat(x + margin, "z"));
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
// Otherwise finish the current line.
|
// Otherwise finish the current line.
|
||||||
ops.push("M".concat(start + margin, ",").concat(y + margin, " h").concat(x + 1 - start, "v1H").concat(start + margin, "z"));
|
pathSegments.push("M".concat(start + margin, ",").concat(y + margin, " h").concat(x + 1 - start, "v1H").concat(start + margin, "z"));
|
||||||
}
|
}
|
||||||
return;
|
continue;
|
||||||
}
|
}
|
||||||
if (cell && start === null) {
|
if (cell && start === null) {
|
||||||
start = x;
|
start = x;
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
});
|
}
|
||||||
return ops.join('');
|
return pathSegments.join('');
|
||||||
}
|
}
|
||||||
function getImageSettings(cells, size, margin, imageSettings) {
|
function getImageSettings(cells, size, margin, imageSettings) {
|
||||||
var width = imageSettings.width, height = imageSettings.height, imageX = imageSettings.x, imageY = imageSettings.y;
|
var width = imageSettings.width, height = imageSettings.height, imageX = imageSettings.x, imageY = imageSettings.y;
|
||||||
var numCells = cells.length + margin * 2;
|
var numCells = cells.length + margin * 2;
|
||||||
var defaultSize = Math.floor(size * 0.1);
|
var defaultSize = Math.floor(size * DEFAULT_IMAGE_SIZE_RATIO);
|
||||||
var scale = numCells / size;
|
var scale = numCells / size;
|
||||||
var w = (width || defaultSize) * scale;
|
var w = (width || defaultSize) * scale;
|
||||||
var h = (height || defaultSize) * scale;
|
var h = (height || defaultSize) * scale;
|
||||||
var x = imageX == null ? cells.length / 2 - w / 2 : imageX * scale;
|
var x = imageX == null ? cells.length / 2 - w / 2 : imageX * scale;
|
||||||
var y = imageY == null ? cells.length / 2 - h / 2 : imageY * scale;
|
var y = imageY == null ? cells.length / 2 - h / 2 : imageY * scale;
|
||||||
var excavation = null;
|
var borderRadius = (imageSettings.borderRadius || 0) * scale;
|
||||||
if (imageSettings.excavate) {
|
return { x: x, y: y, h: h, w: w, borderRadius: borderRadius };
|
||||||
var floorX = Math.floor(x);
|
|
||||||
var floorY = Math.floor(y);
|
|
||||||
var ceilW = Math.ceil(w + x - floorX);
|
|
||||||
var ceilH = Math.ceil(h + y - floorY);
|
|
||||||
excavation = { x: floorX, y: floorY, w: ceilW, h: ceilH };
|
|
||||||
}
|
|
||||||
return { x: x, y: y, h: h, w: w, excavation: excavation };
|
|
||||||
}
|
}
|
||||||
function excavateModules(modules, excavation) {
|
function useQRCode(props) {
|
||||||
return modules.slice().map(function (row, y) {
|
var margin = vue.computed(function () { var _a; return ((_a = props.margin) !== null && _a !== void 0 ? _a : DEFAULT_MARGIN) >>> 0; });
|
||||||
if (y < excavation.y || y >= excavation.y + excavation.h) {
|
var cells = vue.computed(function () {
|
||||||
return row;
|
var level = validErrorCorrectLevel(props.level) ? props.level : defaultErrorCorrectLevel;
|
||||||
}
|
return QR.QrCode.encodeText(props.value, ErrorCorrectLevelMap[level]).getModules();
|
||||||
return row.map(function (cell, x) {
|
|
||||||
if (x < excavation.x || x >= excavation.x + excavation.w) {
|
|
||||||
return cell;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
var numCells = vue.computed(function () { return cells.value.length + margin.value * 2; });
|
||||||
|
var fgPath = vue.computed(function () {
|
||||||
|
if (props.radius > 0) {
|
||||||
|
return generateRoundedPath(cells.value, margin.value, props.radius);
|
||||||
|
}
|
||||||
|
return generatePath(cells.value, margin.value);
|
||||||
|
});
|
||||||
|
var imageProps = vue.computed(function () {
|
||||||
|
if (!props.imageSettings.src)
|
||||||
|
return null;
|
||||||
|
var settings = getImageSettings(cells.value, props.size, margin.value, props.imageSettings);
|
||||||
|
return {
|
||||||
|
x: settings.x + margin.value,
|
||||||
|
y: settings.y + margin.value,
|
||||||
|
width: settings.w,
|
||||||
|
height: settings.h,
|
||||||
|
borderRadius: settings.borderRadius,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
var imageBorderProps = vue.computed(function () {
|
||||||
|
if (!props.imageSettings.excavate || !imageProps.value)
|
||||||
|
return null;
|
||||||
|
var borderThickness = IMAGE_EXCAVATE_THICKNESS / (props.size / numCells.value);
|
||||||
|
return {
|
||||||
|
x: imageProps.value.x - borderThickness,
|
||||||
|
y: imageProps.value.y - borderThickness,
|
||||||
|
width: imageProps.value.width + borderThickness * 2,
|
||||||
|
height: imageProps.value.height + borderThickness * 2,
|
||||||
|
borderRadius: imageProps.value.borderRadius,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
return { margin: margin, numCells: numCells, cells: cells, fgPath: fgPath, imageProps: imageProps, imageBorderProps: imageBorderProps };
|
||||||
}
|
}
|
||||||
var QRCodeProps = {
|
var QRCodeProps = {
|
||||||
value: {
|
value: {
|
||||||
@@ -1006,7 +1082,7 @@ var QRCodeProps = {
|
|||||||
},
|
},
|
||||||
size: {
|
size: {
|
||||||
type: Number,
|
type: Number,
|
||||||
default: 100,
|
default: DEFAULT_QR_SIZE,
|
||||||
},
|
},
|
||||||
level: {
|
level: {
|
||||||
type: String,
|
type: String,
|
||||||
@@ -1024,7 +1100,7 @@ var QRCodeProps = {
|
|||||||
margin: {
|
margin: {
|
||||||
type: Number,
|
type: Number,
|
||||||
required: false,
|
required: false,
|
||||||
default: 0,
|
default: DEFAULT_MARGIN,
|
||||||
},
|
},
|
||||||
imageSettings: {
|
imageSettings: {
|
||||||
type: Object,
|
type: Object,
|
||||||
@@ -1052,6 +1128,12 @@ var QRCodeProps = {
|
|||||||
required: false,
|
required: false,
|
||||||
default: '#fff',
|
default: '#fff',
|
||||||
},
|
},
|
||||||
|
radius: {
|
||||||
|
type: Number,
|
||||||
|
required: false,
|
||||||
|
default: 0,
|
||||||
|
validator: function (r) { return !isNaN(r) && r >= 0 && r <= 0.5; },
|
||||||
|
},
|
||||||
};
|
};
|
||||||
var QRCodeVueProps = __assign(__assign({}, QRCodeProps), { renderAs: {
|
var QRCodeVueProps = __assign(__assign({}, QRCodeProps), { renderAs: {
|
||||||
type: String,
|
type: String,
|
||||||
@@ -1063,36 +1145,11 @@ var QrcodeSvg = vue.defineComponent({
|
|||||||
name: 'QRCodeSvg',
|
name: 'QRCodeSvg',
|
||||||
props: QRCodeProps,
|
props: QRCodeProps,
|
||||||
setup: function (props) {
|
setup: function (props) {
|
||||||
var numCells = vue.ref(0);
|
var _a = useQRCode(props), numCells = _a.numCells, fgPath = _a.fgPath, imageProps = _a.imageProps, imageBorderProps = _a.imageBorderProps;
|
||||||
var fgPath = vue.ref('');
|
var uid = getUid();
|
||||||
var imageProps;
|
var qrGradientId = "qrcode.vue-gradient-".concat(uid);
|
||||||
var generate = function () {
|
var qrLogoClipPathId = "qrcode.vue-logo-clip-path-".concat(uid);
|
||||||
var value = props.value, _level = props.level, _margin = props.margin;
|
var gradientVNode = vue.computed(function () {
|
||||||
var margin = _margin >>> 0;
|
|
||||||
var level = validErrorCorrectLevel(_level) ? _level : defaultErrorCorrectLevel;
|
|
||||||
var cells = QR.QrCode.encodeText(value, ErrorCorrectLevelMap[level]).getModules();
|
|
||||||
numCells.value = cells.length + margin * 2;
|
|
||||||
if (props.imageSettings.src) {
|
|
||||||
var imageSettings = getImageSettings(cells, props.size, margin, props.imageSettings);
|
|
||||||
imageProps = {
|
|
||||||
x: imageSettings.x + margin,
|
|
||||||
y: imageSettings.y + margin,
|
|
||||||
width: imageSettings.w,
|
|
||||||
height: imageSettings.h,
|
|
||||||
};
|
|
||||||
if (imageSettings.excavation) {
|
|
||||||
cells = excavateModules(cells, imageSettings.excavation);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Drawing strategy: instead of a rect per module, we're going to create a
|
|
||||||
// single path for the dark modules and layer that on top of a light rect,
|
|
||||||
// for a total of 2 DOM nodes. We pay a bit more in string concat but that's
|
|
||||||
// way faster than DOM ops.
|
|
||||||
// For level 1, 441 nodes -> 2
|
|
||||||
// For level 40, 31329 -> 2
|
|
||||||
fgPath.value = generatePath(cells, margin);
|
|
||||||
};
|
|
||||||
var renderGradient = function () {
|
|
||||||
if (!props.gradient)
|
if (!props.gradient)
|
||||||
return null;
|
return null;
|
||||||
var gradientProps = props.gradientType === 'linear'
|
var gradientProps = props.gradientType === 'linear'
|
||||||
@@ -1109,7 +1166,7 @@ var QrcodeSvg = vue.defineComponent({
|
|||||||
fx: '50%',
|
fx: '50%',
|
||||||
fy: '50%',
|
fy: '50%',
|
||||||
};
|
};
|
||||||
return vue.h(props.gradientType === 'linear' ? 'linearGradient' : 'radialGradient', __assign({ id: 'qr-gradient' }, gradientProps), [
|
return vue.h(props.gradientType === 'linear' ? 'linearGradient' : 'radialGradient', __assign({ id: qrGradientId }, gradientProps), [
|
||||||
vue.h('stop', {
|
vue.h('stop', {
|
||||||
offset: '0%',
|
offset: '0%',
|
||||||
style: { stopColor: props.gradientStartColor },
|
style: { stopColor: props.gradientStartColor },
|
||||||
@@ -1119,27 +1176,52 @@ var QrcodeSvg = vue.defineComponent({
|
|||||||
style: { stopColor: props.gradientEndColor },
|
style: { stopColor: props.gradientEndColor },
|
||||||
}),
|
}),
|
||||||
]);
|
]);
|
||||||
};
|
});
|
||||||
generate();
|
var clipPathVNode = vue.computed(function () {
|
||||||
vue.onUpdated(generate);
|
if (!imageProps.value)
|
||||||
|
return null;
|
||||||
|
var borderRadius = imageProps.value.borderRadius;
|
||||||
|
if (borderRadius <= 0)
|
||||||
|
return null;
|
||||||
|
return vue.h('clipPath', { id: qrLogoClipPathId }, [
|
||||||
|
vue.h('rect', {
|
||||||
|
x: imageProps.value.x,
|
||||||
|
y: imageProps.value.y,
|
||||||
|
width: imageProps.value.width,
|
||||||
|
height: imageProps.value.height,
|
||||||
|
rx: borderRadius,
|
||||||
|
ry: borderRadius,
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
});
|
||||||
return function () { return vue.h('svg', {
|
return function () { return vue.h('svg', {
|
||||||
width: props.size,
|
width: props.size,
|
||||||
height: props.size,
|
height: props.size,
|
||||||
'shape-rendering': "crispEdges",
|
|
||||||
xmlns: 'http://www.w3.org/2000/svg',
|
xmlns: 'http://www.w3.org/2000/svg',
|
||||||
viewBox: "0 0 ".concat(numCells.value, " ").concat(numCells.value),
|
viewBox: "0 0 ".concat(numCells.value, " ").concat(numCells.value),
|
||||||
|
role: 'img',
|
||||||
|
'aria-label': props.value,
|
||||||
}, [
|
}, [
|
||||||
vue.h('defs', {}, [renderGradient()]),
|
vue.h('defs', {}, [gradientVNode.value, clipPathVNode.value]),
|
||||||
vue.h('rect', {
|
vue.h('rect', {
|
||||||
width: '100%',
|
width: '100%',
|
||||||
height: '100%',
|
height: '100%',
|
||||||
fill: props.background,
|
fill: props.background,
|
||||||
}),
|
}),
|
||||||
vue.h('path', {
|
vue.h('path', {
|
||||||
fill: props.gradient ? 'url(#qr-gradient)' : props.foreground,
|
fill: props.gradient ? "url(#".concat(qrGradientId, ")") : props.foreground,
|
||||||
d: fgPath.value,
|
d: fgPath.value,
|
||||||
}),
|
}),
|
||||||
props.imageSettings.src && vue.h('image', __assign({ href: props.imageSettings.src }, imageProps)),
|
imageBorderProps.value && vue.h('rect', {
|
||||||
|
x: imageBorderProps.value.x,
|
||||||
|
y: imageBorderProps.value.y,
|
||||||
|
width: imageBorderProps.value.width,
|
||||||
|
height: imageBorderProps.value.height,
|
||||||
|
fill: props.background,
|
||||||
|
rx: imageBorderProps.value.borderRadius,
|
||||||
|
ry: imageBorderProps.value.borderRadius,
|
||||||
|
}),
|
||||||
|
props.imageSettings.src && imageProps.value && vue.h('image', __assign(__assign({ href: props.imageSettings.src }, imageProps.value), (imageProps.value.borderRadius > 0 ? { 'clip-path': "url(#".concat(qrLogoClipPathId, ")") } : {}))),
|
||||||
]); };
|
]); };
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -1147,81 +1229,89 @@ var QrcodeCanvas = vue.defineComponent({
|
|||||||
name: 'QRCodeCanvas',
|
name: 'QRCodeCanvas',
|
||||||
props: QRCodeProps,
|
props: QRCodeProps,
|
||||||
setup: function (props, ctx) {
|
setup: function (props, ctx) {
|
||||||
|
var _a = useQRCode(props), margin = _a.margin, cells = _a.cells, numCells = _a.numCells, fgPath = _a.fgPath, imageProps = _a.imageProps, imageBorderProps = _a.imageBorderProps;
|
||||||
var canvasEl = vue.ref(null);
|
var canvasEl = vue.ref(null);
|
||||||
var imageRef = vue.ref(null);
|
var imageEl = vue.ref(null);
|
||||||
|
var drawRoundedRect = function (ctx, x, y, width, height, radius) {
|
||||||
|
ctx.beginPath();
|
||||||
|
if (ctx.roundRect) {
|
||||||
|
ctx.roundRect(x, y, width, height, radius);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
ctx.rect(x, y, width, height);
|
||||||
|
}
|
||||||
|
};
|
||||||
var generate = function () {
|
var generate = function () {
|
||||||
var value = props.value, _level = props.level, size = props.size, _margin = props.margin, background = props.background, foreground = props.foreground, gradient = props.gradient, gradientType = props.gradientType, gradientStartColor = props.gradientStartColor, gradientEndColor = props.gradientEndColor;
|
var size = props.size, background = props.background, foreground = props.foreground, gradient = props.gradient, gradientType = props.gradientType, gradientStartColor = props.gradientStartColor, gradientEndColor = props.gradientEndColor;
|
||||||
var margin = _margin >>> 0;
|
|
||||||
var level = validErrorCorrectLevel(_level) ? _level : defaultErrorCorrectLevel;
|
|
||||||
var canvas = canvasEl.value;
|
var canvas = canvasEl.value;
|
||||||
if (!canvas) {
|
if (!canvas) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
var ctx = canvas.getContext('2d');
|
var canvasCtx = canvas.getContext('2d');
|
||||||
if (!ctx) {
|
if (!canvasCtx) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
var cells = QR.QrCode.encodeText(value, ErrorCorrectLevelMap[level]).getModules();
|
var image = imageEl.value;
|
||||||
var numCells = cells.length + margin * 2;
|
var devicePixelRatio = typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1;
|
||||||
var image = imageRef.value;
|
var scale = (size / numCells.value) * devicePixelRatio;
|
||||||
var imageProps = { x: 0, y: 0, width: 0, height: 0 };
|
|
||||||
var showImage = props.imageSettings.src && image != null && image.naturalWidth !== 0 && image.naturalHeight !== 0;
|
|
||||||
if (showImage) {
|
|
||||||
var imageSettings = getImageSettings(cells, props.size, margin, props.imageSettings);
|
|
||||||
imageProps = {
|
|
||||||
x: imageSettings.x + margin,
|
|
||||||
y: imageSettings.y + margin,
|
|
||||||
width: imageSettings.w,
|
|
||||||
height: imageSettings.h,
|
|
||||||
};
|
|
||||||
if (imageSettings.excavation) {
|
|
||||||
cells = excavateModules(cells, imageSettings.excavation);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var devicePixelRatio = window.devicePixelRatio || 1;
|
|
||||||
var scale = (size / numCells) * devicePixelRatio;
|
|
||||||
canvas.height = canvas.width = size * devicePixelRatio;
|
canvas.height = canvas.width = size * devicePixelRatio;
|
||||||
ctx.scale(scale, scale);
|
canvasCtx.setTransform(scale, 0, 0, scale, 0, 0);
|
||||||
ctx.fillStyle = background;
|
canvasCtx.fillStyle = background;
|
||||||
ctx.fillRect(0, 0, numCells, numCells);
|
canvasCtx.fillRect(0, 0, numCells.value, numCells.value);
|
||||||
if (gradient) {
|
if (gradient) {
|
||||||
var grad = void 0;
|
var grad = void 0;
|
||||||
if (gradientType === 'linear') {
|
if (gradientType === 'linear') {
|
||||||
grad = ctx.createLinearGradient(0, 0, numCells, numCells);
|
grad = canvasCtx.createLinearGradient(0, 0, numCells.value, numCells.value);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
grad = ctx.createRadialGradient(numCells / 2, numCells / 2, 0, numCells / 2, numCells / 2, numCells / 2);
|
grad = canvasCtx.createRadialGradient(numCells.value / 2, numCells.value / 2, 0, numCells.value / 2, numCells.value / 2, numCells.value / 2);
|
||||||
}
|
}
|
||||||
grad.addColorStop(0, gradientStartColor);
|
grad.addColorStop(0, gradientStartColor);
|
||||||
grad.addColorStop(1, gradientEndColor);
|
grad.addColorStop(1, gradientEndColor);
|
||||||
ctx.fillStyle = grad;
|
canvasCtx.fillStyle = grad;
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
ctx.fillStyle = foreground;
|
canvasCtx.fillStyle = foreground;
|
||||||
}
|
}
|
||||||
if (SUPPORTS_PATH2D) {
|
if (SUPPORTS_PATH2D) {
|
||||||
ctx.fill(new Path2D(generatePath(cells, margin)));
|
canvasCtx.fill(new Path2D(fgPath.value));
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
cells.forEach(function (row, rdx) {
|
cells.value.forEach(function (row, rdx) {
|
||||||
row.forEach(function (cell, cdx) {
|
row.forEach(function (cell, cdx) {
|
||||||
if (cell) {
|
if (cell) {
|
||||||
ctx.fillRect(cdx + margin, rdx + margin, 1, 1);
|
canvasCtx.fillRect(cdx + margin.value, rdx + margin.value, 1, 1);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (showImage) {
|
var showImage = props.imageSettings.src && image && image.naturalWidth !== 0 && image.naturalHeight !== 0;
|
||||||
ctx.drawImage(image, imageProps.x, imageProps.y, imageProps.width, imageProps.height);
|
if (showImage && imageProps.value) {
|
||||||
|
if (imageBorderProps.value) {
|
||||||
|
var imageBorder = imageBorderProps.value;
|
||||||
|
canvasCtx.fillStyle = props.background;
|
||||||
|
drawRoundedRect(canvasCtx, imageBorder.x, imageBorder.y, imageBorder.width, imageBorder.height, imageBorder.borderRadius);
|
||||||
|
canvasCtx.fill();
|
||||||
|
}
|
||||||
|
var borderRadius = imageProps.value.borderRadius;
|
||||||
|
if (borderRadius > 0) {
|
||||||
|
canvasCtx.save();
|
||||||
|
drawRoundedRect(canvasCtx, imageProps.value.x, imageProps.value.y, imageProps.value.width, imageProps.value.height, borderRadius);
|
||||||
|
canvasCtx.clip();
|
||||||
|
canvasCtx.drawImage(image, imageProps.value.x, imageProps.value.y, imageProps.value.width, imageProps.value.height);
|
||||||
|
canvasCtx.restore();
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
canvasCtx.drawImage(image, imageProps.value.x, imageProps.value.y, imageProps.value.width, imageProps.value.height);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
vue.onMounted(generate);
|
vue.onMounted(generate);
|
||||||
vue.onUpdated(generate);
|
vue.watchEffect(generate);
|
||||||
var style = ctx.attrs.style;
|
|
||||||
return function () { return vue.h(vue.Fragment, [
|
return function () { return vue.h(vue.Fragment, [
|
||||||
vue.h('canvas', __assign(__assign({}, ctx.attrs), { ref: canvasEl, style: __assign(__assign({}, style), { width: "".concat(props.size, "px"), height: "".concat(props.size, "px") }) })),
|
vue.h('canvas', __assign(__assign({}, ctx.attrs), { ref: canvasEl, role: 'img', 'aria-label': props.value, style: __assign(__assign({}, ctx.attrs.style), { width: "".concat(props.size, "px"), height: "".concat(props.size, "px") }) })),
|
||||||
props.imageSettings.src && vue.h('img', {
|
props.imageSettings.src && vue.h('img', {
|
||||||
ref: imageRef,
|
ref: imageEl,
|
||||||
src: props.imageSettings.src,
|
src: props.imageSettings.src,
|
||||||
style: { display: 'none' },
|
style: { display: 'none' },
|
||||||
onLoad: generate,
|
onLoad: generate,
|
||||||
@@ -1231,23 +1321,23 @@ var QrcodeCanvas = vue.defineComponent({
|
|||||||
});
|
});
|
||||||
var QrcodeVue = vue.defineComponent({
|
var QrcodeVue = vue.defineComponent({
|
||||||
name: 'Qrcode',
|
name: 'Qrcode',
|
||||||
render: function () {
|
|
||||||
var _a = this.$props, renderAs = _a.renderAs, value = _a.value, size = _a.size, margin = _a.margin, level = _a.level, background = _a.background, foreground = _a.foreground, imageSettings = _a.imageSettings, gradient = _a.gradient, gradientType = _a.gradientType, gradientStartColor = _a.gradientStartColor, gradientEndColor = _a.gradientEndColor;
|
|
||||||
return vue.h(renderAs === 'svg' ? QrcodeSvg : QrcodeCanvas, {
|
|
||||||
value: value,
|
|
||||||
size: size,
|
|
||||||
margin: margin,
|
|
||||||
level: level,
|
|
||||||
background: background,
|
|
||||||
foreground: foreground,
|
|
||||||
imageSettings: imageSettings,
|
|
||||||
gradient: gradient,
|
|
||||||
gradientType: gradientType,
|
|
||||||
gradientStartColor: gradientStartColor,
|
|
||||||
gradientEndColor: gradientEndColor,
|
|
||||||
});
|
|
||||||
},
|
|
||||||
props: QRCodeVueProps,
|
props: QRCodeVueProps,
|
||||||
|
setup: function (props) {
|
||||||
|
return function () { return vue.h(props.renderAs === 'svg' ? QrcodeSvg : QrcodeCanvas, {
|
||||||
|
value: props.value,
|
||||||
|
size: props.size,
|
||||||
|
margin: props.margin,
|
||||||
|
level: props.level,
|
||||||
|
background: props.background,
|
||||||
|
foreground: props.foreground,
|
||||||
|
imageSettings: props.imageSettings,
|
||||||
|
gradient: props.gradient,
|
||||||
|
gradientType: props.gradientType,
|
||||||
|
gradientStartColor: props.gradientStartColor,
|
||||||
|
gradientEndColor: props.gradientEndColor,
|
||||||
|
radius: props.radius,
|
||||||
|
}); };
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
exports.QrcodeCanvas = QrcodeCanvas;
|
exports.QrcodeCanvas = QrcodeCanvas;
|
||||||
|
|||||||
Vendored
+15
-28
@@ -43,8 +43,7 @@ summary {
|
|||||||
abbr[title] {
|
abbr[title] {
|
||||||
border-bottom: none;
|
border-bottom: none;
|
||||||
text-decoration: underline;
|
text-decoration: underline;
|
||||||
-webkit-text-decoration: underline dotted;
|
text-decoration: underline dotted;
|
||||||
text-decoration: underline dotted;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -200,8 +199,7 @@ input[type=search]::-webkit-search-decoration {
|
|||||||
.material-symbols-outlined,
|
.material-symbols-outlined,
|
||||||
.material-symbols-rounded,
|
.material-symbols-rounded,
|
||||||
.material-symbols-sharp {
|
.material-symbols-sharp {
|
||||||
-webkit-user-select: none;
|
user-select: none;
|
||||||
user-select: none;
|
|
||||||
cursor: inherit;
|
cursor: inherit;
|
||||||
font-size: inherit;
|
font-size: inherit;
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
@@ -998,8 +996,7 @@ input[type=search]::-webkit-search-decoration {
|
|||||||
height: 1px;
|
height: 1px;
|
||||||
}
|
}
|
||||||
.q-checkbox__bg, .q-checkbox__icon-container {
|
.q-checkbox__bg, .q-checkbox__icon-container {
|
||||||
-webkit-user-select: none;
|
user-select: none;
|
||||||
user-select: none;
|
|
||||||
}
|
}
|
||||||
.q-checkbox__bg {
|
.q-checkbox__bg {
|
||||||
top: 25%;
|
top: 25%;
|
||||||
@@ -2212,8 +2209,7 @@ body.q-ios-padding .q-dialog__inner > div {
|
|||||||
width: 100%;
|
width: 100%;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
outline: 0 !important;
|
outline: 0 !important;
|
||||||
-webkit-user-select: auto;
|
user-select: auto;
|
||||||
user-select: auto;
|
|
||||||
}
|
}
|
||||||
.q-field__native:-webkit-autofill, .q-field__input:-webkit-autofill {
|
.q-field__native:-webkit-autofill, .q-field__input:-webkit-autofill {
|
||||||
-webkit-animation-name: q-autofill;
|
-webkit-animation-name: q-autofill;
|
||||||
@@ -3039,8 +3035,7 @@ body.body--dark .q-knob--editable:focus:before {
|
|||||||
z-index: 2001;
|
z-index: 2001;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
width: 15px;
|
width: 15px;
|
||||||
-webkit-user-select: none;
|
user-select: none;
|
||||||
user-select: none;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.q-layout, .q-header, .q-footer, .q-page {
|
.q-layout, .q-header, .q-footer, .q-page {
|
||||||
@@ -3297,8 +3292,7 @@ body.platform-ios .q-layout--containerized {
|
|||||||
height: 1px;
|
height: 1px;
|
||||||
}
|
}
|
||||||
.q-radio__bg, .q-radio__icon-container {
|
.q-radio__bg, .q-radio__icon-container {
|
||||||
-webkit-user-select: none;
|
user-select: none;
|
||||||
user-select: none;
|
|
||||||
}
|
}
|
||||||
.q-radio__bg {
|
.q-radio__bg {
|
||||||
top: 25%;
|
top: 25%;
|
||||||
@@ -3782,8 +3776,7 @@ body.platform-ios:not(.native-mobile) .q-dialog__inner--top .q-select__dialog--f
|
|||||||
.q-slide-item__content {
|
.q-slide-item__content {
|
||||||
background: inherit;
|
background: inherit;
|
||||||
transition: transform 0.2s ease-in;
|
transition: transform 0.2s ease-in;
|
||||||
-webkit-user-select: none;
|
user-select: none;
|
||||||
user-select: none;
|
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -4156,8 +4149,7 @@ body.desktop .q-slider.q-slider--enabled .q-slider__track-container:hover .q-sli
|
|||||||
}
|
}
|
||||||
.q-splitter__separator {
|
.q-splitter__separator {
|
||||||
background-color: rgba(0, 0, 0, 0.12);
|
background-color: rgba(0, 0, 0, 0.12);
|
||||||
-webkit-user-select: none;
|
user-select: none;
|
||||||
user-select: none;
|
|
||||||
position: relative;
|
position: relative;
|
||||||
z-index: 1;
|
z-index: 1;
|
||||||
}
|
}
|
||||||
@@ -4246,8 +4238,7 @@ body.desktop .q-slider.q-slider--enabled .q-slider__track-container:hover .q-sli
|
|||||||
color: #000;
|
color: #000;
|
||||||
}
|
}
|
||||||
.q-stepper__tab--navigation {
|
.q-stepper__tab--navigation {
|
||||||
-webkit-user-select: none;
|
user-select: none;
|
||||||
user-select: none;
|
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
.q-stepper__tab--active, .q-stepper__tab--done {
|
.q-stepper__tab--active, .q-stepper__tab--done {
|
||||||
@@ -4479,8 +4470,7 @@ body.desktop .q-slider.q-slider--enabled .q-slider__track-container:hover .q-sli
|
|||||||
.q-table th {
|
.q-table th {
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
-webkit-user-select: none;
|
user-select: none;
|
||||||
user-select: none;
|
|
||||||
}
|
}
|
||||||
.q-table th.sortable {
|
.q-table th.sortable {
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
@@ -5484,8 +5474,7 @@ body.desktop .q-table > tbody > tr:not(.q-tr--no-hover):hover > td:not(.q-td--no
|
|||||||
width: 0.5em;
|
width: 0.5em;
|
||||||
height: 0.5em;
|
height: 0.5em;
|
||||||
transition: left 0.22s cubic-bezier(0.4, 0, 0.2, 1);
|
transition: left 0.22s cubic-bezier(0.4, 0, 0.2, 1);
|
||||||
-webkit-user-select: none;
|
user-select: none;
|
||||||
user-select: none;
|
|
||||||
z-index: 0;
|
z-index: 0;
|
||||||
}
|
}
|
||||||
.q-toggle__thumb:after {
|
.q-toggle__thumb:after {
|
||||||
@@ -10337,6 +10326,7 @@ body.body--dark .inset-shadow-down {
|
|||||||
.glossy {
|
.glossy {
|
||||||
background-image: linear-gradient(to bottom, rgba(255, 255, 255, 0.3), rgba(255, 255, 255, 0) 50%, rgba(0, 0, 0, 0.12) 51%, rgba(0, 0, 0, 0.04)) !important;
|
background-image: linear-gradient(to bottom, rgba(255, 255, 255, 0.3), rgba(255, 255, 255, 0) 50%, rgba(0, 0, 0, 0.12) 51%, rgba(0, 0, 0, 0.04)) !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
.q-placeholder::placeholder {
|
.q-placeholder::placeholder {
|
||||||
color: inherit;
|
color: inherit;
|
||||||
opacity: 0.7;
|
opacity: 0.7;
|
||||||
@@ -10368,8 +10358,7 @@ body.body--dark .inset-shadow-down {
|
|||||||
text-decoration: none;
|
text-decoration: none;
|
||||||
}
|
}
|
||||||
.q-link--focusable:focus-visible {
|
.q-link--focusable:focus-visible {
|
||||||
-webkit-text-decoration: underline dashed currentColor 1px;
|
text-decoration: underline dashed currentColor 1px;
|
||||||
text-decoration: underline dashed currentColor 1px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
body.electron .q-electron-drag {
|
body.electron .q-electron-drag {
|
||||||
@@ -10386,8 +10375,7 @@ img.responsive {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.non-selectable {
|
.non-selectable {
|
||||||
-webkit-user-select: none !important;
|
user-select: none !important;
|
||||||
user-select: none !important;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.scroll,
|
.scroll,
|
||||||
@@ -11045,8 +11033,7 @@ body.q-ios-padding .fullscreen {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.q-touch {
|
.q-touch {
|
||||||
-webkit-user-select: none;
|
user-select: none;
|
||||||
user-select: none;
|
|
||||||
user-drag: none;
|
user-drag: none;
|
||||||
-khtml-user-drag: none;
|
-khtml-user-drag: none;
|
||||||
-webkit-user-drag: none;
|
-webkit-user-drag: none;
|
||||||
|
|||||||
+78
-79
File diff suppressed because one or more lines are too long
+3
-3
File diff suppressed because one or more lines are too long
+174
-777
File diff suppressed because it is too large
Load Diff
+9
-9
File diff suppressed because one or more lines are too long
@@ -23,6 +23,7 @@
|
|||||||
name="viewport"
|
name="viewport"
|
||||||
content="width=device-width, initial-scale=1, maximum-scale=1, shrink-to-fit=no"
|
content="width=device-width, initial-scale=1, maximum-scale=1, shrink-to-fit=no"
|
||||||
/>
|
/>
|
||||||
|
<link rel="icon" type="image/x-icon" href="{{ ROOT_PATH }}favicon.ico" />
|
||||||
<meta name="mobile-web-app-capable" content="yes" />
|
<meta name="mobile-web-app-capable" content="yes" />
|
||||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||||
<link
|
<link
|
||||||
@@ -32,6 +33,13 @@
|
|||||||
{% if web_manifest %}
|
{% if web_manifest %}
|
||||||
<link async="async" rel="manifest" href="{{ web_manifest }}" />
|
<link async="async" rel="manifest" href="{{ web_manifest }}" />
|
||||||
{% endif %} {% block head_scripts %}{% endblock %}
|
{% endif %} {% block head_scripts %}{% endblock %}
|
||||||
|
<script type="text/javascript">
|
||||||
|
const ROOT_PATH = '{{ ROOT_PATH }}'
|
||||||
|
const RENDERED_ROUTE = '{{ normalize_path(request.path) }}'.replace(
|
||||||
|
ROOT_PATH.replace(/\/+$/, '') || '/',
|
||||||
|
''
|
||||||
|
)
|
||||||
|
</script>
|
||||||
</head>
|
</head>
|
||||||
|
|
||||||
<body data-theme="bitcoin">
|
<body data-theme="bitcoin">
|
||||||
@@ -52,9 +60,7 @@
|
|||||||
v-if="g.user && !g.isPublicPage"
|
v-if="g.user && !g.isPublicPage"
|
||||||
></lnbits-header-wallets>
|
></lnbits-header-wallets>
|
||||||
<!-- block page content from static extensions -->
|
<!-- block page content from static extensions -->
|
||||||
<div
|
<div v-if="$route.path.startsWith(RENDERED_ROUTE)">
|
||||||
v-if="$route.path.startsWith('{{ normalize_path(request.path) }}')"
|
|
||||||
>
|
|
||||||
{% block page %}{% endblock %}
|
{% block page %}{% endblock %}
|
||||||
</div>
|
</div>
|
||||||
<!-- vue router-view -->
|
<!-- vue router-view -->
|
||||||
|
|||||||
@@ -774,7 +774,13 @@ include('components/lnbits-error.vue') %}
|
|||||||
v-model="password"
|
v-model="password"
|
||||||
name="password"
|
name="password"
|
||||||
:label="$t('password') + ' *'"
|
:label="$t('password') + ' *'"
|
||||||
type="password"
|
:type="showPwd ? 'text' : 'password'"
|
||||||
|
><template v-slot:append>
|
||||||
|
<q-icon
|
||||||
|
:name="showPwd ? 'visibility' : 'visibility_off'"
|
||||||
|
class="cursor-pointer"
|
||||||
|
@click="showPwd = !showPwd"
|
||||||
|
/> </template
|
||||||
></q-input>
|
></q-input>
|
||||||
<div class="row justify-end">
|
<div class="row justify-end">
|
||||||
<q-btn
|
<q-btn
|
||||||
@@ -803,16 +809,28 @@ include('components/lnbits-error.vue') %}
|
|||||||
filled
|
filled
|
||||||
v-model="password"
|
v-model="password"
|
||||||
:label="$t('password') + ' *'"
|
:label="$t('password') + ' *'"
|
||||||
type="password"
|
:type="showPwd ? 'text' : 'password'"
|
||||||
:rules="[val => !val || val.length >= 8 || $t('invalid_password')]"
|
:rules="[val => !val || val.length >= 8 || $t('invalid_password')]"
|
||||||
|
><template v-slot:append>
|
||||||
|
<q-icon
|
||||||
|
:name="showPwd ? 'visibility' : 'visibility_off'"
|
||||||
|
class="cursor-pointer"
|
||||||
|
@click="showPwd = !showPwd"
|
||||||
|
/> </template
|
||||||
></q-input>
|
></q-input>
|
||||||
<q-input
|
<q-input
|
||||||
dense
|
dense
|
||||||
filled
|
filled
|
||||||
v-model="passwordRepeat"
|
v-model="passwordRepeat"
|
||||||
:label="$t('password_repeat') + ' *'"
|
:label="$t('password_repeat') + ' *'"
|
||||||
type="password"
|
:type="showPwdRepeat ? 'text' : 'password'"
|
||||||
:rules="[val => !val || val.length >= 8 || $t('invalid_password')]"
|
:rules="[val => !val || val.length >= 8 || $t('invalid_password')]"
|
||||||
|
><template v-slot:append>
|
||||||
|
<q-icon
|
||||||
|
:name="showPwdRepeat ? 'visibility' : 'visibility_off'"
|
||||||
|
class="cursor-pointer"
|
||||||
|
@click="showPwdRepeat = !showPwdRepeat"
|
||||||
|
/> </template
|
||||||
></q-input>
|
></q-input>
|
||||||
<div
|
<div
|
||||||
v-if="confirmationMethodsCount > 1"
|
v-if="confirmationMethodsCount > 1"
|
||||||
@@ -925,16 +943,28 @@ include('components/lnbits-error.vue') %}
|
|||||||
filled
|
filled
|
||||||
v-model="password"
|
v-model="password"
|
||||||
:label="$t('password') + ' *'"
|
:label="$t('password') + ' *'"
|
||||||
type="password"
|
:type="showPwd ? 'text' : 'password'"
|
||||||
:rules="[val => !val || val.length >= 8 || $t('invalid_password')]"
|
:rules="[val => !val || val.length >= 8 || $t('invalid_password')]"
|
||||||
|
><template v-slot:append>
|
||||||
|
<q-icon
|
||||||
|
:name="showPwd ? 'visibility' : 'visibility_off'"
|
||||||
|
class="cursor-pointer"
|
||||||
|
@click="showPwd = !showPwd"
|
||||||
|
/> </template
|
||||||
></q-input>
|
></q-input>
|
||||||
<q-input
|
<q-input
|
||||||
dense
|
dense
|
||||||
filled
|
filled
|
||||||
v-model="passwordRepeat"
|
v-model="passwordRepeat"
|
||||||
:label="$t('password_repeat') + ' *'"
|
:label="$t('password_repeat') + ' *'"
|
||||||
type="password"
|
:type="showPwdRepeat ? 'text' : 'password'"
|
||||||
:rules="[val => !val || val.length >= 8 || $t('invalid_password')]"
|
:rules="[val => !val || val.length >= 8 || $t('invalid_password')]"
|
||||||
|
><template v-slot:append>
|
||||||
|
<q-icon
|
||||||
|
:name="showPwdRepeat ? 'visibility' : 'visibility_off'"
|
||||||
|
class="cursor-pointer"
|
||||||
|
@click="showPwdRepeat = !showPwdRepeat"
|
||||||
|
/> </template
|
||||||
></q-input>
|
></q-input>
|
||||||
<div class="row justify-end">
|
<div class="row justify-end">
|
||||||
<q-btn
|
<q-btn
|
||||||
|
|||||||
@@ -866,6 +866,7 @@
|
|||||||
</q-expansion-item>
|
</q-expansion-item>
|
||||||
</q-card>
|
</q-card>
|
||||||
</q-expansion-item>
|
</q-expansion-item>
|
||||||
|
<q-separator></q-separator>
|
||||||
<q-expansion-item header-class="text-primary text-bold">
|
<q-expansion-item header-class="text-primary text-bold">
|
||||||
<template v-slot:header>
|
<template v-slot:header>
|
||||||
<q-item-section avatar>
|
<q-item-section avatar>
|
||||||
@@ -1175,8 +1176,8 @@
|
|||||||
<q-chip dense color="positive" text-color="white" icon="check"
|
<q-chip dense color="positive" text-color="white" icon="check"
|
||||||
>Checkout</q-chip
|
>Checkout</q-chip
|
||||||
>
|
>
|
||||||
<q-chip dense color="positive" text-color="white" icon="check"
|
<q-chip dense color="warning" text-color="black" icon="schedule"
|
||||||
>Subscriptions</q-chip
|
>Subscriptions coming soon</q-chip
|
||||||
>
|
>
|
||||||
<q-chip dense color="negative" text-color="white" icon="close"
|
<q-chip dense color="negative" text-color="white" icon="close"
|
||||||
>Tap-to-pay</q-chip
|
>Tap-to-pay</q-chip
|
||||||
|
|||||||
@@ -320,6 +320,15 @@
|
|||||||
>
|
>
|
||||||
</q-toggle>
|
</q-toggle>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="col-12 col-sm-6 col-lg-2">
|
||||||
|
<q-toggle
|
||||||
|
type="bool"
|
||||||
|
v-model="formData.lnbits_default_burger_menu_background"
|
||||||
|
color="primary"
|
||||||
|
:label="$t('burger_menu_background')"
|
||||||
|
>
|
||||||
|
</q-toggle>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</q-card-section>
|
</q-card-section>
|
||||||
|
|||||||
@@ -26,7 +26,7 @@
|
|||||||
@click="g.visibleDrawer = !g.visibleDrawer"
|
@click="g.visibleDrawer = !g.visibleDrawer"
|
||||||
></q-btn>
|
></q-btn>
|
||||||
<q-toolbar-title>
|
<q-toolbar-title>
|
||||||
<q-btn flat no-caps dense class="q-mr-sm" size="lg" type="a" href="/">
|
<q-btn flat no-caps dense class="q-mr-sm" size="lg" type="a" :href="utils.urlFor('/', true)">
|
||||||
<q-avatar v-if="g.settings.customLogo" height="30px">
|
<q-avatar v-if="g.settings.customLogo" height="30px">
|
||||||
<img alt="Logo" :src="g.settings.customLogo" />
|
<img alt="Logo" :src="g.settings.customLogo" />
|
||||||
</q-avatar>
|
</q-avatar>
|
||||||
|
|||||||
@@ -7,7 +7,9 @@
|
|||||||
<a :href="logo.url" target="_blank" rel="noopener noreferrer">
|
<a :href="logo.url" target="_blank" rel="noopener noreferrer">
|
||||||
<q-img
|
<q-img
|
||||||
contain
|
contain
|
||||||
:src="$q.dark.isActive ? logo.darkSrc : logo.lightSrc"
|
:src="
|
||||||
|
utils.urlFor($q.dark.isActive ? logo.darkSrc : logo.lightSrc)
|
||||||
|
"
|
||||||
></q-img>
|
></q-img>
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
@@ -18,7 +20,9 @@
|
|||||||
<a :href="logo.url" target="_blank" rel="noopener noreferrer">
|
<a :href="logo.url" target="_blank" rel="noopener noreferrer">
|
||||||
<q-img
|
<q-img
|
||||||
contain
|
contain
|
||||||
:src="$q.dark.isActive ? logo.darkSrc : logo.lightSrc"
|
:src="
|
||||||
|
utils.urlFor($q.dark.isActive ? logo.darkSrc : logo.lightSrc)
|
||||||
|
"
|
||||||
></q-img>
|
></q-img>
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -20,11 +20,14 @@
|
|||||||
clickable
|
clickable
|
||||||
:active="$route.path.startsWith('/' + extension.code)"
|
:active="$route.path.startsWith('/' + extension.code)"
|
||||||
tag="a"
|
tag="a"
|
||||||
:to="'/' + extension.code + '/'"
|
:to="`/${extension.code}/`"
|
||||||
>
|
>
|
||||||
<q-item-section side>
|
<q-item-section side>
|
||||||
<q-avatar size="md">
|
<q-avatar size="md">
|
||||||
<q-img :src="extension.tile" style="max-width: 20px"></q-img>
|
<q-img
|
||||||
|
:src="utils.urlFor(extension.tile)"
|
||||||
|
style="max-width: 20px"
|
||||||
|
></q-img>
|
||||||
</q-avatar>
|
</q-avatar>
|
||||||
</q-item-section>
|
</q-item-section>
|
||||||
<q-item-section>
|
<q-item-section>
|
||||||
|
|||||||
@@ -285,7 +285,9 @@
|
|||||||
>
|
>
|
||||||
<q-avatar size="32px" class="q-mr-md">
|
<q-avatar size="32px" class="q-mr-md">
|
||||||
<q-img
|
<q-img
|
||||||
:src="'{{ static_url_for('static', 'images/google-logo.png') }}'"
|
:src="
|
||||||
|
utils.urlFor('/static/images/google-logo.png')
|
||||||
|
"
|
||||||
></q-img>
|
></q-img>
|
||||||
</q-avatar>
|
</q-avatar>
|
||||||
<div>Google</div>
|
<div>Google</div>
|
||||||
@@ -306,7 +308,9 @@
|
|||||||
>
|
>
|
||||||
<q-avatar size="32px" class="q-mr-md">
|
<q-avatar size="32px" class="q-mr-md">
|
||||||
<q-img
|
<q-img
|
||||||
:src="'{{ static_url_for('static', 'images/github-logo.png') }}'"
|
:src="
|
||||||
|
utils.urlFor('/static/images/github-logo.png')
|
||||||
|
"
|
||||||
></q-img>
|
></q-img>
|
||||||
</q-avatar>
|
</q-avatar>
|
||||||
<div>GitHub</div>
|
<div>GitHub</div>
|
||||||
@@ -601,6 +605,30 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="row q-mb-md">
|
||||||
|
<div class="col-4">
|
||||||
|
<span v-text="$t('burger_menu_background')"></span>
|
||||||
|
</div>
|
||||||
|
<div class="col-8">
|
||||||
|
<q-toggle
|
||||||
|
dense
|
||||||
|
flat
|
||||||
|
round
|
||||||
|
icon="menu_open"
|
||||||
|
v-model="g.burgerMenuChoice"
|
||||||
|
@update:model-value="
|
||||||
|
siteCustomisationChanged({burgerMenuChoice: $event})
|
||||||
|
"
|
||||||
|
>
|
||||||
|
<q-tooltip
|
||||||
|
><span
|
||||||
|
v-text="$t('toggle_burger_menu_background')"
|
||||||
|
></span
|
||||||
|
></q-tooltip>
|
||||||
|
</q-toggle>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="row q-mb-md">
|
<div class="row q-mb-md">
|
||||||
<div class="col-4">
|
<div class="col-4">
|
||||||
<span v-text="$t('toggle_darkmode')"></span>
|
<span v-text="$t('toggle_darkmode')"></span>
|
||||||
|
|||||||
@@ -136,7 +136,7 @@
|
|||||||
</q-card>
|
</q-card>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
v-show="chartData.showPaymentStatus"
|
v-show="chartData.showPaymentTags"
|
||||||
class="col-lg-3 col-md-6 col-sm-12 text-center"
|
class="col-lg-3 col-md-6 col-sm-12 text-center"
|
||||||
>
|
>
|
||||||
<q-card class="q-pt-sm">
|
<q-card class="q-pt-sm">
|
||||||
|
|||||||
@@ -216,8 +216,12 @@
|
|||||||
<q-card-section class="text-subtitle1">
|
<q-card-section class="text-subtitle1">
|
||||||
<span v-text="g.settings.adSpaceTitle"></span>
|
<span v-text="g.settings.adSpaceTitle"></span>
|
||||||
<a :href="ad[0]" class="lnbits-ad" v-for="ad in g.settings.adSpace">
|
<a :href="ad[0]" class="lnbits-ad" v-for="ad in g.settings.adSpace">
|
||||||
<q-img class="q-mb-xs" v-if="$q.dark.isActive" :src="ad[1]"></q-img>
|
<q-img
|
||||||
<q-img class="q-mb-xs" v-else :src="ad[2]"></q-img>
|
class="q-mb-xs"
|
||||||
|
v-if="$q.dark.isActive"
|
||||||
|
:src="utils.urlFor(ad[1])"
|
||||||
|
></q-img>
|
||||||
|
<q-img class="q-mb-xs" v-else :src="utils.urlFor(ad[2])"></q-img>
|
||||||
</a>
|
</a>
|
||||||
</q-card-section>
|
</q-card-section>
|
||||||
</q-card>
|
</q-card>
|
||||||
|
|||||||
@@ -94,15 +94,15 @@ class PaymentStatus(NamedTuple):
|
|||||||
|
|
||||||
|
|
||||||
class PaymentSuccessStatus(PaymentStatus):
|
class PaymentSuccessStatus(PaymentStatus):
|
||||||
paid = True
|
paid = True # type: ignore[reportIncompatibleVariableOverride]
|
||||||
|
|
||||||
|
|
||||||
class PaymentFailedStatus(PaymentStatus):
|
class PaymentFailedStatus(PaymentStatus):
|
||||||
paid = False
|
paid = False # type: ignore[reportIncompatibleVariableOverride]
|
||||||
|
|
||||||
|
|
||||||
class PaymentPendingStatus(PaymentStatus):
|
class PaymentPendingStatus(PaymentStatus):
|
||||||
paid = None
|
paid = None # type: ignore[reportIncompatibleVariableOverride]
|
||||||
|
|
||||||
|
|
||||||
class Wallet(ABC):
|
class Wallet(ABC):
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ from loguru import logger
|
|||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
from websockets import Subprotocol, connect
|
from websockets import Subprotocol, connect
|
||||||
|
|
||||||
from lnbits import bolt11
|
from lnbits import bolt11 as bolt11_lib
|
||||||
from lnbits.helpers import normalize_endpoint
|
from lnbits.helpers import normalize_endpoint
|
||||||
from lnbits.settings import settings
|
from lnbits.settings import settings
|
||||||
|
|
||||||
@@ -164,15 +164,13 @@ class BlinkWallet(Wallet):
|
|||||||
ok=False, error_message=f"Unable to connect to {self.endpoint}."
|
ok=False, error_message=f"Unable to connect to {self.endpoint}."
|
||||||
)
|
)
|
||||||
|
|
||||||
async def pay_invoice(
|
async def pay_invoice(self, bolt11: str, fee_limit_msat: int) -> PaymentResponse:
|
||||||
self, bolt11_invoice: str, fee_limit_msat: int
|
|
||||||
) -> PaymentResponse:
|
|
||||||
# https://dev.blink.sv/api/btc-ln-send
|
# https://dev.blink.sv/api/btc-ln-send
|
||||||
# Future: add check fee estimate is < fee_limit_msat before paying invoice
|
# Future: add check fee estimate is < fee_limit_msat before paying invoice
|
||||||
|
|
||||||
payment_variables = {
|
payment_variables = {
|
||||||
"input": {
|
"input": {
|
||||||
"paymentRequest": bolt11_invoice,
|
"paymentRequest": bolt11,
|
||||||
"walletId": self.wallet_id,
|
"walletId": self.wallet_id,
|
||||||
"memo": "Payment memo",
|
"memo": "Payment memo",
|
||||||
}
|
}
|
||||||
@@ -190,7 +188,7 @@ class BlinkWallet(Wallet):
|
|||||||
error_message = errors[0].get("message")
|
error_message = errors[0].get("message")
|
||||||
return PaymentResponse(ok=False, error_message=error_message)
|
return PaymentResponse(ok=False, error_message=error_message)
|
||||||
|
|
||||||
checking_id = bolt11.decode(bolt11_invoice).payment_hash
|
checking_id = bolt11_lib.decode(bolt11).payment_hash
|
||||||
|
|
||||||
payment_status = await self.get_payment_status(checking_id)
|
payment_status = await self.get_payment_status(checking_id)
|
||||||
fee_msat = payment_status.fee_msat
|
fee_msat = payment_status.fee_msat
|
||||||
@@ -199,7 +197,7 @@ class BlinkWallet(Wallet):
|
|||||||
ok=True, checking_id=checking_id, fee_msat=fee_msat, preimage=preimage
|
ok=True, checking_id=checking_id, fee_msat=fee_msat, preimage=preimage
|
||||||
)
|
)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
logger.info(f"Failed to pay invoice {bolt11_invoice}")
|
logger.info(f"Failed to pay invoice {bolt11}")
|
||||||
logger.warning(exc)
|
logger.warning(exc)
|
||||||
return PaymentResponse(
|
return PaymentResponse(
|
||||||
error_message=f"Unable to connect to {self.endpoint}."
|
error_message=f"Unable to connect to {self.endpoint}."
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ else:
|
|||||||
|
|
||||||
from bolt11 import Bolt11Exception
|
from bolt11 import Bolt11Exception
|
||||||
from bolt11 import decode as bolt11_decode
|
from bolt11 import decode as bolt11_decode
|
||||||
from breez_sdk import (
|
from breez_sdk import ( # type: ignore[reportMissingImports]
|
||||||
BreezEvent,
|
BreezEvent,
|
||||||
ConnectRequest,
|
ConnectRequest,
|
||||||
EnvironmentType,
|
EnvironmentType,
|
||||||
@@ -39,7 +39,9 @@ else:
|
|||||||
default_config,
|
default_config,
|
||||||
mnemonic_to_seed,
|
mnemonic_to_seed,
|
||||||
)
|
)
|
||||||
from breez_sdk import PaymentStatus as BreezPaymentStatus
|
from breez_sdk import (
|
||||||
|
PaymentStatus as BreezPaymentStatus, # type: ignore[reportMissingImports]
|
||||||
|
)
|
||||||
from loguru import logger
|
from loguru import logger
|
||||||
|
|
||||||
from lnbits.settings import settings
|
from lnbits.settings import settings
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ else:
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from bolt11 import decode as bolt11_decode
|
from bolt11 import decode as bolt11_decode
|
||||||
from breez_sdk_liquid import (
|
from breez_sdk_liquid import ( # type: ignore[reportMissingImports]
|
||||||
ConnectRequest,
|
ConnectRequest,
|
||||||
EventListener,
|
EventListener,
|
||||||
GetInfoResponse,
|
GetInfoResponse,
|
||||||
|
|||||||
@@ -103,7 +103,7 @@ class FakeWallet(Wallet):
|
|||||||
preimage=preimage.hex(),
|
preimage=preimage.hex(),
|
||||||
)
|
)
|
||||||
|
|
||||||
async def pay_invoice(self, bolt11: str, _: int) -> PaymentResponse:
|
async def pay_invoice(self, bolt11: str, fee_limit_msat: int) -> PaymentResponse:
|
||||||
try:
|
try:
|
||||||
invoice = decode(bolt11)
|
invoice = decode(bolt11)
|
||||||
except Bolt11Exception as exc:
|
except Bolt11Exception as exc:
|
||||||
@@ -130,7 +130,7 @@ class FakeWallet(Wallet):
|
|||||||
return PaymentPendingStatus()
|
return PaymentPendingStatus()
|
||||||
return PaymentFailedStatus()
|
return PaymentFailedStatus()
|
||||||
|
|
||||||
async def get_payment_status(self, _: str) -> PaymentStatus:
|
async def get_payment_status(self, checking_id: str) -> PaymentStatus:
|
||||||
return PaymentPendingStatus()
|
return PaymentPendingStatus()
|
||||||
|
|
||||||
async def paid_invoices_stream(self) -> AsyncGenerator[str, None]:
|
async def paid_invoices_stream(self) -> AsyncGenerator[str, None]:
|
||||||
|
|||||||
@@ -118,7 +118,7 @@ class LndWallet(Wallet):
|
|||||||
|
|
||||||
cert = open(cert_path, "rb").read()
|
cert = open(cert_path, "rb").read()
|
||||||
creds = grpc.ssl_channel_credentials(cert)
|
creds = grpc.ssl_channel_credentials(cert)
|
||||||
auth_creds = grpc.metadata_call_credentials(self.metadata_callback)
|
auth_creds = grpc.metadata_call_credentials(self.metadata_callback) # type: ignore[reportArgumentType]
|
||||||
composite_creds = grpc.composite_channel_credentials(creds, auth_creds)
|
composite_creds = grpc.composite_channel_credentials(creds, auth_creds)
|
||||||
channel = grpc.aio.secure_channel(
|
channel = grpc.aio.secure_channel(
|
||||||
f"{self.endpoint}:{self.port}", composite_creds
|
f"{self.endpoint}:{self.port}", composite_creds
|
||||||
@@ -192,6 +192,8 @@ class LndWallet(Wallet):
|
|||||||
fee_limit_msat=fee_limit_msat,
|
fee_limit_msat=fee_limit_msat,
|
||||||
timeout_seconds=30,
|
timeout_seconds=30,
|
||||||
no_inflight_updates=True,
|
no_inflight_updates=True,
|
||||||
|
max_parts=16,
|
||||||
|
time_pref=0.9,
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
res: Payment = await self.router_rpc.SendPaymentV2(req).read()
|
res: Payment = await self.router_rpc.SendPaymentV2(req).read()
|
||||||
|
|||||||
@@ -88,6 +88,8 @@ class NWCWallet(Wallet):
|
|||||||
payment_data = await self.conn.call(
|
payment_data = await self.conn.call(
|
||||||
"lookup_invoice", {"payment_hash": payment["checking_id"]}
|
"lookup_invoice", {"payment_hash": payment["checking_id"]}
|
||||||
)
|
)
|
||||||
|
if payment_data.get("payment_hash") != payment["checking_id"]:
|
||||||
|
raise Exception("Mismatched payment hash")
|
||||||
settled = (
|
settled = (
|
||||||
"settled_at" in payment_data
|
"settled_at" in payment_data
|
||||||
and payment_data["settled_at"]
|
and payment_data["settled_at"]
|
||||||
@@ -264,6 +266,8 @@ class NWCWallet(Wallet):
|
|||||||
payment_data = await self.conn.call(
|
payment_data = await self.conn.call(
|
||||||
"lookup_invoice", {"payment_hash": checking_id}
|
"lookup_invoice", {"payment_hash": checking_id}
|
||||||
)
|
)
|
||||||
|
if payment_data.get("payment_hash") != checking_id:
|
||||||
|
raise Exception("Mismatched payment hash")
|
||||||
settled = payment_data.get("settled_at", None) and payment_data.get(
|
settled = payment_data.get("settled_at", None) and payment_data.get(
|
||||||
"preimage", None
|
"preimage", None
|
||||||
)
|
)
|
||||||
@@ -520,8 +524,9 @@ class NWCConnection:
|
|||||||
"""
|
"""
|
||||||
sub_id = cast(str, msg[1])
|
sub_id = cast(str, msg[1])
|
||||||
event = cast(dict, msg[2])
|
event = cast(dict, msg[2])
|
||||||
if not verify_event(event): # Ensure the event is valid (do not trust relays)
|
# Ensure the event is valid (do not trust relays)
|
||||||
raise Exception("Invalid event signature")
|
if not verify_event(event) or event.get("pubkey") != self.service_pubkey_hex:
|
||||||
|
raise Exception("Invalid event")
|
||||||
tags = event["tags"]
|
tags = event["tags"]
|
||||||
if event["kind"] == 13194: # An info event
|
if event["kind"] == 13194: # An info event
|
||||||
# info events are handled specially,
|
# info events are handled specially,
|
||||||
@@ -687,6 +692,7 @@ class NWCConnection:
|
|||||||
"#p": [self.account_public_key_hex],
|
"#p": [self.account_public_key_hex],
|
||||||
"#e": [event["id"]],
|
"#e": [event["id"]],
|
||||||
"since": event["created_at"],
|
"since": event["created_at"],
|
||||||
|
"authors": [self.service_pubkey_hex],
|
||||||
}
|
}
|
||||||
sub_id = self._get_new_subid()
|
sub_id = self._get_new_subid()
|
||||||
# register a future to receive the response asynchronously
|
# register a future to receive the response asynchronously
|
||||||
|
|||||||
Generated
+678
-203
File diff suppressed because it is too large
Load Diff
+11
-11
@@ -15,24 +15,24 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"clean-css-cli": "^5.6.3",
|
"clean-css-cli": "^5.6.3",
|
||||||
"concat": "^1.0.3",
|
"concat": "^1.0.3",
|
||||||
"prettier": "^3.7.4",
|
"prettier": "^3.8.3",
|
||||||
"pyright": "1.1.289",
|
"pyright": "1.1.409",
|
||||||
"sass": "^1.94.2",
|
"sass": "^1.99.0",
|
||||||
"terser": "^5.44.1"
|
"terser": "^5.47.1"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"axios": "^1.15.0",
|
"axios": "^1.16.0",
|
||||||
"chart.js": "^4.5.1",
|
"chart.js": "^4.5.1",
|
||||||
"moment": "^2.30.1",
|
"moment": "^2.30.1",
|
||||||
"nostr-tools": "^2.18.2",
|
"nostr-tools": "^2.23.3",
|
||||||
"qrcode.vue": "^3.6.0",
|
"qrcode.vue": "^3.9.0",
|
||||||
"quasar": "2.18.6",
|
"quasar": "2.19.3",
|
||||||
"showdown": "^2.1.0",
|
"showdown": "^2.1.0",
|
||||||
"underscore": "^1.13.8",
|
"underscore": "^1.13.8",
|
||||||
"vue": "3.5.25",
|
"vue": "3.5.34",
|
||||||
"vue-i18n": "^11.2.2",
|
"vue-i18n": "^11.4.2",
|
||||||
"vue-qrcode-reader": "^5.7.3",
|
"vue-qrcode-reader": "^5.7.3",
|
||||||
"vue-router": "4.6.3",
|
"vue-router": "5.0.6",
|
||||||
"vuex": "4.1.0"
|
"vuex": "4.1.0"
|
||||||
},
|
},
|
||||||
"vendor": [
|
"vendor": [
|
||||||
|
|||||||
Generated
+23
-10
@@ -1,4 +1,4 @@
|
|||||||
# This file is automatically @generated by Poetry 2.4.0 and should not be changed by hand.
|
# This file is automatically @generated by Poetry 2.2.1 and should not be changed by hand.
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "aiohappyeyeballs"
|
name = "aiohappyeyeballs"
|
||||||
@@ -665,6 +665,19 @@ bitstring = "*"
|
|||||||
click = "*"
|
click = "*"
|
||||||
coincurve = "*"
|
coincurve = "*"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "boltz-client"
|
||||||
|
version = "0.4.0"
|
||||||
|
description = "Boltz Swap library"
|
||||||
|
optional = true
|
||||||
|
python-versions = ">=3.10"
|
||||||
|
groups = ["main"]
|
||||||
|
markers = "extra == \"liquid\""
|
||||||
|
files = [
|
||||||
|
{file = "boltz_client-0.4.0-py3-none-manylinux_2_34_x86_64.whl", hash = "sha256:ed0b520209cf1b05a8523002f5d8f26fa29c04d2faecc9cbde3621b4ddc417e6"},
|
||||||
|
{file = "boltz_client-0.4.0.tar.gz", hash = "sha256:a3f5a6b637350267856e3ab680cd92158de720fa2d5805fc075e4583d020cb2a"},
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "breez-sdk"
|
name = "breez-sdk"
|
||||||
version = "0.8.0"
|
version = "0.8.0"
|
||||||
@@ -2134,7 +2147,7 @@ files = [
|
|||||||
|
|
||||||
[package.dependencies]
|
[package.dependencies]
|
||||||
attrs = ">=22.2.0"
|
attrs = ">=22.2.0"
|
||||||
jsonschema-specifications = ">=2023.3.6"
|
jsonschema-specifications = ">=2023.03.6"
|
||||||
referencing = ">=0.28.4"
|
referencing = ">=0.28.4"
|
||||||
rpds-py = ">=0.25.0"
|
rpds-py = ">=0.25.0"
|
||||||
|
|
||||||
@@ -2295,7 +2308,7 @@ colorama = {version = ">=0.3.4", markers = "sys_platform == \"win32\""}
|
|||||||
win32-setctime = {version = ">=1.0.0", markers = "sys_platform == \"win32\""}
|
win32-setctime = {version = ">=1.0.0", markers = "sys_platform == \"win32\""}
|
||||||
|
|
||||||
[package.extras]
|
[package.extras]
|
||||||
dev = ["Sphinx (==8.1.3) ; python_version >= \"3.11\"", "build (==1.2.2) ; python_version >= \"3.11\"", "colorama (==0.4.5) ; python_version < \"3.8\"", "colorama (==0.4.6) ; python_version >= \"3.8\"", "exceptiongroup (==1.1.3) ; python_version >= \"3.7\" and python_version < \"3.11\"", "freezegun (==1.1.0) ; python_version < \"3.8\"", "freezegun (==1.5.0) ; python_version >= \"3.8\"", "mypy (==0.910) ; python_version < \"3.6\"", "mypy (==0.971) ; python_version == \"3.6\"", "mypy (==1.13.0) ; python_version >= \"3.8\"", "mypy (==1.4.1) ; python_version == \"3.7\"", "myst-parser (==4.0.0) ; python_version >= \"3.11\"", "pre-commit (==4.0.1) ; python_version >= \"3.9\"", "pytest (==6.1.2) ; python_version < \"3.8\"", "pytest (==8.3.2) ; python_version >= \"3.8\"", "pytest-cov (==2.12.1) ; python_version < \"3.8\"", "pytest-cov (==5.0.0) ; python_version == \"3.8\"", "pytest-cov (==6.0.0) ; python_version >= \"3.9\"", "pytest-mypy-plugins (==1.9.3) ; python_version >= \"3.6\" and python_version < \"3.8\"", "pytest-mypy-plugins (==3.1.0) ; python_version >= \"3.8\"", "sphinx-rtd-theme (==3.0.2) ; python_version >= \"3.11\"", "tox (==3.27.1) ; python_version < \"3.8\"", "tox (==4.23.2) ; python_version >= \"3.8\"", "twine (==6.0.1) ; python_version >= \"3.11\""]
|
dev = ["Sphinx (==8.1.3) ; python_version >= \"3.11\"", "build (==1.2.2) ; python_version >= \"3.11\"", "colorama (==0.4.5) ; python_version < \"3.8\"", "colorama (==0.4.6) ; python_version >= \"3.8\"", "exceptiongroup (==1.1.3) ; python_version >= \"3.7\" and python_version < \"3.11\"", "freezegun (==1.1.0) ; python_version < \"3.8\"", "freezegun (==1.5.0) ; python_version >= \"3.8\"", "mypy (==v0.910) ; python_version < \"3.6\"", "mypy (==v0.971) ; python_version == \"3.6\"", "mypy (==v1.13.0) ; python_version >= \"3.8\"", "mypy (==v1.4.1) ; python_version == \"3.7\"", "myst-parser (==4.0.0) ; python_version >= \"3.11\"", "pre-commit (==4.0.1) ; python_version >= \"3.9\"", "pytest (==6.1.2) ; python_version < \"3.8\"", "pytest (==8.3.2) ; python_version >= \"3.8\"", "pytest-cov (==2.12.1) ; python_version < \"3.8\"", "pytest-cov (==5.0.0) ; python_version == \"3.8\"", "pytest-cov (==6.0.0) ; python_version >= \"3.9\"", "pytest-mypy-plugins (==1.9.3) ; python_version >= \"3.6\" and python_version < \"3.8\"", "pytest-mypy-plugins (==3.1.0) ; python_version >= \"3.8\"", "sphinx-rtd-theme (==3.0.2) ; python_version >= \"3.11\"", "tox (==3.27.1) ; python_version < \"3.8\"", "tox (==4.23.2) ; python_version >= \"3.8\"", "twine (==6.0.1) ; python_version >= \"3.11\""]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "markdown-it-py"
|
name = "markdown-it-py"
|
||||||
@@ -3394,7 +3407,7 @@ version = "5.1.2"
|
|||||||
description = "Call stack profiler for Python. Shows you why your code is slow!"
|
description = "Call stack profiler for Python. Shows you why your code is slow!"
|
||||||
optional = false
|
optional = false
|
||||||
python-versions = ">=3.8"
|
python-versions = ">=3.8"
|
||||||
groups = ["dev"]
|
groups = ["main"]
|
||||||
files = [
|
files = [
|
||||||
{file = "pyinstrument-5.1.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:f224fe80ba288a00980af298d3808219f9d246fd95b4f91729c9c33a0dc54fe6"},
|
{file = "pyinstrument-5.1.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:f224fe80ba288a00980af298d3808219f9d246fd95b4f91729c9c33a0dc54fe6"},
|
||||||
{file = "pyinstrument-5.1.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:7df09fc0d5b72daf48b73cdf07738761bff7f656c81aff686b3ccdd7d2abe236"},
|
{file = "pyinstrument-5.1.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:7df09fc0d5b72daf48b73cdf07738761bff7f656c81aff686b3ccdd7d2abe236"},
|
||||||
@@ -4560,14 +4573,14 @@ files = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "urllib3"
|
name = "urllib3"
|
||||||
version = "2.6.3"
|
version = "2.7.0"
|
||||||
description = "HTTP library with thread-safe connection pooling, file post, and more."
|
description = "HTTP library with thread-safe connection pooling, file post, and more."
|
||||||
optional = false
|
optional = false
|
||||||
python-versions = ">=3.9"
|
python-versions = ">=3.10"
|
||||||
groups = ["main", "dev"]
|
groups = ["main", "dev"]
|
||||||
files = [
|
files = [
|
||||||
{file = "urllib3-2.6.3-py3-none-any.whl", hash = "sha256:bf272323e553dfb2e87d9bfd225ca7b0f467b919d7bbd355436d3fd37cb0acd4"},
|
{file = "urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897"},
|
||||||
{file = "urllib3-2.6.3.tar.gz", hash = "sha256:1b62b6884944a57dbe321509ab94fd4d3b307075e0c2eae991ac71ee15ad38ed"},
|
{file = "urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c"},
|
||||||
]
|
]
|
||||||
|
|
||||||
[package.extras]
|
[package.extras]
|
||||||
@@ -5104,10 +5117,10 @@ propcache = ">=0.2.1"
|
|||||||
|
|
||||||
[extras]
|
[extras]
|
||||||
breez = ["breez-sdk", "breez-sdk-liquid"]
|
breez = ["breez-sdk", "breez-sdk-liquid"]
|
||||||
liquid = ["wallycore"]
|
liquid = ["boltz-client", "wallycore"]
|
||||||
migration = ["psycopg2-binary"]
|
migration = ["psycopg2-binary"]
|
||||||
|
|
||||||
[metadata]
|
[metadata]
|
||||||
lock-version = "2.1"
|
lock-version = "2.1"
|
||||||
python-versions = ">=3.10,<3.13"
|
python-versions = ">=3.10,<3.13"
|
||||||
content-hash = "0879a6230bbc0d0e1d8d7d090e1572ba863078b18e0d78478baf2100aa245e08"
|
content-hash = "7c70bdad0089089d383cf8f54c37c4473180cea175689b91322beaed1ab42e94"
|
||||||
|
|||||||
+7
-3
@@ -1,6 +1,6 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "lnbits"
|
name = "lnbits"
|
||||||
version = "1.5.4"
|
version = "1.5.5-rc2"
|
||||||
requires-python = ">=3.10,<3.13"
|
requires-python = ">=3.10,<3.13"
|
||||||
description = "LNbits, free and open-source Lightning wallet and accounts system."
|
description = "LNbits, free and open-source Lightning wallet and accounts system."
|
||||||
authors = [{ name = "Alan Bits", email = "alan@lnbits.com" }]
|
authors = [{ name = "Alan Bits", email = "alan@lnbits.com" }]
|
||||||
@@ -51,6 +51,8 @@ dependencies = [
|
|||||||
"pillow~=12.1.0",
|
"pillow~=12.1.0",
|
||||||
"python-dotenv~=1.2.1",
|
"python-dotenv~=1.2.1",
|
||||||
"greenlet~=3.3.0",
|
"greenlet~=3.3.0",
|
||||||
|
"urllib3>=2.7.0",
|
||||||
|
"pyinstrument>=5.1.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[project.scripts]
|
[project.scripts]
|
||||||
@@ -59,7 +61,7 @@ lnbits-cli = "lnbits.commands:main"
|
|||||||
|
|
||||||
[project.optional-dependencies]
|
[project.optional-dependencies]
|
||||||
breez = ["breez-sdk~=0.8.0", "breez-sdk-liquid~=0.11.11"]
|
breez = ["breez-sdk~=0.8.0", "breez-sdk-liquid~=0.11.11"]
|
||||||
liquid = ["wallycore~=1.5.1"]
|
liquid = ["wallycore~=1.5.1", "boltz-client==0.4.0"]
|
||||||
migration = ["psycopg2-binary~=2.9.11"]
|
migration = ["psycopg2-binary~=2.9.11"]
|
||||||
|
|
||||||
[dependency-groups]
|
[dependency-groups]
|
||||||
@@ -83,9 +85,11 @@ dev = [
|
|||||||
"types-mock~=5.2.0.20250924",
|
"types-mock~=5.2.0.20250924",
|
||||||
"mock~=5.2.0",
|
"mock~=5.2.0",
|
||||||
"grpcio-tools~=1.76.0",
|
"grpcio-tools~=1.76.0",
|
||||||
"pyinstrument>=5.1.2",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[tool.uv]
|
||||||
|
exclude-newer = "1 week"
|
||||||
|
|
||||||
[tool.poetry]
|
[tool.poetry]
|
||||||
packages = [
|
packages = [
|
||||||
{include = "lnbits"},
|
{include = "lnbits"},
|
||||||
|
|||||||
@@ -13,14 +13,15 @@ async def test_asset_api_upload_list_update_and_delete(
|
|||||||
client: AsyncClient,
|
client: AsyncClient,
|
||||||
user_headers_from: dict[str, str],
|
user_headers_from: dict[str, str],
|
||||||
):
|
):
|
||||||
|
payload = get_png_bytes()
|
||||||
upload = await client.post(
|
upload = await client.post(
|
||||||
"/api/v1/assets?public_asset=false",
|
"/api/v1/assets?public_asset=false",
|
||||||
headers={"Authorization": user_headers_from["Authorization"]},
|
headers={"Authorization": user_headers_from["Authorization"]},
|
||||||
files={"file": ("note.txt", b"hello world", "text/plain")},
|
files={"file": ("note.png", payload, "image/png")},
|
||||||
)
|
)
|
||||||
assert upload.status_code == 200
|
assert upload.status_code == 200
|
||||||
asset = upload.json()
|
asset = upload.json()
|
||||||
assert asset["name"] == "note.txt"
|
assert asset["name"] == "note.png"
|
||||||
assert asset["is_public"] is False
|
assert asset["is_public"] is False
|
||||||
|
|
||||||
page = await client.get("/api/v1/assets/paginated", headers=user_headers_from)
|
page = await client.get("/api/v1/assets/paginated", headers=user_headers_from)
|
||||||
@@ -29,27 +30,30 @@ async def test_asset_api_upload_list_update_and_delete(
|
|||||||
|
|
||||||
info = await client.get(f"/api/v1/assets/{asset['id']}", headers=user_headers_from)
|
info = await client.get(f"/api/v1/assets/{asset['id']}", headers=user_headers_from)
|
||||||
assert info.status_code == 200
|
assert info.status_code == 200
|
||||||
assert info.json()["name"] == "note.txt"
|
assert info.json()["name"] == "note.png"
|
||||||
|
|
||||||
data = await client.get(
|
data = await client.get(
|
||||||
f"/api/v1/assets/{asset['id']}/data", headers=user_headers_from
|
f"/api/v1/assets/{asset['id']}/data", headers=user_headers_from
|
||||||
)
|
)
|
||||||
assert data.status_code == 200
|
assert data.status_code == 200
|
||||||
assert data.content == b"hello world"
|
assert data.content == payload
|
||||||
assert data.headers["content-disposition"] == 'inline; filename="note.txt"'
|
assert data.headers["content-type"] == "image/png"
|
||||||
|
assert data.headers["content-disposition"] == 'inline; filename="note.png"'
|
||||||
|
assert data.headers["x-content-type-options"] == "nosniff"
|
||||||
|
assert data.headers["content-security-policy"].startswith("sandbox")
|
||||||
|
|
||||||
updated = await client.put(
|
updated = await client.put(
|
||||||
f"/api/v1/assets/{asset['id']}",
|
f"/api/v1/assets/{asset['id']}",
|
||||||
headers=user_headers_from,
|
headers=user_headers_from,
|
||||||
json={"name": "renamed.txt", "is_public": True},
|
json={"name": "renamed.png", "is_public": True},
|
||||||
)
|
)
|
||||||
assert updated.status_code == 200
|
assert updated.status_code == 200
|
||||||
assert updated.json()["name"] == "renamed.txt"
|
assert updated.json()["name"] == "renamed.png"
|
||||||
assert updated.json()["is_public"] is True
|
assert updated.json()["is_public"] is True
|
||||||
|
|
||||||
public_data = await client.get(f"/api/v1/assets/{asset['id']}/data")
|
public_data = await client.get(f"/api/v1/assets/{asset['id']}/data")
|
||||||
assert public_data.status_code == 200
|
assert public_data.status_code == 200
|
||||||
assert public_data.content == b"hello world"
|
assert public_data.content == payload
|
||||||
|
|
||||||
deleted = await client.delete(
|
deleted = await client.delete(
|
||||||
f"/api/v1/assets/{asset['id']}", headers=user_headers_from
|
f"/api/v1/assets/{asset['id']}", headers=user_headers_from
|
||||||
@@ -98,15 +102,51 @@ async def test_asset_api_enforces_visibility_and_supports_admin_updates(
|
|||||||
assert admin_updated.json()["is_public"] is True
|
assert admin_updated.json()["is_public"] is True
|
||||||
assert admin_updated.json()["name"] == "admin-visible.png"
|
assert admin_updated.json()["name"] == "admin-visible.png"
|
||||||
|
|
||||||
|
image_data = await client.get(f"/api/v1/assets/{private_asset.id}/data")
|
||||||
|
assert image_data.status_code == 200
|
||||||
|
assert image_data.headers["content-type"] == "image/png"
|
||||||
|
assert image_data.headers["content-disposition"] == (
|
||||||
|
'inline; filename="admin-visible.png"'
|
||||||
|
)
|
||||||
|
assert image_data.headers["x-content-type-options"] == "nosniff"
|
||||||
|
|
||||||
thumbnail = await client.get(f"/api/v1/assets/{private_asset.id}/thumbnail")
|
thumbnail = await client.get(f"/api/v1/assets/{private_asset.id}/thumbnail")
|
||||||
assert thumbnail.status_code == 200
|
assert thumbnail.status_code == 200
|
||||||
assert thumbnail.content
|
assert thumbnail.content
|
||||||
assert thumbnail.headers["content-type"] == "image/png"
|
assert thumbnail.headers["content-type"] == "image/png"
|
||||||
|
assert thumbnail.headers["content-disposition"] == (
|
||||||
|
'inline; filename="admin-visible.png"'
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_asset_api_blocks_non_image_uploads(
|
||||||
|
client: AsyncClient,
|
||||||
|
user_headers_from: dict[str, str],
|
||||||
|
):
|
||||||
|
payload = (
|
||||||
|
b'<?xml version="1.0"?>'
|
||||||
|
b'<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform">'
|
||||||
|
b'<xsl:template match="/">'
|
||||||
|
b"<script>alert(1)</script>"
|
||||||
|
b"</xsl:template>"
|
||||||
|
b"</xsl:stylesheet>"
|
||||||
|
)
|
||||||
|
|
||||||
|
blocked = await client.post(
|
||||||
|
"/api/v1/assets",
|
||||||
|
headers={"Authorization": user_headers_from["Authorization"]},
|
||||||
|
files={"file": ("payload.xsl", payload, "text/xml")},
|
||||||
|
)
|
||||||
|
|
||||||
|
assert blocked.status_code == 400
|
||||||
|
assert blocked.json()["detail"] == "File type 'text/xml' not allowed."
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_asset_api_validates_uploads_and_missing_assets(
|
async def test_asset_api_validates_uploads_and_missing_assets(
|
||||||
client: AsyncClient,
|
client: AsyncClient,
|
||||||
|
to_user,
|
||||||
user_headers_from: dict[str, str],
|
user_headers_from: dict[str, str],
|
||||||
):
|
):
|
||||||
invalid = await client.post(
|
invalid = await client.post(
|
||||||
@@ -117,6 +157,15 @@ async def test_asset_api_validates_uploads_and_missing_assets(
|
|||||||
assert invalid.status_code == 400
|
assert invalid.status_code == 400
|
||||||
assert "not allowed" in invalid.json()["detail"]
|
assert "not allowed" in invalid.json()["detail"]
|
||||||
|
|
||||||
|
fake_image_headers = await get_user_token_headers(client, to_user.id)
|
||||||
|
fake_image = await client.post(
|
||||||
|
"/api/v1/assets",
|
||||||
|
headers={"Authorization": fake_image_headers["Authorization"]},
|
||||||
|
files={"file": ("fake.png", b"<root></root>", "image/png")},
|
||||||
|
)
|
||||||
|
assert fake_image.status_code == 400
|
||||||
|
assert "does not match declared file type" in fake_image.json()["detail"]
|
||||||
|
|
||||||
missing = await client.delete(
|
missing = await client.delete(
|
||||||
f"/api/v1/assets/{uuid4().hex}",
|
f"/api/v1/assets/{uuid4().hex}",
|
||||||
headers=user_headers_from,
|
headers=user_headers_from,
|
||||||
@@ -128,7 +177,9 @@ async def test_asset_api_validates_uploads_and_missing_assets(
|
|||||||
|
|
||||||
stored = await create_user_asset(
|
stored = await create_user_asset(
|
||||||
"missing-user-check",
|
"missing-user-check",
|
||||||
make_upload_file(b"content", filename="content.txt", content_type="text/plain"),
|
make_upload_file(
|
||||||
|
get_png_bytes(), filename="content.png", content_type="image/png"
|
||||||
|
),
|
||||||
is_public=True,
|
is_public=True,
|
||||||
)
|
)
|
||||||
fetched = await get_user_asset("missing-user-check", stored.id)
|
fetched = await get_user_asset("missing-user-check", stored.id)
|
||||||
|
|||||||
@@ -72,9 +72,43 @@ async def test_auth_api_sso_login_and_callback(http_client: AsyncClient, mocker)
|
|||||||
login_sso = _FakeSSO()
|
login_sso = _FakeSSO()
|
||||||
mocker.patch("lnbits.core.views.auth_api._new_sso", return_value=login_sso)
|
mocker.patch("lnbits.core.views.auth_api._new_sso", return_value=login_sso)
|
||||||
|
|
||||||
response = await http_client.get(
|
unauthenticated = await http_client.get(
|
||||||
f"/api/v1/auth/{provider}", params={"user_id": user.id}
|
f"/api/v1/auth/{provider}", params={"user_id": user.id}
|
||||||
)
|
)
|
||||||
|
assert unauthenticated.status_code == 403
|
||||||
|
assert unauthenticated.json()["detail"] == "User ID mismatch."
|
||||||
|
|
||||||
|
other_user = await create_user_account(
|
||||||
|
Account(
|
||||||
|
id=uuid4().hex,
|
||||||
|
username=f"user_{uuid4().hex[:8]}",
|
||||||
|
email=f"user_{uuid4().hex[:8]}@lnbits.com",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
other_login = await http_client.post(
|
||||||
|
"/api/v1/auth/usr", json={"usr": other_user.id}
|
||||||
|
)
|
||||||
|
http_client.cookies.clear()
|
||||||
|
assert other_login.status_code == 200
|
||||||
|
other_headers = {
|
||||||
|
"Authorization": f"Bearer {other_login.json()['access_token']}",
|
||||||
|
}
|
||||||
|
wrong_user = await http_client.get(
|
||||||
|
f"/api/v1/auth/{provider}",
|
||||||
|
params={"user_id": user.id},
|
||||||
|
headers=other_headers,
|
||||||
|
)
|
||||||
|
assert wrong_user.status_code == 403
|
||||||
|
assert wrong_user.json()["detail"] == "User ID mismatch."
|
||||||
|
|
||||||
|
login = await http_client.post("/api/v1/auth/usr", json={"usr": user.id})
|
||||||
|
http_client.cookies.clear()
|
||||||
|
assert login.status_code == 200
|
||||||
|
headers = {"Authorization": f"Bearer {login.json()['access_token']}"}
|
||||||
|
|
||||||
|
response = await http_client.get(
|
||||||
|
f"/api/v1/auth/{provider}", params={"user_id": user.id}, headers=headers
|
||||||
|
)
|
||||||
assert response.status_code == 307
|
assert response.status_code == 307
|
||||||
assert response.headers["location"] == "https://example.com/sso/login"
|
assert response.headers["location"] == "https://example.com/sso/login"
|
||||||
assert login_sso.redirect_uri == f"{http_client.base_url}/api/v1/auth/github/token"
|
assert login_sso.redirect_uri == f"{http_client.base_url}/api/v1/auth/github/token"
|
||||||
|
|||||||
+114
-20
@@ -185,23 +185,16 @@ async def test_callback_api_handles_revolut_paid_events(mocker):
|
|||||||
async def test_callback_api_handles_revolut_subscription_event(
|
async def test_callback_api_handles_revolut_subscription_event(
|
||||||
mocker, settings: Settings
|
mocker, settings: Settings
|
||||||
):
|
):
|
||||||
user = await create_user_account(
|
wallet_id = "wallet_1"
|
||||||
Account(
|
payment = mocker.Mock()
|
||||||
id=uuid4().hex,
|
payment.extra = {}
|
||||||
username=f"user_{uuid4().hex[:8]}",
|
payment.msat = 925_000
|
||||||
email=f"user_{uuid4().hex[:8]}@lnbits.com",
|
|
||||||
)
|
|
||||||
)
|
|
||||||
wallet = user.wallets[0]
|
|
||||||
payment = await create_wallet_invoice(
|
|
||||||
wallet.id, CreateInvoice(out=False, amount=15, memo="subscription")
|
|
||||||
)
|
|
||||||
|
|
||||||
settings.revolut_api_endpoint = "https://sandbox-merchant.revolut.com"
|
settings.revolut_api_endpoint = "https://sandbox-merchant.revolut.com"
|
||||||
settings.revolut_api_secret_key = "revolut-secret"
|
settings.revolut_api_secret_key = "revolut-secret"
|
||||||
settings.revolut_api_version = "2026-04-20"
|
settings.revolut_api_version = "2026-04-20"
|
||||||
revolut_provider = RevolutWallet()
|
revolut_provider = RevolutWallet()
|
||||||
mocker.patch.object(
|
get_subscription_mock = mocker.patch.object(
|
||||||
revolut_provider,
|
revolut_provider,
|
||||||
"get_subscription",
|
"get_subscription",
|
||||||
return_value={
|
return_value={
|
||||||
@@ -209,7 +202,7 @@ async def test_callback_api_handles_revolut_subscription_event(
|
|||||||
"current_cycle_id": "CYCLE_1",
|
"current_cycle_id": "CYCLE_1",
|
||||||
"external_reference": json.dumps(
|
"external_reference": json.dumps(
|
||||||
{
|
{
|
||||||
"wallet_id": wallet.id,
|
"wallet_id": wallet_id,
|
||||||
"tag": "members",
|
"tag": "members",
|
||||||
"subscription_request_id": "request_1",
|
"subscription_request_id": "request_1",
|
||||||
"extra": {"link": "link-1", "customer_id": "customer_1"},
|
"extra": {"link": "link-1", "customer_id": "customer_1"},
|
||||||
@@ -241,10 +234,14 @@ async def test_callback_api_handles_revolut_subscription_event(
|
|||||||
"lnbits.core.views.callback_api.get_standalone_payment",
|
"lnbits.core.views.callback_api.get_standalone_payment",
|
||||||
mocker.AsyncMock(side_effect=[None]),
|
mocker.AsyncMock(side_effect=[None]),
|
||||||
)
|
)
|
||||||
create_fiat_invoice_mock = mocker.patch(
|
create_wallet_invoice_mock = mocker.patch(
|
||||||
"lnbits.core.views.callback_api.create_fiat_invoice",
|
"lnbits.core.views.callback_api.create_wallet_invoice",
|
||||||
mocker.AsyncMock(return_value=payment),
|
mocker.AsyncMock(return_value=payment),
|
||||||
)
|
)
|
||||||
|
mocker.patch("lnbits.core.views.callback_api.service_fee_fiat", return_value=2)
|
||||||
|
update_payment_mock = mocker.patch(
|
||||||
|
"lnbits.core.views.callback_api.update_payment", mocker.AsyncMock()
|
||||||
|
)
|
||||||
fiat_status_mock = mocker.patch(
|
fiat_status_mock = mocker.patch(
|
||||||
"lnbits.core.views.callback_api.check_fiat_status", mocker.AsyncMock()
|
"lnbits.core.views.callback_api.check_fiat_status", mocker.AsyncMock()
|
||||||
)
|
)
|
||||||
@@ -256,16 +253,113 @@ async def test_callback_api_handles_revolut_subscription_event(
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
assert create_fiat_invoice_mock.await_count == 1
|
get_subscription_mock.assert_not_awaited()
|
||||||
revolut_call = create_fiat_invoice_mock.await_args.kwargs
|
create_wallet_invoice_mock.assert_not_awaited()
|
||||||
assert revolut_call["wallet_id"] == wallet.id
|
update_payment_mock.assert_not_awaited()
|
||||||
invoice = revolut_call["invoice_data"]
|
fiat_status_mock.assert_not_awaited()
|
||||||
assert invoice.fiat_provider == "revolut"
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_callback_api_handles_revolut_subscription_order_event(
|
||||||
|
mocker, settings: Settings
|
||||||
|
):
|
||||||
|
wallet_id = "wallet_1"
|
||||||
|
payment = mocker.Mock()
|
||||||
|
payment.extra = {}
|
||||||
|
payment.msat = 925_000
|
||||||
|
|
||||||
|
settings.revolut_api_endpoint = "https://sandbox-merchant.revolut.com"
|
||||||
|
settings.revolut_api_secret_key = "revolut-secret"
|
||||||
|
settings.revolut_api_version = "2026-04-20"
|
||||||
|
revolut_provider = RevolutWallet()
|
||||||
|
subscription = {
|
||||||
|
"id": "SUBSCRIPTION_1",
|
||||||
|
"state": "active",
|
||||||
|
"current_cycle_id": "CYCLE_1",
|
||||||
|
"external_reference": json.dumps(
|
||||||
|
{
|
||||||
|
"wallet_id": wallet_id,
|
||||||
|
"tag": "members",
|
||||||
|
"subscription_request_id": "request_1",
|
||||||
|
"extra": {"link": "link-1"},
|
||||||
|
"memo": "Revolut Members",
|
||||||
|
}
|
||||||
|
),
|
||||||
|
}
|
||||||
|
order = {
|
||||||
|
"id": "ORDER_SUB_1",
|
||||||
|
"type": "payment",
|
||||||
|
"state": "completed",
|
||||||
|
"amount": 925,
|
||||||
|
"currency": "USD",
|
||||||
|
"checkout_url": "https://checkout.revolut.com/payment-link/sub_1",
|
||||||
|
"channel_data": {
|
||||||
|
"subscription_id": "SUBSCRIPTION_1",
|
||||||
|
"subscription_cycle_id": "CYCLE_1",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
get_order_mock = mocker.patch.object(
|
||||||
|
revolut_provider, "get_order", side_effect=[order, order]
|
||||||
|
)
|
||||||
|
get_subscription_mock = mocker.patch.object(
|
||||||
|
revolut_provider,
|
||||||
|
"get_subscription",
|
||||||
|
return_value=subscription,
|
||||||
|
)
|
||||||
|
mocker.patch.object(
|
||||||
|
revolut_provider,
|
||||||
|
"get_subscription_cycle",
|
||||||
|
return_value={"id": "CYCLE_1", "order_id": "ORDER_SUB_1"},
|
||||||
|
)
|
||||||
|
mocker.patch(
|
||||||
|
"lnbits.core.views.callback_api.get_fiat_provider",
|
||||||
|
mocker.AsyncMock(return_value=revolut_provider),
|
||||||
|
)
|
||||||
|
get_payment_mock = mocker.patch(
|
||||||
|
"lnbits.core.views.callback_api.get_standalone_payment",
|
||||||
|
mocker.AsyncMock(side_effect=[None, None]),
|
||||||
|
)
|
||||||
|
create_wallet_invoice_mock = mocker.patch(
|
||||||
|
"lnbits.core.views.callback_api.create_wallet_invoice",
|
||||||
|
mocker.AsyncMock(return_value=payment),
|
||||||
|
)
|
||||||
|
mocker.patch("lnbits.core.views.callback_api.service_fee_fiat", return_value=2)
|
||||||
|
update_payment_mock = mocker.patch(
|
||||||
|
"lnbits.core.views.callback_api.update_payment", mocker.AsyncMock()
|
||||||
|
)
|
||||||
|
fiat_status_mock = mocker.patch(
|
||||||
|
"lnbits.core.views.callback_api.check_fiat_status", mocker.AsyncMock()
|
||||||
|
)
|
||||||
|
|
||||||
|
await handle_revolut_event(
|
||||||
|
{
|
||||||
|
"event": "ORDER_COMPLETED",
|
||||||
|
"order_id": "ORDER_SUB_1",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
assert get_payment_mock.await_count == 2
|
||||||
|
get_payment_mock.assert_any_await("fiat_revolut_order_ORDER_SUB_1")
|
||||||
|
assert get_order_mock.await_count == 1
|
||||||
|
assert [call.args for call in get_subscription_mock.await_args_list] == [
|
||||||
|
("SUBSCRIPTION_1",),
|
||||||
|
]
|
||||||
|
assert create_wallet_invoice_mock.await_count == 1
|
||||||
|
called_wallet_id, invoice = create_wallet_invoice_mock.await_args.args
|
||||||
|
assert called_wallet_id == "wallet_1"
|
||||||
assert invoice.amount == 9.25
|
assert invoice.amount == 9.25
|
||||||
assert invoice.memo == "Revolut Members"
|
assert invoice.memo == "Revolut Members"
|
||||||
assert invoice.external_id == "SUBSCRIPTION_1"
|
assert invoice.external_id == "SUBSCRIPTION_1"
|
||||||
|
assert invoice.internal is True
|
||||||
assert invoice.extra["fiat_method"] == "subscription"
|
assert invoice.extra["fiat_method"] == "subscription"
|
||||||
assert invoice.extra["subscription"]["checking_id"] == "order_ORDER_SUB_1"
|
assert invoice.extra["subscription"]["checking_id"] == "order_ORDER_SUB_1"
|
||||||
|
assert payment.fiat_provider == "revolut"
|
||||||
|
assert payment.fee == -2
|
||||||
|
assert payment.extra["fiat_checking_id"] == "order_ORDER_SUB_1"
|
||||||
|
assert payment.checking_id == "fiat_revolut_order_ORDER_SUB_1"
|
||||||
|
update_payment_mock.assert_awaited_once_with(
|
||||||
|
payment, "fiat_revolut_order_ORDER_SUB_1"
|
||||||
|
)
|
||||||
fiat_status_mock.assert_awaited_once_with(payment)
|
fiat_status_mock.assert_awaited_once_with(payment)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
from typing import cast
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
@@ -106,7 +107,7 @@ async def test_lnurl_api_auth_and_pay_flow(mocker):
|
|||||||
await api_perform_lnurlauth(auth_response, wallet_info)
|
await api_perform_lnurlauth(auth_response, wallet_info)
|
||||||
|
|
||||||
action_response = LnurlPayActionResponse(
|
action_response = LnurlPayActionResponse(
|
||||||
pr=LightningInvoice(TEST_BOLT11),
|
pr=cast(LightningInvoice, LightningInvoice(TEST_BOLT11)),
|
||||||
disposable=False,
|
disposable=False,
|
||||||
successAction=parse_obj_as(MessageAction, {"message": "paid"}),
|
successAction=parse_obj_as(MessageAction, {"message": "paid"}),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import pytest
|
|||||||
from fastapi import HTTPException
|
from fastapi import HTTPException
|
||||||
from pydantic import ValidationError
|
from pydantic import ValidationError
|
||||||
|
|
||||||
from lnbits.core.crud.payments import create_payment, get_payments
|
from lnbits.core.crud.payments import create_payment, get_payment, get_payments
|
||||||
from lnbits.core.models import Account, CreateInvoice, PaymentFilters, PaymentState
|
from lnbits.core.models import Account, CreateInvoice, PaymentFilters, PaymentState
|
||||||
from lnbits.core.models.payments import CancelInvoice, CreatePayment, SettleInvoice
|
from lnbits.core.models.payments import CancelInvoice, CreatePayment, SettleInvoice
|
||||||
from lnbits.core.models.users import AccountId
|
from lnbits.core.models.users import AccountId
|
||||||
@@ -161,7 +161,7 @@ async def test_payment_api_fee_reserve_and_hold_invoice_actions(mocker):
|
|||||||
wallet.id, CreateInvoice(out=False, amount=42, memo="reserve")
|
wallet.id, CreateInvoice(out=False, amount=42, memo="reserve")
|
||||||
)
|
)
|
||||||
reserve = await api_payments_fee_reserve(invoice.bolt11)
|
reserve = await api_payments_fee_reserve(invoice.bolt11)
|
||||||
assert json.loads(reserve.body)["fee_reserve"] >= 0
|
assert json.loads(bytes(reserve.body))["fee_reserve"] >= 0
|
||||||
|
|
||||||
with pytest.raises(HTTPException, match="Invoice has no amount."):
|
with pytest.raises(HTTPException, match="Invoice has no amount."):
|
||||||
await api_payments_fee_reserve(ZERO_AMOUNT_INVOICE)
|
await api_payments_fee_reserve(ZERO_AMOUNT_INVOICE)
|
||||||
@@ -218,6 +218,164 @@ async def test_payment_api_fee_reserve_and_hold_invoice_actions(mocker):
|
|||||||
cancel_mock.assert_awaited_once()
|
cancel_mock.assert_awaited_once()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_payment_extra_update_appends_new_keys(
|
||||||
|
client,
|
||||||
|
to_wallet,
|
||||||
|
adminkey_headers_to,
|
||||||
|
):
|
||||||
|
payment_hash = uuid4().hex
|
||||||
|
checking_id = await _create_payment(
|
||||||
|
to_wallet.id,
|
||||||
|
amount_msat=1_000,
|
||||||
|
payment_hash=payment_hash,
|
||||||
|
tag="splitpayments",
|
||||||
|
)
|
||||||
|
|
||||||
|
response = await client.patch(
|
||||||
|
"/api/v1/payments/extra",
|
||||||
|
headers=adminkey_headers_to,
|
||||||
|
json={
|
||||||
|
"payment_hash": payment_hash,
|
||||||
|
"extra": {"child": "daughter", "compliance_note": "reviewed"},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
extra = response.json()["extra"]
|
||||||
|
assert extra["tag"] == "splitpayments"
|
||||||
|
assert extra["child"] == "daughter"
|
||||||
|
assert extra["compliance_note"] == "reviewed"
|
||||||
|
|
||||||
|
payment = await get_payment(checking_id)
|
||||||
|
assert payment.extra == extra
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_payment_extra_update_creates_extra_when_missing(
|
||||||
|
client,
|
||||||
|
to_wallet,
|
||||||
|
adminkey_headers_to,
|
||||||
|
):
|
||||||
|
payment_hash = uuid4().hex
|
||||||
|
checking_id = await _create_payment(
|
||||||
|
to_wallet.id,
|
||||||
|
amount_msat=1_000,
|
||||||
|
payment_hash=payment_hash,
|
||||||
|
)
|
||||||
|
|
||||||
|
response = await client.patch(
|
||||||
|
"/api/v1/payments/extra",
|
||||||
|
headers=adminkey_headers_to,
|
||||||
|
json={"payment_hash": payment_hash, "extra": {"note": "reviewed"}},
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json()["extra"] == {"note": "reviewed"}
|
||||||
|
|
||||||
|
payment = await get_payment(checking_id)
|
||||||
|
assert payment.extra == {"note": "reviewed"}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_payment_extra_update_rejects_existing_keys(
|
||||||
|
client,
|
||||||
|
to_wallet,
|
||||||
|
adminkey_headers_to,
|
||||||
|
):
|
||||||
|
payment_hash = uuid4().hex
|
||||||
|
checking_id = await _create_payment(
|
||||||
|
to_wallet.id,
|
||||||
|
amount_msat=1_000,
|
||||||
|
payment_hash=payment_hash,
|
||||||
|
tag="original",
|
||||||
|
)
|
||||||
|
|
||||||
|
response = await client.patch(
|
||||||
|
"/api/v1/payments/extra",
|
||||||
|
headers=adminkey_headers_to,
|
||||||
|
json={"payment_hash": payment_hash, "extra": {"tag": "overwritten"}},
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert response.json()["detail"] == "Extra keys already exist: tag."
|
||||||
|
|
||||||
|
payment = await get_payment(checking_id)
|
||||||
|
assert payment.extra == {"tag": "original"}
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_payment_extra_update_requires_admin_key(
|
||||||
|
client,
|
||||||
|
to_wallet,
|
||||||
|
inkey_headers_to,
|
||||||
|
):
|
||||||
|
payment_hash = uuid4().hex
|
||||||
|
await _create_payment(
|
||||||
|
to_wallet.id,
|
||||||
|
amount_msat=1_000,
|
||||||
|
payment_hash=payment_hash,
|
||||||
|
)
|
||||||
|
|
||||||
|
response = await client.patch(
|
||||||
|
"/api/v1/payments/extra",
|
||||||
|
headers=inkey_headers_to,
|
||||||
|
json={"payment_hash": payment_hash, "extra": {"note": "invoice key"}},
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.status_code == 403
|
||||||
|
assert response.json()["detail"] == "Invalid adminkey."
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_payment_extra_update_is_wallet_scoped(
|
||||||
|
client,
|
||||||
|
from_wallet,
|
||||||
|
adminkey_headers_to,
|
||||||
|
):
|
||||||
|
payment_hash = uuid4().hex
|
||||||
|
await _create_payment(
|
||||||
|
from_wallet.id,
|
||||||
|
amount_msat=1_000,
|
||||||
|
payment_hash=payment_hash,
|
||||||
|
)
|
||||||
|
|
||||||
|
response = await client.patch(
|
||||||
|
"/api/v1/payments/extra",
|
||||||
|
headers=adminkey_headers_to,
|
||||||
|
json={"payment_hash": payment_hash, "extra": {"note": "wrong wallet"}},
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.status_code == 404
|
||||||
|
assert response.json()["detail"] == "Payment does not exist."
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_payment_extra_update_requires_successful_payment(
|
||||||
|
client,
|
||||||
|
to_wallet,
|
||||||
|
adminkey_headers_to,
|
||||||
|
):
|
||||||
|
payment_hash = uuid4().hex
|
||||||
|
await _create_payment(
|
||||||
|
to_wallet.id,
|
||||||
|
amount_msat=1_000,
|
||||||
|
payment_hash=payment_hash,
|
||||||
|
status=PaymentState.PENDING,
|
||||||
|
)
|
||||||
|
|
||||||
|
response = await client.patch(
|
||||||
|
"/api/v1/payments/extra",
|
||||||
|
headers=adminkey_headers_to,
|
||||||
|
json={"payment_hash": payment_hash, "extra": {"note": "too early"}},
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert (
|
||||||
|
response.json()["detail"] == "Payment extra can only be updated after success."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
async def _create_payment(
|
async def _create_payment(
|
||||||
wallet_id: str,
|
wallet_id: str,
|
||||||
*,
|
*,
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
98ae578877a3479bb0424d2e418b427a
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
6355d3c6c5df49dbb562a74f9deb19ce
|
|
||||||
@@ -74,6 +74,7 @@ class MockHTTPClient:
|
|||||||
|
|
||||||
@pytest.fixture(autouse=True)
|
@pytest.fixture(autouse=True)
|
||||||
def fiat_provider_test_settings(settings: Settings):
|
def fiat_provider_test_settings(settings: Settings):
|
||||||
|
original_lnbits_running = settings.lnbits_running
|
||||||
original_allowed_currencies = settings.lnbits_allowed_currencies
|
original_allowed_currencies = settings.lnbits_allowed_currencies
|
||||||
original_paypal_enabled = settings.paypal_enabled
|
original_paypal_enabled = settings.paypal_enabled
|
||||||
original_square_enabled = settings.square_enabled
|
original_square_enabled = settings.square_enabled
|
||||||
@@ -98,6 +99,7 @@ def fiat_provider_test_settings(settings: Settings):
|
|||||||
settings.square_enabled = False
|
settings.square_enabled = False
|
||||||
settings.revolut_enabled = False
|
settings.revolut_enabled = False
|
||||||
yield
|
yield
|
||||||
|
settings.lnbits_running = original_lnbits_running
|
||||||
settings.lnbits_allowed_currencies = original_allowed_currencies
|
settings.lnbits_allowed_currencies = original_allowed_currencies
|
||||||
settings.paypal_enabled = original_paypal_enabled
|
settings.paypal_enabled = original_paypal_enabled
|
||||||
settings.square_enabled = original_square_enabled
|
settings.square_enabled = original_square_enabled
|
||||||
@@ -445,6 +447,7 @@ async def test_square_wallet_create_invoice(settings: Settings):
|
|||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_square_wallet_create_subscription(settings: Settings):
|
async def test_square_wallet_create_subscription(settings: Settings):
|
||||||
|
settings.lnbits_running = False
|
||||||
settings.square_api_endpoint = "https://connect.squareupsandbox.com"
|
settings.square_api_endpoint = "https://connect.squareupsandbox.com"
|
||||||
settings.square_access_token = "square-token"
|
settings.square_access_token = "square-token"
|
||||||
settings.square_location_id = "LOC123"
|
settings.square_location_id = "LOC123"
|
||||||
@@ -520,6 +523,7 @@ async def test_square_wallet_create_subscription(settings: Settings):
|
|||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_square_wallet_create_subscription_from_plan_id(settings: Settings):
|
async def test_square_wallet_create_subscription_from_plan_id(settings: Settings):
|
||||||
|
settings.lnbits_running = False
|
||||||
settings.square_api_endpoint = "https://connect.squareupsandbox.com"
|
settings.square_api_endpoint = "https://connect.squareupsandbox.com"
|
||||||
settings.square_access_token = "square-token"
|
settings.square_access_token = "square-token"
|
||||||
settings.square_location_id = "LOC123"
|
settings.square_location_id = "LOC123"
|
||||||
@@ -808,6 +812,48 @@ async def test_revolut_wallet_create_invoice(settings: Settings):
|
|||||||
assert payload["redirect_url"] == "https://lnbits.example/success"
|
assert payload["redirect_url"] == "https://lnbits.example/success"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_revolut_wallet_create_invoice_uses_currency_minor_units(
|
||||||
|
settings: Settings,
|
||||||
|
):
|
||||||
|
settings.revolut_api_endpoint = "https://sandbox-merchant.revolut.com"
|
||||||
|
settings.revolut_api_secret_key = "revolut-secret"
|
||||||
|
settings.revolut_api_version = "2026-04-20"
|
||||||
|
|
||||||
|
wallet = RevolutWallet()
|
||||||
|
client = MockHTTPClient(
|
||||||
|
[
|
||||||
|
MockHTTPResponse(
|
||||||
|
json_data={
|
||||||
|
"id": "ORDER_JPY",
|
||||||
|
"checkout_url": "https://checkout.revolut.com/payment-link/jpy",
|
||||||
|
}
|
||||||
|
),
|
||||||
|
MockHTTPResponse(
|
||||||
|
json_data={
|
||||||
|
"id": "ORDER_KWD",
|
||||||
|
"checkout_url": "https://checkout.revolut.com/payment-link/kwd",
|
||||||
|
}
|
||||||
|
),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
wallet.client = client # type: ignore[assignment]
|
||||||
|
|
||||||
|
await wallet.create_invoice(
|
||||||
|
amount=123,
|
||||||
|
payment_hash="hash_jpy",
|
||||||
|
currency="JPY",
|
||||||
|
)
|
||||||
|
await wallet.create_invoice(
|
||||||
|
amount=1.234,
|
||||||
|
payment_hash="hash_kwd",
|
||||||
|
currency="KWD",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert client.calls[0][1]["json"]["amount"] == 123
|
||||||
|
assert client.calls[1][1]["json"]["amount"] == 1234
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_revolut_wallet_get_invoice_status(settings: Settings):
|
async def test_revolut_wallet_get_invoice_status(settings: Settings):
|
||||||
settings.revolut_api_endpoint = "https://sandbox-merchant.revolut.com"
|
settings.revolut_api_endpoint = "https://sandbox-merchant.revolut.com"
|
||||||
@@ -834,6 +880,16 @@ async def test_revolut_wallet_create_subscription(settings: Settings):
|
|||||||
wallet = RevolutWallet()
|
wallet = RevolutWallet()
|
||||||
client = MockHTTPClient(
|
client = MockHTTPClient(
|
||||||
[
|
[
|
||||||
|
MockHTTPResponse(
|
||||||
|
json_data={
|
||||||
|
"customers": [
|
||||||
|
{
|
||||||
|
"id": "CUSTOMER123",
|
||||||
|
"email": "customer@example.com",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
),
|
||||||
MockHTTPResponse(
|
MockHTTPResponse(
|
||||||
json_data={
|
json_data={
|
||||||
"id": "SUBSCRIPTION123",
|
"id": "SUBSCRIPTION123",
|
||||||
@@ -854,7 +910,8 @@ async def test_revolut_wallet_create_subscription(settings: Settings):
|
|||||||
wallet_id="wallet_1",
|
wallet_id="wallet_1",
|
||||||
memo="Monthly Gold",
|
memo="Monthly Gold",
|
||||||
tag="gold",
|
tag="gold",
|
||||||
extra={"customer_id": "CUSTOMER123", "link": "link-1"},
|
customer_email="customer@example.com",
|
||||||
|
extra={"link": "link-1"},
|
||||||
success_url="https://lnbits.example/subscription-success",
|
success_url="https://lnbits.example/subscription-success",
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -863,24 +920,312 @@ async def test_revolut_wallet_create_subscription(settings: Settings):
|
|||||||
)
|
)
|
||||||
|
|
||||||
assert response.ok is True
|
assert response.ok is True
|
||||||
assert response.subscription_request_id == "SUBSCRIPTION123"
|
assert response.subscription_request_id is not None
|
||||||
assert (
|
assert (
|
||||||
response.checkout_session_url
|
response.checkout_session_url
|
||||||
== "https://checkout.revolut.com/payment-link/sub_123"
|
== "https://checkout.revolut.com/payment-link/sub_123"
|
||||||
)
|
)
|
||||||
assert client.calls[0][0] == "/api/subscriptions"
|
assert client.calls[0][0] == "/api/customers"
|
||||||
payload = client.calls[0][1]["json"]
|
assert client.calls[0][1]["params"] == {"limit": 500}
|
||||||
|
assert client.calls[0][1]["timeout"] == 30
|
||||||
|
assert client.calls[1][0] == "/api/subscriptions"
|
||||||
|
payload = client.calls[1][1]["json"]
|
||||||
assert payload["plan_variation_id"] == "PLAN_VARIATION_123"
|
assert payload["plan_variation_id"] == "PLAN_VARIATION_123"
|
||||||
assert payload["customer_id"] == "CUSTOMER123"
|
assert payload["customer_id"] == "CUSTOMER123"
|
||||||
|
assert client.calls[1][1]["timeout"] == 30
|
||||||
|
assert client.calls[1][1]["headers"]["Idempotency-Key"] == (
|
||||||
|
response.subscription_request_id
|
||||||
|
)
|
||||||
assert payload["setup_order_redirect_url"] == (
|
assert payload["setup_order_redirect_url"] == (
|
||||||
"https://lnbits.example/subscription-success"
|
"https://lnbits.example/subscription-success"
|
||||||
)
|
)
|
||||||
reference = json.loads(payload["external_reference"])
|
reference = json.loads(payload["external_reference"])
|
||||||
assert reference["wallet_id"] == "wallet_1"
|
assert reference["wallet_id"] == "wallet_1"
|
||||||
assert reference["tag"] == "gold"
|
assert reference["tag"] == "gold"
|
||||||
|
assert reference["subscription_request_id"] == response.subscription_request_id
|
||||||
assert reference["memo"] == "Monthly Gold"
|
assert reference["memo"] == "Monthly Gold"
|
||||||
assert reference["extra"]["customer_id"] == "CUSTOMER123"
|
assert reference["extra"]["link"] == "link-1"
|
||||||
assert client.calls[1][0] == "/api/orders/ORDER123"
|
assert client.calls[2][0] == "/api/orders/ORDER123"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_revolut_wallet_create_subscription_uses_customer_email(
|
||||||
|
settings: Settings,
|
||||||
|
):
|
||||||
|
settings.revolut_api_endpoint = "https://sandbox-merchant.revolut.com"
|
||||||
|
settings.revolut_api_secret_key = "revolut-secret"
|
||||||
|
settings.revolut_api_version = "2026-04-20"
|
||||||
|
|
||||||
|
wallet = RevolutWallet()
|
||||||
|
client = MockHTTPClient(
|
||||||
|
[
|
||||||
|
MockHTTPResponse(
|
||||||
|
json_data={
|
||||||
|
"customers": [
|
||||||
|
{
|
||||||
|
"id": "CUSTOMER123",
|
||||||
|
"email": "customer@example.com",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
),
|
||||||
|
MockHTTPResponse(
|
||||||
|
json_data={
|
||||||
|
"id": "SUBSCRIPTION123",
|
||||||
|
"setup_order_id": "ORDER123",
|
||||||
|
}
|
||||||
|
),
|
||||||
|
MockHTTPResponse(
|
||||||
|
json_data={
|
||||||
|
"id": "ORDER123",
|
||||||
|
"checkout_url": "https://checkout.revolut.com/payment-link/sub_123",
|
||||||
|
}
|
||||||
|
),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
wallet.client = client # type: ignore[assignment]
|
||||||
|
|
||||||
|
payment_options = FiatSubscriptionPaymentOptions(
|
||||||
|
wallet_id="wallet_1",
|
||||||
|
customer_email="customer@example.com",
|
||||||
|
)
|
||||||
|
|
||||||
|
response = await wallet.create_subscription(
|
||||||
|
"PLAN_VARIATION_123", 1, payment_options
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.ok is True
|
||||||
|
assert client.calls[0][0] == "/api/customers"
|
||||||
|
assert client.calls[0][1]["params"] == {"limit": 500}
|
||||||
|
assert client.calls[0][1]["timeout"] == 30
|
||||||
|
assert client.calls[1][0] == "/api/subscriptions"
|
||||||
|
assert client.calls[1][1]["json"]["customer_id"] == "CUSTOMER123"
|
||||||
|
assert client.calls[1][1]["timeout"] == 30
|
||||||
|
assert client.calls[2][0] == "/api/orders/ORDER123"
|
||||||
|
assert client.calls[2][1]["timeout"] == 30
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_revolut_wallet_create_subscription_uses_paginated_customer_email(
|
||||||
|
settings: Settings,
|
||||||
|
):
|
||||||
|
settings.revolut_api_endpoint = "https://sandbox-merchant.revolut.com"
|
||||||
|
settings.revolut_api_secret_key = "revolut-secret"
|
||||||
|
settings.revolut_api_version = "2026-04-20"
|
||||||
|
|
||||||
|
wallet = RevolutWallet()
|
||||||
|
client = MockHTTPClient(
|
||||||
|
[
|
||||||
|
MockHTTPResponse(
|
||||||
|
json_data={
|
||||||
|
"next_page_token": "PAGE2",
|
||||||
|
"customers": [
|
||||||
|
{
|
||||||
|
"id": "OTHER_CUSTOMER",
|
||||||
|
"email": "other@example.com",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
}
|
||||||
|
),
|
||||||
|
MockHTTPResponse(
|
||||||
|
json_data={
|
||||||
|
"customers": [
|
||||||
|
{
|
||||||
|
"id": "CUSTOMER123",
|
||||||
|
"email": "customer@example.com",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
}
|
||||||
|
),
|
||||||
|
MockHTTPResponse(
|
||||||
|
json_data={
|
||||||
|
"id": "SUBSCRIPTION123",
|
||||||
|
"setup_order_id": "ORDER123",
|
||||||
|
}
|
||||||
|
),
|
||||||
|
MockHTTPResponse(
|
||||||
|
json_data={
|
||||||
|
"id": "ORDER123",
|
||||||
|
"checkout_url": "https://checkout.revolut.com/payment-link/sub_123",
|
||||||
|
}
|
||||||
|
),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
wallet.client = client # type: ignore[assignment]
|
||||||
|
|
||||||
|
payment_options = FiatSubscriptionPaymentOptions(
|
||||||
|
wallet_id="wallet_1",
|
||||||
|
customer_email="customer@example.com",
|
||||||
|
)
|
||||||
|
|
||||||
|
response = await wallet.create_subscription(
|
||||||
|
"PLAN_VARIATION_123", 1, payment_options
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.ok is True
|
||||||
|
assert client.calls[0][0] == "/api/customers"
|
||||||
|
assert client.calls[0][1]["params"] == {"limit": 500}
|
||||||
|
assert client.calls[1][0] == "/api/customers"
|
||||||
|
assert client.calls[1][1]["params"] == {
|
||||||
|
"limit": 500,
|
||||||
|
"page_token": "PAGE2",
|
||||||
|
}
|
||||||
|
assert client.calls[1][1]["timeout"] == 30
|
||||||
|
assert client.calls[2][0] == "/api/subscriptions"
|
||||||
|
assert client.calls[2][1]["json"]["customer_id"] == "CUSTOMER123"
|
||||||
|
assert client.calls[3][0] == "/api/orders/ORDER123"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_revolut_wallet_create_subscription_creates_customer(settings: Settings):
|
||||||
|
settings.revolut_api_endpoint = "https://sandbox-merchant.revolut.com"
|
||||||
|
settings.revolut_api_secret_key = "revolut-secret"
|
||||||
|
settings.revolut_api_version = "2026-04-20"
|
||||||
|
|
||||||
|
wallet = RevolutWallet()
|
||||||
|
client = MockHTTPClient(
|
||||||
|
[
|
||||||
|
MockHTTPResponse(
|
||||||
|
json_data={
|
||||||
|
"next_page_token": "PAGE2",
|
||||||
|
"customers": [
|
||||||
|
{
|
||||||
|
"id": "OTHER_CUSTOMER",
|
||||||
|
"email": "other@example.com",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
}
|
||||||
|
),
|
||||||
|
MockHTTPResponse(json_data={"customers": []}),
|
||||||
|
MockHTTPResponse(json_data={"id": "CUSTOMER123"}),
|
||||||
|
MockHTTPResponse(
|
||||||
|
json_data={
|
||||||
|
"id": "SUBSCRIPTION123",
|
||||||
|
"setup_order_id": "ORDER123",
|
||||||
|
}
|
||||||
|
),
|
||||||
|
MockHTTPResponse(
|
||||||
|
json_data={
|
||||||
|
"id": "ORDER123",
|
||||||
|
"checkout_url": "https://checkout.revolut.com/payment-link/sub_123",
|
||||||
|
}
|
||||||
|
),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
wallet.client = client # type: ignore[assignment]
|
||||||
|
|
||||||
|
payment_options = FiatSubscriptionPaymentOptions(
|
||||||
|
wallet_id="wallet_1",
|
||||||
|
customer_email="customer@example.com",
|
||||||
|
)
|
||||||
|
|
||||||
|
response = await wallet.create_subscription(
|
||||||
|
"PLAN_VARIATION_123", 1, payment_options
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.ok is True
|
||||||
|
assert client.calls[0][0] == "/api/customers"
|
||||||
|
assert client.calls[0][1]["params"] == {"limit": 500}
|
||||||
|
assert client.calls[1][0] == "/api/customers"
|
||||||
|
assert client.calls[1][1]["params"] == {
|
||||||
|
"limit": 500,
|
||||||
|
"page_token": "PAGE2",
|
||||||
|
}
|
||||||
|
assert client.calls[2][0] == "/api/customers"
|
||||||
|
assert client.calls[2][1]["json"] == {"email": "customer@example.com"}
|
||||||
|
assert client.calls[2][1]["timeout"] == 30
|
||||||
|
assert client.calls[3][0] == "/api/subscriptions"
|
||||||
|
assert client.calls[3][1]["json"]["customer_id"] == "CUSTOMER123"
|
||||||
|
assert client.calls[4][0] == "/api/orders/ORDER123"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_revolut_wallet_create_subscription_stops_customer_lookup_after_20_pages(
|
||||||
|
settings: Settings,
|
||||||
|
):
|
||||||
|
settings.revolut_api_endpoint = "https://sandbox-merchant.revolut.com"
|
||||||
|
settings.revolut_api_secret_key = "revolut-secret"
|
||||||
|
settings.revolut_api_version = "2026-04-20"
|
||||||
|
|
||||||
|
wallet = RevolutWallet()
|
||||||
|
customer_pages = [
|
||||||
|
MockHTTPResponse(
|
||||||
|
json_data={
|
||||||
|
"next_page_token": f"PAGE{page + 2}",
|
||||||
|
"customers": [
|
||||||
|
{
|
||||||
|
"id": f"OTHER_CUSTOMER_{page}",
|
||||||
|
"email": f"other-{page}@example.com",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
for page in range(20)
|
||||||
|
]
|
||||||
|
client = MockHTTPClient(
|
||||||
|
[
|
||||||
|
*customer_pages,
|
||||||
|
MockHTTPResponse(json_data={"id": "CUSTOMER123"}),
|
||||||
|
MockHTTPResponse(
|
||||||
|
json_data={
|
||||||
|
"id": "SUBSCRIPTION123",
|
||||||
|
"setup_order_id": "ORDER123",
|
||||||
|
}
|
||||||
|
),
|
||||||
|
MockHTTPResponse(
|
||||||
|
json_data={
|
||||||
|
"id": "ORDER123",
|
||||||
|
"checkout_url": "https://checkout.revolut.com/payment-link/sub_123",
|
||||||
|
}
|
||||||
|
),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
wallet.client = client # type: ignore[assignment]
|
||||||
|
|
||||||
|
payment_options = FiatSubscriptionPaymentOptions(
|
||||||
|
wallet_id="wallet_1",
|
||||||
|
customer_email="customer@example.com",
|
||||||
|
)
|
||||||
|
|
||||||
|
response = await wallet.create_subscription(
|
||||||
|
"PLAN_VARIATION_123", 1, payment_options
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.ok is True
|
||||||
|
assert [call[0] for call in client.calls[:20]] == ["/api/customers"] * 20
|
||||||
|
assert client.calls[0][1]["params"] == {"limit": 500}
|
||||||
|
assert client.calls[19][1]["params"] == {
|
||||||
|
"limit": 500,
|
||||||
|
"page_token": "PAGE20",
|
||||||
|
}
|
||||||
|
assert client.calls[20][0] == "/api/customers"
|
||||||
|
assert client.calls[20][1]["json"] == {"email": "customer@example.com"}
|
||||||
|
assert client.calls[21][0] == "/api/subscriptions"
|
||||||
|
assert client.calls[21][1]["json"]["customer_id"] == "CUSTOMER123"
|
||||||
|
assert client.calls[22][0] == "/api/orders/ORDER123"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_revolut_wallet_create_subscription_requires_customer_email(
|
||||||
|
settings: Settings,
|
||||||
|
):
|
||||||
|
settings.revolut_api_endpoint = "https://sandbox-merchant.revolut.com"
|
||||||
|
settings.revolut_api_secret_key = "revolut-secret"
|
||||||
|
settings.revolut_api_version = "2026-04-20"
|
||||||
|
|
||||||
|
wallet = RevolutWallet()
|
||||||
|
client = MockHTTPClient([])
|
||||||
|
wallet.client = client # type: ignore[assignment]
|
||||||
|
|
||||||
|
payment_options = FiatSubscriptionPaymentOptions(wallet_id="wallet_1")
|
||||||
|
|
||||||
|
response = await wallet.create_subscription(
|
||||||
|
"PLAN_VARIATION_123", 1, payment_options
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.ok is False
|
||||||
|
assert response.error_message == "Revolut subscriptions require customer_email."
|
||||||
|
assert client.calls == []
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
@@ -936,7 +1281,7 @@ async def test_revolut_wallet_create_webhook(mocker: MockerFixture):
|
|||||||
(
|
(
|
||||||
"/api/webhooks",
|
"/api/webhooks",
|
||||||
{
|
{
|
||||||
"timeout": 15,
|
"timeout": 30,
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
(
|
(
|
||||||
@@ -946,7 +1291,7 @@ async def test_revolut_wallet_create_webhook(mocker: MockerFixture):
|
|||||||
"url": "https://lnbits.example/api/v1/callback/revolut",
|
"url": "https://lnbits.example/api/v1/callback/revolut",
|
||||||
"events": REVOLUT_WEBHOOK_EVENTS,
|
"events": REVOLUT_WEBHOOK_EVENTS,
|
||||||
},
|
},
|
||||||
"timeout": 15,
|
"timeout": 30,
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
]
|
]
|
||||||
@@ -986,7 +1331,7 @@ async def test_revolut_wallet_reuses_existing_webhook(mocker: MockerFixture):
|
|||||||
(
|
(
|
||||||
"/api/webhooks",
|
"/api/webhooks",
|
||||||
{
|
{
|
||||||
"timeout": 15,
|
"timeout": 30,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
]
|
]
|
||||||
@@ -1005,20 +1350,22 @@ async def test_revolut_wallet_rejects_local_webhook_url():
|
|||||||
|
|
||||||
def test_check_revolut_signature():
|
def test_check_revolut_signature():
|
||||||
payload = b'{"event":"ORDER_COMPLETED","order_id":"ORDER123"}'
|
payload = b'{"event":"ORDER_COMPLETED","order_id":"ORDER123"}'
|
||||||
timestamp = str(int(time.time()))
|
timestamp = str(int(time.time() * 1000))
|
||||||
secret = "revolut-secret"
|
secret = "revolut-secret"
|
||||||
sig = hmac.new(secret.encode(), payload, hashlib.sha256).hexdigest()
|
signed_payload = b"v1." + timestamp.encode() + b"." + payload
|
||||||
|
sig = "v1=" + hmac.new(secret.encode(), signed_payload, hashlib.sha256).hexdigest()
|
||||||
|
|
||||||
check_revolut_signature(payload, sig, timestamp, secret)
|
check_revolut_signature(payload, sig, timestamp, secret)
|
||||||
|
|
||||||
|
|
||||||
def test_check_revolut_signature_millisecond_timestamp():
|
def test_check_revolut_signature_rejects_payload_only_signature():
|
||||||
payload = b'{"event":"ORDER_COMPLETED","order_id":"ORDER123"}'
|
payload = b'{"event":"ORDER_COMPLETED","order_id":"ORDER123"}'
|
||||||
timestamp = str(int(time.time() * 1000))
|
timestamp = str(int(time.time() * 1000))
|
||||||
secret = "revolut-secret"
|
secret = "revolut-secret"
|
||||||
sig = hmac.new(secret.encode(), payload, hashlib.sha256).hexdigest()
|
sig = hmac.new(secret.encode(), payload, hashlib.sha256).hexdigest()
|
||||||
|
|
||||||
check_revolut_signature(payload, sig, timestamp, secret)
|
with pytest.raises(ValueError, match="signature verification failed"):
|
||||||
|
check_revolut_signature(payload, sig, timestamp, secret)
|
||||||
|
|
||||||
|
|
||||||
def test_check_revolut_signature_v1_header():
|
def test_check_revolut_signature_v1_header():
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ from tests.helpers import make_upload_file
|
|||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_create_user_asset_validates_upload_constraints(
|
async def test_create_user_asset_validates_upload_constraints(
|
||||||
settings: Settings, mocker: MockerFixture
|
app, settings: Settings, mocker: MockerFixture
|
||||||
):
|
):
|
||||||
file_without_type = make_upload_file(b"hello", filename="a.txt", content_type=None)
|
file_without_type = make_upload_file(b"hello", filename="a.txt", content_type=None)
|
||||||
with pytest.raises(ValueError, match="File must have a content type."):
|
with pytest.raises(ValueError, match="File must have a content type."):
|
||||||
@@ -31,6 +31,40 @@ async def test_create_user_asset_validates_upload_constraints(
|
|||||||
):
|
):
|
||||||
await create_user_asset("user-1", bad_type, is_public=False)
|
await create_user_asset("user-1", bad_type, is_public=False)
|
||||||
|
|
||||||
|
xsl_upload = make_upload_file(
|
||||||
|
b"hello",
|
||||||
|
filename="style.xsl",
|
||||||
|
content_type="text/xml",
|
||||||
|
)
|
||||||
|
with pytest.raises(ValueError, match="File type 'text/xml' not allowed."):
|
||||||
|
await create_user_asset("user-1", xsl_upload, is_public=False)
|
||||||
|
|
||||||
|
original_allowed_mime_types = list(settings.lnbits_assets_allowed_mime_types)
|
||||||
|
try:
|
||||||
|
settings.lnbits_assets_allowed_mime_types = [
|
||||||
|
*original_allowed_mime_types,
|
||||||
|
"text/xml",
|
||||||
|
]
|
||||||
|
xsl_content = make_upload_file(
|
||||||
|
b'<stylesheet xmlns="http://www.w3.org/1999/XSL/Transform"></stylesheet>',
|
||||||
|
filename="style.xml",
|
||||||
|
content_type="text/xml",
|
||||||
|
)
|
||||||
|
with pytest.raises(ValueError, match="File type 'text/xml' not allowed."):
|
||||||
|
await create_user_asset("user-1", xsl_content, is_public=False)
|
||||||
|
finally:
|
||||||
|
settings.lnbits_assets_allowed_mime_types = original_allowed_mime_types
|
||||||
|
|
||||||
|
fake_image = make_upload_file(
|
||||||
|
b"<?xml version='1.0'?><root></root>",
|
||||||
|
filename="fake.png",
|
||||||
|
content_type="image/png",
|
||||||
|
)
|
||||||
|
with pytest.raises(
|
||||||
|
ValueError, match="Image file content does not match declared file type."
|
||||||
|
):
|
||||||
|
await create_user_asset("user-1", fake_image, is_public=False)
|
||||||
|
|
||||||
original_max_assets = settings.lnbits_max_assets_per_user
|
original_max_assets = settings.lnbits_max_assets_per_user
|
||||||
original_max_size = settings.lnbits_max_asset_size_mb
|
original_max_size = settings.lnbits_max_asset_size_mb
|
||||||
original_no_limit_users = list(settings.lnbits_assets_no_limit_users)
|
original_no_limit_users = list(settings.lnbits_assets_no_limit_users)
|
||||||
@@ -40,14 +74,14 @@ async def test_create_user_asset_validates_upload_constraints(
|
|||||||
settings.lnbits_assets_no_limit_users = []
|
settings.lnbits_assets_no_limit_users = []
|
||||||
limited_user = await _create_user()
|
limited_user = await _create_user()
|
||||||
allowed_type = make_upload_file(
|
allowed_type = make_upload_file(
|
||||||
b"hello", filename="ok.txt", content_type="text/plain"
|
_png_bytes(), filename="ok.png", content_type="image/png"
|
||||||
)
|
)
|
||||||
await create_user_asset(limited_user, allowed_type, is_public=False)
|
await create_user_asset(limited_user, allowed_type, is_public=False)
|
||||||
|
|
||||||
blocked_by_count = make_upload_file(
|
blocked_by_count = make_upload_file(
|
||||||
b"again",
|
_png_bytes(),
|
||||||
filename="again.txt",
|
filename="again.png",
|
||||||
content_type="text/plain",
|
content_type="image/png",
|
||||||
)
|
)
|
||||||
with pytest.raises(ValueError, match="Max upload count of 1 exceeded."):
|
with pytest.raises(ValueError, match="Max upload count of 1 exceeded."):
|
||||||
await create_user_asset(limited_user, blocked_by_count, is_public=False)
|
await create_user_asset(limited_user, blocked_by_count, is_public=False)
|
||||||
@@ -55,9 +89,9 @@ async def test_create_user_asset_validates_upload_constraints(
|
|||||||
settings.lnbits_max_asset_size_mb = 0.000001
|
settings.lnbits_max_asset_size_mb = 0.000001
|
||||||
oversized_user = await _create_user()
|
oversized_user = await _create_user()
|
||||||
large_file = make_upload_file(
|
large_file = make_upload_file(
|
||||||
b"0123456789",
|
_png_bytes(),
|
||||||
filename="ok.txt",
|
filename="ok.png",
|
||||||
content_type="text/plain",
|
content_type="image/png",
|
||||||
)
|
)
|
||||||
with pytest.raises(ValueError, match="File limit of 1e-06MB exceeded."):
|
with pytest.raises(ValueError, match="File limit of 1e-06MB exceeded."):
|
||||||
await create_user_asset(oversized_user, large_file, is_public=False)
|
await create_user_asset(oversized_user, large_file, is_public=False)
|
||||||
@@ -68,29 +102,66 @@ async def test_create_user_asset_validates_upload_constraints(
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_create_user_asset_success(mocker: MockerFixture):
|
async def test_create_user_asset_success(app, mocker: MockerFixture):
|
||||||
user_id = await _create_user()
|
user_id = await _create_user()
|
||||||
mocker.patch(
|
mocker.patch(
|
||||||
"lnbits.core.services.assets.thumbnail_from_bytes",
|
"lnbits.core.services.assets.thumbnail_from_bytes",
|
||||||
return_value=None,
|
return_value=None,
|
||||||
)
|
)
|
||||||
file = make_upload_file(b"hello", filename="hello.txt", content_type="text/plain")
|
contents = _png_bytes()
|
||||||
|
file = make_upload_file(contents, filename="hello.png", content_type="image/png")
|
||||||
|
|
||||||
asset = await create_user_asset(user_id, file, is_public=True)
|
asset = await create_user_asset(user_id, file, is_public=True)
|
||||||
stored = await get_user_asset(user_id, asset.id)
|
stored = await get_user_asset(user_id, asset.id)
|
||||||
|
|
||||||
assert asset.id
|
assert asset.id
|
||||||
assert asset.user_id == user_id
|
assert asset.user_id == user_id
|
||||||
assert asset.name == "hello.txt"
|
assert asset.name == "hello.png"
|
||||||
assert asset.size_bytes == 5
|
assert asset.size_bytes == len(contents)
|
||||||
assert asset.data == b"hello"
|
assert asset.data == contents
|
||||||
assert asset.is_public is True
|
assert asset.is_public is True
|
||||||
assert stored is not None
|
assert stored is not None
|
||||||
assert stored.id == asset.id
|
assert stored.id == asset.id
|
||||||
assert stored.data == b"hello"
|
assert stored.data == contents
|
||||||
assert await get_user_assets_count(user_id) == 1
|
assert await get_user_assets_count(user_id) == 1
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_create_user_asset_stores_detected_image_mime_type(app):
|
||||||
|
user_id = await _create_user()
|
||||||
|
buffer = BytesIO()
|
||||||
|
Image.new("RGB", (32, 32), color="blue").save(buffer, format="JPEG")
|
||||||
|
file = make_upload_file(
|
||||||
|
buffer.getvalue(), filename="photo.jpg", content_type="image/jpg"
|
||||||
|
)
|
||||||
|
|
||||||
|
asset = await create_user_asset(user_id, file, is_public=True)
|
||||||
|
stored = await get_user_asset(user_id, asset.id)
|
||||||
|
|
||||||
|
assert asset.mime_type == "image/jpeg"
|
||||||
|
assert stored is not None
|
||||||
|
assert stored.mime_type == "image/jpeg"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_create_user_asset_rejects_mismatched_image_content(app):
|
||||||
|
user_id = await _create_user()
|
||||||
|
buffer = BytesIO()
|
||||||
|
Image.new("RGB", (32, 32), color="blue").save(buffer, format="JPEG")
|
||||||
|
file = make_upload_file(
|
||||||
|
buffer.getvalue(), filename="photo.png", content_type="image/png"
|
||||||
|
)
|
||||||
|
|
||||||
|
with pytest.raises(
|
||||||
|
ValueError,
|
||||||
|
match=(
|
||||||
|
"Image file content does not match declared file type. "
|
||||||
|
"Declared: 'image/png', detected: 'image/jpeg'."
|
||||||
|
),
|
||||||
|
):
|
||||||
|
await create_user_asset(user_id, file, is_public=False)
|
||||||
|
|
||||||
|
|
||||||
def test_thumbnail_from_bytes_success_and_failure():
|
def test_thumbnail_from_bytes_success_and_failure():
|
||||||
image = Image.new("RGB", (512, 512), color="red")
|
image = Image.new("RGB", (512, 512), color="red")
|
||||||
buffer = BytesIO()
|
buffer = BytesIO()
|
||||||
@@ -107,3 +178,9 @@ async def _create_user() -> str:
|
|||||||
user_id = uuid4().hex
|
user_id = uuid4().hex
|
||||||
await create_account(Account(id=user_id, username=f"user_{user_id[:8]}"))
|
await create_account(Account(id=user_id, username=f"user_{user_id[:8]}"))
|
||||||
return user_id
|
return user_id
|
||||||
|
|
||||||
|
|
||||||
|
def _png_bytes() -> bytes:
|
||||||
|
buffer = BytesIO()
|
||||||
|
Image.new("RGB", (32, 32), color="green").save(buffer, format="PNG")
|
||||||
|
return buffer.getvalue()
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
from typing import cast
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
@@ -86,7 +87,9 @@ async def test_get_pr_from_lnurl_success_and_error(mocker: MockerFixture):
|
|||||||
mocker.patch(
|
mocker.patch(
|
||||||
"lnbits.core.services.lnurl.execute_pay_request",
|
"lnbits.core.services.lnurl.execute_pay_request",
|
||||||
mocker.AsyncMock(
|
mocker.AsyncMock(
|
||||||
return_value=LnurlPayActionResponse(pr=LightningInvoice(TEST_BOLT11))
|
return_value=LnurlPayActionResponse(
|
||||||
|
pr=cast(LightningInvoice, LightningInvoice(TEST_BOLT11))
|
||||||
|
)
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -106,7 +109,7 @@ async def test_fetch_lnurl_pay_request_converts_currency_and_stores_paylink(
|
|||||||
):
|
):
|
||||||
pay_response = make_lnurl_pay_response(min_sendable_msat=1, text="Test")
|
pay_response = make_lnurl_pay_response(min_sendable_msat=1, text="Test")
|
||||||
action_response = LnurlPayActionResponse(
|
action_response = LnurlPayActionResponse(
|
||||||
pr=LightningInvoice(TEST_BOLT11), disposable=False
|
pr=cast(LightningInvoice, LightningInvoice(TEST_BOLT11)), disposable=False
|
||||||
)
|
)
|
||||||
mocker.patch(
|
mocker.patch(
|
||||||
"lnbits.core.services.lnurl.fiat_amount_as_satoshis",
|
"lnbits.core.services.lnurl.fiat_amount_as_satoshis",
|
||||||
@@ -143,7 +146,7 @@ async def test_store_paylink_appends_and_updates_existing():
|
|||||||
wallet = await _create_wallet()
|
wallet = await _create_wallet()
|
||||||
pay_response = make_lnurl_pay_response(min_sendable_msat=1, text="Test")
|
pay_response = make_lnurl_pay_response(min_sendable_msat=1, text="Test")
|
||||||
action_response = LnurlPayActionResponse(
|
action_response = LnurlPayActionResponse(
|
||||||
pr=LightningInvoice(TEST_BOLT11), disposable=False
|
pr=cast(LightningInvoice, LightningInvoice(TEST_BOLT11)), disposable=False
|
||||||
)
|
)
|
||||||
|
|
||||||
await store_paylink(
|
await store_paylink(
|
||||||
|
|||||||
@@ -37,12 +37,14 @@ def test_dict_to_settings_parses_known_values():
|
|||||||
{
|
{
|
||||||
"lnbits_site_title": "Test Title",
|
"lnbits_site_title": "Test Title",
|
||||||
"lnbits_service_fee": 5,
|
"lnbits_service_fee": 5,
|
||||||
|
"lnbits_default_burger_menu_background": False,
|
||||||
"ignored_field": "ignored",
|
"ignored_field": "ignored",
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
assert parsed.lnbits_site_title == "Test Title"
|
assert parsed.lnbits_site_title == "Test Title"
|
||||||
assert parsed.lnbits_service_fee == 5
|
assert parsed.lnbits_service_fee == 5
|
||||||
|
assert parsed.lnbits_default_burger_menu_background is False
|
||||||
assert not hasattr(parsed, "ignored_field")
|
assert not hasattr(parsed, "ignored_field")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
from typing import Any
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
@@ -66,7 +67,7 @@ async def test_create_user_account_no_check_rejects_duplicate_identity_fields(
|
|||||||
existing = _account(**existing_data)
|
existing = _account(**existing_data)
|
||||||
await create_account(existing)
|
await create_account(existing)
|
||||||
|
|
||||||
resolved = {
|
resolved: dict[str, Any] = {
|
||||||
key: (value(existing) if callable(value) else value)
|
key: (value(existing) if callable(value) else value)
|
||||||
for key, value in new_data.items()
|
for key, value in new_data.items()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
from typing import Any
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from pytest_mock.plugin import MockerFixture
|
from pytest_mock.plugin import MockerFixture
|
||||||
|
|
||||||
@@ -14,22 +16,22 @@ from lnbits.settings import (
|
|||||||
set_cli_settings,
|
set_cli_settings,
|
||||||
)
|
)
|
||||||
|
|
||||||
lnurlp_redirect_path = {
|
lnurlp_redirect_path: dict[str, Any] = {
|
||||||
"from_path": "/.well-known/lnurlp",
|
"from_path": "/.well-known/lnurlp",
|
||||||
"redirect_to_path": "/api/v1/well-known",
|
"redirect_to_path": "/api/v1/well-known",
|
||||||
}
|
}
|
||||||
lnurlp_redirect_path_with_headers = {
|
lnurlp_redirect_path_with_headers: dict[str, Any] = {
|
||||||
"from_path": "/.well-known/lnurlp",
|
"from_path": "/.well-known/lnurlp",
|
||||||
"redirect_to_path": "/api/v1/well-known",
|
"redirect_to_path": "/api/v1/well-known",
|
||||||
"header_filters": {"accept": "application/nostr+json"},
|
"header_filters": {"accept": "application/nostr+json"},
|
||||||
}
|
}
|
||||||
|
|
||||||
lnaddress_redirect_path = {
|
lnaddress_redirect_path: dict[str, Any] = {
|
||||||
"from_path": "/.well-known/lnurlp",
|
"from_path": "/.well-known/lnurlp",
|
||||||
"redirect_to_path": "/api/v1/well-known",
|
"redirect_to_path": "/api/v1/well-known",
|
||||||
}
|
}
|
||||||
|
|
||||||
nostrrelay_redirect_path = {
|
nostrrelay_redirect_path: dict[str, Any] = {
|
||||||
"from_path": "/",
|
"from_path": "/",
|
||||||
"redirect_to_path": "/api/v1/relay-info",
|
"redirect_to_path": "/api/v1/relay-info",
|
||||||
"header_filters": {"accept": "application/nostr+json"},
|
"header_filters": {"accept": "application/nostr+json"},
|
||||||
@@ -232,6 +234,14 @@ def test_installed_extensions_settings_activate_and_deactivate_paths():
|
|||||||
assert installed.find_extension_redirect("/.well-known/lnurlp", []) is None
|
assert installed.find_extension_redirect("/.well-known/lnurlp", []) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_public_settings_include_burger_menu_background(settings: Settings):
|
||||||
|
settings.lnbits_default_burger_menu_background = False
|
||||||
|
|
||||||
|
public_settings = PublicSettings.from_settings(settings)
|
||||||
|
|
||||||
|
assert public_settings.default_burger_menu_background is False
|
||||||
|
|
||||||
|
|
||||||
def test_installed_extensions_settings_detects_conflicting_redirects():
|
def test_installed_extensions_settings_detects_conflicting_redirects():
|
||||||
installed = InstalledExtensionsSettings(
|
installed = InstalledExtensionsSettings(
|
||||||
lnbits_extensions_redirects=[
|
lnbits_extensions_redirects=[
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import os
|
import os
|
||||||
|
from typing import cast
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from loguru import logger
|
from loguru import logger
|
||||||
@@ -29,7 +30,7 @@ logger.info(f"settings.blink_api_endpoint: {settings.blink_api_endpoint}")
|
|||||||
logger.info(f"settings.blink_token: {settings.blink_token}")
|
logger.info(f"settings.blink_token: {settings.blink_token}")
|
||||||
|
|
||||||
set_funding_source()
|
set_funding_source()
|
||||||
funding_source = get_funding_source()
|
funding_source = cast(BlinkWallet, get_funding_source())
|
||||||
assert isinstance(funding_source, BlinkWallet)
|
assert isinstance(funding_source, BlinkWallet)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import importlib
|
import importlib
|
||||||
|
from typing import Any
|
||||||
from unittest.mock import AsyncMock, Mock
|
from unittest.mock import AsyncMock, Mock
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
@@ -80,7 +81,9 @@ def _check_calls(expected_calls):
|
|||||||
for func_call in func_calls:
|
for func_call in func_calls:
|
||||||
req = func_call["request_data"]
|
req = func_call["request_data"]
|
||||||
args = req["args"] if "args" in req else {}
|
args = req["args"] if "args" in req else {}
|
||||||
kwargs = _eval_dict(req["kwargs"]) if "kwargs" in req else {}
|
kwargs: dict[str, Any] = (
|
||||||
|
_eval_dict(req["kwargs"]) or {} if "kwargs" in req else {}
|
||||||
|
)
|
||||||
|
|
||||||
if "klass" in req:
|
if "klass" in req:
|
||||||
*rest, cls = req["klass"].split(".")
|
*rest, cls = req["klass"].split(".")
|
||||||
@@ -166,7 +169,7 @@ def _mock_field(field):
|
|||||||
return response
|
return response
|
||||||
|
|
||||||
|
|
||||||
def _eval_dict(data: dict | None) -> dict | None:
|
def _eval_dict(data: dict | None) -> dict[str, Any] | None:
|
||||||
fn_prefix = "__eval__:"
|
fn_prefix = "__eval__:"
|
||||||
if not data:
|
if not data:
|
||||||
return data
|
return data
|
||||||
@@ -215,9 +218,9 @@ def _data_mock(data: dict) -> Mock:
|
|||||||
def _raise(error: dict | None):
|
def _raise(error: dict | None):
|
||||||
if not error:
|
if not error:
|
||||||
return Exception()
|
return Exception()
|
||||||
data = error["data"] if "data" in error else None
|
data: dict[str, Any] = error["data"] if "data" in error else {}
|
||||||
if "module" not in error or "class" not in error:
|
if "module" not in error or "class" not in error:
|
||||||
return Exception(data)
|
return Exception(data or None)
|
||||||
|
|
||||||
error_module = importlib.import_module(error["module"])
|
error_module = importlib.import_module(error["module"])
|
||||||
error_class = getattr(error_module, error["class"])
|
error_class = getattr(error_module, error["class"])
|
||||||
|
|||||||
Reference in New Issue
Block a user