Merge pull request #1080 from lnbits/switchupdate

Adds multiple pin option to bitcoinSwitch in LNURLDevices
This commit is contained in:
Arc 2022-10-27 01:16:57 +01:00 committed by GitHub
commit 0a8d287f19
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 489 additions and 67 deletions

View File

@ -23,9 +23,22 @@ async def create_lnurldevice(
currency,
device,
profit,
amount
amount,
pin,
profit1,
amount1,
pin1,
profit2,
amount2,
pin2,
profit3,
amount3,
pin3,
profit4,
amount4,
pin4
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
lnurldevice_id,
@ -36,6 +49,19 @@ async def create_lnurldevice(
data.device,
data.profit,
data.amount,
data.pin,
data.profit1,
data.amount1,
data.pin1,
data.profit2,
data.amount2,
data.pin2,
data.profit3,
data.amount3,
data.pin3,
data.profit4,
data.amount4,
data.pin4,
),
)
return await get_lnurldevice(lnurldevice_id)

View File

@ -8,6 +8,7 @@ from typing import Optional
from embit import bech32, compact
from fastapi import Request
from fastapi.param_functions import Query
from loguru import logger
from starlette.exceptions import HTTPException
from lnbits.core.services import create_invoice
@ -91,6 +92,9 @@ async def lnurl_v1_params(
device_id: str = Query(None),
p: str = Query(None),
atm: str = Query(None),
gpio: str = Query(None),
profit: str = Query(None),
amount: str = Query(None),
):
device = await get_lnurldevice(device_id)
if not device:
@ -105,16 +109,24 @@ async def lnurl_v1_params(
if device.device == "switch":
price_msat = (
await fiat_amount_as_satoshis(float(device.profit), device.currency)
await fiat_amount_as_satoshis(float(profit), device.currency)
if device.currency != "sat"
else amount_in_cent
) * 1000
# Check they're not trying to trick the switch!
check = False
for switch in device.switches(request):
if switch[0] == gpio and switch[1] == profit and switch[2] == amount:
check = True
if not check:
return {"status": "ERROR", "reason": f"Switch params wrong"}
lnurldevicepayment = await create_lnurldevicepayment(
deviceid=device.id,
payload="bla",
payload=amount,
sats=price_msat,
pin=1,
pin=gpio,
payhash="bla",
)
if not lnurldevicepayment:
@ -126,7 +138,7 @@ async def lnurl_v1_params(
),
"minSendable": price_msat,
"maxSendable": price_msat,
"metadata": await device.lnurlpay_metadata(),
"metadata": device.lnurlpay_metadata,
}
if len(p) % 4 > 0:
p += "=" * (4 - (len(p) % 4))
@ -188,7 +200,7 @@ async def lnurl_v1_params(
),
"minSendable": price_msat * 1000,
"maxSendable": price_msat * 1000,
"metadata": await device.lnurlpay_metadata(),
"metadata": device.lnurlpay_metadata,
}
@ -233,11 +245,17 @@ async def lnurl_callback(
if device.device == "switch":
payment_hash, payment_request = await create_invoice(
wallet_id=device.wallet,
amount=lnurldevicepayment.sats / 1000,
memo=device.title + "-" + lnurldevicepayment.id,
unhashed_description=(await device.lnurlpay_metadata()).encode("utf-8"),
extra={"tag": "Switch", "id": paymentid, "time": device.amount},
amount=int(lnurldevicepayment.sats / 1000),
memo=device.id + " PIN " + str(lnurldevicepayment.pin),
unhashed_description=device.lnurlpay_metadata.encode("utf-8"),
extra={
"tag": "Switch",
"pin": str(lnurldevicepayment.pin),
"amount": str(lnurldevicepayment.payload),
"id": paymentid,
},
)
lnurldevicepayment = await update_lnurldevicepayment(
lnurldevicepayment_id=paymentid, payhash=payment_hash
)
@ -248,9 +266,9 @@ async def lnurl_callback(
payment_hash, payment_request = await create_invoice(
wallet_id=device.wallet,
amount=lnurldevicepayment.sats / 1000,
amount=int(lnurldevicepayment.sats / 1000),
memo=device.title,
unhashed_description=(await device.lnurlpay_metadata()).encode("utf-8"),
unhashed_description=device.lnurlpay_metadata.encode("utf-8"),
extra={"tag": "PoS"},
)
lnurldevicepayment = await update_lnurldevicepayment(

View File

@ -88,3 +88,52 @@ async def m003_redux(db):
await db.execute(
"ALTER TABLE lnurldevice.lnurldevices ADD COLUMN amount INT DEFAULT 0;"
)
async def m004_redux(db):
"""
Add 'meta' for storing various metadata about the wallet
"""
await db.execute(
"ALTER TABLE lnurldevice.lnurldevices ADD COLUMN pin INT DEFAULT 0"
)
await db.execute(
"ALTER TABLE lnurldevice.lnurldevices ADD COLUMN profit1 FLOAT DEFAULT 0"
)
await db.execute(
"ALTER TABLE lnurldevice.lnurldevices ADD COLUMN amount1 INT DEFAULT 0"
)
await db.execute(
"ALTER TABLE lnurldevice.lnurldevices ADD COLUMN pin1 INT DEFAULT 0"
)
await db.execute(
"ALTER TABLE lnurldevice.lnurldevices ADD COLUMN profit2 FLOAT DEFAULT 0"
)
await db.execute(
"ALTER TABLE lnurldevice.lnurldevices ADD COLUMN amount2 INT DEFAULT 0"
)
await db.execute(
"ALTER TABLE lnurldevice.lnurldevices ADD COLUMN pin2 INT DEFAULT 0"
)
await db.execute(
"ALTER TABLE lnurldevice.lnurldevices ADD COLUMN profit3 FLOAT DEFAULT 0"
)
await db.execute(
"ALTER TABLE lnurldevice.lnurldevices ADD COLUMN amount3 INT DEFAULT 0"
)
await db.execute(
"ALTER TABLE lnurldevice.lnurldevices ADD COLUMN pin3 INT DEFAULT 0"
)
await db.execute(
"ALTER TABLE lnurldevice.lnurldevices ADD COLUMN profit4 FLOAT DEFAULT 0"
)
await db.execute(
"ALTER TABLE lnurldevice.lnurldevices ADD COLUMN amount4 INT DEFAULT 0"
)
await db.execute(
"ALTER TABLE lnurldevice.lnurldevices ADD COLUMN pin4 INT DEFAULT 0"
)

View File

@ -1,12 +1,13 @@
import json
from sqlite3 import Row
from typing import Optional
from typing import List, Optional
from fastapi import Request
from lnurl import Lnurl
from lnurl import encode as lnurl_encode # type: ignore
from lnurl.models import LnurlPaySuccessAction, UrlAction # type: ignore
from lnurl.types import LnurlPayMetadata # type: ignore
from loguru import logger
from pydantic import BaseModel
from pydantic.main import BaseModel
@ -18,6 +19,19 @@ class createLnurldevice(BaseModel):
device: str
profit: float
amount: int
pin: int = 0
profit1: float = 0
amount1: int = 0
pin1: int = 0
profit2: float = 0
amount2: int = 0
pin2: int = 0
profit3: float = 0
amount3: int = 0
pin3: int = 0
profit4: float = 0
amount4: int = 0
pin4: int = 0
class lnurldevices(BaseModel):
@ -29,18 +43,122 @@ class lnurldevices(BaseModel):
device: str
profit: float
amount: int
pin: int
profit1: float
amount1: int
pin1: int
profit2: float
amount2: int
pin2: int
profit3: float
amount3: int
pin3: int
profit4: float
amount4: int
pin4: int
timestamp: str
def from_row(cls, row: Row) -> "lnurldevices":
return cls(**dict(row))
def lnurl(self, req: Request) -> Lnurl:
url = req.url_for("lnurldevice.lnurl_v1_params", device_id=self.id)
return lnurl_encode(url)
async def lnurlpay_metadata(self) -> LnurlPayMetadata:
@property
def lnurlpay_metadata(self) -> LnurlPayMetadata:
return LnurlPayMetadata(json.dumps([["text/plain", self.title]]))
def switches(self, req: Request) -> List:
switches = []
if self.profit > 0:
url = req.url_for("lnurldevice.lnurl_v1_params", device_id=self.id)
switches.append(
[
str(self.pin),
str(self.profit),
str(self.amount),
lnurl_encode(
url
+ "?gpio="
+ str(self.pin)
+ "&profit="
+ str(self.profit)
+ "&amount="
+ str(self.amount)
),
]
)
if self.profit1 > 0:
url = req.url_for("lnurldevice.lnurl_v1_params", device_id=self.id)
switches.append(
[
str(self.pin1),
str(self.profit1),
str(self.amount1),
lnurl_encode(
url
+ "?gpio="
+ str(self.pin1)
+ "&profit="
+ str(self.profit1)
+ "&amount="
+ str(self.amount1)
),
]
)
if self.profit2 > 0:
url = req.url_for("lnurldevice.lnurl_v1_params", device_id=self.id)
switches.append(
[
str(self.pin2),
str(self.profit2),
str(self.amount2),
lnurl_encode(
url
+ "?gpio="
+ str(self.pin2)
+ "&profit="
+ str(self.profit2)
+ "&amount="
+ str(self.amount2)
),
]
)
if self.profit3 > 0:
url = req.url_for("lnurldevice.lnurl_v1_params", device_id=self.id)
switches.append(
[
str(self.pin3),
str(self.profit3),
str(self.amount3),
lnurl_encode(
url
+ "?gpio="
+ str(self.pin3)
+ "&profit="
+ str(self.profit3)
+ "&amount="
+ str(self.amount3)
),
]
)
if self.profit4 > 0:
url = req.url_for("lnurldevice.lnurl_v1_params", device_id=self.id)
switches.append(
[
str(self.pin4),
str(self.profit4),
str(self.amount4),
lnurl_encode(
url
+ "?gpio="
+ str(self.pin4)
+ "&profit="
+ str(self.profit4)
+ "&amount="
+ str(self.amount4)
),
]
)
return switches
class lnurldevicepayment(BaseModel):
id: str

View File

@ -36,5 +36,9 @@ async def on_invoice_paid(payment: Payment) -> None:
lnurldevicepayment = await update_lnurldevicepayment(
lnurldevicepayment_id=payment.extra.get("id"), payhash="used"
)
return await updater(lnurldevicepayment.deviceid)
return await updater(
lnurldevicepayment.deviceid,
lnurldevicepayment.pin,
lnurldevicepayment.payload,
)
return

View File

@ -105,7 +105,7 @@
@click="openQrCodeDialog(props.row.id)"
><q-tooltip v-if="protocol == 'http:'">
LNURLs only work over HTTPS </q-tooltip
><q-tooltip v-else> view LNURL </q-tooltip></q-btn
><q-tooltip v-else> view LNURLS </q-tooltip></q-btn
>
</q-td>
<q-td
@ -230,29 +230,221 @@
label="Profit margin (% added to invoices/deducted from faucets)"
></q-input>
<div v-else>
<q-input
ref="setAmount"
filled
dense
v-model.trim="formDialoglnurldevice.data.profit"
class="q-pb-md"
:label="'Amount (' + formDialoglnurldevice.data.currency + ') *'"
:mask="'#.##'"
fill-mask="0"
reverse-fill-mask
:step="'0.01'"
value="0.00"
></q-input>
<q-input
filled
dense
v-model.trim="formDialoglnurldevice.data.amount"
type="number"
value="1000"
label="milesecs to turn Switch on for (1sec = 1000ms)"
></q-input>
</div>
<q-btn
unelevated
class="q-mb-lg"
round
size="sm"
icon="add"
@click="addSwitch"
v-model="switches"
color="primary"
></q-btn>
<q-btn
unelevated
class="q-mb-lg"
round
size="sm"
icon="remove"
@click="removeSwitch"
v-model="switches"
color="primary"
></q-btn>
<div v-if="switches >= 0">
<div class="row">
<div class="col">
<q-input
ref="setAmount"
filled
dense
v-model.trim="formDialoglnurldevice.data.profit"
class="q-pb-md"
:label="'Amount (' + formDialoglnurldevice.data.currency + ') *'"
:mask="'#.##'"
fill-mask="0"
reverse-fill-mask
:step="'0.01'"
value="0.00"
></q-input>
</div>
<div class="col q-ml-md">
<q-input
filled
dense
v-model.trim="formDialoglnurldevice.data.amount"
type="number"
value="1000"
label="milesecs to turn Switch on for (1sec = 1000ms)"
></q-input>
</div>
<div class="col q-ml-md">
<q-input
filled
dense
v-model.trim="formDialoglnurldevice.data.pin"
type="number"
label="GPIO to turn on"
></q-input>
</div>
</div>
</div>
<div v-if="switches >= 1">
<div class="row">
<div class="col">
<q-input
ref="setAmount"
filled
dense
v-model.trim="formDialoglnurldevice.data.profit1"
class="q-pb-md"
:label="'Amount (' + formDialoglnurldevice.data.currency + ') *'"
:mask="'#.##'"
fill-mask="0"
reverse-fill-mask
:step="'0.01'"
value="0.00"
></q-input>
</div>
<div class="col q-ml-md">
<q-input
filled
dense
v-model.trim="formDialoglnurldevice.data.amount1"
type="number"
value="1000"
label="milesecs to turn Switch on for (1sec = 1000ms)"
></q-input>
</div>
<div class="col q-ml-md">
<q-input
filled
dense
v-model.trim="formDialoglnurldevice.data.pin1"
type="number"
label="GPIO to turn on"
></q-input>
</div>
</div>
</div>
<div v-if="switches >= 2">
<div class="row">
<div class="col">
<q-input
ref="setAmount"
filled
dense
v-model.trim="formDialoglnurldevice.data.profit2"
class="q-pb-md"
:label="'Amount (' + formDialoglnurldevice.data.currency + ') *'"
:mask="'#.##'"
fill-mask="0"
reverse-fill-mask
:step="'0.01'"
value="0.00"
></q-input>
</div>
<div class="col q-ml-md">
<q-input
filled
dense
v-model.trim="formDialoglnurldevice.data.amount2"
type="number"
value="1000"
label="milesecs to turn Switch on for (1sec = 1000ms)"
></q-input>
</div>
<div class="col q-ml-md">
<q-input
filled
dense
v-model.trim="formDialoglnurldevice.data.pin2"
type="number"
label="GPIO to turn on"
></q-input>
</div>
</div>
</div>
<div v-if="switches >= 3">
<div class="row">
<div class="col">
<q-input
ref="setAmount"
filled
dense
v-model.trim="formDialoglnurldevice.data.profit3"
class="q-pb-md"
:label="'Amount (' + formDialoglnurldevice.data.currency + ') *'"
:mask="'#.##'"
fill-mask="0"
reverse-fill-mask
:step="'0.01'"
value="0.00"
></q-input>
</div>
<div class="col q-ml-md">
<q-input
filled
dense
v-model.trim="formDialoglnurldevice.data.amount3"
type="number"
value="1000"
label="milesecs to turn Switch on for (1sec = 1000ms)"
></q-input>
</div>
<div class="col q-ml-md">
<q-input
filled
dense
v-model.trim="formDialoglnurldevice.data.pin3"
type="number"
label="GPIO to turn on"
></q-input>
</div>
</div>
</div>
<div v-if="switches >= 4">
<div class="row">
<div class="col">
<q-input
ref="setAmount"
filled
dense
v-model.trim="formDialoglnurldevice.data.profit4"
class="q-pb-md"
:label="'Amount (' + formDialoglnurldevice.data.currency + ') *'"
:mask="'#.##'"
fill-mask="0"
reverse-fill-mask
:step="'0.01'"
value="0.00"
></q-input>
</div>
<div class="col q-ml-md">
<q-input
filled
dense
v-model.trim="formDialoglnurldevice.data.amount4"
type="number"
value="1000"
label="milesecs to turn Switch on for (1sec = 1000ms)"
></q-input>
</div>
<div class="col q-ml-md">
<q-input
filled
dense
v-model.trim="formDialoglnurldevice.data.pin4"
type="number"
label="GPIO to turn on"
></q-input>
</div>
</div>
</div>
</div>
<div class="row q-mt-lg">
<q-btn
v-if="formDialoglnurldevice.data.id"
@ -284,24 +476,26 @@
<q-card v-if="qrCodeDialog.data" class="q-pa-lg lnbits__dialog-card">
<q-responsive :ratio="1" class="q-mx-xl q-mb-md">
<qrcode
:value="qrCodeDialog.data.url + '/?lightning=' + qrCodeDialog.data.lnurl"
:value="lnurlValue"
:options="{width: 800}"
class="rounded-borders"
></qrcode>
{% raw %}
</q-responsive>
<p style="word-break: break-all">
<strong>ID:</strong> {{ qrCodeDialog.data.id }}<br />
</p>
{% endraw %}
<q-btn
outline
color="grey"
@click="copyText(lnurlValue, 'LNURL copied to clipboard!')"
>Copy LNURL</q-btn
>
<br />
<div class="row q-mt-lg q-gutter-sm">
<q-btn
v-for="switch_ in qrCodeDialog.data.switches"
outline
color="grey"
@click="copyText(qrCodeDialog.data.lnurl, 'LNURL copied to clipboard!')"
class="q-ml-sm"
>Copy LNURL</q-btn
>
color="primary"
:label="'Switch PIN:' + switch_[0]"
@click="lnurlValueFetch(switch_[3])"
></q-btn>
<q-btn v-close-popup flat color="grey" class="q-ml-auto">Close</q-btn>
</div>
</q-card>
@ -333,11 +527,14 @@
mixins: [windowMixin],
data: function () {
return {
tab: 'mails',
protocol: window.location.protocol,
location: window.location.hostname,
wslocation: window.location.hostname,
filter: '',
currency: 'USD',
lnurlValue: '',
switches: 0,
lnurldeviceLinks: [],
lnurldeviceLinksObj: [],
devices: [
@ -386,12 +583,6 @@
label: 'device',
field: 'device'
},
{
name: 'profit',
align: 'left',
label: 'profit',
field: 'profit'
},
{
name: 'currency',
align: 'left',
@ -440,8 +631,20 @@
this.qrCodeDialog.data = _.clone(lnurldevice)
this.qrCodeDialog.data.url =
window.location.protocol + '//' + window.location.host
this.lnurlValueFetch(this.qrCodeDialog.data.switches[0][3])
this.qrCodeDialog.show = true
},
lnurlValueFetch: function (lnurl) {
this.lnurlValue = lnurl
},
addSwitch: function () {
var self = this
self.switches = self.switches + 1
},
removeSwitch: function () {
var self = this
self.switches = self.switches - 1
},
cancellnurldevice: function (data) {
var self = this
self.formDialoglnurldevice.show = false
@ -498,7 +701,9 @@
.then(function (response) {
if (response.data) {
self.lnurldeviceLinks = response.data.map(maplnurldevice)
console.log('response.data')
console.log(response.data)
console.log('response.data')
}
})
.catch(function (error) {
@ -592,7 +797,7 @@
LNbits.utils.notifyApiError(error)
})
},
clearFormDialoglnurldevice() {
clearFormDialoglnurldevice () {
this.formDialoglnurldevice.data = {
lnurl_toggle: false,
show_message: false,

View File

@ -103,8 +103,10 @@ async def websocket_endpoint(websocket: WebSocket, lnurldevice_id: str):
manager.disconnect(websocket)
async def updater(lnurldevice_id):
async def updater(lnurldevice_id, lnurldevice_pin, lnurldevice_amount):
lnurldevice = await get_lnurldevice(lnurldevice_id)
if not lnurldevice:
return
await manager.send_personal_message(f"{lnurldevice.amount}", lnurldevice_id)
return await manager.send_personal_message(
f"{lnurldevice_pin}-{lnurldevice_amount}", lnurldevice_id
)

View File

@ -39,10 +39,10 @@ async def api_lnurldevice_create_or_update(
):
if not lnurldevice_id:
lnurldevice = await create_lnurldevice(data)
return {**lnurldevice.dict(), **{"lnurl": lnurldevice.lnurl(req)}}
return {**lnurldevice.dict(), **{"switches": lnurldevice.switches(req)}}
else:
lnurldevice = await update_lnurldevice(data, lnurldevice_id=lnurldevice_id)
return {**lnurldevice.dict(), **{"lnurl": lnurldevice.lnurl(req)}}
return {**lnurldevice.dict(), **{"switches": lnurldevice.switches(req)}}
@lnurldevice_ext.get("/api/v1/lnurlpos")
@ -52,7 +52,7 @@ async def api_lnurldevices_retrieve(
wallet_ids = (await get_user(wallet.wallet.user)).wallet_ids
try:
return [
{**lnurldevice.dict(), **{"lnurl": lnurldevice.lnurl(req)}}
{**lnurldevice.dict(), **{"switches": lnurldevice.switches(req)}}
for lnurldevice in await get_lnurldevices(wallet_ids)
]
except:
@ -78,7 +78,7 @@ async def api_lnurldevice_retrieve(
)
if not lnurldevice.lnurl_toggle:
return {**lnurldevice.dict()}
return {**lnurldevice.dict(), **{"lnurl": lnurldevice.lnurl(req)}}
return {**lnurldevice.dict(), **{"switches": lnurldevice.switches(req)}}
@lnurldevice_ext.delete("/api/v1/lnurlpos/{lnurldevice_id}")