Skip to content

Commit

Permalink
fixup!
Browse files Browse the repository at this point in the history
  • Loading branch information
dni committed Oct 23, 2024
1 parent fb8517a commit b45b5cc
Show file tree
Hide file tree
Showing 7 changed files with 88 additions and 112 deletions.
2 changes: 1 addition & 1 deletion crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ async def get_hits_today(card_id: str) -> list[Hit]:
)
updatedrow = []
for hit in rows:
if datetime.now().date() == datetime.fromtimestamp(hit.time).date():
if datetime.now().date() == hit.time.date():
updatedrow.append(hit)

return updatedrow
Expand Down
26 changes: 8 additions & 18 deletions models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import json
from sqlite3 import Row
from datetime import datetime

from fastapi import Query, Request
from lnurl import Lnurl
Expand All @@ -17,8 +17,10 @@ class Card(BaseModel):
uid: str
external_id: str
counter: int
tx_limit: int
daily_limit: int
# TODO: database column is TEXT should be INT
tx_limit: str
# TODO: database column is TEXT should be INT
daily_limit: str
enable: bool
k0: str
k1: str
Expand All @@ -27,11 +29,7 @@ class Card(BaseModel):
prev_k1: str
prev_k2: str
otp: str
time: int

@classmethod
def from_row(cls, row: Row) -> "Card":
return cls(**dict(row))
time: datetime

