Add files via upload

This commit is contained in:
Arc 2023-12-08 15:43:40 +00:00 committed by GitHub
parent 762ac58daf
commit aa560fd89d
17 changed files with 2948 additions and 2 deletions

37
LICENSE
View file

@ -1,6 +1,39 @@
MIT License
> Use any license you like, its your extension.
Copyright (c) 2023 LNbits
---
# DON'T BE A DICK PUBLIC LICENSE
> Version 1.1, December 2016
> Copyright (C) [year] [fullname]
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document.
> DON'T BE A DICK PUBLIC LICENSE
> TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
1. Do whatever you like with the original work, just don't be a dick.
Being a dick includes - but is not limited to - the following instances:
1a. Outright copyright infringement - Don't just copy this and change the name.
1b. Selling the unmodified original with no work done what-so-ever, that's REALLY being a dick.
1c. Modifying the original work to contain hidden harmful content. That would make you a PROPER dick.
2. If you become rich through modifications, related works/services, or supporting the original work,
share the love. Only a dick would make loads off this work and not buy the original work's
creator(s) a pint.
3. Code is provided with no warranty. Using somebody else's code and bitching when it goes wrong makes
you a DONKEY dick. Fix the problem yourself. A non-dick would submit the fix back.
---
# MIT License
> Copyright (c) [year] [fullname]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

17
README.md Normal file
View file

