diff --git a/lnbits/extensions/tpos/README.md b/lnbits/extensions/tpos/README.md deleted file mode 100644 index c7e3481d2..000000000 --- a/lnbits/extensions/tpos/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# TPoS - -## A Shareable PoS (Point of Sale) that doesn't need to be installed and can run in the browser! - -An easy, fast and secure way to accept Bitcoin, over Lightning Network, at your business. The PoS is isolated from the wallet, so it's safe for any employee to use. You can create as many TPOS's as you need, for example one for each employee, or one for each branch of your business. - -### Usage - -1. Enable extension -2. Create a TPOS\ - ![create](https://imgur.com/8jNj8Zq.jpg) -3. Open TPOS on the browser\ - ![open](https://imgur.com/LZuoWzb.jpg) -4. Present invoice QR to customer\ - ![pay](https://imgur.com/tOwxn77.jpg) diff --git a/lnbits/extensions/tpos/__init__.py b/lnbits/extensions/tpos/__init__.py deleted file mode 100644 index c1b5a7ddd..000000000 --- a/lnbits/extensions/tpos/__init__.py +++ /dev/null @@ -1,34 +0,0 @@ -import asyncio - -from fastapi import APIRouter -from fastapi.staticfiles import StaticFiles - -from lnbits.db import Database -from lnbits.helpers import template_renderer -from lnbits.tasks import catch_everything_and_restart - -db = Database("ext_tpos") - -tpos_ext: APIRouter = APIRouter(prefix="/tpos", tags=["TPoS"]) - -tpos_static_files = [ - { - "path": "/tpos/static", - "app": StaticFiles(directory="lnbits/extensions/tpos/static"), - "name": "tpos_static", - } -] - - -def tpos_renderer(): - return template_renderer(["lnbits/extensions/tpos/templates"]) - - -from .tasks import wait_for_paid_invoices -from .views import * # noqa -from .views_api import * # noqa - - -def tpos_start(): - loop = asyncio.get_event_loop() - loop.create_task(catch_everything_and_restart(wait_for_paid_invoices)) diff --git a/lnbits/extensions/tpos/config.json b/lnbits/extensions/tpos/config.json deleted file mode 100644 index 0c118e1a5..000000000 --- a/lnbits/extensions/tpos/config.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "name": "TPoS", - "short_description": "A shareable PoS terminal!", - "tile": "/tpos/static/image/tpos.png", - "contributors": ["talvasconcelos", "arcbtc", "leesalminen"] -} diff --git a/lnbits/extensions/tpos/crud.py b/lnbits/extensions/tpos/crud.py deleted file mode 100644 index 94e2c0068..000000000 --- a/lnbits/extensions/tpos/crud.py +++ /dev/null @@ -1,49 +0,0 @@ -from typing import List, Optional, Union - -from lnbits.helpers import urlsafe_short_hash - -from . import db -from .models import CreateTposData, TPoS - - -async def create_tpos(wallet_id: str, data: CreateTposData) -> TPoS: - tpos_id = urlsafe_short_hash() - await db.execute( - """ - INSERT INTO tpos.tposs (id, wallet, name, currency, tip_options, tip_wallet) - VALUES (?, ?, ?, ?, ?, ?) - """, - ( - tpos_id, - wallet_id, - data.name, - data.currency, - data.tip_options, - data.tip_wallet, - ), - ) - - tpos = await get_tpos(tpos_id) - assert tpos, "Newly created tpos couldn't be retrieved" - return tpos - - -async def get_tpos(tpos_id: str) -> Optional[TPoS]: - row = await db.fetchone("SELECT * FROM tpos.tposs WHERE id = ?", (tpos_id,)) - return TPoS(**row) if row else None - - -async def get_tposs(wallet_ids: Union[str, List[str]]) -> List[TPoS]: - if isinstance(wallet_ids, str): - wallet_ids = [wallet_ids] - - q = ",".join(["?"] * len(wallet_ids)) - rows = await db.fetchall( - f"SELECT * FROM tpos.tposs WHERE wallet IN ({q})", (*wallet_ids,) - ) - - return [TPoS(**row) for row in rows] - - -async def delete_tpos(tpos_id: str) -> None: - await db.execute("DELETE FROM tpos.tposs WHERE id = ?", (tpos_id,)) diff --git a/lnbits/extensions/tpos/migrations.py b/lnbits/extensions/tpos/migrations.py deleted file mode 100644 index 565c05abf..000000000 --- a/lnbits/extensions/tpos/migrations.py +++ /dev/null @@ -1,36 +0,0 @@ -async def m001_initial(db): - """ - Initial tposs table. - """ - await db.execute( - """ - CREATE TABLE tpos.tposs ( - id TEXT PRIMARY KEY, - wallet TEXT NOT NULL, - name TEXT NOT NULL, - currency TEXT NOT NULL - ); - """ - ) - - -async def m002_addtip_wallet(db): - """ - Add tips to tposs table - """ - await db.execute( - """ - ALTER TABLE tpos.tposs ADD tip_wallet TEXT NULL; - """ - ) - - -async def m003_addtip_options(db): - """ - Add tips to tposs table - """ - await db.execute( - """ - ALTER TABLE tpos.tposs ADD tip_options TEXT NULL; - """ - ) diff --git a/lnbits/extensions/tpos/models.py b/lnbits/extensions/tpos/models.py deleted file mode 100644 index f6522adda..000000000 --- a/lnbits/extensions/tpos/models.py +++ /dev/null @@ -1,29 +0,0 @@ -from sqlite3 import Row -from typing import Optional - -from fastapi import Query -from pydantic import BaseModel - - -class CreateTposData(BaseModel): - name: str - currency: str - tip_options: str = Query(None) - tip_wallet: str = Query(None) - - -class TPoS(BaseModel): - id: str - wallet: str - name: str - currency: str - tip_options: Optional[str] - tip_wallet: Optional[str] - - @classmethod - def from_row(cls, row: Row) -> "TPoS": - return cls(**dict(row)) - - -class PayLnurlWData(BaseModel): - lnurl: str diff --git a/lnbits/extensions/tpos/static/image/tpos.png b/lnbits/extensions/tpos/static/image/tpos.png deleted file mode 100644 index c663032d9..000000000 Binary files a/lnbits/extensions/tpos/static/image/tpos.png and /dev/null differ diff --git a/lnbits/extensions/tpos/tasks.py b/lnbits/extensions/tpos/tasks.py deleted file mode 100644 index 4b7bd9f9c..000000000 --- a/lnbits/extensions/tpos/tasks.py +++ /dev/null @@ -1,64 +0,0 @@ -import asyncio - -from loguru import logger - -from lnbits.core.models import Payment -from lnbits.core.services import create_invoice, pay_invoice, websocketUpdater -from lnbits.helpers import get_current_extension_name -from lnbits.tasks import register_invoice_listener - -from .crud import get_tpos - - -async def wait_for_paid_invoices(): - invoice_queue = asyncio.Queue() - register_invoice_listener(invoice_queue, get_current_extension_name()) - - while True: - payment = await invoice_queue.get() - await on_invoice_paid(payment) - - -async def on_invoice_paid(payment: Payment) -> None: - if payment.extra.get("tag") != "tpos": - return - - tipAmount = payment.extra.get("tipAmount") - - strippedPayment = { - "amount": payment.amount, - "fee": payment.fee, - "checking_id": payment.checking_id, - "payment_hash": payment.payment_hash, - "bolt11": payment.bolt11, - } - - tpos_id = payment.extra.get("tposId") - assert tpos_id - - tpos = await get_tpos(tpos_id) - assert tpos - - await websocketUpdater(tpos_id, str(strippedPayment)) - - if not tipAmount: - # no tip amount - return - - wallet_id = tpos.tip_wallet - assert wallet_id - - payment_hash, payment_request = await create_invoice( - wallet_id=wallet_id, - amount=int(tipAmount), - internal=True, - memo=f"tpos tip", - ) - logger.debug(f"tpos: tip invoice created: {payment_hash}") - - checking_id = await pay_invoice( - payment_request=payment_request, - wallet_id=payment.wallet_id, - extra={**payment.extra, "tipSplitted": True}, - ) - logger.debug(f"tpos: tip invoice paid: {checking_id}") diff --git a/lnbits/extensions/tpos/templates/tpos/_api_docs.html b/lnbits/extensions/tpos/templates/tpos/_api_docs.html deleted file mode 100644 index cbb21be13..000000000 --- a/lnbits/extensions/tpos/templates/tpos/_api_docs.html +++ /dev/null @@ -1,79 +0,0 @@ - - - - - - GET /tpos/api/v1/tposs -
Headers
- {"X-Api-Key": <invoice_key>}
-
Body (application/json)
-
- Returns 200 OK (application/json) -
- [<tpos_object>, ...] -
Curl example
- curl -X GET {{ request.base_url }}tpos/api/v1/tposs -H "X-Api-Key: - <invoice_key>" - -
-
-
- - - - POST /tpos/api/v1/tposs -
Headers
- {"X-Api-Key": <invoice_key>}
-
Body (application/json)
- {"name": <string>, "currency": <string*ie USD*>} -
- Returns 201 CREATED (application/json) -
- {"currency": <string>, "id": <string>, "name": - <string>, "wallet": <string>} -
Curl example
- curl -X POST {{ request.base_url }}tpos/api/v1/tposs -d '{"name": - <string>, "currency": <string>}' -H "Content-type: - application/json" -H "X-Api-Key: <admin_key>" - -
-
-
- - - - - DELETE - /tpos/api/v1/tposs/<tpos_id> -
Headers
- {"X-Api-Key": <admin_key>}
-
Returns 204 NO CONTENT
- -
Curl example
- curl -X DELETE {{ request.base_url - }}tpos/api/v1/tposs/<tpos_id> -H "X-Api-Key: <admin_key>" - -
-
-
-
diff --git a/lnbits/extensions/tpos/templates/tpos/_tpos.html b/lnbits/extensions/tpos/templates/tpos/_tpos.html deleted file mode 100644 index 97f4d52cb..000000000 --- a/lnbits/extensions/tpos/templates/tpos/_tpos.html +++ /dev/null @@ -1,21 +0,0 @@ - - - -