def lnurl(self, req: Request) -> Lnurl:
url = str(
Expand Down Expand Up @@ -67,19 +65,11 @@ class Hit(BaseModel):
old_ctr: int
new_ctr: int
amount: int
time: int

@classmethod
def from_row(cls, row: Row) -> "Hit":
return cls(**dict(row))
time: datetime


class Refund(BaseModel):
id: str
hit_id: str
refund_amount: int
time: int

@classmethod
def from_row(cls, row: Row) -> "Refund":
return cls(**dict(row))
time: datetime
104 changes: 49 additions & 55 deletions static/js/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ window.app = Vue.createApp({
data() {
return {
toggleAdvanced: false,
nfcTagReading: false,
disableNfcButton: true,
lnurlLink: `${window.location.host}/boltcards/api/v1/scan/`,
cards: [],
hits: [],
Expand Down Expand Up @@ -150,59 +150,36 @@ window.app = Vue.createApp({
},
methods: {
readNfcTag() {
try {
if (typeof NDEFReader == 'undefined') {
throw {
toString() {
return 'NFC not supported on this device or browser.'
}
}
}
const ndef = new NDEFReader()
const readerAbortController = new AbortController()
readerAbortController.signal.onabort = event => {
console.log('All NFC Read operations have been aborted.')
}

const ndef = new NDEFReader()
Quasar.Notify.create({
message: 'Tap your NFC tag to copy its UID here.'
})

const readerAbortController = new AbortController()
readerAbortController.signal.onabort = event => {
console.log('All NFC Read operations have been aborted.')
return ndef.scan({signal: readerAbortController.signal}).then(() => {
ndef.onreadingerror = () => {
this.disableNfcButton = false
Quasar.Notify.create({
type: 'negative',
message: 'There was an error reading this NFC tag.'
})
readerAbortController.abort()
}

this.nfcTagReading = true
this.$q.notify({
message: 'Tap your NFC tag to copy its UID here.'
})

return ndef.scan({signal: readerAbortController.signal}).then(() => {
ndef.onreadingerror = () => {
this.nfcTagReading = false

this.$q.notify({
type: 'negative',
message: 'There was an error reading this NFC tag.'
})

readerAbortController.abort()
}

ndef.onreading = ({message, serialNumber}) => {
//Decode NDEF data from tag
this.cardDialog.data.uid = serialNumber
.toUpperCase()
.replaceAll(':', '')
this.$q.notify({
type: 'positive',
message: 'NFC tag read successfully.'
})
}
})
} catch (error) {
this.nfcTagReading = false
this.$q.notify({
type: 'negative',
message: error
? error.toString()
: 'An unexpected error has occurred.'
})
}
ndef.onreading = ({message, serialNumber}) => {
const uid = serialNumber.toUpperCase().replaceAll(':', '')
//Decode NDEF data from tag
this.cardDialog.data.uid = uid
Quasar.Notify.create({
type: 'positive',
message: 'NFC tag read successfully.'
})
}
})
},
getCards() {
LNbits.api
Expand All @@ -228,7 +205,7 @@ window.app = Vue.createApp({
this.g.user.wallets[0].inkey
)
.then(response => {
this.hits = response.data.map(function (obj) {
this.hits = response.data.map(obj => {
obj.card_name = this.cards.find(d => d.id == obj.card_id).card_name
return mapCards(obj)
})
Expand All @@ -242,7 +219,7 @@ window.app = Vue.createApp({
this.g.user.wallets[0].inkey
)
.then(response => {
this.refunds = response.data.map(function (obj) {
this.refunds = response.data.map(obj => {
return mapCards(obj)
})
})
Expand Down Expand Up @@ -322,9 +299,7 @@ window.app = Vue.createApp({
this.cardDialog.show = false
this.cardDialog.data = {}
})
.catch(function (error) {
LNbits.utils.notifyApiError(error)
})
.catch(LNbits.utils.notifyApiError)
},
updateCardDialog(formId) {
var card = _.findWhere(this.cards, {id: formId})
Expand Down Expand Up @@ -432,5 +407,24 @@ window.app = Vue.createApp({
this.getCards()
this.getRefunds()
}
try {
if (typeof NDEFReader == 'undefined') {
throw {
toString() {
return 'NFC not supported on this device or browser.'
}
}
}
this.disableNfcButton = false
Quasar.Notify.create({
type: 'positive',
message: 'NFC is supported on this device. You can now read NFC tags.'
})
} catch (error) {
Quasar.Notify.create({
type: 'negative',
message: error ? error.toString() : 'An unexpected error has occurred.'
})
}
}
})
14 changes: 7 additions & 7 deletions templates/boltcards/display.html
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,8 @@
{% endblock %}{% block scripts %}
<script>
const mapHits = obj => {
obj.date = Quasar.utils.date.formatDate(
new Date(obj.time * 1000),
obj.date = Quasar.date.formatDate(
new Date(obj.time),
'YYYY-MM-DD HH:mm'
)

Expand All @@ -86,7 +86,7 @@
el: '#vue',
delimiters: ['${', '}'],
mixins: [windowMixin],
data: function () {
data() {
return {
card: null,
hits: null,
Expand Down Expand Up @@ -119,11 +119,11 @@
}
},
created() {
this.card = JSON.parse('{{ card | tojson}}')
let hits = JSON.parse('{{ hits | tojson}}')
let refunds = JSON.parse('{{ refunds | tojson}}')
this.card = JSON.parse({{ card | tojson }})
const hits = {{ hits | tojson | safe }}
this.hits = hits.map(JSON.parse).map(mapHits)
const refunds = {{ refunds | tojson | safe }}
this.refunds = refunds || []
this.hits = hits.map(mapHits)
},
computed: {
enabled() {
Expand Down
23 changes: 11 additions & 12 deletions templates/boltcards/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ <h6 class="text-subtitle1 q-my-none">
filled
dense
emit-value
v-model.trim="cardDialog.data.tx_limit"
v-model="cardDialog.data.tx_limit"
type="number"
label="Max transaction (sats)"
class="q-pr-sm"
Expand All @@ -263,7 +263,7 @@ <h6 class="text-subtitle1 q-my-none">
filled
dense
emit-value
v-model.trim="cardDialog.data.daily_limit"
v-model="cardDialog.data.daily_limit"
type="number"
label="Daily limit (sats)"
></q-input>
Expand All @@ -273,7 +273,7 @@ <h6 class="text-subtitle1 q-my-none">
filled
dense
emit-value
v-model.trim="cardDialog.data.card_name"
v-model="cardDialog.data.card_name"
type="text"
label="Card name "
>
Expand All @@ -284,7 +284,7 @@ <h6 class="text-subtitle1 q-my-none">
filled
dense
emit-value
v-model.trim="cardDialog.data.uid"
v-model="cardDialog.data.uid"
type="text"
label="Card UID "
>
Expand All @@ -293,10 +293,9 @@ <h6 class="text-subtitle1 q-my-none">
<div class="col-2 q-pl-sm">
<q-btn
outline
disable
color="grey"
icon="nfc"
:disable="nfcTagReading"
:disable="disableNfcButton"
@click="readNfcTag()"
>
<q-tooltip>Tap card to scan UID</q-tooltip>
Expand All @@ -312,7 +311,7 @@ <h6 class="text-subtitle1 q-my-none">
<q-input
filled
dense
v-model.trim="cardDialog.data.k0"
v-model="cardDialog.data.k0"
type="text"
label="Card Auth key (K0)"
hint="Used to authentificate with the card (16 bytes in HEX). "
Expand All @@ -321,15 +320,15 @@ <h6 class="text-subtitle1 q-my-none">
<q-input
filled
dense
v-model.trim="cardDialog.data.k1"
v-model="cardDialog.data.k1"
type="text"
label="Card Meta key (K1)"
hint="Used for encypting of the message (16 bytes in HEX)."
></q-input>
<q-input
filled
dense
v-model.trim="cardDialog.data.k2"
v-model="cardDialog.data.k2"
type="text"
label="Card File key (K2)"
hint="Used for CMAC of the message (16 bytes in HEX)."
Expand Down Expand Up @@ -382,8 +381,8 @@ <h6 class="text-subtitle1 q-my-none">
<div class="col q-mt-lg text-center">
<lnbits-qrcode
:value="qrCodeDialog.data.link"
:options="{width: 800}"
class="rounded-borders"
v-show="!qrCodeDialog.wipe"
></lnbits-qrcode>
<p class="text-center" v-show="!qrCodeDialog.wipe">
(QR for <strong>create</strong> the card in
Expand All @@ -397,8 +396,8 @@ <h6 class="text-subtitle1 q-my-none">
</p>
<lnbits-qrcode
:value="qrCodeDialog.data_wipe"
:options="{width: 800}"
class="rounded-borders"
v-show="qrCodeDialog.wipe"
></lnbits-qrcode>
<p class="text-center" v-show="qrCodeDialog.wipe">
(QR for <strong>wipe</strong> the card in
Expand Down Expand Up @@ -482,5 +481,5 @@ <h6 class="text-subtitle1 q-my-none">
</div>

{% endblock %} {% block scripts %} {{ window_vars(user) }}
<script src="/boltcards/static/js/index.js"></script>
<script src="{{ static_url_for('boltcards/static', path='js/index.js') }}"></script>
{% endblock %}
14 changes: 5 additions & 9 deletions views.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,11 @@ async def display(request: Request, card_id: str):
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="Card does not exist."
)
hits = [hit.dict() for hit in await get_hits([card.id])]
refunds = [
refund.hit_id for refund in await get_refunds([hit["id"] for hit in hits])
]
card_dict = card.dict()
# Remove wallet id from card dict
del card_dict["wallet"]

hits = await get_hits([card.id])
hits_json = [hit.json() for hit in hits]
refunds = [refund.hit_id for refund in await get_refunds([hit.id for hit in hits])]
card_json = card.json(exclude={"wallet"})
return boltcards_renderer().TemplateResponse(
"boltcards/display.html",
{"request": request, "card": card_dict, "hits": hits, "refunds": refunds},
{"request": request, "card": card_json, "hits": hits_json, "refunds": refunds},
)
Loading

0 comments on commit b45b5cc

Please sign in to comment.