forked from lnbits/tpos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
views_api.py
299 lines (254 loc) · 9.27 KB
/
views_api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
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_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,
check_admin,
get_key_type,
require_admin_key,
require_invoice_key,
)
from lnbits.utils.exchange_rates import get_fiat_rate_satoshis
from . import tpos_ext
from .crud import (
create_tpos,
update_tpos,
delete_tpos,
get_tpos,
get_tposs,
start_lnurlcharge,
get_lnurlcharge,
update_lnurlcharge,
)
from .models import CreateTposData, PayLnurlWData, LNURLCharge, CreateUpdateItemData
@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.put("/api/v1/tposs/{tpos_id}")
async def api_tpos_update(
data: CreateTposData,
tpos_id: str,
wallet: WalletTypeInfo = Depends(require_admin_key),
):
if not tpos_id:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="TPoS does not exist."
)
tpos = await get_tpos(tpos_id)
assert tpos, "TPoS couldn't be retrieved"
if wallet.wallet.id != tpos.wallet:
raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="Not your TPoS.")
tpos = await update_tpos(tpos_id=tpos_id, **data.dict(exclude_unset=True))
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,
details: str = Query(None),
) -> 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,
"details": details if details else None,
},
)
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"}
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
@tpos_ext.get("/api/v1/atm/{tpos_id}/{atmpin}", status_code=HTTPStatus.CREATED)
async def api_tpos_atm_pin_check(tpos_id: str, atmpin: int):
tpos = await get_tpos(tpos_id)
logger.debug(tpos)
if not tpos:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="TPoS does not exist."
)
if int(tpos.withdrawpin) != int(atmpin):
raise HTTPException(status_code=HTTPStatus.NOT_FOUND, detail="Wrong PIN.")
token = await start_lnurlcharge(tpos_id)
return token
@tpos_ext.get(
"/api/v1/atm/withdraw/{withdraw_token}/{amount}", status_code=HTTPStatus.CREATED
)
async def api_tpos_create_withdraw(
request: Request, withdraw_token: str, amount: str
) -> dict:
lnurlcharge = await get_lnurlcharge(withdraw_token)
if not lnurlcharge:
return {
"status": "ERROR",
"reason": f"lnurlcharge {withdraw_token} not found on this server",
}
tpos = await get_tpos(lnurlcharge.tpos_id)
if not tpos:
return {
"status": "ERROR",
"reason": f"TPoS {lnurlcharge.tpos_id} not found on this server",
}
lnurlcharge = await update_lnurlcharge(
LNURLCharge(id=withdraw_token, tpos_id=lnurlcharge.tpos_id, amount=int(amount))
)
return {**lnurlcharge.dict(), **{"lnurl": lnurlcharge.lnurl(request)}}
@tpos_ext.get("/api/v1/rate/{currency}", status_code=HTTPStatus.OK)
async def api_check_fiat_rate(currency):
try:
rate = await get_fiat_rate_satoshis(currency)
except AssertionError:
rate = None
return {"rate": rate}
## ITEMS
@tpos_ext.put("/api/v1/tposs/{tpos_id}/items", status_code=HTTPStatus.CREATED)
async def api_tpos_create_items(
data: CreateUpdateItemData,
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 wallet.wallet.id != tpos.wallet:
raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="Not your TPoS.")
items = json.dumps(data.dict()["items"])
tpos = await update_tpos(tpos_id=tpos_id, items=items)
return tpos.dict()