- Thiago's Point of Sale is a secure, mobile-ready, instant and shareable - point of sale terminal (PoS) for merchants. The PoS is linked to your - LNbits wallet but completely air-gapped so users can ONLY create - invoices. To share the TPoS hit the hash on the terminal. -

- Created by - Tiago Vasconcelos. -
-
-
diff --git a/lnbits/extensions/tpos/templates/tpos/index.html b/lnbits/extensions/tpos/templates/tpos/index.html deleted file mode 100644 index 1aa75fcf1..000000000 --- a/lnbits/extensions/tpos/templates/tpos/index.html +++ /dev/null @@ -1,471 +0,0 @@ -{% extends "base.html" %} {% from "macros.jinja" import window_vars with context -%} {% block page %} -
-
- - - New TPoS - - - - - -
-
-
TPoS
-
-
- Export to CSV -
-
- - {% raw %} - - - - {% endraw %} - -
-
-
- -
- - -
{{SITE_TITLE}} TPoS extension
-
- - - - {% include "tpos/_api_docs.html" %} - - {% include "tpos/_tpos.html" %} - - -
-
- - - - - - - - - Hit enter to add values - - -
- Create TPoS - Cancel -
-
-
-
-
-{% endblock %} {% block scripts %} {{ window_vars(user) }} - -{% endblock %} diff --git a/lnbits/extensions/tpos/templates/tpos/tpos.html b/lnbits/extensions/tpos/templates/tpos/tpos.html deleted file mode 100644 index 438fc22ea..000000000 --- a/lnbits/extensions/tpos/templates/tpos/tpos.html +++ /dev/null @@ -1,686 +0,0 @@ -{% extends "public.html" %} {% block toolbar_title %} {{ tpos.name }} - -{% endblock %} {% block footer %}{% endblock %} {% block page_container %} - - - -
-
-