@ -0,0 +1,17 @@
# Temp - <small>[LNbits](https://github.com/lnbits/lnbits) extension</small>
<small>For more about LNBits extension check [this tutorial](https://github.com/lnbits/lnbits/wiki/LNbits-Extensions)</small>
## A template extension you can fork and use as a base for a template
Let the hacking begin! After you have forked this extension you can copy functions from other extensions that you might need. Usually the README is used as a guide of how to us ethe extensiobn.
### Usage
1. Enable extension
2. Create a Temp\
![create](https://imgur.com/8jNj8Zq.jpg)
3. Open the link for the Temp\
![open](https://imgur.com/LZuoWzb.jpg)
4. Press button to generate an invoice and pay\
![pay](https://imgur.com/tOwxn77.jpg)

36
__init__.py Normal file
View file

@ -0,0 +1,36 @@
import asyncio
from fastapi import APIRouter, Request, Response
from fastapi.routing import APIRoute
from lnbits.db import Database
from lnbits.helpers import temp_renderer
from lnbits.tasks import catch_everything_and_restart
from typing import Callable
from fastapi.responses import JSONResponse
db = Database("ext_temp")
temp_ext: APIRouter = APIRouter(
prefix="/temp", tags=["Temp"]
)
temp_static_files = [
{
"path": "/temp/static",
"name": "temp_static",
}
]
def temp_renderer():
return temp_renderer(["temp/temps"])
from .tasks import wait_for_paid_invoices
from .views import *
from .views_api import *
def temp_start():
loop = asyncio.get_event_loop()
loop.create_task(catch_everything_and_restart(wait_for_paid_invoices))

7
config.json Normal file
View file

@ -0,0 +1,7 @@
{
"name": "Temp",
"short_description": "Minimal extension to build on",
"tile": "/temp/static/image/temp.png",
"contributors": ["arcbtc"],
"min_lnbits_version": "0.0.1"
}

53
crud.py Normal file
View file

@ -0,0 +1,53 @@
from typing import List, Optional, Union
from lnbits.helpers import urlsafe_short_hash
from . import db
from .models import CreateTempData, Temp, TempClean, LNURLCharge
from loguru import logger
async def create_temp(wallet_id: str, data: CreateTempData) -> Temp:
temp_id = urlsafe_short_hash()
await db.execute(
"""
INSERT INTO temp.temp (id, wallet, name, total)
VALUES (?, ?, ?, ?)
""",
(
temp_id,
wallet_id,
data.name,
data.total
),
)
temp = await get_temp(temp_id)
assert temp, "Newly created temp couldn't be retrieved"
return temp
async def get_temp(temp_id: str) -> Optional[Temp]:
row = await db.fetchone("SELECT * FROM temp.temp WHERE id = ?", (temp_id,))
return Temp(**row) if row else None
async def get_temps(wallet_ids: Union[str, List[str]]) -> List[Temp]:
if isinstance(wallet_ids, str):
wallet_ids = [wallet_ids]
q = ",".join(["?"] * len(wallet_ids))
rows = await db.fetchall(
f"SELECT * FROM temp.temp WHERE wallet IN ({q})", (*wallet_ids,)
)
return [Temp(**row) for row in rows]
async def update_temp(temp_id: str, **kwargs) -> Temp:
q = ", ".join([f"{field[0]} = ?" for field in kwargs.items()])
await db.execute(
f"UPDATE temp.temp SET {q} WHERE id = ?", (*kwargs.values(), temp_id)
)
temp = await get_temp(temp_id)
assert temp, "Newly updated temp couldn't be retrieved"
return temp
async def delete_temp(temp_id: str) -> None:
await db.execute("DELETE FROM temp.temp WHERE id = ?", (temp_id,))

1
lnurl.py Normal file
View file

@ -0,0 +1 @@
# Maybe your extensions needs some LNURL stuff, for anything LNURL always make sure you are on spec https://github.com/lnurl/luds

9
manifest.json Normal file
View file

@ -0,0 +1,9 @@
{
"repos": [
{
"id": "temp",
"organisation": "lnbits",
"repository": "temp"
}
]
}

28
migrations.py Normal file
View file

@ -0,0 +1,28 @@
# The migration file is like a blockchain, never edit only add!
async def m001_initial(db):
"""
Initial templates table.
"""
await db.execute(
"""
CREATE TABLE temp.temp (
id TEXT PRIMARY KEY,
wallet TEXT NOT NULL,
name TEXT NOT NULL
);
"""
)
# Here we are adding an extra field to the database
async def m002_addtip_wallet(db):
"""
Add total to templates table
"""
await db.execute(
"""
ALTER TABLE temp.temp ADD total withdrawlimit INTEGER DEFAULT 0,;
"""
)

24
models.py Normal file
View file

@ -0,0 +1,24 @@
from sqlite3 import Row
from typing import Optional, List
from pydantic import BaseModel
class CreateTempData(BaseModel):
wallet: Optional[str]
name: Optional[str]
total: Optional[int]
class Temp(BaseModel):
id: str
wallet: str
name: str
total: Optional[int]
@classmethod
def from_row(cls, row: Row) -> "Temp":
return cls(**dict(row))
class CreateUpdateItemData(BaseModel):
items: List[Item]
# add something lnurly

BIN
static/image/template.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

59
tasks.py Normal file
View file

@ -0,0 +1,59 @@
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_temp
#######################################
########## RUN YOU TASKS HERE #########
#######################################
# the usual task is to listen to invoices related to this extension
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)
# do somethhing when an invoice related top this extension is paid
async def on_invoice_paid(payment: Payment) -> None:
if payment.extra.get("tag") != "temp":
return
temp_id = payment.extra.get("tempId")
assert temp_id
temp = await get_temp(temp_id)
assert temp
# update something
data_to_update = {
"total" temp.total + payment.amount
}
await update_temp(temp_id=temp_id, **data_to_update.dict())
# here we could send some data to a websocket on wss://<your-lnbits>/api/v1/ws/<temp_id>
some_payment_data = {
"name": temp.name,
"amount": payment.amount,
"fee": payment.fee,
"checking_id": payment.checking_id
}
await websocketUpdater(temp_id, str(some_payment_data))

View file

@ -0,0 +1,79 @@
<q-expansion-item
group="extras"
icon="swap_vertical_circle"
label="API info"
:content-inset-level="0.5"
>
<q-btn flat label="Swagger API" type="a" href="../docs#/temp"></q-btn>
<q-expansion-item group="api" dense expand-separator label="List Temp">
<q-card>
<q-card-section>
<code><span class="text-blue">GET</span> /temp/api/v1/temps</code>
<h5 class="text-caption q-mt-sm q-mb-none">Headers</h5>
<code>{"X-Api-Key": &lt;invoice_key&gt;}</code><br />
<h5 class="text-caption q-mt-sm q-mb-none">Body (application/json)</h5>
<h5 class="text-caption q-mt-sm q-mb-none">
Returns 200 OK (application/json)
</h5>
<code>[&lt;temp_object&gt;, ...]</code>
<h5 class="text-caption q-mt-sm q-mb-none">Curl example</h5>
<code
>curl -X GET {{ request.base_url }}temp/api/v1/temps -H "X-Api-Key:
&lt;invoice_key&gt;"
</code>
</q-card-section>
</q-card>
</q-expansion-item>
<q-expansion-item group="api" dense expand-separator label="Create a Temp">
<q-card>
<q-card-section>
<code><span class="text-green">POST</span> /temp/api/v1/temps</code>
<h5 class="text-caption q-mt-sm q-mb-none">Headers</h5>
<code>{"X-Api-Key": &lt;invoice_key&gt;}</code><br />
<h5 class="text-caption q-mt-sm q-mb-none">Body (application/json)</h5>
<code
>{"name": &lt;string&gt;, "currency": &lt;string*ie USD*&gt;}</code
>
<h5 class="text-caption q-mt-sm q-mb-none">
Returns 201 CREATED (application/json)
</h5>
<code
>{"currency": &lt;string&gt;, "id": &lt;string&gt;, "name":
&lt;string&gt;, "wallet": &lt;string&gt;}</code
>
<h5 class="text-caption q-mt-sm q-mb-none">Curl example</h5>
<code
>curl -X POST {{ request.base_url }}temp/api/v1/temps -d '{"name":
&lt;string&gt;, "currency": &lt;string&gt;}' -H "Content-type:
application/json" -H "X-Api-Key: &lt;admin_key&gt;"
</code>
</q-card-section>
</q-card>
</q-expansion-item>
<q-expansion-item
group="api"
dense
expand-separator
label="Delete a Temp"
class="q-pb-md"
>
<q-card>
<q-card-section>
<code
><span class="text-pink">DELETE</span>
/temp/api/v1/temps/&lt;temp_id&gt;</code
>
<h5 class="text-caption q-mt-sm q-mb-none">Headers</h5>
<code>{"X-Api-Key": &lt;admin_key&gt;}</code><br />
<h5 class="text-caption q-mt-sm q-mb-none">Returns 204 NO CONTENT</h5>
<code></code>
<h5 class="text-caption q-mt-sm q-mb-none">Curl example</h5>
<code
>curl -X DELETE {{ request.base_url
}}temp/api/v1/temps/&lt;temp_id&gt; -H "X-Api-Key: &lt;admin_key&gt;"
</code>
</q-card-section>
</q-card>
</q-expansion-item>
</q-expansion-item>

21
templates/tpos/_tpos.html Normal file
View file

@ -0,0 +1,21 @@
<q-expansion-item group="extras" icon="info" label="About Temp">
<q-card>
<q-card-section>
<p>
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 Temp hit the hash on the terminal.
</p>
<small
>Created by
<a
class="text-secondary"
href="https://github.com/talvasconcelos"
target="_blank"
>Tiago Vasconcelos</a
>.</small
>
</q-card-section>
</q-card>
</q-expansion-item>

1150
templates/tpos/index.html Normal file

File diff suppressed because it is too large Load diff

1205
templates/tpos/tpos.html Normal file

File diff suppressed because it is too large Load diff

88
views.py Normal file
View file

@ -0,0 +1,88 @@
from http import HTTPStatus
from fastapi import Depends, Request
from fastapi.templating import Jinja2Temps
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 temp_ext, temp_renderer
from .crud import get_temp
temps = Jinja2Temps(directory="temps")
#######################################
##### ADD YOUR PAGE ENDPOINTS HERE ####
#######################################
# Backend admin page
@temp_ext.get("/", response_class=HTMLResponse)
async def index(request: Request, user: User = Depends(check_user_exists)):
return temp_renderer().TempResponse(
"temp/index.html", {"request": request, "user": user.dict()}
)
# Frontend shareable page
@temp_ext.get("/{temp_id}")
async def temp(request: Request, temp_id):
temp = await get_temp(temp_id)
if not temp:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="Temp does not exist."
)
return temp_renderer().TempResponse(
"temp/temp.html",
{
"request": request,
"temp": temp,
"withdrawamtemps": temp.withdrawamtemps,
"web_manifest": f"/temp/manifest/{temp_id}.webmanifest",
},
)
# Customise a manifest, or remove manifest completely
@temp_ext.get("/manifest/{temp_id}.webmanifest")
async def manifest(temp_id: str):
remp= await get_temp(temp_id)
if not temp:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="Temp does not exist."
)
return {
"short_name": settings.lnbits_site_title,
"name": temp.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": "/temp/" + temp_id,
"background_color": "#1F2234",
"description": "Minimal extension to build on",
"display": "standalone",
"scope": "/temp/" + temp_id,
"theme_color": "#1F2234",
"shortcuts": [
{
"name": temp.name + " - " + settings.lnbits_site_title,
"short_name": temp.name,
"description": temp.name + " - " + settings.lnbits_site_title,
"url": "/temp/" + temp_id,
}
],
}

136
views_api.py Normal file
View file

@ -0,0 +1,136 @@
from http import HTTPStatus
import json
import httpx
from fastapi import Depends, Query, Request
from lnurl import decode as decode_lnurl
from loguru import logger
from starlette.exceptions import HTTPException
from lnbits.core.crud import 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,
check_admin,
get_key_type,
require_admin_key,
require_invoice_key,
)
from . import temp_ext
from .crud import (
create_temp,
update_temp,
delete_temp,
get_temp,
get_temps
)
from .models import CreateTempData, PayLnurlWData, LNURLCharge, CreateUpdateItemData
#######################################
##### ADD YOUR API ENDPOINTS HERE #####
#######################################
# TYPICAL ENDPOINTS
# get all the records belonging to the user
@temp_ext.get("/api/v1/temps", status_code=HTTPStatus.OK)
async def api_temps(
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 [temp.dict() for temp in await get_temps(wallet_ids)]
# get a specific record belonging to a user
@temp_ext.put("/api/v1/temps/{temp_id}")
async def api_temp_update(
data: CreateTempData,
temp_id: str,
wallet: WalletTypeInfo = Depends(require_admin_key),
):
if not temp_id:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="Temp does not exist."
)
temp = await get_temp(temp_id)
assert temp, "Temp couldn't be retrieved"
if wallet.wallet.id != temp.wallet:
raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="Not your Temp.")
temp = await update_temp(temp_id=temp_id, **data.dict())
return temp.dict()
# Create a new record
@temp_ext.post("/api/v1/temps", status_code=HTTPStatus.CREATED)
async def api_temp_create(
data: CreateTempData, wallet: WalletTypeInfo = Depends(get_key_type)
):
temp = await create_temp(wallet_id=wallet.wallet.id, data=data)
return temp.dict()
# Delete a record
@temp_ext.delete("/api/v1/temps/{temp_id}")
async def api_temp_delete(
temp_id: str, wallet: WalletTypeInfo = Depends(require_admin_key)
):
temp = await get_temp(temp_id)
if not temp:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="Temp does not exist."
)
if temp.wallet != wallet.wallet.id:
raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="Not your Temp.")
await delete_temp(temp_id)
return "", HTTPStatus.NO_CONTENT
# ANY OTHER ENDPOINTS YOU NEED
# This endpoint creates a payment
@tpos_ext.post("/api/v1/temps/payment/{temp_id}", status_code=HTTPStatus.CREATED)
async def api_tpos_create_invoice(
temp_id: str, amount: int = Query(..., ge=1), memo: str = ""
) -> dict:
temp = await get_temp(temp_id)
if not temp:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="Temp does not exist."
)
# we create a payment and add some tags, so tasks.py can grab the payment once its paid
try:
payment_hash, payment_request = await create_invoice(
wallet_id=temp.wallet,
amount=amount,
memo=f"{memo} to {temp.name}" if memo else f"{temp.name}",
extra={
"tag": "temp",
"tipAmount": tipAmount,
"tempId": tempId,
"amount": amount,
},
)
except Exception as e:
raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(e))
return {"payment_hash": payment_hash, "payment_request": payment_request}