{% raw %}{{ amountFormatted }}{% endraw %}

-
- {% raw %}{{ fsat }}{% endraw %} sat -
-
-
-
- -
-
-
- 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - DEL - 0 - C - OK -
-
-
-
- - - - - - - - -
-

- {% raw %}{{ amountWithTipFormatted }}{% endraw %} -

-
- {% raw %}{{ fsat }} - sat - ( + {{ tipAmountFormatted }} tip) - {% endraw %} -
- -
-
- Copy invoice - Close -
-
-
- - - -
- Would you like to leave a tip? -
-
- {% raw %}{{ tip }}{% endraw %}% - -
- - - Ok -
-
-
- No, thanks - Close -
-
-
- - - - - - -
-

- {{ tpos.name }}
{{ request.url }} -

-
-
- Copy URL - Close -
-
-
- - - - - - - - - - - - - - - No paid invoices - - - - {%raw%} - - {{payment.amount / 1000}} sats - Hash: {{payment.checking_id.slice(0, 30)}}... - - - {{payment.dateFrom}} - - - {%endraw%} - - - - -
-
-{% endblock %} {% block styles %} - -{% endblock %} {% block scripts %} - - -{% endblock %} diff --git a/lnbits/extensions/tpos/views.py b/lnbits/extensions/tpos/views.py deleted file mode 100644 index fee5914f2..000000000 --- a/lnbits/extensions/tpos/views.py +++ /dev/null @@ -1,77 +0,0 @@ -from http import HTTPStatus - -from fastapi import Depends, Request -from fastapi.templating import Jinja2Templates -from starlette.exceptions import HTTPException -from starlette.responses import HTMLResponse - -from lnbits.core.models import User -from lnbits.decorators import check_user_exists -from lnbits.settings import settings - -from . import tpos_ext, tpos_renderer -from .crud import get_tpos - -templates = Jinja2Templates(directory="templates") - - -@tpos_ext.get("/", response_class=HTMLResponse) -async def index(request: Request, user: User = Depends(check_user_exists)): - return tpos_renderer().TemplateResponse( - "tpos/index.html", {"request": request, "user": user.dict()} - ) - - -@tpos_ext.get("/{tpos_id}") -async def tpos(request: Request, tpos_id): - tpos = await get_tpos(tpos_id) - if not tpos: - raise HTTPException( - status_code=HTTPStatus.NOT_FOUND, detail="TPoS does not exist." - ) - - return tpos_renderer().TemplateResponse( - "tpos/tpos.html", - { - "request": request, - "tpos": tpos, - "web_manifest": f"/tpos/manifest/{tpos_id}.webmanifest", - }, - ) - - -@tpos_ext.get("/manifest/{tpos_id}.webmanifest") -async def manifest(tpos_id: str): - tpos = await get_tpos(tpos_id) - if not tpos: - raise HTTPException( - status_code=HTTPStatus.NOT_FOUND, detail="TPoS does not exist." - ) - - return { - "short_name": settings.lnbits_site_title, - "name": tpos.name + " - " + settings.lnbits_site_title, - "icons": [ - { - "src": settings.lnbits_custom_logo - if settings.lnbits_custom_logo - else "https://cdn.jsdelivr.net/gh/lnbits/lnbits@0.3.0/docs/logos/lnbits.png", - "type": "image/png", - "sizes": "900x900", - } - ], - "start_url": "/tpos/" + tpos_id, - "background_color": "#1F2234", - "description": "Bitcoin Lightning tPOS", - "display": "standalone", - "scope": "/tpos/" + tpos_id, - "theme_color": "#1F2234", - "shortcuts": [ - { - "name": tpos.name + " - " + settings.lnbits_site_title, - "short_name": tpos.name, - "description": tpos.name + " - " + settings.lnbits_site_title, - "url": "/tpos/" + tpos_id, - } - ], - } diff --git a/lnbits/extensions/tpos/views_api.py b/lnbits/extensions/tpos/views_api.py deleted file mode 100644 index 1be1428d9..000000000 --- a/lnbits/extensions/tpos/views_api.py +++ /dev/null @@ -1,193 +0,0 @@ -from http import HTTPStatus - -import httpx -from fastapi import Depends, Query -from lnurl import decode as decode_lnurl -from loguru import logger -from starlette.exceptions import HTTPException - -from lnbits.core.crud import get_latest_payments_by_extension, get_user -from lnbits.core.models import Payment -from lnbits.core.services import create_invoice -from lnbits.core.views.api import api_payment -from lnbits.decorators import WalletTypeInfo, get_key_type, require_admin_key -from lnbits.settings import settings - -from . import tpos_ext -from .crud import create_tpos, delete_tpos, get_tpos, get_tposs -from .models import CreateTposData, PayLnurlWData - - -@tpos_ext.get("/api/v1/tposs", status_code=HTTPStatus.OK) -async def api_tposs( - all_wallets: bool = Query(False), wallet: WalletTypeInfo = Depends(get_key_type) -): - wallet_ids = [wallet.wallet.id] - if all_wallets: - user = await get_user(wallet.wallet.user) - wallet_ids = user.wallet_ids if user else [] - - return [tpos.dict() for tpos in await get_tposs(wallet_ids)] - - -@tpos_ext.post("/api/v1/tposs", status_code=HTTPStatus.CREATED) -async def api_tpos_create( - data: CreateTposData, wallet: WalletTypeInfo = Depends(get_key_type) -): - tpos = await create_tpos(wallet_id=wallet.wallet.id, data=data) - return tpos.dict() - - -@tpos_ext.delete("/api/v1/tposs/{tpos_id}") -async def api_tpos_delete( - tpos_id: str, wallet: WalletTypeInfo = Depends(require_admin_key) -): - tpos = await get_tpos(tpos_id) - - if not tpos: - raise HTTPException( - status_code=HTTPStatus.NOT_FOUND, detail="TPoS does not exist." - ) - - if tpos.wallet != wallet.wallet.id: - raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="Not your TPoS.") - - await delete_tpos(tpos_id) - return "", HTTPStatus.NO_CONTENT - - -@tpos_ext.post("/api/v1/tposs/{tpos_id}/invoices", status_code=HTTPStatus.CREATED) -async def api_tpos_create_invoice( - tpos_id: str, amount: int = Query(..., ge=1), memo: str = "", tipAmount: int = 0 -) -> dict: - - tpos = await get_tpos(tpos_id) - - if not tpos: - raise HTTPException( - status_code=HTTPStatus.NOT_FOUND, detail="TPoS does not exist." - ) - - if tipAmount > 0: - amount += tipAmount - - try: - payment_hash, payment_request = await create_invoice( - wallet_id=tpos.wallet, - amount=amount, - memo=f"{memo} to {tpos.name}" if memo else f"{tpos.name}", - extra={ - "tag": "tpos", - "tipAmount": tipAmount, - "tposId": tpos_id, - "amount": amount - tipAmount if tipAmount else False, - }, - ) - except Exception as e: - raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(e)) - - return {"payment_hash": payment_hash, "payment_request": payment_request} - - -@tpos_ext.get("/api/v1/tposs/{tpos_id}/invoices") -async def api_tpos_get_latest_invoices(tpos_id: str): - try: - payments = [ - Payment.from_row(row) - for row in await get_latest_payments_by_extension( - ext_name="tpos", ext_id=tpos_id - ) - ] - - except Exception as e: - raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(e)) - - return [ - { - "checking_id": payment.checking_id, - "amount": payment.amount, - "time": payment.time, - "pending": payment.pending, - } - for payment in payments - ] - - -@tpos_ext.post( - "/api/v1/tposs/{tpos_id}/invoices/{payment_request}/pay", status_code=HTTPStatus.OK -) -async def api_tpos_pay_invoice( - lnurl_data: PayLnurlWData, payment_request: str, tpos_id: str -): - tpos = await get_tpos(tpos_id) - - if not tpos: - raise HTTPException( - status_code=HTTPStatus.NOT_FOUND, detail="TPoS does not exist." - ) - - lnurl = ( - lnurl_data.lnurl.replace("lnurlw://", "") - .replace("lightning://", "") - .replace("LIGHTNING://", "") - .replace("lightning:", "") - .replace("LIGHTNING:", "") - ) - - if lnurl.lower().startswith("lnurl"): - lnurl = decode_lnurl(lnurl) - else: - lnurl = "https://" + lnurl - - async with httpx.AsyncClient() as client: - try: - headers = {"user-agent": f"lnbits/tpos commit {settings.lnbits_commit[:7]}"} - r = await client.get(lnurl, follow_redirects=True, headers=headers) - if r.is_error: - lnurl_response = {"success": False, "detail": "Error loading"} - else: - resp = r.json() - if resp["tag"] != "withdrawRequest": - lnurl_response = {"success": False, "detail": "Wrong tag type"} - else: - r2 = await client.get( - resp["callback"], - follow_redirects=True, - headers=headers, - params={ - "k1": resp["k1"], - "pr": payment_request, - }, - ) - resp2 = r2.json() - if r2.is_error: - lnurl_response = { - "success": False, - "detail": "Error loading callback", - } - elif resp2["status"] == "ERROR": - lnurl_response = {"success": False, "detail": resp2["reason"]} - else: - lnurl_response = {"success": True, "detail": resp2} - except (httpx.ConnectError, httpx.RequestError): - lnurl_response = {"success": False, "detail": "Unexpected error occurred"} - - return lnurl_response - - -@tpos_ext.get( - "/api/v1/tposs/{tpos_id}/invoices/{payment_hash}", status_code=HTTPStatus.OK -) -async def api_tpos_check_invoice(tpos_id: str, payment_hash: str): - tpos = await get_tpos(tpos_id) - if not tpos: - raise HTTPException( - status_code=HTTPStatus.NOT_FOUND, detail="TPoS does not exist." - ) - try: - status = await api_payment(payment_hash) - - except Exception as exc: - logger.error(exc) - return {"paid": False} - return status diff --git a/tests/data/mock_data.zip b/tests/data/mock_data.zip index 90c1393b2..154c4528a 100644 Binary files a/tests/data/mock_data.zip and b/tests/data/mock_data.zip differ