diff --git a/lnbits/core/templates/core/extensions_builder.html b/lnbits/core/templates/core/extensions_builder.html deleted file mode 100644 index 614e944e..00000000 --- a/lnbits/core/templates/core/extensions_builder.html +++ /dev/null @@ -1,830 +0,0 @@ -{% if not ajax %} {% extends "base.html" %} {% endif %} - -{% from "macros.jinja" import window_vars with context %} - -{% block scripts %} {{ window_vars(user) }}{% endblock %} {% block page %} - -
-
- - -
-
- - Tell us something about your extension: - -
    -
  • This is the first step, you can return and change it.
  • -
  • - The `name` and - `sort description` fields are what the users will - see when browsing the list of extensions. -
  • -
  • - The `id` field is used internally and in the URL of - your extension. -
  • -
-
- - - -
-
- - -
-
-
- -
-
- - -
-
- - -
-
- - -
-
-
-
- - -
-
-
- - -
-
- -
-
- - -
- -
    -
  • Define what settings your extension will have.
  • -
  • - You can choose if each user has its own settings or if the - settings are global (set by the admin). -
  • -
-
-
- - -
-
- -
-
- Each user can set its own settings for this extension. - Settings are set by the admin and apply to all users of the - extension -
-
-
-
- -
-
-
- - -
-
- -
-
- - - - -
    -
  • - The owner of the extension manages this data. It can add, remove - and update instances of it. -
  • - -
  • - Some fileds are present by default, like - created_at, updated_at and - extra. -
  • -
-
-
- -
-
- -
-
-
- - -
-
- -
-
- - - - -
    -
  • - This data is created by users of the extension. Usually when - they submit a form or make a payment. -
  • -
  • - The owner of the extension can view this data, but should not - modify it. -
  • -
-
-
- -
-
- -
-
-
- - -
-
- -
- -
- - -
- -
    -
  • - Most extensions have a public page that can be shared (this page - will still be accessible even if you have restricted access to - your LNbits install). -
  • -
-
-
-
-
-
- - - Public page title - Select the field from the -   - (Owner Data) that will be used as a title for the public - page. - - - - - -
-
- - - Public page description - Select the field from the -   - (Owner Data) that will be used as a description for the - public page. - - - - - -
-
- - - Public page inputs - -
    -
  • - Select the fields from the -   (Client Data) that will be shown as inputs in - the public page form. -
  • -
  • You can select multiple fields.
  • -
  • - A corresponding input field will be created for each - selected field. -
  • -
-
-
- - - -
-
-
- - - Generate Action Button - -
    -
  • - If enabled, the public page will have a button to - perform an action (e.g. generate a payment request). -
  • -
  • - The action will use the selected input fields from -   (Client Data) as parameters. -
  • -
  • - A corresponding REST API endpoint will be created. -
  • -
-
- - - -
-
-
- - -
-
-
- - - Generate Payment Logic - -
    -
  • - If enabled, the endpoint will create an invoice from - the submitted data and the UI will show the QR code - with the invoice. -
  • -
  • - A listener will be created to check for the pay event. -
  • -
  • You must map the fieds.
  • -
-
- - - -
-
- -
-
-
-
- - - Wallet - -
    -
  • - Select the field from the -   (Owner Data) that represents the wallet which - will generate the invoice and receive the payments. -
  • - -
  • - Only fields with the type Wallet will be - shown. -
  • -
-
-
- - - -
-
- -
- - - Currency - -
    -
  • - Select the field from the -   (Owner Data) that represents the currency - which will be used to for the amount. -
  • -
  • - Only fields with the type Currency will - be shown. -
  • -
  • Empty if you want to use sats.
  • -
-
-
- - - -
-
- -
- - - Amount - -
    -
  • - Select the field from the -   (Owner Data) or -   (Client Data) that represents the amount (in - the selected currency). -
  • -
  • - Only fields with the type Integer and - Float will be shown. -
  • -
-
-
- -
-
- -
-
- -
-
-
-
-
- -
- - - Paid Flag - -
    -
  • - Select the field from the -   (Client Data) that will be set to true when - the invoice is paid. -
  • -
  • - Only fields with the type Boolean will be - shown. -
  • -
-
-
- - - -
-
-
-
-
-
- - -
-
- -
-
- - - -
    -
  • - The extension builder uses caching to speed up the build - process. -
  • -
  • - This action clears old data and redownloads the Extension - Builder Stub release. -
  • -
-
-
-
-
-
-
-
- - - -
    -
  • - Installs the extension directly to this LNbits instance. -
  • -
  • - The extension will be enabled by default, and available to - all users. -
  • -
-
-
-
-
-
- -
-
-
- - - - Builds the extension and downloads a zip file with the code. - You can then install it manually in your LNbits instance. - - -
-
-
-
- - -
-
-
-
- -{% endblock %} diff --git a/lnbits/core/views/generic.py b/lnbits/core/views/generic.py index cc216f27..e27344c9 100644 --- a/lnbits/core/views/generic.py +++ b/lnbits/core/views/generic.py @@ -213,24 +213,6 @@ async def extensions(request: Request, user: User = Depends(check_user_exists)): ) -@generic_router.get( - "/extensions/builder", - name="extensions builder", - dependencies=[Depends(check_extension_builder)], -) -async def extensions_builder( - request: Request, user: User = Depends(check_user_exists) -) -> HTMLResponse: - return template_renderer().TemplateResponse( - request, - "core/extensions_builder.html", - { - "user": user.json(), - "ajax": _is_ajax_request(request), - }, - ) - - @generic_router.get( "/extensions/builder/preview/{ext_id}", name="extensions builder", @@ -392,6 +374,9 @@ admin_ui_checks = [Depends(check_admin), Depends(check_admin_ui)] @generic_router.get("/audit", dependencies=admin_ui_checks) @generic_router.get("/node", dependencies=admin_ui_checks) @generic_router.get("/admin", dependencies=admin_ui_checks) +@generic_router.get( + "/extensions/builder", dependencies=[Depends(check_extension_builder)] +) async def index( request: Request, user: User = Depends(check_user_exists) ) -> HTMLResponse: diff --git a/lnbits/static/bundle-components.min.js b/lnbits/static/bundle-components.min.js index 9188c5ab..7cbe5dc5 100644 --- a/lnbits/static/bundle-components.min.js +++ b/lnbits/static/bundle-components.min.js @@ -1 +1 @@ -window.PagePayments={template:"#page-payments",mixins:[window.windowMixin],data:()=>({payments:[],dailyChartData:[],searchDate:{from:null,to:null},searchData:{wallet_id:null,payment_hash:null,memo:null,internal_memo:null},statusFilters:{success:!0,pending:!0,failed:!0,incoming:!0,outgoing:!0},chartData:{showPaymentStatus:!0,showPaymentTags:!0,showBalance:!0,showWalletsSize:!1,showBalanceInOut:!1,showPaymentCountInOut:!1},searchOptions:{status:[]},paymentsTable:{columns:[{name:"status",align:"left",label:"Status",field:"status",sortable:!1},{name:"created_at",align:"left",label:"Created At",field:"created_at",sortable:!0},{name:"amount",align:"right",label:"Amount",field:"amount",sortable:!0},{name:"amountFiat",align:"right",label:"Fiat",field:"amountFiat",sortable:!1},{name:"fee_sats",align:"left",label:"Fee",field:"fee_sats",sortable:!0},{name:"tag",align:"left",label:"Tag",field:"tag",sortable:!1},{name:"memo",align:"left",label:"Memo",field:"memo",sortable:!1,max_length:20},{name:"internal_memo",align:"left",label:"Internal Memo",field:"internal_memo",sortable:!1,max_length:20},{name:"wallet_id",align:"left",label:"Wallet (ID)",field:"wallet_id",sortable:!1},{name:"payment_hash",align:"left",label:"Payment Hash",field:"payment_hash",sortable:!1}],pagination:{sortBy:"created_at",rowsPerPage:25,page:1,descending:!0,rowsNumber:10},search:null,hideEmpty:!0,loading:!1},chartsReady:!1,showDetails:!1,paymentDetails:null,lnbitsBalance:0}),async mounted(){this.chartsReady=!0,await this.$nextTick(),this.initCharts(),await this.fetchPayments()},computed:{},methods:{async fetchPayments(t){const e=Object.entries(this.searchData).reduce(((t,[e,a])=>a?(t[e]=a,t):t),{});delete e["time[ge]"],delete e["time[le]"],this.searchDate.from&&(e["time[ge]"]=this.searchDate.from+"T00:00:00"),this.searchDate.to&&(e["time[le]"]=this.searchDate.to+"T23:59:59"),this.paymentsTable.filter=e;try{const e=LNbits.utils.prepareFilterQuery(this.paymentsTable,t),{data:a}=await LNbits.api.request("GET",`/api/v1/payments/all/paginated?${e}`);this.paymentsTable.pagination.rowsNumber=a.total,this.payments=a.data.map((t=>(t.extra&&t.extra.tag&&(t.tag=t.extra.tag),t.timeFrom=moment.utc(t.created_at).local().fromNow(),t.outgoing=t.amount<0,t.amount=new Intl.NumberFormat(window.LOCALE).format(t.amount/1e3)+" sats",t.extra?.wallet_fiat_amount&&(t.amountFiat=this.formatCurrency(t.extra.wallet_fiat_amount,t.extra.wallet_fiat_currency)),t.extra?.internal_memo&&(t.internal_memo=t.extra.internal_memo),t.fee_sats=new Intl.NumberFormat(window.LOCALE).format(t.fee/1e3)+" sats",t)))}catch(t){console.error(t),LNbits.utils.notifyApiError(t)}finally{this.updateCharts(t)}},async searchPaymentsBy(t,e){t&&(this.searchData[t]=e),await this.fetchPayments()},clearDateSeach(){this.searchDate={from:null,to:null},delete this.paymentsTable.filter["time[ge]"],delete this.paymentsTable.filter["time[le]"],this.fetchPayments()},searchByDate(){"string"==typeof this.searchDate&&(this.searchDate={from:this.searchDate,to:this.searchDate}),this.searchDate.from&&(this.paymentsTable.filter["time[ge]"]=this.searchDate.from+"T00:00:00"),this.searchDate.to&&(this.paymentsTable.filter["time[le]"]=this.searchDate.to+"T23:59:59"),this.fetchPayments()},handleFilterChanged(){const{success:t,pending:e,failed:a,incoming:s,outgoing:i}=this.statusFilters;delete this.searchData["status[ne]"],delete this.searchData["status[eq]"],t&&e&&a||(t&&e?this.searchData["status[ne]"]="failed":t&&a?this.searchData["status[ne]"]="pending":a&&e?this.searchData["status[ne]"]="success":t?this.searchData["status[eq]"]="success":e?this.searchData["status[eq]"]="pending":a&&(this.searchData["status[eq]"]="failed")),delete this.searchData["amount[ge]"],delete this.searchData["amount[le]"],s&&i||(s?this.searchData["amount[ge]"]="0":i&&(this.searchData["amount[le]"]="0")),this.fetchPayments()},showDetailsToggle(t){return this.paymentDetails=t,this.showDetails=!this.showDetails},formatDate:t=>LNbits.utils.formatDateString(t),formatCurrency(t,e){try{return LNbits.utils.formatCurrency(t,e)}catch(e){return console.error(e),`${t} ???`}},shortify:(t,e=10)=>(valueLength=(t||"").length,valueLength<=e?t:`${t.substring(0,5)}...${t.substring(valueLength-5,valueLength)}`),async updateCharts(t){let e=LNbits.utils.prepareFilterQuery(this.paymentsTable,t);try{const{data:t}=await LNbits.api.request("GET",`/api/v1/payments/stats/count?${e}&count_by=status`);t.sort(((t,e)=>t.field-e.field)).reverse(),this.searchOptions.status=t.map((t=>t.field)),this.paymentsStatusChart.data.datasets[0].data=t.map((t=>t.total)),this.paymentsStatusChart.data.labels=[...this.searchOptions.status],this.paymentsStatusChart.update()}catch(t){console.warn(t),LNbits.utils.notifyApiError(t)}try{const{data:t}=await LNbits.api.request("GET",`/api/v1/payments/stats/wallets?${e}`),a=t.map((t=>t.balance/t.payments_count)),s=Math.min(...a),i=Math.max(...a),n=t=>Math.floor(3+22*(t-s)/(i-s)),l=this.randomColors(20),o=t.map(((t,e)=>({data:[{x:t.payments_count,y:t.balance,r:n(Math.max(t.balance/t.payments_count,5))}],label:t.wallet_name,wallet_id:t.wallet_id,backgroundColor:l[e%100],hoverOffset:4})));this.paymentsWalletsChart.data.datasets=o,this.paymentsWalletsChart.update()}catch(t){console.warn(t),LNbits.utils.notifyApiError(t)}try{const{data:t}=await LNbits.api.request("GET",`/api/v1/payments/stats/count?${e}&count_by=tag`);this.searchOptions.tag=t.map((t=>t.field)),this.searchOptions.status.sort(),this.paymentsTagsChart.data.datasets[0].data=t.map((t=>t.total)),this.paymentsTagsChart.data.labels=t.map((t=>t.field||"core")),this.paymentsTagsChart.update()}catch(t){console.warn(t),LNbits.utils.notifyApiError(t)}try{const e=Object.entries(this.searchData).reduce(((t,[e,a])=>a?(t[e]=a,t):t),{}),a={...this.paymentsTable,filter:e},s=LNbits.utils.prepareFilterQuery(a,t);let{data:i}=await LNbits.api.request("GET",`/api/v1/payments/stats/daily?${s}`);const n=this.searchDate.from+"T00:00:00",l=this.searchDate.to+"T23:59:59";this.lnbitsBalance=i.length?i[i.length-1].balance:0,i=i.filter((t=>this.searchDate.from&&this.searchDate.to?t.date>=n&&t.date<=l:this.searchDate.from?t.date>=n:!this.searchDate.to||t.date<=l)),this.paymentsDailyChart.data.datasets=[{label:"Balance",data:i.map((t=>t.balance)),pointStyle:!1,borderWidth:2,tension:.7,fill:1},{label:"Fees",data:i.map((t=>t.fee)),pointStyle:!1,borderWidth:1,tension:.4,fill:1}],this.paymentsDailyChart.data.labels=i.map((t=>t.date.substring(0,10))),this.paymentsDailyChart.update(),this.paymentsBalanceInOutChart.data.datasets=[{label:"Incoming Payments Balance",data:i.map((t=>t.balance_in))},{label:"Outgoing Payments Balance",data:i.map((t=>t.balance_out))}],this.paymentsBalanceInOutChart.data.labels=i.map((t=>t.date.substring(0,10))),this.paymentsBalanceInOutChart.update(),this.paymentsCountInOutChart.data.datasets=[{label:"Incoming Payments Count",data:i.map((t=>t.count_in))},{label:"Outgoing Payments Count",data:i.map((t=>-t.count_out))}],this.paymentsCountInOutChart.data.labels=i.map((t=>t.date.substring(0,10))),this.paymentsCountInOutChart.update()}catch(t){console.warn(t),LNbits.utils.notifyApiError(t)}},async initCharts(){const t=this.$q.localStorage.getItem("lnbits.payments.chartData")||{};this.chartData={...this.chartData,...t},this.chartsReady?(this.paymentsStatusChart=new Chart(this.$refs.paymentsStatusChart.getContext("2d"),{type:"doughnut",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1}},onClick:(t,e,a)=>{if(e[0]){const t=e[0].index;this.searchPaymentsBy("status",a.data.labels[t])}}},data:{datasets:[{label:"",data:[],backgroundColor:["rgb(0, 205, 86)","rgb(64, 72, 78)","rgb(255, 99, 132)"],hoverOffset:4}]}}),this.paymentsWalletsChart=new Chart(this.$refs.paymentsWalletsChart.getContext("2d"),{type:"bubble",options:{responsive:!0,maintainAspectRatio:!1,plugins:{legend:{display:!1},title:{display:!1}},onClick:(t,e,a)=>{if(e[0]){const t=e[0].datasetIndex;this.searchPaymentsBy("wallet_id",a.data.datasets[t].wallet_id)}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(20),hoverOffset:4}]}}),this.paymentsTagsChart=new Chart(this.$refs.paymentsTagsChart.getContext("2d"),{type:"pie",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1},legend:{display:!1,title:{display:!1,text:"Tags"}}},onClick:(t,e,a)=>{if(e[0]){const t=e[0].index;this.searchPaymentsBy("tag",a.data.labels[t])}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(10),hoverOffset:4}]}}),this.paymentsDailyChart=new Chart(this.$refs.paymentsDailyChart.getContext("2d"),{type:"line",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1},legend:{display:!0,title:{display:!1,text:"Tags"}}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(10),hoverOffset:4}]}}),this.paymentsBalanceInOutChart=new Chart(this.$refs.paymentsBalanceInOutChart.getContext("2d"),{type:"bar",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1},legend:{display:!0,title:{display:!1,text:"Tags"}}},scales:{x:{stacked:!0},y:{stacked:!0}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(50),hoverOffset:4}]}}),this.paymentsCountInOutChart=new Chart(this.$refs.paymentsCountInOutChart.getContext("2d"),{type:"bar",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1},legend:{display:!0,title:{display:!1,text:""}}},scales:{x:{stacked:!0},y:{stacked:!0}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(80),hoverOffset:4}]}})):console.warn("Charts are not ready yet. Initialization delayed.")},saveChartsPreferences(){this.$q.localStorage.set("lnbits.payments.chartData",this.chartData)},randomColors(t=1){const e=[];for(let a=1;a<=10;a++)for(let s=1;s<=10;s++)e.push(`rgb(${s*t*33%200}, ${71*(a+s+t)%255}, ${(a+30*t)%255})`);return e}}},window.PageNode={mixins:[window.windowMixin],template:"#page-node",config:{globalProperties:{LNbits:LNbits,msg:"hello"}},data(){return{isSuperUser:!1,wallet:{},tab:"dashboard",payments:1e3,info:{},channel_stats:{},channels:{data:[],filter:""},activeBalance:{},ranks:{},peers:{data:[],filter:""},connectPeerDialog:{show:!1,data:{}},setFeeDialog:{show:!1,data:{fee_ppm:0,fee_base_msat:0}},openChannelDialog:{show:!1,data:{}},closeChannelDialog:{show:!1,data:{}},nodeInfoDialog:{show:!1,data:{}},transactionDetailsDialog:{show:!1,data:{}},states:[{label:"Active",value:"active",color:"green"},{label:"Pending",value:"pending",color:"orange"},{label:"Inactive",value:"inactive",color:"grey"},{label:"Closed",value:"closed",color:"red"}],stateFilters:[{label:"Active",value:"active"},{label:"Pending",value:"pending"}],paymentsTable:{data:[],columns:[{name:"pending",label:""},{name:"date",align:"left",label:this.$t("date"),field:"date",sortable:!0},{name:"sat",align:"right",label:this.$t("amount")+" ("+LNBITS_DENOMINATION+")",field:t=>this.formatMsat(t.amount),sortable:!0},{name:"fee",align:"right",label:this.$t("fee")+" (m"+LNBITS_DENOMINATION+")",field:"fee"},{name:"destination",align:"right",label:"Destination",field:"destination"},{name:"memo",align:"left",label:this.$t("memo"),field:"memo"}],pagination:{rowsPerPage:10,page:1,rowsNumber:10},filter:null},invoiceTable:{data:[],columns:[{name:"pending",label:""},{name:"paid_at",field:"paid_at",align:"left",label:"Paid at",sortable:!0},{name:"expiry",label:this.$t("expiry"),field:"expiry",align:"left",sortable:!0},{name:"amount",label:this.$t("amount")+" ("+LNBITS_DENOMINATION+")",field:t=>this.formatMsat(t.amount),sortable:!0},{name:"memo",align:"left",label:this.$t("memo"),field:"memo"}],pagination:{rowsPerPage:10,page:1,rowsNumber:10},filter:null}}},created(){this.getInfo(),this.get1MLStats()},watch:{tab(t){"transactions"!==t||this.paymentsTable.data.length?"channels"!==t||this.channels.data.length||(this.getChannels(),this.getPeers()):(this.getPayments(),this.getInvoices())}},computed:{checkChanges(){return!_.isEqual(this.settings,this.formData)},filteredChannels(){return this.stateFilters?this.channels.data.filter((t=>this.stateFilters.find((({value:e})=>e==t.state)))):this.channels.data},totalBalance(){return this.filteredChannels.reduce(((t,e)=>(t.local_msat+=e.balance.local_msat,t.remote_msat+=e.balance.remote_msat,t.total_msat+=e.balance.total_msat,t)),{local_msat:0,remote_msat:0,total_msat:0})}},methods:{formatMsat:t=>LNbits.utils.formatMsat(t),api(t,e,a){const s=new URLSearchParams(a?.query);return LNbits.api.request(t,`/node/api/v1${e}?${s}`,{},a?.data).catch((t=>{LNbits.utils.notifyApiError(t)}))},getChannel(t){return this.api("GET",`/channels/${t}`).then((t=>{this.setFeeDialog.data.fee_ppm=t.data.fee_ppm,this.setFeeDialog.data.fee_base_msat=t.data.fee_base_msat}))},getChannels(){return this.api("GET","/channels").then((t=>{this.channels.data=t.data}))},getInfo(){return this.api("GET","/info").then((t=>{this.info=t.data,this.channel_stats=t.data.channel_stats})).catch((()=>{this.info={},this.channel_stats={}}))},get1MLStats(){return this.api("GET","/rank").then((t=>{this.ranks=t.data})).catch((()=>{this.ranks={}}))},getPayments(t){t&&(this.paymentsTable.pagination=t.pagination);let e=this.paymentsTable.pagination;const a={limit:e.rowsPerPage,offset:(e.page-1)*e.rowsPerPage??0};return this.api("GET","/payments",{query:a}).then((t=>{this.paymentsTable.data=t.data.data,this.paymentsTable.pagination.rowsNumber=t.data.total}))},getInvoices(t){t&&(this.invoiceTable.pagination=t.pagination);let e=this.invoiceTable.pagination;const a={limit:e.rowsPerPage,offset:(e.page-1)*e.rowsPerPage??0};return this.api("GET","/invoices",{query:a}).then((t=>{this.invoiceTable.data=t.data.data,this.invoiceTable.pagination.rowsNumber=t.data.total}))},getPeers(){return this.api("GET","/peers").then((t=>{this.peers.data=t.data}))},connectPeer(){this.api("POST","/peers",{data:this.connectPeerDialog.data}).then((()=>{this.connectPeerDialog.show=!1,this.getPeers()}))},disconnectPeer(t){LNbits.utils.confirmDialog("Do you really wanna disconnect this peer?").onOk((()=>{this.api("DELETE",`/peers/${t}`).then((t=>{Quasar.Notify.create({message:"Disconnected",icon:null}),this.needsRestart=!0,this.getPeers()}))}))},setChannelFee(t){this.api("PUT",`/channels/${t}`,{data:this.setFeeDialog.data}).then((t=>{this.setFeeDialog.show=!1,this.getChannels()})).catch(LNbits.utils.notifyApiError)},openChannel(){this.api("POST","/channels",{data:this.openChannelDialog.data}).then((t=>{this.openChannelDialog.show=!1,this.getChannels()})).catch((t=>{console.log(t)}))},showCloseChannelDialog(t){this.closeChannelDialog.show=!0,this.closeChannelDialog.data={force:!1,short_id:t.short_id,...t.point}},closeChannel(){this.api("DELETE","/channels",{query:this.closeChannelDialog.data}).then((t=>{this.closeChannelDialog.show=!1,this.getChannels()}))},showSetFeeDialog(t){this.setFeeDialog.show=!0,this.setFeeDialog.channel_id=t,this.getChannel(t)},showOpenChannelDialog(t){this.openChannelDialog.show=!0,this.openChannelDialog.data={peer_id:t,funding_amount:0}},showNodeInfoDialog(t){this.nodeInfoDialog.show=!0,this.nodeInfoDialog.data=t},showTransactionDetailsDialog(t){this.transactionDetailsDialog.show=!0,this.transactionDetailsDialog.data=t},shortenNodeId:t=>t?t.substring(0,5)+"..."+t.substring(t.length-5):"..."}},window.PageNodePublic={template:"#page-node-public",mixins:[window.windowMixin],data:()=>({enabled:!1,isSuperUser:!1,wallet:{},tab:"dashboard",payments:1e3,info:{},channel_stats:{},channels:[],activeBalance:{},ranks:{},peers:[],connectPeerDialog:{show:!1,data:{}},openChannelDialog:{show:!1,data:{}},closeChannelDialog:{show:!1,data:{}},nodeInfoDialog:{show:!1,data:{}},states:[{label:"Active",value:"active",color:"green"},{label:"Pending",value:"pending",color:"orange"},{label:"Inactive",value:"inactive",color:"grey"},{label:"Closed",value:"closed",color:"red"}]}),created(){this.getInfo(),this.get1MLStats()},methods:{formatMsat:t=>LNbits.utils.formatMsat(t),api:(t,e,a)=>LNbits.api.request(t,"/node/public/api/v1"+e,{},a),getInfo(){this.api("GET","/info",{}).then((t=>{this.info=t.data,this.channel_stats=t.data.channel_stats,this.enabled=!0})).catch((()=>{this.info={},this.channel_stats={}}))},get1MLStats(){this.api("GET","/rank",{}).then((t=>{this.ranks=t.data})).catch((()=>{this.ranks={}}))}}},window.PageAudit={template:"#page-audit",mixins:[window.windowMixin],data:()=>({chartsReady:!1,auditEntries:[],searchData:{user_id:"",ip_address:"",request_type:"",component:"",request_method:"",response_code:"",path:""},searchOptions:{component:[],request_method:[],response_code:[]},auditTable:{columns:[{name:"created_at",align:"center",label:"Date",field:"created_at",sortable:!0},{name:"duration",align:"left",label:"Duration (sec)",field:"duration",sortable:!0},{name:"component",align:"left",label:"Component",field:"component",sortable:!1},{name:"request_method",align:"left",label:"Method",field:"request_method",sortable:!1},{name:"response_code",align:"left",label:"Code",field:"response_code",sortable:!1},{name:"user_id",align:"left",label:"User Id",field:"user_id",sortable:!1},{name:"ip_address",align:"left",label:"IP Address",field:"ip_address",sortable:!1},{name:"path",align:"left",label:"Path",field:"path",sortable:!1}],pagination:{sortBy:"created_at",rowsPerPage:10,page:1,descending:!0,rowsNumber:10},search:null,hideEmpty:!0,loading:!1},auditDetailsDialog:{data:null,show:!1}}),async created(){},async mounted(){this.chartsReady=!0,await this.$nextTick(),this.initCharts(),await this.fetchAudit()},methods:{formatDate:t=>LNbits.utils.formatDateString(t),async fetchAudit(t){try{const e=LNbits.utils.prepareFilterQuery(this.auditTable,t),{data:a}=await LNbits.api.request("GET",`/audit/api/v1?${e}`);this.auditTable.pagination.rowsNumber=a.total,this.auditEntries=a.data,await this.fetchAuditStats(t)}catch(t){console.warn(t),LNbits.utils.notifyApiError(t)}finally{this.auditTable.loading=!1}},async fetchAuditStats(t){try{const e=LNbits.utils.prepareFilterQuery(this.auditTable,t),{data:a}=await LNbits.api.request("GET",`/audit/api/v1/stats?${e}`),s=a.request_method.map((t=>t.field));this.searchOptions.request_method=[...new Set(this.searchOptions.request_method.concat(s))],this.requestMethodChart.data.labels=s,this.requestMethodChart.data.datasets[0].data=a.request_method.map((t=>t.total)),this.requestMethodChart.update();const i=a.response_code.map((t=>t.field));this.searchOptions.response_code=[...new Set(this.searchOptions.response_code.concat(i))],this.responseCodeChart.data.labels=i,this.responseCodeChart.data.datasets[0].data=a.response_code.map((t=>t.total)),this.responseCodeChart.update();const n=a.component.map((t=>t.field));this.searchOptions.component=[...new Set(this.searchOptions.component.concat(n))],this.componentUseChart.data.labels=n,this.componentUseChart.data.datasets[0].data=a.component.map((t=>t.total)),this.componentUseChart.update(),this.longDurationChart.data.labels=a.long_duration.map((t=>t.field)),this.longDurationChart.data.datasets[0].data=a.long_duration.map((t=>t.total)),this.longDurationChart.update()}catch(t){console.warn(t),LNbits.utils.notifyApiError(t)}},async searchAuditBy(t,e){t&&(this.searchData[t]=e),this.auditTable.filter=Object.entries(this.searchData).reduce(((t,[e,a])=>a?(t[e]=a,t):t),{}),await this.fetchAudit()},showDetailsDialog(t){const e=JSON.parse(t?.request_details||"");try{e.body&&(e.body=JSON.parse(e.body))}catch(t){}this.auditDetailsDialog.data=JSON.stringify(e,null,4),this.auditDetailsDialog.show=!0},shortify:t=>(valueLength=(t||"").length,valueLength<=10?t:`${t.substring(0,5)}...${t.substring(valueLength-5,valueLength)}`),async initCharts(){this.chartsReady?(this.responseCodeChart=new Chart(this.$refs.responseCodeChart.getContext("2d"),{type:"doughnut",options:{responsive:!0,plugins:{legend:{position:"bottom"},title:{display:!1,text:"HTTP Response Codes"}},onClick:(t,e,a)=>{if(e[0]){const t=e[0].index;this.searchAuditBy("response_code",a.data.labels[t])}}},data:{datasets:[{label:"",data:[20,10],backgroundColor:["rgb(100, 99, 200)","rgb(54, 162, 235)","rgb(255, 205, 86)","rgb(255, 5, 86)","rgb(25, 205, 86)","rgb(255, 205, 250)"]}],labels:[]}}),this.requestMethodChart=new Chart(this.$refs.requestMethodChart.getContext("2d"),{type:"bar",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1}},onClick:(t,e,a)=>{if(e[0]){const t=e[0].index;this.searchAuditBy("request_method",a.data.labels[t])}}},data:{datasets:[{label:"",data:[],backgroundColor:["rgb(255, 99, 132)","rgb(54, 162, 235)","rgb(255, 205, 86)","rgb(255, 5, 86)","rgb(25, 205, 86)","rgb(255, 205, 250)"],hoverOffset:4}]}}),this.componentUseChart=new Chart(this.$refs.componentUseChart.getContext("2d"),{type:"pie",options:{responsive:!0,plugins:{legend:{position:"xxx"},title:{display:!1,text:"Components"}},onClick:(t,e,a)=>{if(e[0]){const t=e[0].index;this.searchAuditBy("component",a.data.labels[t])}}},data:{datasets:[{data:[],backgroundColor:["rgb(255, 99, 132)","rgb(54, 162, 235)","rgb(255, 205, 86)","rgb(255, 5, 86)","rgb(25, 205, 86)","rgb(255, 205, 250)","rgb(100, 205, 250)","rgb(120, 205, 250)","rgb(140, 205, 250)","rgb(160, 205, 250)"],hoverOffset:4}]}}),this.longDurationChart=new Chart(this.$refs.longDurationChart.getContext("2d"),{type:"bar",options:{responsive:!0,indexAxis:"y",maintainAspectRatio:!1,plugins:{legend:{title:{display:!1,text:"Long Duration"}}},onClick:(t,e,a)=>{if(e[0]){const t=e[0].index;this.searchAuditBy("path",a.data.labels[t])}}},data:{datasets:[{label:"",data:[],backgroundColor:["rgb(255, 99, 132)","rgb(54, 162, 235)","rgb(255, 205, 86)","rgb(255, 5, 86)","rgb(25, 205, 86)","rgb(255, 205, 250)","rgb(100, 205, 250)","rgb(120, 205, 250)","rgb(140, 205, 250)","rgb(160, 205, 250)"],hoverOffset:4}]}})):console.warn("Charts are not ready yet. Initialization delayed.")}}},window.PageWallets={template:"#page-wallets",mixins:[window.windowMixin],data:()=>({user:null,tab:"wallets",wallets:[],addWalletDialog:{show:!1},walletsTable:{columns:[{name:"name",align:"left",label:"Name",field:"name",sortable:!0},{name:"currency",align:"center",label:"Currency",field:"currency",sortable:!0},{name:"updated_at",align:"right",label:"Last Updated",field:"updated_at",sortable:!0}],pagination:{sortBy:"updated_at",rowsPerPage:12,page:1,descending:!0,rowsNumber:10},search:"",hideEmpty:!0,loading:!1}}),watch:{"walletsTable.search":{handler(){const t={};this.walletsTable.search&&(t.search=this.walletsTable.search),this.getUserWallets()}}},methods:{async getUserWallets(t){try{this.walletsTable.loading=!0;const e=LNbits.utils.prepareFilterQuery(this.walletsTable,t),{data:a}=await LNbits.api.request("GET",`/api/v1/wallet/paginated?${e}`,null);this.wallets=a.data,this.walletsTable.pagination.rowsNumber=a.total}catch(t){LNbits.utils.notifyApiError(t)}finally{this.walletsTable.loading=!1}},showNewWalletDialog(){this.addWalletDialog={show:!0,walletType:"lightning"},this.showAddNewWalletDialog()},goToWallet(t){window.location=`/wallet?wal=${t}`},formattedFiatAmount:(t,e)=>LNbits.utils.formatCurrency(Number(t).toFixed(2),e),formattedSatAmount:t=>LNbits.utils.formatMsat(t)+" sat"},async created(){await this.getUserWallets()}},window.PageUsers={template:"#page-users",mixins:[window.windowMixin],data:()=>({paymentsWallet:{},cancel:{},users:[],wallets:[],searchData:{user:"",username:"",email:"",pubkey:""},paymentPage:{show:!1},activeWallet:{userId:null,show:!1},activeUser:{data:null,showUserId:!1,show:!1},createWalletDialog:{data:{},show:!1},walletTable:{columns:[{name:"name",align:"left",label:"Name",field:"name"},{name:"id",align:"left",label:"Wallet Id",field:"id"},{name:"currency",align:"left",label:"Currency",field:"currency"},{name:"balance_msat",align:"left",label:"Balance",field:"balance_msat"}],pagination:{sortBy:"name",rowsPerPage:10,page:1,descending:!0,rowsNumber:10},search:null,hideEmpty:!0,loading:!1},usersTable:{columns:[{name:"admin",align:"left",label:"Admin",field:"admin",sortable:!1},{name:"wallet_id",align:"left",label:"Wallets",field:"wallet_id",sortable:!1},{name:"user",align:"left",label:"User Id",field:"user",sortable:!1},{name:"username",align:"left",label:"Username",field:"username",sortable:!1},{name:"email",align:"left",label:"Email",field:"email",sortable:!1},{name:"pubkey",align:"left",label:"Public Key",field:"pubkey",sortable:!1},{name:"balance_msat",align:"left",label:"Balance",field:"balance_msat",sortable:!0},{name:"transaction_count",align:"left",label:"Payments",field:"transaction_count",sortable:!0},{name:"last_payment",align:"left",label:"Last Payment",field:"last_payment",sortable:!0}],pagination:{sortBy:"balance_msat",rowsPerPage:10,page:1,descending:!0,rowsNumber:10},search:null,hideEmpty:!0,loading:!1}}),watch:{"usersTable.hideEmpty":function(t,e){this.usersTable.filter=t?{"transaction_count[gt]":0}:{},this.fetchUsers()}},created(){this.fetchUsers()},methods:{formatDate:t=>LNbits.utils.formatDateString(t),formatSat:t=>LNbits.utils.formatSat(Math.floor(t/1e3)),backToUsersPage(){this.activeUser.show=!1,this.paymentPage.show=!1,this.activeWallet.show=!1,this.fetchUsers()},handleBalanceUpdate(){this.fetchWallets(this.activeWallet.userId)},resetPassword(t){return LNbits.api.request("PUT",`/users/api/v1/user/${t}/reset_password`).then((t=>{LNbits.utils.confirmDialog(this.$t("reset_key_generated")+" "+this.$t("reset_key_copy")).onOk((()=>{const e=window.location.origin+"?reset_key="+t.data;this.copyText(e)}))})).catch(LNbits.utils.notifyApiError)},createUser(){LNbits.api.request("POST","/users/api/v1/user",null,this.activeUser.data).then((t=>{Quasar.Notify.create({type:"positive",message:"User created!",icon:null}),this.activeUser.setPassword=!0,this.activeUser.data=t.data,this.fetchUsers()})).catch(LNbits.utils.notifyApiError)},updateUser(){LNbits.api.request("PUT",`/users/api/v1/user/${this.activeUser.data.id}`,null,this.activeUser.data).then((()=>{Quasar.Notify.create({type:"positive",message:"User updated!",icon:null}),this.activeUser.data=null,this.activeUser.show=!1,this.fetchUsers()})).catch(LNbits.utils.notifyApiError)},createWallet(){const t=this.activeWallet.userId;t?LNbits.api.request("POST",`/users/api/v1/user/${t}/wallet`,null,this.createWalletDialog.data).then((()=>{this.fetchWallets(t),Quasar.Notify.create({type:"positive",message:"Wallet created!"})})).catch(LNbits.utils.notifyApiError):Quasar.Notify.create({type:"warning",message:"No user selected!",icon:null})},deleteUser(t){LNbits.utils.confirmDialog("Are you sure you want to delete this user?").onOk((()=>{LNbits.api.request("DELETE",`/users/api/v1/user/${t}`).then((()=>{this.fetchUsers(),Quasar.Notify.create({type:"positive",message:"User deleted!",icon:null}),this.activeUser.data=null,this.activeUser.show=!1})).catch(LNbits.utils.notifyApiError)}))},undeleteUserWallet(t,e){LNbits.api.request("PUT",`/users/api/v1/user/${t}/wallet/${e}/undelete`).then((()=>{this.fetchWallets(t),Quasar.Notify.create({type:"positive",message:"Undeleted user wallet!",icon:null})})).catch(LNbits.utils.notifyApiError)},deleteUserWallet(t,e,a){const s=a?"Wallet is already deleted, are you sure you want to permanently delete this user wallet?":"Are you sure you want to delete this user wallet?";LNbits.utils.confirmDialog(s).onOk((()=>{LNbits.api.request("DELETE",`/users/api/v1/user/${t}/wallet/${e}`).then((()=>{this.fetchWallets(t),Quasar.Notify.create({type:"positive",message:"User wallet deleted!",icon:null})})).catch(LNbits.utils.notifyApiError)}))},deleteAllUserWallets(t){LNbits.utils.confirmDialog(this.$t("confirm_delete_all_wallets")).onOk((()=>{LNbits.api.request("DELETE",`/users/api/v1/user/${t}/wallets`).then((e=>{Quasar.Notify.create({type:"positive",message:e.data.message,icon:null}),this.fetchWallets(t)})).catch(LNbits.utils.notifyApiError)}))},copyWalletLink(t){const e=`${window.location.origin}/wallet?usr=${this.activeWallet.userId}&wal=${t}`;this.copyText(e)},fetchUsers(t){this.relaxFilterForFields(["username","email"]);const e=LNbits.utils.prepareFilterQuery(this.usersTable,t);LNbits.api.request("GET",`/users/api/v1/user?${e}`).then((t=>{this.usersTable.loading=!1,this.usersTable.pagination.rowsNumber=t.data.total,this.users=t.data.data})).catch(LNbits.utils.notifyApiError)},fetchWallets(t){return LNbits.api.request("GET",`/users/api/v1/user/${t}/wallet`).then((e=>{this.wallets=e.data,this.activeWallet.userId=t,this.activeWallet.show=!0})).catch(LNbits.utils.notifyApiError)},relaxFilterForFields(t=[]){t.forEach((t=>{const e=this.usersTable?.filter?.[t];e&&this.usersTable.filter[t]&&(this.usersTable.filter[`${t}[like]`]=e,delete this.usersTable.filter[t])}))},updateWallet(t){LNbits.api.request("PATCH","/api/v1/wallet",t.adminkey,{name:t.name}).then((()=>{t.editable=!1,Quasar.Notify.create({message:"Wallet name updated.",type:"positive",timeout:3500})})).catch((t=>{LNbits.utils.notifyApiError(t)}))},toggleAdmin(t){LNbits.api.request("GET",`/users/api/v1/user/${t}/admin`).then((()=>{this.fetchUsers(),Quasar.Notify.create({type:"positive",message:"Toggled admin!",icon:null})})).catch(LNbits.utils.notifyApiError)},async showAccountPage(t){if(this.activeUser.showPassword=!1,this.activeUser.showUserId=!1,this.activeUser.setPassword=!1,!t)return this.activeUser.data={extra:{}},void(this.activeUser.show=!0);try{const{data:e}=await LNbits.api.request("GET",`/users/api/v1/user/${t}`);this.activeUser.data=e,this.activeUser.show=!0}catch(t){console.warn(t),Quasar.Notify.create({type:"warning",message:"Failed to get user!"}),this.activeUser.show=!1}},async showWalletPayments(t){this.activeUser.show=!1,await this.fetchWallets(this.users[0].id),await this.showPayments(t)},showPayments(t){this.paymentsWallet=this.wallets.find((e=>e.id===t)),this.paymentPage.show=!0},searchUserBy(t){const e=this.searchData[t];this.usersTable.filter={},e&&(this.usersTable.filter[t]=e),this.fetchUsers()},shortify:t=>(valueLength=(t||"").length,valueLength<=10?t:`${t.substring(0,5)}...${t.substring(valueLength-5,valueLength)}`)}},window.PageAccount={template:"#page-account",mixins:[window.windowMixin],data(){return{user:null,hasUsername:!1,showUserId:!1,reactionOptions:["None","confettiBothSides","confettiFireworks","confettiStars","confettiTop"],borderOptions:["retro-border","hard-border","neon-border","no-border"],tab:"user",credentialsData:{show:!1,oldPassword:null,newPassword:null,newPasswordRepeat:null,username:null,pubkey:null},apiAcl:{showNewAclDialog:!1,showPasswordDialog:!1,showNewTokenDialog:!1,data:[],passwordGuardedFunction:null,newAclName:"",newTokenName:"",password:"",apiToken:null,selectedTokenId:null,columns:[{name:"Name",align:"left",label:this.$t("Name"),field:"Name",sortable:!1},{name:"path",align:"left",label:this.$t("path"),field:"path",sortable:!1},{name:"read",align:"left",label:this.$t("read"),field:"read",sortable:!1},{name:"write",align:"left",label:this.$t("write"),field:"write",sortable:!1}],pagination:{rowsPerPage:100,page:1}},selectedApiAcl:{id:null,name:null,endpoints:[],token_id_list:[],allRead:!1,allWrite:!1},notifications:{nostr:{identifier:""}}}},methods:{activeLanguage:t=>window.i18n.global.locale===t,changeLanguage(t){window.i18n.global.locale=t,this.$q.localStorage.set("lnbits.lang",t)},async updateAccount(){try{const{data:t}=await LNbits.api.request("PUT","/api/v1/auth/update",null,{user_id:this.user.id,username:this.user.username,email:this.user.email,extra:this.user.extra});this.user=t,this.hasUsername=!!t.username,Quasar.Notify.create({type:"positive",message:"Account updated."})}catch(t){LNbits.utils.notifyApiError(t)}},disableUpdatePassword(){return!this.credentialsData.newPassword||!this.credentialsData.newPasswordRepeat||this.credentialsData.newPassword!==this.credentialsData.newPasswordRepeat},async updatePassword(){if(this.credentialsData.username)try{const{data:t}=await LNbits.api.request("PUT","/api/v1/auth/password",null,{user_id:this.user.id,username:this.credentialsData.username,password_old:this.credentialsData.oldPassword,password:this.credentialsData.newPassword,password_repeat:this.credentialsData.newPasswordRepeat});this.user=t,this.hasUsername=!!t.username,this.credentialsData.show=!1,Quasar.Notify.create({type:"positive",message:"Password updated."})}catch(t){LNbits.utils.notifyApiError(t)}else Quasar.Notify.create({type:"warning",message:"Please set a username."})},async updatePubkey(){try{const{data:t}=await LNbits.api.request("PUT","/api/v1/auth/pubkey",null,{user_id:this.user.id,pubkey:this.credentialsData.pubkey});this.user=t,this.hasUsername=!!t.username,this.credentialsData.show=!1,this.$q.notify({type:"positive",message:"Public key updated."})}catch(t){LNbits.utils.notifyApiError(t)}},showUpdateCredentials(){this.credentialsData={show:!0,oldPassword:null,username:this.user.username,pubkey:this.user.pubkey,newPassword:null,newPasswordRepeat:null}},newApiAclDialog(){this.apiAcl.newAclName=null,this.apiAcl.showNewAclDialog=!0},newTokenAclDialog(){this.apiAcl.newTokenName=null,this.apiAcl.newTokenExpiry=null,this.apiAcl.showNewTokenDialog=!0},handleApiACLSelected(t){this.selectedApiAcl={id:null,name:null,endpoints:[],token_id_list:[]},this.apiAcl.selectedTokenId=null,t&&setTimeout((()=>{const e=this.apiAcl.data.find((e=>e.id===t));this.selectedApiAcl&&(this.selectedApiAcl={...e},this.selectedApiAcl.allRead=this.selectedApiAcl.endpoints.every((t=>t.read)),this.selectedApiAcl.allWrite=this.selectedApiAcl.endpoints.every((t=>t.write)))}))},handleAllEndpointsReadAccess(){this.selectedApiAcl.endpoints.forEach((t=>t.read=this.selectedApiAcl.allRead))},handleAllEndpointsWriteAccess(){this.selectedApiAcl.endpoints.forEach((t=>t.write=this.selectedApiAcl.allWrite))},async getApiACLs(){try{const{data:t}=await LNbits.api.request("GET","/api/v1/auth/acl",null);this.apiAcl.data=t.access_control_list}catch(t){LNbits.utils.notifyApiError(t)}},askPasswordAndRunFunction(t){this.apiAcl.passwordGuardedFunction=t,this.apiAcl.showPasswordDialog=!0},runPasswordGuardedFunction(){this.apiAcl.showPasswordDialog=!1;const t=this.apiAcl.passwordGuardedFunction;t&&this[t]()},async addApiACL(){if(this.apiAcl.newAclName){try{const{data:t}=await LNbits.api.request("PUT","/api/v1/auth/acl",null,{id:this.apiAcl.newAclName,name:this.apiAcl.newAclName,password:this.apiAcl.password});this.apiAcl.data=t.access_control_list;const e=this.apiAcl.data.find((t=>t.name===this.apiAcl.newAclName));this.handleApiACLSelected(e.id),this.apiAcl.showNewAclDialog=!1,this.$q.notify({type:"positive",message:"Access Control List created."})}catch(t){LNbits.utils.notifyApiError(t)}finally{this.apiAcl.name="",this.apiAcl.password=""}this.apiAcl.showNewAclDialog=!1}else this.$q.notify({type:"warning",message:"Name is required."})},async updateApiACLs(){try{const{data:t}=await LNbits.api.request("PUT","/api/v1/auth/acl",null,{id:this.user.id,password:this.apiAcl.password,...this.selectedApiAcl});this.apiAcl.data=t.access_control_list}catch(t){LNbits.utils.notifyApiError(t)}finally{this.apiAcl.password=""}},async deleteApiACL(){if(this.selectedApiAcl.id){try{await LNbits.api.request("DELETE","/api/v1/auth/acl",null,{id:this.selectedApiAcl.id,password:this.apiAcl.password}),this.$q.notify({type:"positive",message:"Access Control List deleted."})}catch(t){LNbits.utils.notifyApiError(t)}finally{this.apiAcl.password=""}this.apiAcl.data=this.apiAcl.data.filter((t=>t.id!==this.selectedApiAcl.id)),this.handleApiACLSelected(this.apiAcl.data[0]?.id)}},async generateApiToken(){if(!this.selectedApiAcl.id)return;const t=new Date(this.apiAcl.newTokenExpiry)-new Date;try{const{data:e}=await LNbits.api.request("POST","/api/v1/auth/acl/token",null,{acl_id:this.selectedApiAcl.id,token_name:this.apiAcl.newTokenName,password:this.apiAcl.password,expiration_time_minutes:Math.trunc(t/6e4)});this.apiAcl.apiToken=e.api_token,this.apiAcl.selectedTokenId=e.id,Quasar.Notify.create({type:"positive",message:"Token Generated."}),await this.getApiACLs(),this.handleApiACLSelected(this.selectedApiAcl.id),this.apiAcl.showNewTokenDialog=!1}catch(t){LNbits.utils.notifyApiError(t)}finally{this.apiAcl.password=""}},async deleteToken(){if(this.apiAcl.selectedTokenId)try{await LNbits.api.request("DELETE","/api/v1/auth/acl/token",null,{id:this.apiAcl.selectedTokenId,acl_id:this.selectedApiAcl.id,password:this.apiAcl.password}),this.$q.notify({type:"positive",message:"Token deleted."}),this.selectedApiAcl.token_id_list=this.selectedApiAcl.token_id_list.filter((t=>t.id!==this.apiAcl.selectedTokenId)),this.apiAcl.selectedTokenId=null}catch(t){LNbits.utils.notifyApiError(t)}finally{this.apiAcl.password=""}}},async created(){try{const{data:t}=await LNbits.api.getAuthenticatedUser();this.user=t,this.hasUsername=!!t.username,this.user.extra||(this.user.extra={})}catch(t){LNbits.utils.notifyApiError(t)}const t=window.location.hash.replace("#","");t&&(this.tab=t),await this.getApiACLs()}},window.PageAdmin={template:"#page-admin",mixins:[windowMixin],data:()=>({tab:"funding",settings:{},formData:{lnbits_exchange_rate_providers:[],lnbits_audit_exclude_paths:[],lnbits_audit_include_paths:[],lnbits_audit_http_response_codes:[]},isSuperUser:!1,needsRestart:!1}),async created(){await this.getSettings();const t=window.location.hash.replace("#","");t&&(this.tab=t)},computed:{checkChanges(){return!_.isEqual(this.settings,this.formData)}},methods:{getDefaultSetting(t){LNbits.api.request("GET",`/admin/api/v1/settings/default?field_name=${t}`).then((e=>{this.formData[t]=e.data.default_value})).catch((function(t){LNbits.utils.notifyApiError(t)}))},restartServer(){LNbits.api.request("GET","/admin/api/v1/restart/").then((t=>{this.$q.notify({type:"positive",message:"Success! Restarted Server",icon:null}),this.needsRestart=!1})).catch(LNbits.utils.notifyApiError)},async getSettings(){await LNbits.api.request("GET","/admin/api/v1/settings",this.g.user.wallets[0].adminkey).then((t=>{this.isSuperUser=t.data.is_super_user||!1,this.settings=t.data,this.formData={...this.settings}})).catch(LNbits.utils.notifyApiError)},updateSettings(){const t=_.omit(this.formData,["is_super_user","lnbits_allowed_funding_sources","touch"]);LNbits.api.request("PUT","/admin/api/v1/settings",this.g.user.wallets[0].adminkey,t).then((t=>{this.needsRestart=this.settings.lnbits_backend_wallet_class!==this.formData.lnbits_backend_wallet_class,this.settings=this.formData,this.formData=_.clone(this.settings),Quasar.Notify.create({type:"positive",message:"Success! Settings changed! "+(this.needsRestart?"Restart required!":""),icon:null})})).catch(LNbits.utils.notifyApiError)},deleteSettings(){LNbits.utils.confirmDialog("Are you sure you want to restore settings to default?").onOk((()=>{LNbits.api.request("DELETE","/admin/api/v1/settings").then((t=>{Quasar.Notify.create({type:"positive",message:"Success! Restored settings to defaults. Restarting...",icon:null}),this.$q.localStorage.clear()})).catch(LNbits.utils.notifyApiError)}))},downloadBackup(){window.open("/admin/api/v1/backup","_blank")}}},window.app.component("lnbits-admin-funding",{props:["is-super-user","form-data","settings"],template:"#lnbits-admin-funding",mixins:[window.windowMixin],data:()=>({auditData:[]}),created(){this.getAudit()},methods:{getAudit(){LNbits.api.request("GET","/admin/api/v1/audit",this.g.user.wallets[0].adminkey).then((t=>{this.auditData=t.data})).catch(LNbits.utils.notifyApiError)}}}),window.app.component("lnbits-admin-funding-sources",{template:"#lnbits-admin-funding-sources",mixins:[window.windowMixin],props:["form-data","allowed-funding-sources"],methods:{getFundingSourceLabel(t){const e=this.rawFundingSources.find((e=>e[0]===t));return e?e[1]:t},showQRValue(t){this.qrValue=t,this.showQRDialog=!0}},computed:{fundingSources(){let t=[];for(const[e,a,s]of this.rawFundingSources){const a={};if(null!==s)for(let[t,e]of Object.entries(s))a[t]="string"==typeof e?{label:e,value:null}:e||{};t.push([e,a])}return new Map(t)},sortedAllowedFundingSources(){return this.allowedFundingSources.sort()}},data:()=>({hideInput:!0,showQRDialog:!1,qrValue:"",rawFundingSources:[["VoidWallet","Void Wallet",null],["FakeWallet","Fake Wallet",{fake_wallet_secret:"Secret",lnbits_denomination:'"sats" or 3 Letter Custom Denomination'}],["CLNRestWallet","Core Lightning Rest (plugin)",{clnrest_url:"Endpoint",clnrest_ca:"ca.pem",clnrest_cert:"server.pem",clnrest_readonly_rune:"Rune used for readonly requests",clnrest_invoice_rune:"Rune used for creating invoices",clnrest_pay_rune:"Rune used for paying invoices using pay",clnrest_renepay_rune:"Rune used for paying invoices using renepay",clnrest_last_pay_index:"Ignores any invoices paid prior to or including this index. 0 is equivalent to not specifying and negative value is invalid.",clnrest_nodeid:"Node id"}],["CoreLightningWallet","Core Lightning",{corelightning_rpc:"Endpoint",corelightning_pay_command:"Custom Pay Command"}],["CoreLightningRestWallet","Core Lightning Rest (legacy)",{corelightning_rest_url:"Endpoint",corelightning_rest_cert:"Certificate",corelightning_rest_macaroon:"Macaroon"}],["LndRestWallet","Lightning Network Daemon (LND Rest)",{lnd_rest_endpoint:"Endpoint",lnd_rest_cert:"Certificate",lnd_rest_macaroon:"Macaroon",lnd_rest_macaroon_encrypted:"Encrypted Macaroon",lnd_rest_route_hints:"Enable Route Hints",lnd_rest_allow_self_payment:"Allow Self Payment"}],["LndWallet","Lightning Network Daemon (LND)",{lnd_grpc_endpoint:"Endpoint",lnd_grpc_cert:"Certificate",lnd_grpc_port:"Port",lnd_grpc_macaroon:"GRPC Macaroon",lnd_grpc_invoice_macaroon:"GRPC Invoice Macaroon",lnd_grpc_admin_macaroon:"GRPC Admin Macaroon",lnd_grpc_macaroon_encrypted:"Encrypted Macaroon"}],["LnTipsWallet","LN.Tips",{lntips_api_endpoint:"Endpoint",lntips_api_key:"API Key"}],["LNPayWallet","LN Pay",{lnpay_api_endpoint:"Endpoint",lnpay_api_key:"API Key",lnpay_wallet_key:"Wallet Key"}],["EclairWallet","Eclair (ACINQ)",{eclair_url:"URL",eclair_pass:"Password"}],["LNbitsWallet","LNbits",{lnbits_endpoint:"Endpoint",lnbits_key:"Admin Key"}],["BlinkWallet","Blink",{blink_api_endpoint:"Endpoint",blink_ws_endpoint:"WebSocket",blink_token:"Key"}],["AlbyWallet","Alby",{alby_api_endpoint:"Endpoint",alby_access_token:"Key"}],["BoltzWallet","Boltz",{boltz_client_endpoint:"Endpoint",boltz_client_macaroon:"Admin Macaroon path or hex",boltz_client_cert:"Certificate path or hex",boltz_client_wallet:"Wallet Name",boltz_client_password:"Wallet Password (can be empty)",boltz_mnemonic:{label:"Liquid mnemonic (copy into greenwallet)",readonly:!0,copy:!0,qrcode:!0}}],["ZBDWallet","ZBD",{zbd_api_endpoint:"Endpoint",zbd_api_key:"Key"}],["PhoenixdWallet","Phoenixd",{phoenixd_api_endpoint:"Endpoint",phoenixd_api_password:"Key"}],["OpenNodeWallet","OpenNode",{opennode_api_endpoint:"Endpoint",opennode_key:"Key"}],["ClicheWallet","Cliche (NBD)",{cliche_endpoint:"Endpoint"}],["SparkWallet","Spark",{spark_url:"Endpoint",spark_token:"Token"}],["NWCWallet","Nostr Wallet Connect",{nwc_pairing_url:"Pairing URL"}],["BreezSdkWallet","Breez SDK",{breez_api_key:"Breez API Key",breez_greenlight_seed:"Greenlight Seed",breez_greenlight_device_key:"Greenlight Device Key",breez_greenlight_device_cert:"Greenlight Device Cert",breez_greenlight_invite_code:"Greenlight Invite Code"}],["StrikeWallet","Strike (alpha)",{strike_api_endpoint:"API Endpoint",strike_api_key:"API Key"}],["BreezLiquidSdkWallet","Breez Liquid SDK",{breez_liquid_api_key:"Breez API Key (can be empty)",breez_liquid_seed:"Liquid seed phrase",breez_liquid_fee_offset_sat:"Offset amount in sats to increase fee limit"}]]})}),window.app.component("lnbits-admin-fiat-providers",{props:["form-data"],template:"#lnbits-admin-fiat-providers",mixins:[window.windowMixin],data:()=>({formAddStripeUser:"",hideInputToggle:!0}),methods:{addStripeAllowedUser(){const t=this.formAddStripeUser||"";t.length&&!this.formData.stripe_limits.allowed_users.includes(t)&&(this.formData.stripe_limits.allowed_users=[...this.formData.stripe_limits.allowed_users,t],this.formAddStripeUser="")},removeStripeAllowedUser(t){this.formData.stripe_limits.allowed_users=this.formData.stripe_limits.allowed_users.filter((e=>e!==t))},checkFiatProvider(t){LNbits.api.request("PUT",`/api/v1/fiat/check/${t}`).then((t=>{const e=t.data;Quasar.Notify.create({type:e.success?"positive":"warning",message:e.message,icon:null})})).catch(LNbits.utils.notifyApiError)}}}),window.app.component("lnbits-admin-exchange-providers",{props:["form-data"],template:"#lnbits-admin-exchange-providers",mixins:[window.windowMixin],data:()=>({exchangeData:{selectedProvider:null,showTickerConversion:!1,convertFromTicker:null,convertToTicker:null},exchangesTable:{columns:[{name:"name",align:"left",label:"Exchange Name",field:"name",sortable:!0},{name:"api_url",align:"left",label:"URL",field:"api_url",sortable:!1},{name:"path",align:"left",label:"JSON Path",field:"path",sortable:!1},{name:"exclude_to",align:"left",label:"Exclude Currencies",field:"exclude_to",sortable:!1},{name:"ticker_conversion",align:"left",label:"Ticker Conversion",field:"ticker_conversion",sortable:!1}],pagination:{sortBy:"name",rowsPerPage:100,page:1,rowsNumber:100},search:null,hideEmpty:!0}}),mounted(){this.getExchangeRateHistory()},created(){const t=window.location.hash.replace("#","");"exchange_providers"===t&&this.showExchangeProvidersTab(t)},methods:{getExchangeRateHistory(){LNbits.api.request("GET","/api/v1/rate/history",this.g.user.wallets[0].inkey).then((t=>{this.initExchangeChart(t.data)})).catch((function(t){LNbits.utils.notifyApiError(t)}))},showExchangeProvidersTab(t){"exchange_providers"===t&&this.getExchangeRateHistory()},addExchangeProvider(){this.formData.lnbits_exchange_rate_providers=[{name:"",api_url:"",path:"",exclude_to:[]},...this.formData.lnbits_exchange_rate_providers]},removeExchangeProvider(t){this.formData.lnbits_exchange_rate_providers=this.formData.lnbits_exchange_rate_providers.filter((e=>e!==t))},removeExchangeTickerConversion(t,e){t.ticker_conversion=t.ticker_conversion.filter((t=>t!==e)),this.formData.touch=null},addExchangeTickerConversion(){this.exchangeData.selectedProvider&&(this.exchangeData.selectedProvider.ticker_conversion.push(`${this.exchangeData.convertFromTicker}:${this.exchangeData.convertToTicker}`),this.formData.touch=null,this.exchangeData.showTickerConversion=!1)},showTickerConversionDialog(t){this.exchangeData.convertFromTicker=null,this.exchangeData.convertToTicker=null,this.exchangeData.selectedProvider=t,this.exchangeData.showTickerConversion=!0},initExchangeChart(t){const e=t.map((t=>Quasar.date.formatDate(new Date(1e3*t.timestamp),"HH:mm"))),a=[...this.formData.lnbits_exchange_rate_providers,{name:"LNbits"}].map((e=>({label:e.name,data:t.map((t=>t.rates[e.name])),pointStyle:!0,borderWidth:"LNbits"===e.name?4:1,tension:.4})));this.exchangeRatesChart=new Chart(this.$refs.exchangeRatesChart.getContext("2d"),{type:"line",options:{plugins:{legend:{display:!1}}},data:{labels:e,datasets:a}})}}}),window.app.component("lnbits-admin-security",{props:["form-data"],template:"#lnbits-admin-security",mixins:[window.windowMixin],data:()=>({logs:[],formBlockedIPs:"",serverlogEnabled:!1,nostrAcceptedUrl:"",formAllowedIPs:"",formCallbackUrlRule:""}),created(){},methods:{addAllowedIPs(){const t=this.formAllowedIPs.trim(),e=this.formData.lnbits_allowed_ips;t&&t.length&&!e.includes(t)&&(this.formData.lnbits_allowed_ips=[...e,t],this.formAllowedIPs="")},removeAllowedIPs(t){const e=this.formData.lnbits_allowed_ips;this.formData.lnbits_allowed_ips=e.filter((e=>e!==t))},addBlockedIPs(){const t=this.formBlockedIPs.trim(),e=this.formData.lnbits_blocked_ips;t&&t.length&&!e.includes(t)&&(this.formData.lnbits_blocked_ips=[...e,t],this.formBlockedIPs="")},removeBlockedIPs(t){const e=this.formData.lnbits_blocked_ips;this.formData.lnbits_blocked_ips=e.filter((e=>e!==t))},addCallbackUrlRule(){const t=this.formCallbackUrlRule.trim(),e=this.formData.lnbits_callback_url_rules;t&&t.length&&!e.includes(t)&&(this.formData.lnbits_callback_url_rules=[...e,t],this.formCallbackUrlRule="")},removeCallbackUrlRule(t){const e=this.formData.lnbits_callback_url_rules;this.formData.lnbits_callback_url_rules=e.filter((e=>e!==t))},addNostrUrl(){const t=this.nostrAcceptedUrl.trim();this.removeNostrUrl(t),this.formData.nostr_absolute_request_urls.push(t),this.nostrAcceptedUrl=""},removeNostrUrl(t){this.formData.nostr_absolute_request_urls=this.formData.nostr_absolute_request_urls.filter((e=>e!==t))},async toggleServerLog(){if(this.serverlogEnabled=!this.serverlogEnabled,this.serverlogEnabled){const t="http:"!==location.protocol?"wss://":"ws://",e=await LNbits.utils.digestMessage(this.g.user.id),a=t+document.domain+":"+location.port+"/api/v1/ws/"+e;this.ws=new WebSocket(a),this.ws.addEventListener("message",(async({data:t})=>{this.logs.push(t.toString());const e=this.$refs.logScroll;if(e){const t=e.getScrollTarget(),a=0;e.setScrollPosition(t.scrollHeight,a)}}))}else this.ws.close()}}}),window.app.component("lnbits-admin-users",{props:["form-data"],template:"#lnbits-admin-users",mixins:[window.windowMixin],data:()=>({formAddUser:"",formAddAdmin:""}),methods:{addAllowedUser(){let t=this.formAddUser,e=this.formData.lnbits_allowed_users;t&&t.length&&!e.includes(t)&&(this.formData.lnbits_allowed_users=[...e,t],this.formAddUser="")},removeAllowedUser(t){let e=this.formData.lnbits_allowed_users;this.formData.lnbits_allowed_users=e.filter((e=>e!==t))},addAdminUser(){let t=this.formAddAdmin,e=this.formData.lnbits_admin_users;t&&t.length&&!e.includes(t)&&(this.formData.lnbits_admin_users=[...e,t],this.formAddAdmin="")},removeAdminUser(t){let e=this.formData.lnbits_admin_users;this.formData.lnbits_admin_users=e.filter((e=>e!==t))}}}),window.app.component("lnbits-admin-server",{props:["form-data"],template:"#lnbits-admin-server",mixins:[window.windowMixin],data:()=>({currencies:[]}),async created(){this.currencies=await LNbits.api.getCurrencies()}}),window.app.component("lnbits-admin-extensions",{props:["form-data"],template:"#lnbits-admin-extensions",mixins:[window.windowMixin],data:()=>({formAddExtensionsManifest:""}),methods:{addExtensionsManifest(){const t=this.formAddExtensionsManifest.trim(),e=this.formData.lnbits_extensions_manifests;t&&t.length&&!e.includes(t)&&(this.formData.lnbits_extensions_manifests=[...e,t],this.formAddExtensionsManifest="")},removeExtensionsManifest(t){const e=this.formData.lnbits_extensions_manifests;this.formData.lnbits_extensions_manifests=e.filter((e=>e!==t))}}}),window.app.component("lnbits-admin-notifications",{props:["form-data"],template:"#lnbits-admin-notifications",mixins:[window.windowMixin],data:()=>({nostrNotificationIdentifier:"",emailNotificationAddress:""}),methods:{sendTestEmail(){LNbits.api.request("GET","/admin/api/v1/testemail",this.g.user.wallets[0].adminkey).then((t=>{if("error"===t.data.status)throw new Error(t.data.message);this.$q.notify({message:"Test email sent!",color:"positive"})})).catch((t=>{this.$q.notify({message:t.message,color:"negative"})}))},addNostrNotificationIdentifier(){const t=this.nostrNotificationIdentifier.trim(),e=this.formData.lnbits_nostr_notifications_identifiers;t&&t.length&&!e.includes(t)&&(this.formData.lnbits_nostr_notifications_identifiers=[...e,t],this.nostrNotificationIdentifier="")},removeNostrNotificationIdentifier(t){const e=this.formData.lnbits_nostr_notifications_identifiers;this.formData.lnbits_nostr_notifications_identifiers=e.filter((e=>e!==t))},addEmailNotificationAddress(){const t=this.emailNotificationAddress.trim(),e=this.formData.lnbits_email_notifications_to_emails;t&&t.length&&!e.includes(t)&&(this.formData.lnbits_email_notifications_to_emails=[...e,t],this.emailNotificationAddress="")},removeEmailNotificationAddress(t){const e=this.formData.lnbits_email_notifications_to_emails;this.formData.lnbits_email_notifications_to_emails=e.filter((e=>e!==t))}}}),window.app.component("lnbits-admin-site-customisation",{props:["form-data"],template:"#lnbits-admin-site-customisation",mixins:[window.windowMixin],data:()=>({lnbits_theme_options:["classic","bitcoin","flamingo","cyber","freedom","mint","autumn","monochrome","salvador"],colors:["primary","secondary","accent","positive","negative","info","warning","red","yellow","orange"],reactionOptions:["none","confettiBothSides","confettiFireworks","confettiStars","confettiTop"],globalBorderOptions:["retro-border","hard-border","neon-border","no-border"]}),methods:{}}),window.app.component("lnbits-admin-library",{props:["form-data"],template:"#lnbits-admin-library",mixins:[window.windowMixin],data:()=>({library_images:[]}),async created(){await this.getUploadedImages()},methods:{onImageInput(t){const e=t.target.files[0];e&&this.uploadImage(e)},uploadImage(t){const e=new FormData;e.append("file",t),LNbits.api.request("POST","/admin/api/v1/images",this.g.user.wallets[0].adminkey,e,{headers:{"Content-Type":"multipart/form-data"}}).then((()=>{this.$q.notify({type:"positive",message:"Image uploaded!",icon:null}),this.getUploadedImages()})).catch(LNbits.utils.notifyApiError)},getUploadedImages(){LNbits.api.request("GET","/admin/api/v1/images",this.g.user.wallets[0].inkey).then((t=>{this.library_images=t.data.map((t=>({...t,url:`${window.origin}/${t.directory}/${t.filename}`})))})).catch(LNbits.utils.notifyApiError)},deleteImage(t){LNbits.utils.confirmDialog("Are you sure you want to delete this image?").onOk((()=>{LNbits.api.request("DELETE",`/admin/api/v1/images/${t}`,this.g.user.wallets[0].adminkey).then((()=>{this.$q.notify({type:"positive",message:"Image deleted!",icon:null}),this.getUploadedImages()})).catch(LNbits.utils.notifyApiError)}))}}}),window.app.component("lnbits-admin-audit",{props:["form-data"],template:"#lnbits-admin-audit",mixins:[window.windowMixin],data:()=>({formAddIncludePath:"",formAddExcludePath:"",formAddIncludeResponseCode:""}),methods:{addIncludePath(){if(""===this.formAddIncludePath)return;const t=this.formData.lnbits_audit_include_paths;t.includes(this.formAddIncludePath)||(this.formData.lnbits_audit_include_paths=[...t,this.formAddIncludePath]),this.formAddIncludePath=""},removeIncludePath(t){this.formData.lnbits_audit_include_paths=this.formData.lnbits_audit_include_paths.filter((e=>e!==t))},addExcludePath(){if(""===this.formAddExcludePath)return;const t=this.formData.lnbits_audit_exclude_paths;t.includes(this.formAddExcludePath)||(this.formData.lnbits_audit_exclude_paths=[...t,this.formAddExcludePath]),this.formAddExcludePath=""},removeExcludePath(t){this.formData.lnbits_audit_exclude_paths=this.formData.lnbits_audit_exclude_paths.filter((e=>e!==t))},addIncludeResponseCode(){if(""===this.formAddIncludeResponseCode)return;const t=this.formData.lnbits_audit_http_response_codes;t.includes(this.formAddIncludeResponseCode)||(this.formData.lnbits_audit_http_response_codes=[...t,this.formAddIncludeResponseCode]),this.formAddIncludeResponseCode=""},removeIncludeResponseCode(t){this.formData.lnbits_audit_http_response_codes=this.formData.lnbits_audit_http_response_codes.filter((e=>e!==t))}}}),window.app.component("lnbits-new-user-wallet",{props:["form-data"],template:"#lnbits-new-user-wallet",mixins:[window.windowMixin],data:()=>({newWallet:{walletType:"lightning",name:"",sharedWalletId:""}}),methods:{async submitRejectWalletInvitation(){try{const t=this.g.user.extra.wallet_invite_requests||[],e=t.find((t=>t.to_wallet_id===this.newWallet.sharedWalletId));if(!e)return void Quasar.Notify.create({message:"Cannot find invitation for the selected wallet.",type:"warning"});await LNbits.api.request("DELETE",`/api/v1/wallet/share/invite/${e.request_id}`,this.g.wallet.adminkey),Quasar.Notify.create({message:"Invitation rejected.",type:"positive"}),this.g.user.extra.wallet_invite_requests=t.filter((t=>t.request_id!==e.request_id))}catch(t){LNbits.utils.notifyApiError(t)}},async submitAddWallet(){console.log("### submitAddWallet",this.newWallet);const t=this.newWallet;if("lightning"!==t.walletType||t.name)if("lightning-shared"!==t.walletType||t.sharedWalletId)try{await LNbits.api.createWallet(this.g.user.wallets[0],t.name,t.walletType,{shared_wallet_id:t.sharedWalletId})}catch(t){console.warn(t),LNbits.utils.notifyApiError(t)}else this.$q.notify({message:"Missing a shared wallet ID",color:"warning"});else this.$q.notify({message:"Please enter a name for the wallet",color:"warning"})}}}),window.app.component("lnbits-qrcode",{mixins:[window.windowMixin],template:"#lnbits-qrcode",components:{QrcodeVue:QrcodeVue},props:{value:{type:String,required:!0},nfc:{type:Boolean,default:!1},showButtons:{type:Boolean,default:!0},href:{type:String,default:""},margin:{type:Number,default:3},maxWidth:{type:Number,default:450},logo:{type:String,default:LNBITS_QR_LOGO}},data:()=>({nfcTagWriting:!1,nfcSupported:"undefined"!=typeof NDEFReader}),methods:{clickQrCode(t){if(""===this.href)return this.copyText(this.value),t.preventDefault(),t.stopPropagation(),!1},async writeNfcTag(){try{if(!this.nfcSupported)throw{toString:function(){return"NFC not supported on this device or browser."}};const t=new NDEFReader;this.nfcTagWriting=!0,this.$q.notify({message:"Tap your NFC tag to write the LNURL-withdraw link to it."}),await t.write({records:[{recordType:"url",data:this.value,lang:"en"}]}),this.nfcTagWriting=!1,this.$q.notify({type:"positive",message:"NFC tag written successfully."})}catch(t){this.nfcTagWriting=!1,this.$q.notify({type:"negative",message:t?t.toString():"An unexpected error has occurred."})}},downloadSVG(){const t=this.$refs.qrCode.$el;if(!t)return void console.error("SVG element not found");let e=(new XMLSerializer).serializeToString(t);e.match(/^]+xmlns="http:\/\/www\.w3\.org\/2000\/svg"/)||(e=e.replace(/^({tab:"bech32",lnurl:""}),methods:{setLnurl(){if("bech32"==this.tab){const t=(new TextEncoder).encode(this.url),e=NostrTools.nip19.encodeBytes("lnurl",t);this.lnurl=`lightning:${e.toUpperCase()}`}else"lud17"==this.tab&&(this.url.startsWith("http://")?this.lnurl=this.url.replace("http://",this.prefix+"://"):this.lnurl=this.url.replace("https://",this.prefix+"://"));this.$emit("update:lnurl",this.lnurl)}},watch:{url(){this.setLnurl()},tab(){this.setLnurl()}},created(){this.setLnurl()}}),window.app.component("lnbits-extension-settings-form",{name:"lnbits-extension-settings-form",template:"#lnbits-extension-settings-form",props:["options","adminkey","endpoint"],methods:{async updateSettings(){if(!this.settings)return Quasar.Notify.create({message:"No settings to update",type:"negative"});try{const{data:t}=await LNbits.api.request("PUT",this.endpoint,this.adminkey,this.settings);this.settings=t}catch(t){LNbits.utils.notifyApiError(t)}},async getSettings(){try{const{data:t}=await LNbits.api.request("GET",this.endpoint,this.adminkey);this.settings=t}catch(t){LNbits.utils.notifyApiError(t)}},async resetSettings(){LNbits.utils.confirmDialog("Are you sure you want to reset the settings?").onOk((async()=>{try{await LNbits.api.request("DELETE",this.endpoint,this.adminkey),await this.getSettings()}catch(t){LNbits.utils.notifyApiError(t)}}))}},async created(){await this.getSettings()},data:()=>({settings:void 0})}),window.app.component("lnbits-extension-settings-btn-dialog",{template:"#lnbits-extension-settings-btn-dialog",name:"lnbits-extension-settings-btn-dialog",props:["options","adminkey","endpoint"],data:()=>({show:!1})}),window.app.component("lnbits-data-fields",{name:"lnbits-data-fields",template:"#lnbits-data-fields",props:["fields","hide-advanced"],data:()=>({fieldTypes:[{label:"Text",value:"str"},{label:"Integer",value:"int"},{label:"Float",value:"float"},{label:"Boolean",value:"bool"},{label:"Date Time",value:"datetime"},{label:"JSON",value:"json"},{label:"Wallet Select",value:"wallet"},{label:"Currency Select",value:"currency"}],fieldsTable:{columns:[{name:"name",align:"left",label:"Field Name",field:"name",sortable:!0},{name:"type",align:"left",label:"Type",field:"type",sortable:!1},{name:"label",align:"left",label:"UI Label",field:"label",sortable:!0},{name:"hint",align:"left",label:"UI Hint",field:"hint",sortable:!1},{name:"optional",align:"left",label:"Optional",field:"optional",sortable:!1}],pagination:{sortBy:"name",rowsPerPage:100,page:1,rowsNumber:100},search:null,hideEmpty:!0}}),methods:{addField:function(){this.fields.push({name:"field_name_"+(this.fields.length+1),type:"text",label:"",hint:"",optional:!0,sortable:!0,searchable:!0,editable:!0,fields:[]})},removeField:function(t){const e=this.fields.indexOf(t);e>-1&&this.fields.splice(e,1)}},async created(){this.hideAdvanced||this.fieldsTable.columns.push({name:"editable",align:"left",label:"UI Editable",field:"editable",sortable:!1},{name:"sortable",align:"left",label:"Sortable",field:"sortable",sortable:!1},{name:"searchable",align:"left",label:"Searchable",field:"searchable",sortable:!1})}}),window.app.component("payment-list",{name:"payment-list",template:"#payment-list",props:["update","lazy","wallet"],mixins:[window.windowMixin],data(){return{denomination:LNBITS_DENOMINATION,payments:[],paymentsTable:{columns:[{name:"time",align:"left",label:this.$t("memo")+"/"+this.$t("date"),field:"date",sortable:!0},{name:"amount",align:"right",label:this.$t("amount")+" ("+LNBITS_DENOMINATION+")",field:"sat",sortable:!0}],pagination:{rowsPerPage:10,page:1,sortBy:"time",descending:!0,rowsNumber:10},search:"",filter:{"status[ne]":"failed"},loading:!1},searchDate:{from:null,to:null},searchStatus:{success:!0,pending:!0,failed:!1,incoming:!0,outgoing:!0},exportTagName:"",exportPaymentTagList:[],paymentsCSV:{columns:[{name:"pending",align:"left",label:"Pending",field:"pending"},{name:"memo",align:"left",label:this.$t("memo"),field:"memo"},{name:"time",align:"left",label:this.$t("date"),field:"date",sortable:!0},{name:"amount",align:"right",label:this.$t("amount")+" ("+LNBITS_DENOMINATION+")",field:"sat",sortable:!0},{name:"fee",align:"right",label:this.$t("fee")+" (m"+LNBITS_DENOMINATION+")",field:"fee"},{name:"tag",align:"right",label:this.$t("tag"),field:"tag"},{name:"payment_hash",align:"right",label:this.$t("payment_hash"),field:"payment_hash"},{name:"payment_proof",align:"right",label:this.$t("payment_proof"),field:"payment_proof"},{name:"webhook",align:"right",label:this.$t("webhook"),field:"webhook"},{name:"fiat_currency",align:"right",label:"Fiat Currency",field:t=>t.extra.wallet_fiat_currency},{name:"fiat_amount",align:"right",label:"Fiat Amount",field:t=>t.extra.wallet_fiat_amount}],preimage:null,loading:!1},hodlInvoice:{show:!1,payment:null,preimage:null}}},computed:{currentWallet(){return this.wallet||this.g.wallet},filteredPayments(){const t=this.paymentsTable.search;return t&&""!==t?LNbits.utils.search(this.payments,t):this.payments},paymentsOmitter(){return this.$q.screen.lt.md&&this.mobileSimple?this.payments.length>0?[this.payments[0]]:[]:this.payments},pendingPaymentsExist(){return-1!==this.payments.findIndex((t=>t.pending))}},methods:{searchByDate(){"string"==typeof this.searchDate&&(this.searchDate={from:this.searchDate,to:this.searchDate}),this.searchDate.from&&(this.paymentsTable.filter["time[ge]"]=this.searchDate.from+"T00:00:00"),this.searchDate.to&&(this.paymentsTable.filter["time[le]"]=this.searchDate.to+"T23:59:59"),this.fetchPayments()},clearDateSeach(){this.searchDate={from:null,to:null},delete this.paymentsTable.filter["time[ge]"],delete this.paymentsTable.filter["time[le]"],this.fetchPayments()},fetchPayments(t){this.$emit("filter-changed",{...this.paymentsTable.filter});const e=LNbits.utils.prepareFilterQuery(this.paymentsTable,t);return LNbits.api.getPayments(this.currentWallet,e).then((t=>{this.paymentsTable.loading=!1,this.paymentsTable.pagination.rowsNumber=t.data.total,this.payments=t.data.data.map((t=>LNbits.map.payment(t)))})).catch((t=>{this.paymentsTable.loading=!1,g.user.admin?this.fetchPaymentsAsAdmin(this.currentWallet.id,e):LNbits.utils.notifyApiError(t)}))},fetchPaymentsAsAdmin(t,e){return e=(e||"")+"&wallet_id="+t,LNbits.api.request("GET","/api/v1/payments/all/paginated?"+e).then((t=>{this.paymentsTable.loading=!1,this.paymentsTable.pagination.rowsNumber=t.data.total,this.payments=t.data.data.map((t=>LNbits.map.payment(t)))})).catch((t=>{this.paymentsTable.loading=!1,LNbits.utils.notifyApiError(t)}))},checkPayment(t){LNbits.api.getPayment(this.g.wallet,t).then((t=>{this.update=!this.update,"success"==t.data.status&&Quasar.Notify.create({type:"positive",message:this.$t("payment_successful")}),"pending"==t.data.status&&Quasar.Notify.create({type:"info",message:this.$t("payment_pending")})})).catch(LNbits.utils.notifyApiError)},showHoldInvoiceDialog(t){this.hodlInvoice.show=!0,this.hodlInvoice.preimage="",this.hodlInvoice.payment=t},cancelHoldInvoice(t){LNbits.api.cancelInvoice(this.g.wallet,t).then((()=>{this.update=!this.update,Quasar.Notify.create({type:"positive",message:this.$t("invoice_cancelled")})})).catch(LNbits.utils.notifyApiError)},settleHoldInvoice(t){LNbits.api.settleInvoice(this.g.wallet,t).then((()=>{this.update=!this.update,Quasar.Notify.create({type:"positive",message:this.$t("invoice_settled")})})).catch(LNbits.utils.notifyApiError)},paymentTableRowKey:t=>t.payment_hash+t.amount,exportCSV(t=!1){const e=this.paymentsTable.pagination,a={sortby:e.sortBy??"time",direction:e.descending?"desc":"asc"},s=new URLSearchParams(a);LNbits.api.getPayments(this.g.wallet,s).then((e=>{let a=e.data.data.map(LNbits.map.payment),s=this.paymentsCSV.columns;if(t){this.exportPaymentTagList.length&&(a=a.filter((t=>this.exportPaymentTagList.includes(t.tag))));const t=Object.keys(a.reduce(((t,e)=>({...t,...e.details})),{})).map((t=>({name:t,align:"right",label:t.charAt(0).toUpperCase()+t.slice(1).replace(/([A-Z])/g," $1"),field:e=>e.details[t],format:t=>"object"==typeof t?JSON.stringify(t):t})));s=this.paymentsCSV.columns.concat(t)}LNbits.utils.exportCSV(s,a,this.g.wallet.name+"-payments")}))},addFilterTag(){if(!this.exportTagName)return;const t=this.exportTagName.trim();this.exportPaymentTagList=this.exportPaymentTagList.filter((e=>e!==t)),this.exportPaymentTagList.push(t),this.exportTagName=""},removeExportTag(t){this.exportPaymentTagList=this.exportPaymentTagList.filter((e=>e!==t))},formatCurrency(t,e){try{return LNbits.utils.formatCurrency(t,e)}catch(e){return console.error(e),`${t} ???`}},handleFilterChanged(){const{success:t,pending:e,failed:a,incoming:s,outgoing:i}=this.searchStatus;delete this.paymentsTable.filter["status[ne]"],delete this.paymentsTable.filter["status[eq]"],t&&e&&a||(t&&e?this.paymentsTable.filter["status[ne]"]="failed":t&&a?this.paymentsTable.filter["status[ne]"]="pending":a&&e?this.paymentsTable.filter["status[ne]"]="success":t?this.paymentsTable.filter["status[eq]"]="success":e?this.paymentsTable.filter["status[eq]"]="pending":a&&(this.paymentsTable.filter["status[eq]"]="failed")),delete this.paymentsTable.filter["amount[ge]"],delete this.paymentsTable.filter["amount[le]"],s&&i||(s?this.paymentsTable.filter["amount[ge]"]=0:i&&(this.paymentsTable.filter["amount[le]"]=0))}},watch:{"paymentsTable.search":{handler(){const t={};this.paymentsTable.search&&(t.search=this.paymentsTable.search),this.fetchPayments()}},lazy(t){!0===t&&this.fetchPayments()},update(){this.fetchPayments()},"g.updatePayments"(){this.fetchPayments()},"g.wallet":{handler(t){this.fetchPayments()},deep:!0}},created(){void 0===this.lazy&&this.fetchPayments()}}),window.app.component(QrcodeVue),window.app.component("lnbits-extension-rating",{template:"#lnbits-extension-rating",name:"lnbits-extension-rating",props:["rating"]}),window.app.component("lnbits-fsat",{template:"{{ fsat }}",props:{amount:{type:Number,default:0}},computed:{fsat(){return LNbits.utils.formatSat(this.amount)}}}),window.app.component("lnbits-wallet-list",{mixins:[window.windowMixin],template:"#lnbits-wallet-list",props:["balance"],data:()=>({activeWallet:null,balance:0,walletName:"",LNBITS_DENOMINATION:LNBITS_DENOMINATION}),methods:{createWallet(){this.$emit("wallet-action",{action:"create-wallet"})}},created(){document.addEventListener("updateWalletBalance",this.updateWalletBalance)}}),window.app.component("lnbits-extension-list",{mixins:[window.windowMixin],template:"#lnbits-extension-list",data:()=>({extensions:[],searchTerm:""}),watch:{"g.user.extensions":{handler(t){this.loadExtensions()},deep:!0}},computed:{userExtensions(){return this.updateUserExtensions(this.searchTerm)}},methods:{async loadExtensions(){try{const{data:t}=await LNbits.api.request("GET","/api/v1/extension");this.extensions=t.map((t=>LNbits.map.extension(t))).sort(((t,e)=>t.name.localeCompare(e.name)))}catch(t){LNbits.utils.notifyApiError(t)}},updateUserExtensions(t){const e=window.location.pathname,a=this.g.user.extensions;return this.extensions.filter((t=>a.includes(t.code))).filter((e=>!t||`${e.code} ${e.name} ${e.short_description} ${e.url}`.toLocaleLowerCase().includes(t.toLocaleLowerCase()))).map((t=>(t.isActive=e.startsWith(t.url),t)))}},async created(){await this.loadExtensions()}}),window.app.component("lnbits-manage",{mixins:[window.windowMixin],template:"#lnbits-manage",props:["showAdmin","showNode","showExtensions","showUsers","showAudit"],methods:{isActive:t=>window.location.pathname===t},data:()=>({extensions:[]})}),window.app.component("lnbits-payment-details",{mixins:[window.windowMixin],template:"#lnbits-payment-details",props:["payment"],mixins:[window.windowMixin],data:()=>({LNBITS_DENOMINATION:LNBITS_DENOMINATION}),computed:{hasPreimage(){return this.payment.preimage&&"0000000000000000000000000000000000000000000000000000000000000000"!==this.payment.preimage},hasExpiry(){return!!this.payment.expiry},hasSuccessAction(){return this.hasPreimage&&this.payment.extra&&this.payment.extra.success_action},webhookStatusColor(){return this.payment.webhook_status>=300||this.payment.webhook_status<0?"red-10":this.payment.webhook_status?"green-10":"cyan-7"},webhookStatusText(){return this.payment.webhook_status?this.payment.webhook_status:"not sent yet"},hasTag(){return this.payment.extra&&!!this.payment.extra.tag},extras(){if(!this.payment.extra)return[];let t=_.omit(this.payment.extra,["tag","success_action"]);return Object.keys(t).map((e=>({key:e,value:t[e]})))}}}),window.app.component("lnbits-lnurlpay-success-action",{mixins:[window.windowMixin],template:"#lnbits-lnurlpay-success-action",props:["payment","success_action"],data(){return{decryptedValue:this.success_action.ciphertext}},mounted(){if("aes"!==this.success_action.tag)return null;decryptLnurlPayAES(this.success_action,this.payment.preimage).then((t=>{this.decryptedValue=t}))}}),window.app.component("lnbits-notifications-btn",{template:"#lnbits-notifications-btn",mixins:[window.windowMixin],props:["pubkey"],data:()=>({isSupported:!1,isSubscribed:!1,isPermissionGranted:!1,isPermissionDenied:!1}),methods:{urlB64ToUint8Array(t){const e=(t+"=".repeat((4-t.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/"),a=atob(e),s=new Uint8Array(a.length);for(let t=0;te!==t)),this.$q.localStorage.set("lnbits.webpush.subscribedUsers",JSON.stringify(e))},isUserSubscribed(t){return(JSON.parse(this.$q.localStorage.getItem("lnbits.webpush.subscribedUsers"))||[]).includes(t)},subscribe(){this.isSupported&&!this.isPermissionDenied&&(Notification.requestPermission().then((t=>{this.isPermissionGranted="granted"===t,this.isPermissionDenied="denied"===t})).catch(console.log),navigator.serviceWorker.ready.then((t=>{navigator.serviceWorker.getRegistration().then((t=>{t.pushManager.getSubscription().then((e=>{if(null===e||!this.isUserSubscribed(this.g.user.id)){const e={applicationServerKey:this.urlB64ToUint8Array(this.pubkey),userVisibleOnly:!0};t.pushManager.subscribe(e).then((t=>{LNbits.api.request("POST","/api/v1/webpush",null,{subscription:JSON.stringify(t)}).then((t=>{this.saveUserSubscribed(t.data.user),this.isSubscribed=!0})).catch(LNbits.utils.notifyApiError)}))}})).catch(console.log)}))})))},unsubscribe(){navigator.serviceWorker.ready.then((t=>{t.pushManager.getSubscription().then((t=>{t&&LNbits.api.request("DELETE","/api/v1/webpush?endpoint="+btoa(t.endpoint),null).then((()=>{this.removeUserSubscribed(this.g.user.id),this.isSubscribed=!1})).catch(LNbits.utils.notifyApiError)}))})).catch(console.log)},checkSupported(){let t="https:"===window.location.protocol,e="serviceWorker"in navigator,a="Notification"in window,s="PushManager"in window;return this.isSupported=t&&e&&a&&s,this.isSupported||console.log("Notifications disabled because requirements are not met:",{HTTPS:t,"Service Worker API":e,"Notification API":a,"Push API":s}),this.isSupported},async updateSubscriptionStatus(){await navigator.serviceWorker.ready.then((t=>{t.pushManager.getSubscription().then((t=>{this.isSubscribed=!!t&&this.isUserSubscribed(this.g.user.id)}))})).catch(console.log)}},created(){this.isPermissionDenied="denied"===Notification.permission,this.checkSupported()&&this.updateSubscriptionStatus()}}),window.app.component("lnbits-dynamic-fields",{template:"#lnbits-dynamic-fields",mixins:[window.windowMixin],props:["options","modelValue"],data:()=>({formData:null,rules:[t=>!!t||"Field is required"]}),methods:{applyRules(t){return t?this.rules:[]},buildData(t,e={}){return t.reduce(((t,a)=>(a.options?.length?t[a.name]=this.buildData(a.options,e[a.name]):t[a.name]=e[a.name]??a.default,t)),{})},handleValueChanged(){this.$emit("update:model-value",this.formData)}},created(){this.formData=this.buildData(this.options,this.modelValue)}}),window.app.component("lnbits-dynamic-chips",{template:"#lnbits-dynamic-chips",mixins:[window.windowMixin],props:["modelValue"],data:()=>({chip:"",chips:[]}),methods:{addChip(){this.chip&&(this.chips.push(this.chip),this.chip="",this.$emit("update:model-value",this.chips.join(",")))},removeChip(t){this.chips.splice(t,1),this.$emit("update:model-value",this.chips.join(","))}},created(){"string"==typeof this.modelValue?this.chips=this.modelValue.split(","):this.chips=[...this.modelValue]}}),window.app.component("lnbits-update-balance",{template:"#lnbits-update-balance",mixins:[window.windowMixin],props:["wallet_id","small_btn"],computed:{denomination:()=>LNBITS_DENOMINATION,admin:()=>user.super_user},data:()=>({credit:0}),methods:{updateBalance(t){LNbits.api.updateBalance(t.value,this.wallet_id).then((e=>{if(!0!==e.data.success)throw new Error(e.data);credit=parseInt(t.value),Quasar.Notify.create({type:"positive",message:this.$t("credit_ok",{amount:credit}),icon:null}),this.credit=0,t.value=0,t.set()})).catch(LNbits.utils.notifyApiError)}}}),window.app.component("user-id-only",{template:"#user-id-only",mixins:[window.windowMixin],props:{allowed_new_users:Boolean,authAction:String,authMethod:String,usr:String,wallet:String},data(){return{user:this.usr,walletName:this.wallet}},methods:{showLogin(t){this.$emit("show-login",t)},showRegister(t){this.$emit("show-register",t)},loginUsr(){this.$emit("update:usr",this.user),this.$emit("login-usr")},createWallet(){this.$emit("update:wallet",this.walletName),this.$emit("create-wallet")}},computed:{showInstantLogin(){return"username-password"!==this.authMethod||"register"!==this.authAction}},created(){}}),window.app.component("username-password",{template:"#username-password",mixins:[window.windowMixin],props:{allowed_new_users:Boolean,authMethods:Array,authAction:String,username:String,password_1:String,password_2:String,resetKey:String},data(){return{oauth:["nostr-auth-nip98","google-auth","github-auth","keycloak-auth"],username:this.userName,password:this.password_1,passwordRepeat:this.password_2,reset_key:this.resetKey,keycloakOrg:LNBITS_AUTH_KEYCLOAK_ORG||"Keycloak",keycloakIcon:LNBITS_AUTH_KEYCLOAK_ICON}},methods:{login(){this.$emit("update:userName",this.username),this.$emit("update:password_1",this.password),this.$emit("login")},register(){this.$emit("update:userName",this.username),this.$emit("update:password_1",this.password),this.$emit("update:password_2",this.passwordRepeat),this.$emit("register")},reset(){this.$emit("update:resetKey",this.reset_key),this.$emit("update:password_1",this.password),this.$emit("update:password_2",this.passwordRepeat),this.$emit("reset")},validateUsername:t=>new RegExp("^(?=[a-zA-Z0-9._]{2,20}$)(?!.*[_.]{2})[^_.].*[^_.]$").test(t),async signInWithNostr(){try{const t=await this.createNostrToken();if(!t)return;resp=await LNbits.api.loginByProvider("nostr",{Authorization:t},{}),window.location.href="/wallet"}catch(t){console.warn(t);const e=t?.response?.data?.detail||`${t}`;Quasar.Notify.create({type:"negative",message:"Failed to sign in with Nostr.",caption:e})}},async createNostrToken(){try{if(!window.nostr?.signEvent)return void Quasar.Notify.create({type:"negative",message:"No Nostr signing app detected.",caption:'Is "window.nostr" present?'});const t=`${window.location}nostr`,e="POST",a=await NostrTools.nip98.getToken(t,e,(t=>async function(t){try{const{data:e}=await LNbits.api.getServerHealth();return t.created_at=e.server_time,await window.nostr.signEvent(t)}catch(t){console.error(t),Quasar.Notify.create({type:"negative",message:"Failed to sign nostr event.",caption:`${t}`})}}(t)),!0);if(!await NostrTools.nip98.validateToken(a,t,e))throw new Error("Invalid signed token!");return a}catch(t){console.warn(t),Quasar.Notify.create({type:"negative",message:"Failed create Nostr event.",caption:`${t}`})}}},computed:{showOauth(){return this.oauth.some((t=>this.authMethods.includes(t)))}},created(){}}),window.app.component("separator-text",{template:"#separator-text",props:{text:String,uppercase:{type:Boolean,default:!1},color:{type:String,default:"grey"}}}),window.app.component("lnbits-node-ranks",{props:["ranks"],data:()=>({stats:[{label:"Capacity",key:"capacity"},{label:"Channels",key:"channelcount"},{label:"Age",key:"age"},{label:"Growth",key:"growth"},{label:"Availability",key:"availability"}]}),template:"\n \n
\n
1ml Node Rank
\n
\n
\n
{{ stat.label }}
\n
\n {{ (ranks && ranks[stat.key]) ?? '-' }}\n
\n
\n
\n
\n
\n "}),window.app.component("lnbits-channel-stats",{props:["stats"],data:()=>({states:[{label:"Active",value:"active",color:"green"},{label:"Pending",value:"pending",color:"orange"},{label:"Inactive",value:"inactive",color:"grey"},{label:"Closed",value:"closed",color:"red"}]}),template:"\n \n
\n
Channels
\n
\n
\n
\n {{ state.label }}\n
\n
\n {{ (stats?.counts && stats.counts[state.value]) ?? \"-\" }}\n
\n
\n
\n
\n
\n "}),window.app.component("lnbits-stat",{props:["title","amount","msat","btc"],computed:{value(){return this.amount??(this.btc?LNbits.utils.formatSat(this.btc):LNbits.utils.formatMsat(this.msat))}},template:"\n \n \n
\n {{ title }}\n
\n
\n {{ value }}\n sats\n BTC\n
\n
\n
\n "}),window.app.component("lnbits-node-qrcode",{props:["info"],mixins:[window.windowMixin],template:'\n \n \n
\n
\n \n
\n No addresses available\n
\n
\n
\n
\n \n Public Key Click to copy \n \n \n
\n '}),window.app.component("lnbits-channel-balance",{props:["balance","color"],methods:{formatMsat:t=>LNbits.utils.formatMsat(t)},template:'\n
\n
\n \n Local: {{ formatMsat(balance.local_msat) }}\n sats\n \n \n Remote: {{ formatMsat(balance.remote_msat) }}\n sats\n \n
\n\n \n
\n \n {{ balance.alias }}\n \n
\n \n
\n '}),window.app.component("lnbits-date",{props:["ts"],computed:{date(){return LNbits.utils.formatDate(this.ts)},dateFrom(){return moment.utc(this.date).local().fromNow()}},template:"\n
\n {{ this.date }}\n {{ this.dateFrom }}\n
\n "}),window.app.component("lnbits-node-info",{props:["info"],data:()=>({showDialog:!1}),mixins:[window.windowMixin],methods:{shortenNodeId:t=>t?t.substring(0,5)+"..."+t.substring(t.length-5):"..."},template:"\n
\n
{{ this.info.alias }}
\n
\n
{{ this.info.backend_name }}
\n \n #{{ this.info.color }}\n \n
{{ shortenNodeId(this.info.id) }}
\n \n \n
\n \n \n \n
\n "}),window.app.component("lnbits-stat",{props:["title","amount","msat","btc"],computed:{value(){return this.amount??(this.btc?LNbits.utils.formatSat(this.btc):LNbits.utils.formatMsat(this.msat))}},template:"\n \n \n
\n {{ title }}\n
\n
\n {{ value }}\n sats\n BTC\n
\n
\n
\n "});const DynamicComponent={props:{fetchUrl:{type:String,required:!0},scripts:{type:Array,default:()=>[]}},data:()=>({keys:[]}),async mounted(){await this.loadDynamicContent()},methods:{loadScript:async t=>new Promise(((e,a)=>{const s=document.querySelector(`script[src="${t}"]`);s&&s.remove();const i=document.createElement("script");i.src=t,i.async=!0,i.onload=e,i.onerror=()=>a(new Error(`Failed to load script: ${t}`)),document.head.appendChild(i)})),async loadDynamicContent(){this.$q.loading.show();try{const t=this.fetchUrl.split("#")[0],e=await fetch(t,{credentials:"include",headers:{Accept:"text/html","X-Requested-With":"XMLHttpRequest"}}),a=await e.text(),s=new DOMParser,i=s.parseFromString(a,"text/html").querySelector("#window-vars-script");i&&new Function(i.innerHTML)(),await this.loadScript("/static/js/base.js");for(const t of this.scripts)await this.loadScript(t);const n=this.$router.currentRoute.value.meta.previousRouteName;n&&window.app._context.components[n]&&delete window.app._context.components[n];const l=`${this.$route.name}PageLogic`,o=window[l];if(!o)throw new Error(`Component logic '${l}' not found. Ensure it is defined in the script.`);o.mixins=o.mixins||[],window.windowMixin&&o.mixins.push(window.windowMixin),window.app.component(this.$route.name,{...o,template:a}),delete window[l],this.$forceUpdate()}catch(t){console.error("Error loading dynamic content:",t)}finally{this.$q.loading.hide()}}},watch:{$route(t,e){routes.map((t=>t.name)).includes(t.name)?(this.$router.currentRoute.value.meta.previousRouteName=e.name,this.loadDynamicContent()):console.log(`Route '${t.name}' is not valid. Leave this one to Fastapi.`)}},template:'\n \n '},routes=[{path:"/wallet",name:"Wallet",component:DynamicComponent,props:t=>{let e="/wallet";if(Object.keys(t.query).length>0){e+="?";for(const[a,s]of Object.entries(t.query))e+=`${a}=${s}&`;e=e.slice(0,-1)}return{fetchUrl:e,scripts:["/static/js/wallet.js"]}}},{path:"/extensions",name:"Extensions",component:DynamicComponent,props:{fetchUrl:"/extensions",scripts:["/static/js/extensions.js"]}},{path:"/extensions/builder",name:"ExtensionsBuilder",component:DynamicComponent,props:{fetchUrl:"/extensions/builder",scripts:["/static/js/extensions_builder.js"]}},{path:"/node",name:"Node",component:PageNode},{path:"/node/public",name:"NodePublic",component:PageNodePublic},{path:"/payments",name:"Payments",component:PagePayments},{path:"/audit",name:"Audit",component:PageAudit},{path:"/wallets",name:"Wallets",component:PageWallets},{path:"/users",name:"Users",component:PageUsers},{path:"/admin",name:"Admin",component:PageAdmin},{path:"/account",name:"Account",component:PageAccount}];window.router=VueRouter.createRouter({history:VueRouter.createWebHistory(),routes:routes}),window.app.mixin({computed:{isVueRoute(){const t=window.location.pathname,e=window.router.resolve(t);return e?.matched?.length>0}}}),window.app.use(VueQrcodeReader),window.app.use(Quasar,{config:{loading:{spinner:Quasar.QSpinnerBars}}}),window.app.use(window.i18n),window.app.provide("g",g),window.app.use(window.router),window.app.component("DynamicComponent",DynamicComponent),window.app.mount("#vue"); +window.PageExtensionBuilder={template:"#page-extension-builder",mixins:[windowMixin],data:()=>({step:1,previewStepNames:{2:"settings",3:"owner_data",4:"client_data",5:"public_page"},extensionDataCleanString:"",extensionData:{id:"",name:"",stub_version:"",short_description:"",description:"",public_page:{has_public_page:!0,owner_data_fields:{name:"",description:""},client_data_fields:{public_inputs:[]},action_fields:{generate_action:!0,generate_payment_logic:!1,wallet_id:"",currency:"",amount:"",paid_flag:""}},preview_action:{is_preview_mode:!1,is_settings_preview:!1,is_owner_data_preview:!1,is_client_data_preview:!1,is_public_page_preview:!1},settings_data:{name:"Settings",enabled:!0,type:"user",fields:[]},owner_data:{name:"OwnerData",fields:[]},client_data:{enabled:!0,name:"ClientData",fields:[]}},sampleField:{name:"name",type:"str",label:"Name",hint:"",optional:!0,editable:!0,searchable:!0,sortable:!0},settingsTypes:[{label:"User Settings",value:"user"},{label:"Admin Settings",value:"admin"}],amountSource:[{label:"Client Data",value:"client_data"},{label:"Owner Data",value:"owner_data"}],extensionStubVersions:[]}),watch:{"extensionData.public_page.action_fields.amount_source":function(t,e){e&&t!==e&&(this.extensionData.public_page.action_fields.amount="")}},computed:{paymentActionAmountFields(){const t=this.extensionData.public_page.action_fields.amount_source;return t?"owner_data"===t?[""].concat(this.extensionData.owner_data.fields.filter((t=>"int"===t.type||"float"===t.type)).map((t=>t.name))):"client_data"===t?[""].concat(this.extensionData.client_data.fields.filter((t=>"int"===t.type||"float"===t.type)).map((t=>t.name))):void 0:[""]}},methods:{saveState(){this.$q.localStorage.set("lnbits.extension.builder.data",JSON.stringify(this.extensionData)),this.$q.localStorage.set("lnbits.extension.builder.step",this.step)},nextStep(){this.saveState(),this.$refs.stepper.next(),this.refreshPreview()},previousStep(){this.saveState(),this.$refs.stepper.previous(),this.refreshPreview()},onStepChange(){this.saveState(),this.refreshPreview()},clearAllData(){LNbits.utils.confirmDialog("Are you sure you want to clear all data? This action cannot be undone.").onOk((()=>{this.extensionData=JSON.parse(this.extensionDataCleanString),this.$q.localStorage.remove("lnbits.extension.builder.data"),this.$refs.stepper.set(1)}))},exportJsonData(){!0!==Quasar.exportFile(`${this.extensionData.id||"data-export"}.json`,JSON.stringify(this.extensionData,null,2),"text/json")?Quasar.Notify.create({message:"Browser denied file download...",color:"negative",icon:null}):Quasar.Notify.create({message:"File downloaded!",color:"positive",icon:"file_download"})},onJsonDataInput(t){const e=t.target.files[0],a=new FileReader;a.onload=t=>{this.extensionData={...this.extensionData,...JSON.parse(t.target.result)},this.$refs.extensionDataInput.value=null,Quasar.Notify.create({message:"File loaded!",color:"positive",icon:"file_upload"})},a.readAsText(e)},async buildExtension(){try{const t={responseType:"blob"},e=await LNbits.api.request("POST","/api/v1/extension/builder/zip",null,this.extensionData,t),a=window.URL.createObjectURL(new Blob([e.data])),s=document.createElement("a");s.href=a,s.download=`${this.extensionData.id||"lnbits-extension"}.zip`,document.body.appendChild(s),s.click(),s.remove(),window.URL.revokeObjectURL(a)}catch(t){LNbits.utils.notifyApiError(t)}},async buildExtensionAndDeploy(){try{const{data:t}=await LNbits.api.request("POST","/api/v1/extension/builder/deploy",null,this.extensionData);Quasar.Notify.create({message:t.message||"Extension deployed!",color:"positive"})}catch(t){LNbits.utils.notifyApiError(t)}},async cleanCacheData(){LNbits.utils.confirmDialog("Are you sure you want to clean the cache data? This action cannot be undone.","Clean Cache Data").onOk((async()=>{try{const{data:t}=await LNbits.api.request("DELETE","/api/v1/extension/builder",null,{});Quasar.Notify.create({message:t.message||"Cache data cleaned!",color:"positive"})}catch(t){LNbits.utils.notifyApiError(t)}}))},async previewExtension(t){this.saveState();try{await LNbits.api.request("POST","/api/v1/extension/builder/preview",null,{...this.extensionData,preview_action:{is_preview_mode:!!t,is_settings_preview:"settings"===t,is_owner_data_preview:"owner_data"===t,is_client_data_preview:"client_data"===t,is_public_page_preview:"public_page"===t}}),this.refreshIframe(t)}catch(t){LNbits.utils.notifyApiError(t)}},async refreshPreview(){setTimeout((()=>{const t=this.previewStepNames[`${this.step}`]||"";t&&this.previewExtension(t)}),100)},async getStubExtensionReleases(){try{const t="extension_builder_stub",{data:e}=await LNbits.api.request("GET",`/api/v1/extension/${t}/releases`);this.extensionStubVersions=e.sort(((t,e)=>t.version{const t=e.contentDocument||e.contentWindow.document;t.body.style.transform="scale(0.8)",t.body.style.transformOrigin="center top"},e.src=`/extensions/builder/preview/${this.extensionData.id}?page_name=${t}`):console.warn("Extension Builder Preview iframe not loaded yet.")},initBasicData(){this.extensionData.owner_data.fields=[JSON.parse(JSON.stringify(this.sampleField))],this.extensionData.client_data.fields=[JSON.parse(JSON.stringify(this.sampleField))],this.extensionData.settings_data.fields=[JSON.parse(JSON.stringify(this.sampleField))],this.extensionDataCleanString=JSON.stringify(this.extensionData)}},created(){this.initBasicData();const t=this.$q.localStorage.getItem("lnbits.extension.builder.data");t&&(this.extensionData={...this.extensionData,...JSON.parse(t)});const e=+this.$q.localStorage.getItem("lnbits.extension.builder.step");e&&(this.step=e),this.g.user.admin&&this.getStubExtensionReleases(),setTimeout((()=>{this.refreshIframe()}),1e3)}},window.PagePayments={template:"#page-payments",mixins:[window.windowMixin],data:()=>({payments:[],dailyChartData:[],searchDate:{from:null,to:null},searchData:{wallet_id:null,payment_hash:null,memo:null,internal_memo:null},statusFilters:{success:!0,pending:!0,failed:!0,incoming:!0,outgoing:!0},chartData:{showPaymentStatus:!0,showPaymentTags:!0,showBalance:!0,showWalletsSize:!1,showBalanceInOut:!1,showPaymentCountInOut:!1},searchOptions:{status:[]},paymentsTable:{columns:[{name:"status",align:"left",label:"Status",field:"status",sortable:!1},{name:"created_at",align:"left",label:"Created At",field:"created_at",sortable:!0},{name:"amount",align:"right",label:"Amount",field:"amount",sortable:!0},{name:"amountFiat",align:"right",label:"Fiat",field:"amountFiat",sortable:!1},{name:"fee_sats",align:"left",label:"Fee",field:"fee_sats",sortable:!0},{name:"tag",align:"left",label:"Tag",field:"tag",sortable:!1},{name:"memo",align:"left",label:"Memo",field:"memo",sortable:!1,max_length:20},{name:"internal_memo",align:"left",label:"Internal Memo",field:"internal_memo",sortable:!1,max_length:20},{name:"wallet_id",align:"left",label:"Wallet (ID)",field:"wallet_id",sortable:!1},{name:"payment_hash",align:"left",label:"Payment Hash",field:"payment_hash",sortable:!1}],pagination:{sortBy:"created_at",rowsPerPage:25,page:1,descending:!0,rowsNumber:10},search:null,hideEmpty:!0,loading:!1},chartsReady:!1,showDetails:!1,paymentDetails:null,lnbitsBalance:0}),async mounted(){this.chartsReady=!0,await this.$nextTick(),this.initCharts(),await this.fetchPayments()},computed:{},methods:{async fetchPayments(t){const e=Object.entries(this.searchData).reduce(((t,[e,a])=>a?(t[e]=a,t):t),{});delete e["time[ge]"],delete e["time[le]"],this.searchDate.from&&(e["time[ge]"]=this.searchDate.from+"T00:00:00"),this.searchDate.to&&(e["time[le]"]=this.searchDate.to+"T23:59:59"),this.paymentsTable.filter=e;try{const e=LNbits.utils.prepareFilterQuery(this.paymentsTable,t),{data:a}=await LNbits.api.request("GET",`/api/v1/payments/all/paginated?${e}`);this.paymentsTable.pagination.rowsNumber=a.total,this.payments=a.data.map((t=>(t.extra&&t.extra.tag&&(t.tag=t.extra.tag),t.timeFrom=moment.utc(t.created_at).local().fromNow(),t.outgoing=t.amount<0,t.amount=new Intl.NumberFormat(window.LOCALE).format(t.amount/1e3)+" sats",t.extra?.wallet_fiat_amount&&(t.amountFiat=this.formatCurrency(t.extra.wallet_fiat_amount,t.extra.wallet_fiat_currency)),t.extra?.internal_memo&&(t.internal_memo=t.extra.internal_memo),t.fee_sats=new Intl.NumberFormat(window.LOCALE).format(t.fee/1e3)+" sats",t)))}catch(t){console.error(t),LNbits.utils.notifyApiError(t)}finally{this.updateCharts(t)}},async searchPaymentsBy(t,e){t&&(this.searchData[t]=e),await this.fetchPayments()},clearDateSeach(){this.searchDate={from:null,to:null},delete this.paymentsTable.filter["time[ge]"],delete this.paymentsTable.filter["time[le]"],this.fetchPayments()},searchByDate(){"string"==typeof this.searchDate&&(this.searchDate={from:this.searchDate,to:this.searchDate}),this.searchDate.from&&(this.paymentsTable.filter["time[ge]"]=this.searchDate.from+"T00:00:00"),this.searchDate.to&&(this.paymentsTable.filter["time[le]"]=this.searchDate.to+"T23:59:59"),this.fetchPayments()},handleFilterChanged(){const{success:t,pending:e,failed:a,incoming:s,outgoing:i}=this.statusFilters;delete this.searchData["status[ne]"],delete this.searchData["status[eq]"],t&&e&&a||(t&&e?this.searchData["status[ne]"]="failed":t&&a?this.searchData["status[ne]"]="pending":a&&e?this.searchData["status[ne]"]="success":t?this.searchData["status[eq]"]="success":e?this.searchData["status[eq]"]="pending":a&&(this.searchData["status[eq]"]="failed")),delete this.searchData["amount[ge]"],delete this.searchData["amount[le]"],s&&i||(s?this.searchData["amount[ge]"]="0":i&&(this.searchData["amount[le]"]="0")),this.fetchPayments()},showDetailsToggle(t){return this.paymentDetails=t,this.showDetails=!this.showDetails},formatDate:t=>LNbits.utils.formatDateString(t),formatCurrency(t,e){try{return LNbits.utils.formatCurrency(t,e)}catch(e){return console.error(e),`${t} ???`}},shortify:(t,e=10)=>(valueLength=(t||"").length,valueLength<=e?t:`${t.substring(0,5)}...${t.substring(valueLength-5,valueLength)}`),async updateCharts(t){let e=LNbits.utils.prepareFilterQuery(this.paymentsTable,t);try{const{data:t}=await LNbits.api.request("GET",`/api/v1/payments/stats/count?${e}&count_by=status`);t.sort(((t,e)=>t.field-e.field)).reverse(),this.searchOptions.status=t.map((t=>t.field)),this.paymentsStatusChart.data.datasets[0].data=t.map((t=>t.total)),this.paymentsStatusChart.data.labels=[...this.searchOptions.status],this.paymentsStatusChart.update()}catch(t){console.warn(t),LNbits.utils.notifyApiError(t)}try{const{data:t}=await LNbits.api.request("GET",`/api/v1/payments/stats/wallets?${e}`),a=t.map((t=>t.balance/t.payments_count)),s=Math.min(...a),i=Math.max(...a),n=t=>Math.floor(3+22*(t-s)/(i-s)),o=this.randomColors(20),l=t.map(((t,e)=>({data:[{x:t.payments_count,y:t.balance,r:n(Math.max(t.balance/t.payments_count,5))}],label:t.wallet_name,wallet_id:t.wallet_id,backgroundColor:o[e%100],hoverOffset:4})));this.paymentsWalletsChart.data.datasets=l,this.paymentsWalletsChart.update()}catch(t){console.warn(t),LNbits.utils.notifyApiError(t)}try{const{data:t}=await LNbits.api.request("GET",`/api/v1/payments/stats/count?${e}&count_by=tag`);this.searchOptions.tag=t.map((t=>t.field)),this.searchOptions.status.sort(),this.paymentsTagsChart.data.datasets[0].data=t.map((t=>t.total)),this.paymentsTagsChart.data.labels=t.map((t=>t.field||"core")),this.paymentsTagsChart.update()}catch(t){console.warn(t),LNbits.utils.notifyApiError(t)}try{const e=Object.entries(this.searchData).reduce(((t,[e,a])=>a?(t[e]=a,t):t),{}),a={...this.paymentsTable,filter:e},s=LNbits.utils.prepareFilterQuery(a,t);let{data:i}=await LNbits.api.request("GET",`/api/v1/payments/stats/daily?${s}`);const n=this.searchDate.from+"T00:00:00",o=this.searchDate.to+"T23:59:59";this.lnbitsBalance=i.length?i[i.length-1].balance:0,i=i.filter((t=>this.searchDate.from&&this.searchDate.to?t.date>=n&&t.date<=o:this.searchDate.from?t.date>=n:!this.searchDate.to||t.date<=o)),this.paymentsDailyChart.data.datasets=[{label:"Balance",data:i.map((t=>t.balance)),pointStyle:!1,borderWidth:2,tension:.7,fill:1},{label:"Fees",data:i.map((t=>t.fee)),pointStyle:!1,borderWidth:1,tension:.4,fill:1}],this.paymentsDailyChart.data.labels=i.map((t=>t.date.substring(0,10))),this.paymentsDailyChart.update(),this.paymentsBalanceInOutChart.data.datasets=[{label:"Incoming Payments Balance",data:i.map((t=>t.balance_in))},{label:"Outgoing Payments Balance",data:i.map((t=>t.balance_out))}],this.paymentsBalanceInOutChart.data.labels=i.map((t=>t.date.substring(0,10))),this.paymentsBalanceInOutChart.update(),this.paymentsCountInOutChart.data.datasets=[{label:"Incoming Payments Count",data:i.map((t=>t.count_in))},{label:"Outgoing Payments Count",data:i.map((t=>-t.count_out))}],this.paymentsCountInOutChart.data.labels=i.map((t=>t.date.substring(0,10))),this.paymentsCountInOutChart.update()}catch(t){console.warn(t),LNbits.utils.notifyApiError(t)}},async initCharts(){const t=this.$q.localStorage.getItem("lnbits.payments.chartData")||{};this.chartData={...this.chartData,...t},this.chartsReady?(this.paymentsStatusChart=new Chart(this.$refs.paymentsStatusChart.getContext("2d"),{type:"doughnut",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1}},onClick:(t,e,a)=>{if(e[0]){const t=e[0].index;this.searchPaymentsBy("status",a.data.labels[t])}}},data:{datasets:[{label:"",data:[],backgroundColor:["rgb(0, 205, 86)","rgb(64, 72, 78)","rgb(255, 99, 132)"],hoverOffset:4}]}}),this.paymentsWalletsChart=new Chart(this.$refs.paymentsWalletsChart.getContext("2d"),{type:"bubble",options:{responsive:!0,maintainAspectRatio:!1,plugins:{legend:{display:!1},title:{display:!1}},onClick:(t,e,a)=>{if(e[0]){const t=e[0].datasetIndex;this.searchPaymentsBy("wallet_id",a.data.datasets[t].wallet_id)}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(20),hoverOffset:4}]}}),this.paymentsTagsChart=new Chart(this.$refs.paymentsTagsChart.getContext("2d"),{type:"pie",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1},legend:{display:!1,title:{display:!1,text:"Tags"}}},onClick:(t,e,a)=>{if(e[0]){const t=e[0].index;this.searchPaymentsBy("tag",a.data.labels[t])}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(10),hoverOffset:4}]}}),this.paymentsDailyChart=new Chart(this.$refs.paymentsDailyChart.getContext("2d"),{type:"line",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1},legend:{display:!0,title:{display:!1,text:"Tags"}}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(10),hoverOffset:4}]}}),this.paymentsBalanceInOutChart=new Chart(this.$refs.paymentsBalanceInOutChart.getContext("2d"),{type:"bar",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1},legend:{display:!0,title:{display:!1,text:"Tags"}}},scales:{x:{stacked:!0},y:{stacked:!0}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(50),hoverOffset:4}]}}),this.paymentsCountInOutChart=new Chart(this.$refs.paymentsCountInOutChart.getContext("2d"),{type:"bar",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1},legend:{display:!0,title:{display:!1,text:""}}},scales:{x:{stacked:!0},y:{stacked:!0}}},data:{datasets:[{label:"",data:[],backgroundColor:this.randomColors(80),hoverOffset:4}]}})):console.warn("Charts are not ready yet. Initialization delayed.")},saveChartsPreferences(){this.$q.localStorage.set("lnbits.payments.chartData",this.chartData)},randomColors(t=1){const e=[];for(let a=1;a<=10;a++)for(let s=1;s<=10;s++)e.push(`rgb(${s*t*33%200}, ${71*(a+s+t)%255}, ${(a+30*t)%255})`);return e}}},window.PageNode={mixins:[window.windowMixin],template:"#page-node",config:{globalProperties:{LNbits:LNbits,msg:"hello"}},data(){return{isSuperUser:!1,wallet:{},tab:"dashboard",payments:1e3,info:{},channel_stats:{},channels:{data:[],filter:""},activeBalance:{},ranks:{},peers:{data:[],filter:""},connectPeerDialog:{show:!1,data:{}},setFeeDialog:{show:!1,data:{fee_ppm:0,fee_base_msat:0}},openChannelDialog:{show:!1,data:{}},closeChannelDialog:{show:!1,data:{}},nodeInfoDialog:{show:!1,data:{}},transactionDetailsDialog:{show:!1,data:{}},states:[{label:"Active",value:"active",color:"green"},{label:"Pending",value:"pending",color:"orange"},{label:"Inactive",value:"inactive",color:"grey"},{label:"Closed",value:"closed",color:"red"}],stateFilters:[{label:"Active",value:"active"},{label:"Pending",value:"pending"}],paymentsTable:{data:[],columns:[{name:"pending",label:""},{name:"date",align:"left",label:this.$t("date"),field:"date",sortable:!0},{name:"sat",align:"right",label:this.$t("amount")+" ("+LNBITS_DENOMINATION+")",field:t=>this.formatMsat(t.amount),sortable:!0},{name:"fee",align:"right",label:this.$t("fee")+" (m"+LNBITS_DENOMINATION+")",field:"fee"},{name:"destination",align:"right",label:"Destination",field:"destination"},{name:"memo",align:"left",label:this.$t("memo"),field:"memo"}],pagination:{rowsPerPage:10,page:1,rowsNumber:10},filter:null},invoiceTable:{data:[],columns:[{name:"pending",label:""},{name:"paid_at",field:"paid_at",align:"left",label:"Paid at",sortable:!0},{name:"expiry",label:this.$t("expiry"),field:"expiry",align:"left",sortable:!0},{name:"amount",label:this.$t("amount")+" ("+LNBITS_DENOMINATION+")",field:t=>this.formatMsat(t.amount),sortable:!0},{name:"memo",align:"left",label:this.$t("memo"),field:"memo"}],pagination:{rowsPerPage:10,page:1,rowsNumber:10},filter:null}}},created(){this.getInfo(),this.get1MLStats()},watch:{tab(t){"transactions"!==t||this.paymentsTable.data.length?"channels"!==t||this.channels.data.length||(this.getChannels(),this.getPeers()):(this.getPayments(),this.getInvoices())}},computed:{checkChanges(){return!_.isEqual(this.settings,this.formData)},filteredChannels(){return this.stateFilters?this.channels.data.filter((t=>this.stateFilters.find((({value:e})=>e==t.state)))):this.channels.data},totalBalance(){return this.filteredChannels.reduce(((t,e)=>(t.local_msat+=e.balance.local_msat,t.remote_msat+=e.balance.remote_msat,t.total_msat+=e.balance.total_msat,t)),{local_msat:0,remote_msat:0,total_msat:0})}},methods:{formatMsat:t=>LNbits.utils.formatMsat(t),api(t,e,a){const s=new URLSearchParams(a?.query);return LNbits.api.request(t,`/node/api/v1${e}?${s}`,{},a?.data).catch((t=>{LNbits.utils.notifyApiError(t)}))},getChannel(t){return this.api("GET",`/channels/${t}`).then((t=>{this.setFeeDialog.data.fee_ppm=t.data.fee_ppm,this.setFeeDialog.data.fee_base_msat=t.data.fee_base_msat}))},getChannels(){return this.api("GET","/channels").then((t=>{this.channels.data=t.data}))},getInfo(){return this.api("GET","/info").then((t=>{this.info=t.data,this.channel_stats=t.data.channel_stats})).catch((()=>{this.info={},this.channel_stats={}}))},get1MLStats(){return this.api("GET","/rank").then((t=>{this.ranks=t.data})).catch((()=>{this.ranks={}}))},getPayments(t){t&&(this.paymentsTable.pagination=t.pagination);let e=this.paymentsTable.pagination;const a={limit:e.rowsPerPage,offset:(e.page-1)*e.rowsPerPage??0};return this.api("GET","/payments",{query:a}).then((t=>{this.paymentsTable.data=t.data.data,this.paymentsTable.pagination.rowsNumber=t.data.total}))},getInvoices(t){t&&(this.invoiceTable.pagination=t.pagination);let e=this.invoiceTable.pagination;const a={limit:e.rowsPerPage,offset:(e.page-1)*e.rowsPerPage??0};return this.api("GET","/invoices",{query:a}).then((t=>{this.invoiceTable.data=t.data.data,this.invoiceTable.pagination.rowsNumber=t.data.total}))},getPeers(){return this.api("GET","/peers").then((t=>{this.peers.data=t.data}))},connectPeer(){this.api("POST","/peers",{data:this.connectPeerDialog.data}).then((()=>{this.connectPeerDialog.show=!1,this.getPeers()}))},disconnectPeer(t){LNbits.utils.confirmDialog("Do you really wanna disconnect this peer?").onOk((()=>{this.api("DELETE",`/peers/${t}`).then((t=>{Quasar.Notify.create({message:"Disconnected",icon:null}),this.needsRestart=!0,this.getPeers()}))}))},setChannelFee(t){this.api("PUT",`/channels/${t}`,{data:this.setFeeDialog.data}).then((t=>{this.setFeeDialog.show=!1,this.getChannels()})).catch(LNbits.utils.notifyApiError)},openChannel(){this.api("POST","/channels",{data:this.openChannelDialog.data}).then((t=>{this.openChannelDialog.show=!1,this.getChannels()})).catch((t=>{console.log(t)}))},showCloseChannelDialog(t){this.closeChannelDialog.show=!0,this.closeChannelDialog.data={force:!1,short_id:t.short_id,...t.point}},closeChannel(){this.api("DELETE","/channels",{query:this.closeChannelDialog.data}).then((t=>{this.closeChannelDialog.show=!1,this.getChannels()}))},showSetFeeDialog(t){this.setFeeDialog.show=!0,this.setFeeDialog.channel_id=t,this.getChannel(t)},showOpenChannelDialog(t){this.openChannelDialog.show=!0,this.openChannelDialog.data={peer_id:t,funding_amount:0}},showNodeInfoDialog(t){this.nodeInfoDialog.show=!0,this.nodeInfoDialog.data=t},showTransactionDetailsDialog(t){this.transactionDetailsDialog.show=!0,this.transactionDetailsDialog.data=t},shortenNodeId:t=>t?t.substring(0,5)+"..."+t.substring(t.length-5):"..."}},window.PageNodePublic={template:"#page-node-public",mixins:[window.windowMixin],data:()=>({enabled:!1,isSuperUser:!1,wallet:{},tab:"dashboard",payments:1e3,info:{},channel_stats:{},channels:[],activeBalance:{},ranks:{},peers:[],connectPeerDialog:{show:!1,data:{}},openChannelDialog:{show:!1,data:{}},closeChannelDialog:{show:!1,data:{}},nodeInfoDialog:{show:!1,data:{}},states:[{label:"Active",value:"active",color:"green"},{label:"Pending",value:"pending",color:"orange"},{label:"Inactive",value:"inactive",color:"grey"},{label:"Closed",value:"closed",color:"red"}]}),created(){this.getInfo(),this.get1MLStats()},methods:{formatMsat:t=>LNbits.utils.formatMsat(t),api:(t,e,a)=>LNbits.api.request(t,"/node/public/api/v1"+e,{},a),getInfo(){this.api("GET","/info",{}).then((t=>{this.info=t.data,this.channel_stats=t.data.channel_stats,this.enabled=!0})).catch((()=>{this.info={},this.channel_stats={}}))},get1MLStats(){this.api("GET","/rank",{}).then((t=>{this.ranks=t.data})).catch((()=>{this.ranks={}}))}}},window.PageAudit={template:"#page-audit",mixins:[window.windowMixin],data:()=>({chartsReady:!1,auditEntries:[],searchData:{user_id:"",ip_address:"",request_type:"",component:"",request_method:"",response_code:"",path:""},searchOptions:{component:[],request_method:[],response_code:[]},auditTable:{columns:[{name:"created_at",align:"center",label:"Date",field:"created_at",sortable:!0},{name:"duration",align:"left",label:"Duration (sec)",field:"duration",sortable:!0},{name:"component",align:"left",label:"Component",field:"component",sortable:!1},{name:"request_method",align:"left",label:"Method",field:"request_method",sortable:!1},{name:"response_code",align:"left",label:"Code",field:"response_code",sortable:!1},{name:"user_id",align:"left",label:"User Id",field:"user_id",sortable:!1},{name:"ip_address",align:"left",label:"IP Address",field:"ip_address",sortable:!1},{name:"path",align:"left",label:"Path",field:"path",sortable:!1}],pagination:{sortBy:"created_at",rowsPerPage:10,page:1,descending:!0,rowsNumber:10},search:null,hideEmpty:!0,loading:!1},auditDetailsDialog:{data:null,show:!1}}),async created(){},async mounted(){this.chartsReady=!0,await this.$nextTick(),this.initCharts(),await this.fetchAudit()},methods:{formatDate:t=>LNbits.utils.formatDateString(t),async fetchAudit(t){try{const e=LNbits.utils.prepareFilterQuery(this.auditTable,t),{data:a}=await LNbits.api.request("GET",`/audit/api/v1?${e}`);this.auditTable.pagination.rowsNumber=a.total,this.auditEntries=a.data,await this.fetchAuditStats(t)}catch(t){console.warn(t),LNbits.utils.notifyApiError(t)}finally{this.auditTable.loading=!1}},async fetchAuditStats(t){try{const e=LNbits.utils.prepareFilterQuery(this.auditTable,t),{data:a}=await LNbits.api.request("GET",`/audit/api/v1/stats?${e}`),s=a.request_method.map((t=>t.field));this.searchOptions.request_method=[...new Set(this.searchOptions.request_method.concat(s))],this.requestMethodChart.data.labels=s,this.requestMethodChart.data.datasets[0].data=a.request_method.map((t=>t.total)),this.requestMethodChart.update();const i=a.response_code.map((t=>t.field));this.searchOptions.response_code=[...new Set(this.searchOptions.response_code.concat(i))],this.responseCodeChart.data.labels=i,this.responseCodeChart.data.datasets[0].data=a.response_code.map((t=>t.total)),this.responseCodeChart.update();const n=a.component.map((t=>t.field));this.searchOptions.component=[...new Set(this.searchOptions.component.concat(n))],this.componentUseChart.data.labels=n,this.componentUseChart.data.datasets[0].data=a.component.map((t=>t.total)),this.componentUseChart.update(),this.longDurationChart.data.labels=a.long_duration.map((t=>t.field)),this.longDurationChart.data.datasets[0].data=a.long_duration.map((t=>t.total)),this.longDurationChart.update()}catch(t){console.warn(t),LNbits.utils.notifyApiError(t)}},async searchAuditBy(t,e){t&&(this.searchData[t]=e),this.auditTable.filter=Object.entries(this.searchData).reduce(((t,[e,a])=>a?(t[e]=a,t):t),{}),await this.fetchAudit()},showDetailsDialog(t){const e=JSON.parse(t?.request_details||"");try{e.body&&(e.body=JSON.parse(e.body))}catch(t){}this.auditDetailsDialog.data=JSON.stringify(e,null,4),this.auditDetailsDialog.show=!0},shortify:t=>(valueLength=(t||"").length,valueLength<=10?t:`${t.substring(0,5)}...${t.substring(valueLength-5,valueLength)}`),async initCharts(){this.chartsReady?(this.responseCodeChart=new Chart(this.$refs.responseCodeChart.getContext("2d"),{type:"doughnut",options:{responsive:!0,plugins:{legend:{position:"bottom"},title:{display:!1,text:"HTTP Response Codes"}},onClick:(t,e,a)=>{if(e[0]){const t=e[0].index;this.searchAuditBy("response_code",a.data.labels[t])}}},data:{datasets:[{label:"",data:[20,10],backgroundColor:["rgb(100, 99, 200)","rgb(54, 162, 235)","rgb(255, 205, 86)","rgb(255, 5, 86)","rgb(25, 205, 86)","rgb(255, 205, 250)"]}],labels:[]}}),this.requestMethodChart=new Chart(this.$refs.requestMethodChart.getContext("2d"),{type:"bar",options:{responsive:!0,maintainAspectRatio:!1,plugins:{title:{display:!1}},onClick:(t,e,a)=>{if(e[0]){const t=e[0].index;this.searchAuditBy("request_method",a.data.labels[t])}}},data:{datasets:[{label:"",data:[],backgroundColor:["rgb(255, 99, 132)","rgb(54, 162, 235)","rgb(255, 205, 86)","rgb(255, 5, 86)","rgb(25, 205, 86)","rgb(255, 205, 250)"],hoverOffset:4}]}}),this.componentUseChart=new Chart(this.$refs.componentUseChart.getContext("2d"),{type:"pie",options:{responsive:!0,plugins:{legend:{position:"xxx"},title:{display:!1,text:"Components"}},onClick:(t,e,a)=>{if(e[0]){const t=e[0].index;this.searchAuditBy("component",a.data.labels[t])}}},data:{datasets:[{data:[],backgroundColor:["rgb(255, 99, 132)","rgb(54, 162, 235)","rgb(255, 205, 86)","rgb(255, 5, 86)","rgb(25, 205, 86)","rgb(255, 205, 250)","rgb(100, 205, 250)","rgb(120, 205, 250)","rgb(140, 205, 250)","rgb(160, 205, 250)"],hoverOffset:4}]}}),this.longDurationChart=new Chart(this.$refs.longDurationChart.getContext("2d"),{type:"bar",options:{responsive:!0,indexAxis:"y",maintainAspectRatio:!1,plugins:{legend:{title:{display:!1,text:"Long Duration"}}},onClick:(t,e,a)=>{if(e[0]){const t=e[0].index;this.searchAuditBy("path",a.data.labels[t])}}},data:{datasets:[{label:"",data:[],backgroundColor:["rgb(255, 99, 132)","rgb(54, 162, 235)","rgb(255, 205, 86)","rgb(255, 5, 86)","rgb(25, 205, 86)","rgb(255, 205, 250)","rgb(100, 205, 250)","rgb(120, 205, 250)","rgb(140, 205, 250)","rgb(160, 205, 250)"],hoverOffset:4}]}})):console.warn("Charts are not ready yet. Initialization delayed.")}}},window.PageWallets={template:"#page-wallets",mixins:[window.windowMixin],data:()=>({user:null,tab:"wallets",wallets:[],addWalletDialog:{show:!1},walletsTable:{columns:[{name:"name",align:"left",label:"Name",field:"name",sortable:!0},{name:"currency",align:"center",label:"Currency",field:"currency",sortable:!0},{name:"updated_at",align:"right",label:"Last Updated",field:"updated_at",sortable:!0}],pagination:{sortBy:"updated_at",rowsPerPage:12,page:1,descending:!0,rowsNumber:10},search:"",hideEmpty:!0,loading:!1}}),watch:{"walletsTable.search":{handler(){const t={};this.walletsTable.search&&(t.search=this.walletsTable.search),this.getUserWallets()}}},methods:{async getUserWallets(t){try{this.walletsTable.loading=!0;const e=LNbits.utils.prepareFilterQuery(this.walletsTable,t),{data:a}=await LNbits.api.request("GET",`/api/v1/wallet/paginated?${e}`,null);this.wallets=a.data,this.walletsTable.pagination.rowsNumber=a.total}catch(t){LNbits.utils.notifyApiError(t)}finally{this.walletsTable.loading=!1}},showNewWalletDialog(){this.addWalletDialog={show:!0,walletType:"lightning"},this.showAddNewWalletDialog()},goToWallet(t){window.location=`/wallet?wal=${t}`},formattedFiatAmount:(t,e)=>LNbits.utils.formatCurrency(Number(t).toFixed(2),e),formattedSatAmount:t=>LNbits.utils.formatMsat(t)+" sat"},async created(){await this.getUserWallets()}},window.PageUsers={template:"#page-users",mixins:[window.windowMixin],data:()=>({paymentsWallet:{},cancel:{},users:[],wallets:[],searchData:{user:"",username:"",email:"",pubkey:""},paymentPage:{show:!1},activeWallet:{userId:null,show:!1},activeUser:{data:null,showUserId:!1,show:!1},createWalletDialog:{data:{},show:!1},walletTable:{columns:[{name:"name",align:"left",label:"Name",field:"name"},{name:"id",align:"left",label:"Wallet Id",field:"id"},{name:"currency",align:"left",label:"Currency",field:"currency"},{name:"balance_msat",align:"left",label:"Balance",field:"balance_msat"}],pagination:{sortBy:"name",rowsPerPage:10,page:1,descending:!0,rowsNumber:10},search:null,hideEmpty:!0,loading:!1},usersTable:{columns:[{name:"admin",align:"left",label:"Admin",field:"admin",sortable:!1},{name:"wallet_id",align:"left",label:"Wallets",field:"wallet_id",sortable:!1},{name:"user",align:"left",label:"User Id",field:"user",sortable:!1},{name:"username",align:"left",label:"Username",field:"username",sortable:!1},{name:"email",align:"left",label:"Email",field:"email",sortable:!1},{name:"pubkey",align:"left",label:"Public Key",field:"pubkey",sortable:!1},{name:"balance_msat",align:"left",label:"Balance",field:"balance_msat",sortable:!0},{name:"transaction_count",align:"left",label:"Payments",field:"transaction_count",sortable:!0},{name:"last_payment",align:"left",label:"Last Payment",field:"last_payment",sortable:!0}],pagination:{sortBy:"balance_msat",rowsPerPage:10,page:1,descending:!0,rowsNumber:10},search:null,hideEmpty:!0,loading:!1}}),watch:{"usersTable.hideEmpty":function(t,e){this.usersTable.filter=t?{"transaction_count[gt]":0}:{},this.fetchUsers()}},created(){this.fetchUsers()},methods:{formatDate:t=>LNbits.utils.formatDateString(t),formatSat:t=>LNbits.utils.formatSat(Math.floor(t/1e3)),backToUsersPage(){this.activeUser.show=!1,this.paymentPage.show=!1,this.activeWallet.show=!1,this.fetchUsers()},handleBalanceUpdate(){this.fetchWallets(this.activeWallet.userId)},resetPassword(t){return LNbits.api.request("PUT",`/users/api/v1/user/${t}/reset_password`).then((t=>{LNbits.utils.confirmDialog(this.$t("reset_key_generated")+" "+this.$t("reset_key_copy")).onOk((()=>{const e=window.location.origin+"?reset_key="+t.data;this.copyText(e)}))})).catch(LNbits.utils.notifyApiError)},createUser(){LNbits.api.request("POST","/users/api/v1/user",null,this.activeUser.data).then((t=>{Quasar.Notify.create({type:"positive",message:"User created!",icon:null}),this.activeUser.setPassword=!0,this.activeUser.data=t.data,this.fetchUsers()})).catch(LNbits.utils.notifyApiError)},updateUser(){LNbits.api.request("PUT",`/users/api/v1/user/${this.activeUser.data.id}`,null,this.activeUser.data).then((()=>{Quasar.Notify.create({type:"positive",message:"User updated!",icon:null}),this.activeUser.data=null,this.activeUser.show=!1,this.fetchUsers()})).catch(LNbits.utils.notifyApiError)},createWallet(){const t=this.activeWallet.userId;t?LNbits.api.request("POST",`/users/api/v1/user/${t}/wallet`,null,this.createWalletDialog.data).then((()=>{this.fetchWallets(t),Quasar.Notify.create({type:"positive",message:"Wallet created!"})})).catch(LNbits.utils.notifyApiError):Quasar.Notify.create({type:"warning",message:"No user selected!",icon:null})},deleteUser(t){LNbits.utils.confirmDialog("Are you sure you want to delete this user?").onOk((()=>{LNbits.api.request("DELETE",`/users/api/v1/user/${t}`).then((()=>{this.fetchUsers(),Quasar.Notify.create({type:"positive",message:"User deleted!",icon:null}),this.activeUser.data=null,this.activeUser.show=!1})).catch(LNbits.utils.notifyApiError)}))},undeleteUserWallet(t,e){LNbits.api.request("PUT",`/users/api/v1/user/${t}/wallet/${e}/undelete`).then((()=>{this.fetchWallets(t),Quasar.Notify.create({type:"positive",message:"Undeleted user wallet!",icon:null})})).catch(LNbits.utils.notifyApiError)},deleteUserWallet(t,e,a){const s=a?"Wallet is already deleted, are you sure you want to permanently delete this user wallet?":"Are you sure you want to delete this user wallet?";LNbits.utils.confirmDialog(s).onOk((()=>{LNbits.api.request("DELETE",`/users/api/v1/user/${t}/wallet/${e}`).then((()=>{this.fetchWallets(t),Quasar.Notify.create({type:"positive",message:"User wallet deleted!",icon:null})})).catch(LNbits.utils.notifyApiError)}))},deleteAllUserWallets(t){LNbits.utils.confirmDialog(this.$t("confirm_delete_all_wallets")).onOk((()=>{LNbits.api.request("DELETE",`/users/api/v1/user/${t}/wallets`).then((e=>{Quasar.Notify.create({type:"positive",message:e.data.message,icon:null}),this.fetchWallets(t)})).catch(LNbits.utils.notifyApiError)}))},copyWalletLink(t){const e=`${window.location.origin}/wallet?usr=${this.activeWallet.userId}&wal=${t}`;this.copyText(e)},fetchUsers(t){this.relaxFilterForFields(["username","email"]);const e=LNbits.utils.prepareFilterQuery(this.usersTable,t);LNbits.api.request("GET",`/users/api/v1/user?${e}`).then((t=>{this.usersTable.loading=!1,this.usersTable.pagination.rowsNumber=t.data.total,this.users=t.data.data})).catch(LNbits.utils.notifyApiError)},fetchWallets(t){return LNbits.api.request("GET",`/users/api/v1/user/${t}/wallet`).then((e=>{this.wallets=e.data,this.activeWallet.userId=t,this.activeWallet.show=!0})).catch(LNbits.utils.notifyApiError)},relaxFilterForFields(t=[]){t.forEach((t=>{const e=this.usersTable?.filter?.[t];e&&this.usersTable.filter[t]&&(this.usersTable.filter[`${t}[like]`]=e,delete this.usersTable.filter[t])}))},updateWallet(t){LNbits.api.request("PATCH","/api/v1/wallet",t.adminkey,{name:t.name}).then((()=>{t.editable=!1,Quasar.Notify.create({message:"Wallet name updated.",type:"positive",timeout:3500})})).catch((t=>{LNbits.utils.notifyApiError(t)}))},toggleAdmin(t){LNbits.api.request("GET",`/users/api/v1/user/${t}/admin`).then((()=>{this.fetchUsers(),Quasar.Notify.create({type:"positive",message:"Toggled admin!",icon:null})})).catch(LNbits.utils.notifyApiError)},async showAccountPage(t){if(this.activeUser.showPassword=!1,this.activeUser.showUserId=!1,this.activeUser.setPassword=!1,!t)return this.activeUser.data={extra:{}},void(this.activeUser.show=!0);try{const{data:e}=await LNbits.api.request("GET",`/users/api/v1/user/${t}`);this.activeUser.data=e,this.activeUser.show=!0}catch(t){console.warn(t),Quasar.Notify.create({type:"warning",message:"Failed to get user!"}),this.activeUser.show=!1}},async showWalletPayments(t){this.activeUser.show=!1,await this.fetchWallets(this.users[0].id),await this.showPayments(t)},showPayments(t){this.paymentsWallet=this.wallets.find((e=>e.id===t)),this.paymentPage.show=!0},searchUserBy(t){const e=this.searchData[t];this.usersTable.filter={},e&&(this.usersTable.filter[t]=e),this.fetchUsers()},shortify:t=>(valueLength=(t||"").length,valueLength<=10?t:`${t.substring(0,5)}...${t.substring(valueLength-5,valueLength)}`)}},window.PageAccount={template:"#page-account",mixins:[window.windowMixin],data(){return{user:null,hasUsername:!1,showUserId:!1,reactionOptions:["None","confettiBothSides","confettiFireworks","confettiStars","confettiTop"],borderOptions:["retro-border","hard-border","neon-border","no-border"],tab:"user",credentialsData:{show:!1,oldPassword:null,newPassword:null,newPasswordRepeat:null,username:null,pubkey:null},apiAcl:{showNewAclDialog:!1,showPasswordDialog:!1,showNewTokenDialog:!1,data:[],passwordGuardedFunction:null,newAclName:"",newTokenName:"",password:"",apiToken:null,selectedTokenId:null,columns:[{name:"Name",align:"left",label:this.$t("Name"),field:"Name",sortable:!1},{name:"path",align:"left",label:this.$t("path"),field:"path",sortable:!1},{name:"read",align:"left",label:this.$t("read"),field:"read",sortable:!1},{name:"write",align:"left",label:this.$t("write"),field:"write",sortable:!1}],pagination:{rowsPerPage:100,page:1}},selectedApiAcl:{id:null,name:null,endpoints:[],token_id_list:[],allRead:!1,allWrite:!1},notifications:{nostr:{identifier:""}}}},methods:{activeLanguage:t=>window.i18n.global.locale===t,changeLanguage(t){window.i18n.global.locale=t,this.$q.localStorage.set("lnbits.lang",t)},async updateAccount(){try{const{data:t}=await LNbits.api.request("PUT","/api/v1/auth/update",null,{user_id:this.user.id,username:this.user.username,email:this.user.email,extra:this.user.extra});this.user=t,this.hasUsername=!!t.username,Quasar.Notify.create({type:"positive",message:"Account updated."})}catch(t){LNbits.utils.notifyApiError(t)}},disableUpdatePassword(){return!this.credentialsData.newPassword||!this.credentialsData.newPasswordRepeat||this.credentialsData.newPassword!==this.credentialsData.newPasswordRepeat},async updatePassword(){if(this.credentialsData.username)try{const{data:t}=await LNbits.api.request("PUT","/api/v1/auth/password",null,{user_id:this.user.id,username:this.credentialsData.username,password_old:this.credentialsData.oldPassword,password:this.credentialsData.newPassword,password_repeat:this.credentialsData.newPasswordRepeat});this.user=t,this.hasUsername=!!t.username,this.credentialsData.show=!1,Quasar.Notify.create({type:"positive",message:"Password updated."})}catch(t){LNbits.utils.notifyApiError(t)}else Quasar.Notify.create({type:"warning",message:"Please set a username."})},async updatePubkey(){try{const{data:t}=await LNbits.api.request("PUT","/api/v1/auth/pubkey",null,{user_id:this.user.id,pubkey:this.credentialsData.pubkey});this.user=t,this.hasUsername=!!t.username,this.credentialsData.show=!1,this.$q.notify({type:"positive",message:"Public key updated."})}catch(t){LNbits.utils.notifyApiError(t)}},showUpdateCredentials(){this.credentialsData={show:!0,oldPassword:null,username:this.user.username,pubkey:this.user.pubkey,newPassword:null,newPasswordRepeat:null}},newApiAclDialog(){this.apiAcl.newAclName=null,this.apiAcl.showNewAclDialog=!0},newTokenAclDialog(){this.apiAcl.newTokenName=null,this.apiAcl.newTokenExpiry=null,this.apiAcl.showNewTokenDialog=!0},handleApiACLSelected(t){this.selectedApiAcl={id:null,name:null,endpoints:[],token_id_list:[]},this.apiAcl.selectedTokenId=null,t&&setTimeout((()=>{const e=this.apiAcl.data.find((e=>e.id===t));this.selectedApiAcl&&(this.selectedApiAcl={...e},this.selectedApiAcl.allRead=this.selectedApiAcl.endpoints.every((t=>t.read)),this.selectedApiAcl.allWrite=this.selectedApiAcl.endpoints.every((t=>t.write)))}))},handleAllEndpointsReadAccess(){this.selectedApiAcl.endpoints.forEach((t=>t.read=this.selectedApiAcl.allRead))},handleAllEndpointsWriteAccess(){this.selectedApiAcl.endpoints.forEach((t=>t.write=this.selectedApiAcl.allWrite))},async getApiACLs(){try{const{data:t}=await LNbits.api.request("GET","/api/v1/auth/acl",null);this.apiAcl.data=t.access_control_list}catch(t){LNbits.utils.notifyApiError(t)}},askPasswordAndRunFunction(t){this.apiAcl.passwordGuardedFunction=t,this.apiAcl.showPasswordDialog=!0},runPasswordGuardedFunction(){this.apiAcl.showPasswordDialog=!1;const t=this.apiAcl.passwordGuardedFunction;t&&this[t]()},async addApiACL(){if(this.apiAcl.newAclName){try{const{data:t}=await LNbits.api.request("PUT","/api/v1/auth/acl",null,{id:this.apiAcl.newAclName,name:this.apiAcl.newAclName,password:this.apiAcl.password});this.apiAcl.data=t.access_control_list;const e=this.apiAcl.data.find((t=>t.name===this.apiAcl.newAclName));this.handleApiACLSelected(e.id),this.apiAcl.showNewAclDialog=!1,this.$q.notify({type:"positive",message:"Access Control List created."})}catch(t){LNbits.utils.notifyApiError(t)}finally{this.apiAcl.name="",this.apiAcl.password=""}this.apiAcl.showNewAclDialog=!1}else this.$q.notify({type:"warning",message:"Name is required."})},async updateApiACLs(){try{const{data:t}=await LNbits.api.request("PUT","/api/v1/auth/acl",null,{id:this.user.id,password:this.apiAcl.password,...this.selectedApiAcl});this.apiAcl.data=t.access_control_list}catch(t){LNbits.utils.notifyApiError(t)}finally{this.apiAcl.password=""}},async deleteApiACL(){if(this.selectedApiAcl.id){try{await LNbits.api.request("DELETE","/api/v1/auth/acl",null,{id:this.selectedApiAcl.id,password:this.apiAcl.password}),this.$q.notify({type:"positive",message:"Access Control List deleted."})}catch(t){LNbits.utils.notifyApiError(t)}finally{this.apiAcl.password=""}this.apiAcl.data=this.apiAcl.data.filter((t=>t.id!==this.selectedApiAcl.id)),this.handleApiACLSelected(this.apiAcl.data[0]?.id)}},async generateApiToken(){if(!this.selectedApiAcl.id)return;const t=new Date(this.apiAcl.newTokenExpiry)-new Date;try{const{data:e}=await LNbits.api.request("POST","/api/v1/auth/acl/token",null,{acl_id:this.selectedApiAcl.id,token_name:this.apiAcl.newTokenName,password:this.apiAcl.password,expiration_time_minutes:Math.trunc(t/6e4)});this.apiAcl.apiToken=e.api_token,this.apiAcl.selectedTokenId=e.id,Quasar.Notify.create({type:"positive",message:"Token Generated."}),await this.getApiACLs(),this.handleApiACLSelected(this.selectedApiAcl.id),this.apiAcl.showNewTokenDialog=!1}catch(t){LNbits.utils.notifyApiError(t)}finally{this.apiAcl.password=""}},async deleteToken(){if(this.apiAcl.selectedTokenId)try{await LNbits.api.request("DELETE","/api/v1/auth/acl/token",null,{id:this.apiAcl.selectedTokenId,acl_id:this.selectedApiAcl.id,password:this.apiAcl.password}),this.$q.notify({type:"positive",message:"Token deleted."}),this.selectedApiAcl.token_id_list=this.selectedApiAcl.token_id_list.filter((t=>t.id!==this.apiAcl.selectedTokenId)),this.apiAcl.selectedTokenId=null}catch(t){LNbits.utils.notifyApiError(t)}finally{this.apiAcl.password=""}}},async created(){try{const{data:t}=await LNbits.api.getAuthenticatedUser();this.user=t,this.hasUsername=!!t.username,this.user.extra||(this.user.extra={})}catch(t){LNbits.utils.notifyApiError(t)}const t=window.location.hash.replace("#","");t&&(this.tab=t),await this.getApiACLs()}},window.PageAdmin={template:"#page-admin",mixins:[windowMixin],data:()=>({tab:"funding",settings:{},formData:{lnbits_exchange_rate_providers:[],lnbits_audit_exclude_paths:[],lnbits_audit_include_paths:[],lnbits_audit_http_response_codes:[]},isSuperUser:!1,needsRestart:!1}),async created(){await this.getSettings();const t=window.location.hash.replace("#","");t&&(this.tab=t)},computed:{checkChanges(){return!_.isEqual(this.settings,this.formData)}},methods:{getDefaultSetting(t){LNbits.api.request("GET",`/admin/api/v1/settings/default?field_name=${t}`).then((e=>{this.formData[t]=e.data.default_value})).catch((function(t){LNbits.utils.notifyApiError(t)}))},restartServer(){LNbits.api.request("GET","/admin/api/v1/restart/").then((t=>{this.$q.notify({type:"positive",message:"Success! Restarted Server",icon:null}),this.needsRestart=!1})).catch(LNbits.utils.notifyApiError)},async getSettings(){await LNbits.api.request("GET","/admin/api/v1/settings",this.g.user.wallets[0].adminkey).then((t=>{this.isSuperUser=t.data.is_super_user||!1,this.settings=t.data,this.formData={...this.settings}})).catch(LNbits.utils.notifyApiError)},updateSettings(){const t=_.omit(this.formData,["is_super_user","lnbits_allowed_funding_sources","touch"]);LNbits.api.request("PUT","/admin/api/v1/settings",this.g.user.wallets[0].adminkey,t).then((t=>{this.needsRestart=this.settings.lnbits_backend_wallet_class!==this.formData.lnbits_backend_wallet_class,this.settings=this.formData,this.formData=_.clone(this.settings),Quasar.Notify.create({type:"positive",message:"Success! Settings changed! "+(this.needsRestart?"Restart required!":""),icon:null})})).catch(LNbits.utils.notifyApiError)},deleteSettings(){LNbits.utils.confirmDialog("Are you sure you want to restore settings to default?").onOk((()=>{LNbits.api.request("DELETE","/admin/api/v1/settings").then((t=>{Quasar.Notify.create({type:"positive",message:"Success! Restored settings to defaults. Restarting...",icon:null}),this.$q.localStorage.clear()})).catch(LNbits.utils.notifyApiError)}))},downloadBackup(){window.open("/admin/api/v1/backup","_blank")}}},window.app.component("lnbits-admin-funding",{props:["is-super-user","form-data","settings"],template:"#lnbits-admin-funding",mixins:[window.windowMixin],data:()=>({auditData:[]}),created(){this.getAudit()},methods:{getAudit(){LNbits.api.request("GET","/admin/api/v1/audit",this.g.user.wallets[0].adminkey).then((t=>{this.auditData=t.data})).catch(LNbits.utils.notifyApiError)}}}),window.app.component("lnbits-admin-funding-sources",{template:"#lnbits-admin-funding-sources",mixins:[window.windowMixin],props:["form-data","allowed-funding-sources"],methods:{getFundingSourceLabel(t){const e=this.rawFundingSources.find((e=>e[0]===t));return e?e[1]:t},showQRValue(t){this.qrValue=t,this.showQRDialog=!0}},computed:{fundingSources(){let t=[];for(const[e,a,s]of this.rawFundingSources){const a={};if(null!==s)for(let[t,e]of Object.entries(s))a[t]="string"==typeof e?{label:e,value:null}:e||{};t.push([e,a])}return new Map(t)},sortedAllowedFundingSources(){return this.allowedFundingSources.sort()}},data:()=>({hideInput:!0,showQRDialog:!1,qrValue:"",rawFundingSources:[["VoidWallet","Void Wallet",null],["FakeWallet","Fake Wallet",{fake_wallet_secret:"Secret",lnbits_denomination:'"sats" or 3 Letter Custom Denomination'}],["CLNRestWallet","Core Lightning Rest (plugin)",{clnrest_url:"Endpoint",clnrest_ca:"ca.pem",clnrest_cert:"server.pem",clnrest_readonly_rune:"Rune used for readonly requests",clnrest_invoice_rune:"Rune used for creating invoices",clnrest_pay_rune:"Rune used for paying invoices using pay",clnrest_renepay_rune:"Rune used for paying invoices using renepay",clnrest_last_pay_index:"Ignores any invoices paid prior to or including this index. 0 is equivalent to not specifying and negative value is invalid.",clnrest_nodeid:"Node id"}],["CoreLightningWallet","Core Lightning",{corelightning_rpc:"Endpoint",corelightning_pay_command:"Custom Pay Command"}],["CoreLightningRestWallet","Core Lightning Rest (legacy)",{corelightning_rest_url:"Endpoint",corelightning_rest_cert:"Certificate",corelightning_rest_macaroon:"Macaroon"}],["LndRestWallet","Lightning Network Daemon (LND Rest)",{lnd_rest_endpoint:"Endpoint",lnd_rest_cert:"Certificate",lnd_rest_macaroon:"Macaroon",lnd_rest_macaroon_encrypted:"Encrypted Macaroon",lnd_rest_route_hints:"Enable Route Hints",lnd_rest_allow_self_payment:"Allow Self Payment"}],["LndWallet","Lightning Network Daemon (LND)",{lnd_grpc_endpoint:"Endpoint",lnd_grpc_cert:"Certificate",lnd_grpc_port:"Port",lnd_grpc_macaroon:"GRPC Macaroon",lnd_grpc_invoice_macaroon:"GRPC Invoice Macaroon",lnd_grpc_admin_macaroon:"GRPC Admin Macaroon",lnd_grpc_macaroon_encrypted:"Encrypted Macaroon"}],["LnTipsWallet","LN.Tips",{lntips_api_endpoint:"Endpoint",lntips_api_key:"API Key"}],["LNPayWallet","LN Pay",{lnpay_api_endpoint:"Endpoint",lnpay_api_key:"API Key",lnpay_wallet_key:"Wallet Key"}],["EclairWallet","Eclair (ACINQ)",{eclair_url:"URL",eclair_pass:"Password"}],["LNbitsWallet","LNbits",{lnbits_endpoint:"Endpoint",lnbits_key:"Admin Key"}],["BlinkWallet","Blink",{blink_api_endpoint:"Endpoint",blink_ws_endpoint:"WebSocket",blink_token:"Key"}],["AlbyWallet","Alby",{alby_api_endpoint:"Endpoint",alby_access_token:"Key"}],["BoltzWallet","Boltz",{boltz_client_endpoint:"Endpoint",boltz_client_macaroon:"Admin Macaroon path or hex",boltz_client_cert:"Certificate path or hex",boltz_client_wallet:"Wallet Name",boltz_client_password:"Wallet Password (can be empty)",boltz_mnemonic:{label:"Liquid mnemonic (copy into greenwallet)",readonly:!0,copy:!0,qrcode:!0}}],["ZBDWallet","ZBD",{zbd_api_endpoint:"Endpoint",zbd_api_key:"Key"}],["PhoenixdWallet","Phoenixd",{phoenixd_api_endpoint:"Endpoint",phoenixd_api_password:"Key"}],["OpenNodeWallet","OpenNode",{opennode_api_endpoint:"Endpoint",opennode_key:"Key"}],["ClicheWallet","Cliche (NBD)",{cliche_endpoint:"Endpoint"}],["SparkWallet","Spark",{spark_url:"Endpoint",spark_token:"Token"}],["NWCWallet","Nostr Wallet Connect",{nwc_pairing_url:"Pairing URL"}],["BreezSdkWallet","Breez SDK",{breez_api_key:"Breez API Key",breez_greenlight_seed:"Greenlight Seed",breez_greenlight_device_key:"Greenlight Device Key",breez_greenlight_device_cert:"Greenlight Device Cert",breez_greenlight_invite_code:"Greenlight Invite Code"}],["StrikeWallet","Strike (alpha)",{strike_api_endpoint:"API Endpoint",strike_api_key:"API Key"}],["BreezLiquidSdkWallet","Breez Liquid SDK",{breez_liquid_api_key:"Breez API Key (can be empty)",breez_liquid_seed:"Liquid seed phrase",breez_liquid_fee_offset_sat:"Offset amount in sats to increase fee limit"}]]})}),window.app.component("lnbits-admin-fiat-providers",{props:["form-data"],template:"#lnbits-admin-fiat-providers",mixins:[window.windowMixin],data:()=>({formAddStripeUser:"",hideInputToggle:!0}),methods:{addStripeAllowedUser(){const t=this.formAddStripeUser||"";t.length&&!this.formData.stripe_limits.allowed_users.includes(t)&&(this.formData.stripe_limits.allowed_users=[...this.formData.stripe_limits.allowed_users,t],this.formAddStripeUser="")},removeStripeAllowedUser(t){this.formData.stripe_limits.allowed_users=this.formData.stripe_limits.allowed_users.filter((e=>e!==t))},checkFiatProvider(t){LNbits.api.request("PUT",`/api/v1/fiat/check/${t}`).then((t=>{const e=t.data;Quasar.Notify.create({type:e.success?"positive":"warning",message:e.message,icon:null})})).catch(LNbits.utils.notifyApiError)}}}),window.app.component("lnbits-admin-exchange-providers",{props:["form-data"],template:"#lnbits-admin-exchange-providers",mixins:[window.windowMixin],data:()=>({exchangeData:{selectedProvider:null,showTickerConversion:!1,convertFromTicker:null,convertToTicker:null},exchangesTable:{columns:[{name:"name",align:"left",label:"Exchange Name",field:"name",sortable:!0},{name:"api_url",align:"left",label:"URL",field:"api_url",sortable:!1},{name:"path",align:"left",label:"JSON Path",field:"path",sortable:!1},{name:"exclude_to",align:"left",label:"Exclude Currencies",field:"exclude_to",sortable:!1},{name:"ticker_conversion",align:"left",label:"Ticker Conversion",field:"ticker_conversion",sortable:!1}],pagination:{sortBy:"name",rowsPerPage:100,page:1,rowsNumber:100},search:null,hideEmpty:!0}}),mounted(){this.getExchangeRateHistory()},created(){const t=window.location.hash.replace("#","");"exchange_providers"===t&&this.showExchangeProvidersTab(t)},methods:{getExchangeRateHistory(){LNbits.api.request("GET","/api/v1/rate/history",this.g.user.wallets[0].inkey).then((t=>{this.initExchangeChart(t.data)})).catch((function(t){LNbits.utils.notifyApiError(t)}))},showExchangeProvidersTab(t){"exchange_providers"===t&&this.getExchangeRateHistory()},addExchangeProvider(){this.formData.lnbits_exchange_rate_providers=[{name:"",api_url:"",path:"",exclude_to:[]},...this.formData.lnbits_exchange_rate_providers]},removeExchangeProvider(t){this.formData.lnbits_exchange_rate_providers=this.formData.lnbits_exchange_rate_providers.filter((e=>e!==t))},removeExchangeTickerConversion(t,e){t.ticker_conversion=t.ticker_conversion.filter((t=>t!==e)),this.formData.touch=null},addExchangeTickerConversion(){this.exchangeData.selectedProvider&&(this.exchangeData.selectedProvider.ticker_conversion.push(`${this.exchangeData.convertFromTicker}:${this.exchangeData.convertToTicker}`),this.formData.touch=null,this.exchangeData.showTickerConversion=!1)},showTickerConversionDialog(t){this.exchangeData.convertFromTicker=null,this.exchangeData.convertToTicker=null,this.exchangeData.selectedProvider=t,this.exchangeData.showTickerConversion=!0},initExchangeChart(t){const e=t.map((t=>Quasar.date.formatDate(new Date(1e3*t.timestamp),"HH:mm"))),a=[...this.formData.lnbits_exchange_rate_providers,{name:"LNbits"}].map((e=>({label:e.name,data:t.map((t=>t.rates[e.name])),pointStyle:!0,borderWidth:"LNbits"===e.name?4:1,tension:.4})));this.exchangeRatesChart=new Chart(this.$refs.exchangeRatesChart.getContext("2d"),{type:"line",options:{plugins:{legend:{display:!1}}},data:{labels:e,datasets:a}})}}}),window.app.component("lnbits-admin-security",{props:["form-data"],template:"#lnbits-admin-security",mixins:[window.windowMixin],data:()=>({logs:[],formBlockedIPs:"",serverlogEnabled:!1,nostrAcceptedUrl:"",formAllowedIPs:"",formCallbackUrlRule:""}),created(){},methods:{addAllowedIPs(){const t=this.formAllowedIPs.trim(),e=this.formData.lnbits_allowed_ips;t&&t.length&&!e.includes(t)&&(this.formData.lnbits_allowed_ips=[...e,t],this.formAllowedIPs="")},removeAllowedIPs(t){const e=this.formData.lnbits_allowed_ips;this.formData.lnbits_allowed_ips=e.filter((e=>e!==t))},addBlockedIPs(){const t=this.formBlockedIPs.trim(),e=this.formData.lnbits_blocked_ips;t&&t.length&&!e.includes(t)&&(this.formData.lnbits_blocked_ips=[...e,t],this.formBlockedIPs="")},removeBlockedIPs(t){const e=this.formData.lnbits_blocked_ips;this.formData.lnbits_blocked_ips=e.filter((e=>e!==t))},addCallbackUrlRule(){const t=this.formCallbackUrlRule.trim(),e=this.formData.lnbits_callback_url_rules;t&&t.length&&!e.includes(t)&&(this.formData.lnbits_callback_url_rules=[...e,t],this.formCallbackUrlRule="")},removeCallbackUrlRule(t){const e=this.formData.lnbits_callback_url_rules;this.formData.lnbits_callback_url_rules=e.filter((e=>e!==t))},addNostrUrl(){const t=this.nostrAcceptedUrl.trim();this.removeNostrUrl(t),this.formData.nostr_absolute_request_urls.push(t),this.nostrAcceptedUrl=""},removeNostrUrl(t){this.formData.nostr_absolute_request_urls=this.formData.nostr_absolute_request_urls.filter((e=>e!==t))},async toggleServerLog(){if(this.serverlogEnabled=!this.serverlogEnabled,this.serverlogEnabled){const t="http:"!==location.protocol?"wss://":"ws://",e=await LNbits.utils.digestMessage(this.g.user.id),a=t+document.domain+":"+location.port+"/api/v1/ws/"+e;this.ws=new WebSocket(a),this.ws.addEventListener("message",(async({data:t})=>{this.logs.push(t.toString());const e=this.$refs.logScroll;if(e){const t=e.getScrollTarget(),a=0;e.setScrollPosition(t.scrollHeight,a)}}))}else this.ws.close()}}}),window.app.component("lnbits-admin-users",{props:["form-data"],template:"#lnbits-admin-users",mixins:[window.windowMixin],data:()=>({formAddUser:"",formAddAdmin:""}),methods:{addAllowedUser(){let t=this.formAddUser,e=this.formData.lnbits_allowed_users;t&&t.length&&!e.includes(t)&&(this.formData.lnbits_allowed_users=[...e,t],this.formAddUser="")},removeAllowedUser(t){let e=this.formData.lnbits_allowed_users;this.formData.lnbits_allowed_users=e.filter((e=>e!==t))},addAdminUser(){let t=this.formAddAdmin,e=this.formData.lnbits_admin_users;t&&t.length&&!e.includes(t)&&(this.formData.lnbits_admin_users=[...e,t],this.formAddAdmin="")},removeAdminUser(t){let e=this.formData.lnbits_admin_users;this.formData.lnbits_admin_users=e.filter((e=>e!==t))}}}),window.app.component("lnbits-admin-server",{props:["form-data"],template:"#lnbits-admin-server",mixins:[window.windowMixin],data:()=>({currencies:[]}),async created(){this.currencies=await LNbits.api.getCurrencies()}}),window.app.component("lnbits-admin-extensions",{props:["form-data"],template:"#lnbits-admin-extensions",mixins:[window.windowMixin],data:()=>({formAddExtensionsManifest:""}),methods:{addExtensionsManifest(){const t=this.formAddExtensionsManifest.trim(),e=this.formData.lnbits_extensions_manifests;t&&t.length&&!e.includes(t)&&(this.formData.lnbits_extensions_manifests=[...e,t],this.formAddExtensionsManifest="")},removeExtensionsManifest(t){const e=this.formData.lnbits_extensions_manifests;this.formData.lnbits_extensions_manifests=e.filter((e=>e!==t))}}}),window.app.component("lnbits-admin-notifications",{props:["form-data"],template:"#lnbits-admin-notifications",mixins:[window.windowMixin],data:()=>({nostrNotificationIdentifier:"",emailNotificationAddress:""}),methods:{sendTestEmail(){LNbits.api.request("GET","/admin/api/v1/testemail",this.g.user.wallets[0].adminkey).then((t=>{if("error"===t.data.status)throw new Error(t.data.message);this.$q.notify({message:"Test email sent!",color:"positive"})})).catch((t=>{this.$q.notify({message:t.message,color:"negative"})}))},addNostrNotificationIdentifier(){const t=this.nostrNotificationIdentifier.trim(),e=this.formData.lnbits_nostr_notifications_identifiers;t&&t.length&&!e.includes(t)&&(this.formData.lnbits_nostr_notifications_identifiers=[...e,t],this.nostrNotificationIdentifier="")},removeNostrNotificationIdentifier(t){const e=this.formData.lnbits_nostr_notifications_identifiers;this.formData.lnbits_nostr_notifications_identifiers=e.filter((e=>e!==t))},addEmailNotificationAddress(){const t=this.emailNotificationAddress.trim(),e=this.formData.lnbits_email_notifications_to_emails;t&&t.length&&!e.includes(t)&&(this.formData.lnbits_email_notifications_to_emails=[...e,t],this.emailNotificationAddress="")},removeEmailNotificationAddress(t){const e=this.formData.lnbits_email_notifications_to_emails;this.formData.lnbits_email_notifications_to_emails=e.filter((e=>e!==t))}}}),window.app.component("lnbits-admin-site-customisation",{props:["form-data"],template:"#lnbits-admin-site-customisation",mixins:[window.windowMixin],data:()=>({lnbits_theme_options:["classic","bitcoin","flamingo","cyber","freedom","mint","autumn","monochrome","salvador"],colors:["primary","secondary","accent","positive","negative","info","warning","red","yellow","orange"],reactionOptions:["none","confettiBothSides","confettiFireworks","confettiStars","confettiTop"],globalBorderOptions:["retro-border","hard-border","neon-border","no-border"]}),methods:{}}),window.app.component("lnbits-admin-library",{props:["form-data"],template:"#lnbits-admin-library",mixins:[window.windowMixin],data:()=>({library_images:[]}),async created(){await this.getUploadedImages()},methods:{onImageInput(t){const e=t.target.files[0];e&&this.uploadImage(e)},uploadImage(t){const e=new FormData;e.append("file",t),LNbits.api.request("POST","/admin/api/v1/images",this.g.user.wallets[0].adminkey,e,{headers:{"Content-Type":"multipart/form-data"}}).then((()=>{this.$q.notify({type:"positive",message:"Image uploaded!",icon:null}),this.getUploadedImages()})).catch(LNbits.utils.notifyApiError)},getUploadedImages(){LNbits.api.request("GET","/admin/api/v1/images",this.g.user.wallets[0].inkey).then((t=>{this.library_images=t.data.map((t=>({...t,url:`${window.origin}/${t.directory}/${t.filename}`})))})).catch(LNbits.utils.notifyApiError)},deleteImage(t){LNbits.utils.confirmDialog("Are you sure you want to delete this image?").onOk((()=>{LNbits.api.request("DELETE",`/admin/api/v1/images/${t}`,this.g.user.wallets[0].adminkey).then((()=>{this.$q.notify({type:"positive",message:"Image deleted!",icon:null}),this.getUploadedImages()})).catch(LNbits.utils.notifyApiError)}))}}}),window.app.component("lnbits-admin-audit",{props:["form-data"],template:"#lnbits-admin-audit",mixins:[window.windowMixin],data:()=>({formAddIncludePath:"",formAddExcludePath:"",formAddIncludeResponseCode:""}),methods:{addIncludePath(){if(""===this.formAddIncludePath)return;const t=this.formData.lnbits_audit_include_paths;t.includes(this.formAddIncludePath)||(this.formData.lnbits_audit_include_paths=[...t,this.formAddIncludePath]),this.formAddIncludePath=""},removeIncludePath(t){this.formData.lnbits_audit_include_paths=this.formData.lnbits_audit_include_paths.filter((e=>e!==t))},addExcludePath(){if(""===this.formAddExcludePath)return;const t=this.formData.lnbits_audit_exclude_paths;t.includes(this.formAddExcludePath)||(this.formData.lnbits_audit_exclude_paths=[...t,this.formAddExcludePath]),this.formAddExcludePath=""},removeExcludePath(t){this.formData.lnbits_audit_exclude_paths=this.formData.lnbits_audit_exclude_paths.filter((e=>e!==t))},addIncludeResponseCode(){if(""===this.formAddIncludeResponseCode)return;const t=this.formData.lnbits_audit_http_response_codes;t.includes(this.formAddIncludeResponseCode)||(this.formData.lnbits_audit_http_response_codes=[...t,this.formAddIncludeResponseCode]),this.formAddIncludeResponseCode=""},removeIncludeResponseCode(t){this.formData.lnbits_audit_http_response_codes=this.formData.lnbits_audit_http_response_codes.filter((e=>e!==t))}}}),window.app.component("lnbits-new-user-wallet",{props:["form-data"],template:"#lnbits-new-user-wallet",mixins:[window.windowMixin],data:()=>({newWallet:{walletType:"lightning",name:"",sharedWalletId:""}}),methods:{async submitRejectWalletInvitation(){try{const t=this.g.user.extra.wallet_invite_requests||[],e=t.find((t=>t.to_wallet_id===this.newWallet.sharedWalletId));if(!e)return void Quasar.Notify.create({message:"Cannot find invitation for the selected wallet.",type:"warning"});await LNbits.api.request("DELETE",`/api/v1/wallet/share/invite/${e.request_id}`,this.g.wallet.adminkey),Quasar.Notify.create({message:"Invitation rejected.",type:"positive"}),this.g.user.extra.wallet_invite_requests=t.filter((t=>t.request_id!==e.request_id))}catch(t){LNbits.utils.notifyApiError(t)}},async submitAddWallet(){console.log("### submitAddWallet",this.newWallet);const t=this.newWallet;if("lightning"!==t.walletType||t.name)if("lightning-shared"!==t.walletType||t.sharedWalletId)try{await LNbits.api.createWallet(this.g.user.wallets[0],t.name,t.walletType,{shared_wallet_id:t.sharedWalletId})}catch(t){console.warn(t),LNbits.utils.notifyApiError(t)}else this.$q.notify({message:"Missing a shared wallet ID",color:"warning"});else this.$q.notify({message:"Please enter a name for the wallet",color:"warning"})}}}),window.app.component("lnbits-qrcode",{mixins:[window.windowMixin],template:"#lnbits-qrcode",components:{QrcodeVue:QrcodeVue},props:{value:{type:String,required:!0},nfc:{type:Boolean,default:!1},showButtons:{type:Boolean,default:!0},href:{type:String,default:""},margin:{type:Number,default:3},maxWidth:{type:Number,default:450},logo:{type:String,default:LNBITS_QR_LOGO}},data:()=>({nfcTagWriting:!1,nfcSupported:"undefined"!=typeof NDEFReader}),methods:{clickQrCode(t){if(""===this.href)return this.copyText(this.value),t.preventDefault(),t.stopPropagation(),!1},async writeNfcTag(){try{if(!this.nfcSupported)throw{toString:function(){return"NFC not supported on this device or browser."}};const t=new NDEFReader;this.nfcTagWriting=!0,this.$q.notify({message:"Tap your NFC tag to write the LNURL-withdraw link to it."}),await t.write({records:[{recordType:"url",data:this.value,lang:"en"}]}),this.nfcTagWriting=!1,this.$q.notify({type:"positive",message:"NFC tag written successfully."})}catch(t){this.nfcTagWriting=!1,this.$q.notify({type:"negative",message:t?t.toString():"An unexpected error has occurred."})}},downloadSVG(){const t=this.$refs.qrCode.$el;if(!t)return void console.error("SVG element not found");let e=(new XMLSerializer).serializeToString(t);e.match(/^]+xmlns="http:\/\/www\.w3\.org\/2000\/svg"/)||(e=e.replace(/^({tab:"bech32",lnurl:""}),methods:{setLnurl(){if("bech32"==this.tab){const t=(new TextEncoder).encode(this.url),e=NostrTools.nip19.encodeBytes("lnurl",t);this.lnurl=`lightning:${e.toUpperCase()}`}else"lud17"==this.tab&&(this.url.startsWith("http://")?this.lnurl=this.url.replace("http://",this.prefix+"://"):this.lnurl=this.url.replace("https://",this.prefix+"://"));this.$emit("update:lnurl",this.lnurl)}},watch:{url(){this.setLnurl()},tab(){this.setLnurl()}},created(){this.setLnurl()}}),window.app.component("lnbits-extension-settings-form",{name:"lnbits-extension-settings-form",template:"#lnbits-extension-settings-form",props:["options","adminkey","endpoint"],methods:{async updateSettings(){if(!this.settings)return Quasar.Notify.create({message:"No settings to update",type:"negative"});try{const{data:t}=await LNbits.api.request("PUT",this.endpoint,this.adminkey,this.settings);this.settings=t}catch(t){LNbits.utils.notifyApiError(t)}},async getSettings(){try{const{data:t}=await LNbits.api.request("GET",this.endpoint,this.adminkey);this.settings=t}catch(t){LNbits.utils.notifyApiError(t)}},async resetSettings(){LNbits.utils.confirmDialog("Are you sure you want to reset the settings?").onOk((async()=>{try{await LNbits.api.request("DELETE",this.endpoint,this.adminkey),await this.getSettings()}catch(t){LNbits.utils.notifyApiError(t)}}))}},async created(){await this.getSettings()},data:()=>({settings:void 0})}),window.app.component("lnbits-extension-settings-btn-dialog",{template:"#lnbits-extension-settings-btn-dialog",name:"lnbits-extension-settings-btn-dialog",props:["options","adminkey","endpoint"],data:()=>({show:!1})}),window.app.component("lnbits-data-fields",{name:"lnbits-data-fields",template:"#lnbits-data-fields",props:["fields","hide-advanced"],data:()=>({fieldTypes:[{label:"Text",value:"str"},{label:"Integer",value:"int"},{label:"Float",value:"float"},{label:"Boolean",value:"bool"},{label:"Date Time",value:"datetime"},{label:"JSON",value:"json"},{label:"Wallet Select",value:"wallet"},{label:"Currency Select",value:"currency"}],fieldsTable:{columns:[{name:"name",align:"left",label:"Field Name",field:"name",sortable:!0},{name:"type",align:"left",label:"Type",field:"type",sortable:!1},{name:"label",align:"left",label:"UI Label",field:"label",sortable:!0},{name:"hint",align:"left",label:"UI Hint",field:"hint",sortable:!1},{name:"optional",align:"left",label:"Optional",field:"optional",sortable:!1}],pagination:{sortBy:"name",rowsPerPage:100,page:1,rowsNumber:100},search:null,hideEmpty:!0}}),methods:{addField:function(){this.fields.push({name:"field_name_"+(this.fields.length+1),type:"text",label:"",hint:"",optional:!0,sortable:!0,searchable:!0,editable:!0,fields:[]})},removeField:function(t){const e=this.fields.indexOf(t);e>-1&&this.fields.splice(e,1)}},async created(){this.hideAdvanced||this.fieldsTable.columns.push({name:"editable",align:"left",label:"UI Editable",field:"editable",sortable:!1},{name:"sortable",align:"left",label:"Sortable",field:"sortable",sortable:!1},{name:"searchable",align:"left",label:"Searchable",field:"searchable",sortable:!1})}}),window.app.component("payment-list",{name:"payment-list",template:"#payment-list",props:["update","lazy","wallet"],mixins:[window.windowMixin],data(){return{denomination:LNBITS_DENOMINATION,payments:[],paymentsTable:{columns:[{name:"time",align:"left",label:this.$t("memo")+"/"+this.$t("date"),field:"date",sortable:!0},{name:"amount",align:"right",label:this.$t("amount")+" ("+LNBITS_DENOMINATION+")",field:"sat",sortable:!0}],pagination:{rowsPerPage:10,page:1,sortBy:"time",descending:!0,rowsNumber:10},search:"",filter:{"status[ne]":"failed"},loading:!1},searchDate:{from:null,to:null},searchStatus:{success:!0,pending:!0,failed:!1,incoming:!0,outgoing:!0},exportTagName:"",exportPaymentTagList:[],paymentsCSV:{columns:[{name:"pending",align:"left",label:"Pending",field:"pending"},{name:"memo",align:"left",label:this.$t("memo"),field:"memo"},{name:"time",align:"left",label:this.$t("date"),field:"date",sortable:!0},{name:"amount",align:"right",label:this.$t("amount")+" ("+LNBITS_DENOMINATION+")",field:"sat",sortable:!0},{name:"fee",align:"right",label:this.$t("fee")+" (m"+LNBITS_DENOMINATION+")",field:"fee"},{name:"tag",align:"right",label:this.$t("tag"),field:"tag"},{name:"payment_hash",align:"right",label:this.$t("payment_hash"),field:"payment_hash"},{name:"payment_proof",align:"right",label:this.$t("payment_proof"),field:"payment_proof"},{name:"webhook",align:"right",label:this.$t("webhook"),field:"webhook"},{name:"fiat_currency",align:"right",label:"Fiat Currency",field:t=>t.extra.wallet_fiat_currency},{name:"fiat_amount",align:"right",label:"Fiat Amount",field:t=>t.extra.wallet_fiat_amount}],preimage:null,loading:!1},hodlInvoice:{show:!1,payment:null,preimage:null}}},computed:{currentWallet(){return this.wallet||this.g.wallet},filteredPayments(){const t=this.paymentsTable.search;return t&&""!==t?LNbits.utils.search(this.payments,t):this.payments},paymentsOmitter(){return this.$q.screen.lt.md&&this.mobileSimple?this.payments.length>0?[this.payments[0]]:[]:this.payments},pendingPaymentsExist(){return-1!==this.payments.findIndex((t=>t.pending))}},methods:{searchByDate(){"string"==typeof this.searchDate&&(this.searchDate={from:this.searchDate,to:this.searchDate}),this.searchDate.from&&(this.paymentsTable.filter["time[ge]"]=this.searchDate.from+"T00:00:00"),this.searchDate.to&&(this.paymentsTable.filter["time[le]"]=this.searchDate.to+"T23:59:59"),this.fetchPayments()},clearDateSeach(){this.searchDate={from:null,to:null},delete this.paymentsTable.filter["time[ge]"],delete this.paymentsTable.filter["time[le]"],this.fetchPayments()},fetchPayments(t){this.$emit("filter-changed",{...this.paymentsTable.filter});const e=LNbits.utils.prepareFilterQuery(this.paymentsTable,t);return LNbits.api.getPayments(this.currentWallet,e).then((t=>{this.paymentsTable.loading=!1,this.paymentsTable.pagination.rowsNumber=t.data.total,this.payments=t.data.data.map((t=>LNbits.map.payment(t)))})).catch((t=>{this.paymentsTable.loading=!1,g.user.admin?this.fetchPaymentsAsAdmin(this.currentWallet.id,e):LNbits.utils.notifyApiError(t)}))},fetchPaymentsAsAdmin(t,e){return e=(e||"")+"&wallet_id="+t,LNbits.api.request("GET","/api/v1/payments/all/paginated?"+e).then((t=>{this.paymentsTable.loading=!1,this.paymentsTable.pagination.rowsNumber=t.data.total,this.payments=t.data.data.map((t=>LNbits.map.payment(t)))})).catch((t=>{this.paymentsTable.loading=!1,LNbits.utils.notifyApiError(t)}))},checkPayment(t){LNbits.api.getPayment(this.g.wallet,t).then((t=>{this.update=!this.update,"success"==t.data.status&&Quasar.Notify.create({type:"positive",message:this.$t("payment_successful")}),"pending"==t.data.status&&Quasar.Notify.create({type:"info",message:this.$t("payment_pending")})})).catch(LNbits.utils.notifyApiError)},showHoldInvoiceDialog(t){this.hodlInvoice.show=!0,this.hodlInvoice.preimage="",this.hodlInvoice.payment=t},cancelHoldInvoice(t){LNbits.api.cancelInvoice(this.g.wallet,t).then((()=>{this.update=!this.update,Quasar.Notify.create({type:"positive",message:this.$t("invoice_cancelled")})})).catch(LNbits.utils.notifyApiError)},settleHoldInvoice(t){LNbits.api.settleInvoice(this.g.wallet,t).then((()=>{this.update=!this.update,Quasar.Notify.create({type:"positive",message:this.$t("invoice_settled")})})).catch(LNbits.utils.notifyApiError)},paymentTableRowKey:t=>t.payment_hash+t.amount,exportCSV(t=!1){const e=this.paymentsTable.pagination,a={sortby:e.sortBy??"time",direction:e.descending?"desc":"asc"},s=new URLSearchParams(a);LNbits.api.getPayments(this.g.wallet,s).then((e=>{let a=e.data.data.map(LNbits.map.payment),s=this.paymentsCSV.columns;if(t){this.exportPaymentTagList.length&&(a=a.filter((t=>this.exportPaymentTagList.includes(t.tag))));const t=Object.keys(a.reduce(((t,e)=>({...t,...e.details})),{})).map((t=>({name:t,align:"right",label:t.charAt(0).toUpperCase()+t.slice(1).replace(/([A-Z])/g," $1"),field:e=>e.details[t],format:t=>"object"==typeof t?JSON.stringify(t):t})));s=this.paymentsCSV.columns.concat(t)}LNbits.utils.exportCSV(s,a,this.g.wallet.name+"-payments")}))},addFilterTag(){if(!this.exportTagName)return;const t=this.exportTagName.trim();this.exportPaymentTagList=this.exportPaymentTagList.filter((e=>e!==t)),this.exportPaymentTagList.push(t),this.exportTagName=""},removeExportTag(t){this.exportPaymentTagList=this.exportPaymentTagList.filter((e=>e!==t))},formatCurrency(t,e){try{return LNbits.utils.formatCurrency(t,e)}catch(e){return console.error(e),`${t} ???`}},handleFilterChanged(){const{success:t,pending:e,failed:a,incoming:s,outgoing:i}=this.searchStatus;delete this.paymentsTable.filter["status[ne]"],delete this.paymentsTable.filter["status[eq]"],t&&e&&a||(t&&e?this.paymentsTable.filter["status[ne]"]="failed":t&&a?this.paymentsTable.filter["status[ne]"]="pending":a&&e?this.paymentsTable.filter["status[ne]"]="success":t?this.paymentsTable.filter["status[eq]"]="success":e?this.paymentsTable.filter["status[eq]"]="pending":a&&(this.paymentsTable.filter["status[eq]"]="failed")),delete this.paymentsTable.filter["amount[ge]"],delete this.paymentsTable.filter["amount[le]"],s&&i||(s?this.paymentsTable.filter["amount[ge]"]=0:i&&(this.paymentsTable.filter["amount[le]"]=0))}},watch:{"paymentsTable.search":{handler(){const t={};this.paymentsTable.search&&(t.search=this.paymentsTable.search),this.fetchPayments()}},lazy(t){!0===t&&this.fetchPayments()},update(){this.fetchPayments()},"g.updatePayments"(){this.fetchPayments()},"g.wallet":{handler(t){this.fetchPayments()},deep:!0}},created(){void 0===this.lazy&&this.fetchPayments()}}),window.app.component(QrcodeVue),window.app.component("lnbits-extension-rating",{template:"#lnbits-extension-rating",name:"lnbits-extension-rating",props:["rating"]}),window.app.component("lnbits-fsat",{template:"{{ fsat }}",props:{amount:{type:Number,default:0}},computed:{fsat(){return LNbits.utils.formatSat(this.amount)}}}),window.app.component("lnbits-wallet-list",{mixins:[window.windowMixin],template:"#lnbits-wallet-list",props:["balance"],data:()=>({activeWallet:null,balance:0,walletName:"",LNBITS_DENOMINATION:LNBITS_DENOMINATION}),methods:{createWallet(){this.$emit("wallet-action",{action:"create-wallet"})}},created(){document.addEventListener("updateWalletBalance",this.updateWalletBalance)}}),window.app.component("lnbits-extension-list",{mixins:[window.windowMixin],template:"#lnbits-extension-list",data:()=>({extensions:[],searchTerm:""}),watch:{"g.user.extensions":{handler(t){this.loadExtensions()},deep:!0}},computed:{userExtensions(){return this.updateUserExtensions(this.searchTerm)}},methods:{async loadExtensions(){try{const{data:t}=await LNbits.api.request("GET","/api/v1/extension");this.extensions=t.map((t=>LNbits.map.extension(t))).sort(((t,e)=>t.name.localeCompare(e.name)))}catch(t){LNbits.utils.notifyApiError(t)}},updateUserExtensions(t){const e=window.location.pathname,a=this.g.user.extensions;return this.extensions.filter((t=>a.includes(t.code))).filter((e=>!t||`${e.code} ${e.name} ${e.short_description} ${e.url}`.toLocaleLowerCase().includes(t.toLocaleLowerCase()))).map((t=>(t.isActive=e.startsWith(t.url),t)))}},async created(){await this.loadExtensions()}}),window.app.component("lnbits-manage",{mixins:[window.windowMixin],template:"#lnbits-manage",props:["showAdmin","showNode","showExtensions","showUsers","showAudit"],methods:{isActive:t=>window.location.pathname===t},data:()=>({extensions:[]})}),window.app.component("lnbits-payment-details",{mixins:[window.windowMixin],template:"#lnbits-payment-details",props:["payment"],mixins:[window.windowMixin],data:()=>({LNBITS_DENOMINATION:LNBITS_DENOMINATION}),computed:{hasPreimage(){return this.payment.preimage&&"0000000000000000000000000000000000000000000000000000000000000000"!==this.payment.preimage},hasExpiry(){return!!this.payment.expiry},hasSuccessAction(){return this.hasPreimage&&this.payment.extra&&this.payment.extra.success_action},webhookStatusColor(){return this.payment.webhook_status>=300||this.payment.webhook_status<0?"red-10":this.payment.webhook_status?"green-10":"cyan-7"},webhookStatusText(){return this.payment.webhook_status?this.payment.webhook_status:"not sent yet"},hasTag(){return this.payment.extra&&!!this.payment.extra.tag},extras(){if(!this.payment.extra)return[];let t=_.omit(this.payment.extra,["tag","success_action"]);return Object.keys(t).map((e=>({key:e,value:t[e]})))}}}),window.app.component("lnbits-lnurlpay-success-action",{mixins:[window.windowMixin],template:"#lnbits-lnurlpay-success-action",props:["payment","success_action"],data(){return{decryptedValue:this.success_action.ciphertext}},mounted(){if("aes"!==this.success_action.tag)return null;decryptLnurlPayAES(this.success_action,this.payment.preimage).then((t=>{this.decryptedValue=t}))}}),window.app.component("lnbits-notifications-btn",{template:"#lnbits-notifications-btn",mixins:[window.windowMixin],props:["pubkey"],data:()=>({isSupported:!1,isSubscribed:!1,isPermissionGranted:!1,isPermissionDenied:!1}),methods:{urlB64ToUint8Array(t){const e=(t+"=".repeat((4-t.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/"),a=atob(e),s=new Uint8Array(a.length);for(let t=0;te!==t)),this.$q.localStorage.set("lnbits.webpush.subscribedUsers",JSON.stringify(e))},isUserSubscribed(t){return(JSON.parse(this.$q.localStorage.getItem("lnbits.webpush.subscribedUsers"))||[]).includes(t)},subscribe(){this.isSupported&&!this.isPermissionDenied&&(Notification.requestPermission().then((t=>{this.isPermissionGranted="granted"===t,this.isPermissionDenied="denied"===t})).catch(console.log),navigator.serviceWorker.ready.then((t=>{navigator.serviceWorker.getRegistration().then((t=>{t.pushManager.getSubscription().then((e=>{if(null===e||!this.isUserSubscribed(this.g.user.id)){const e={applicationServerKey:this.urlB64ToUint8Array(this.pubkey),userVisibleOnly:!0};t.pushManager.subscribe(e).then((t=>{LNbits.api.request("POST","/api/v1/webpush",null,{subscription:JSON.stringify(t)}).then((t=>{this.saveUserSubscribed(t.data.user),this.isSubscribed=!0})).catch(LNbits.utils.notifyApiError)}))}})).catch(console.log)}))})))},unsubscribe(){navigator.serviceWorker.ready.then((t=>{t.pushManager.getSubscription().then((t=>{t&&LNbits.api.request("DELETE","/api/v1/webpush?endpoint="+btoa(t.endpoint),null).then((()=>{this.removeUserSubscribed(this.g.user.id),this.isSubscribed=!1})).catch(LNbits.utils.notifyApiError)}))})).catch(console.log)},checkSupported(){let t="https:"===window.location.protocol,e="serviceWorker"in navigator,a="Notification"in window,s="PushManager"in window;return this.isSupported=t&&e&&a&&s,this.isSupported||console.log("Notifications disabled because requirements are not met:",{HTTPS:t,"Service Worker API":e,"Notification API":a,"Push API":s}),this.isSupported},async updateSubscriptionStatus(){await navigator.serviceWorker.ready.then((t=>{t.pushManager.getSubscription().then((t=>{this.isSubscribed=!!t&&this.isUserSubscribed(this.g.user.id)}))})).catch(console.log)}},created(){this.isPermissionDenied="denied"===Notification.permission,this.checkSupported()&&this.updateSubscriptionStatus()}}),window.app.component("lnbits-dynamic-fields",{template:"#lnbits-dynamic-fields",mixins:[window.windowMixin],props:["options","modelValue"],data:()=>({formData:null,rules:[t=>!!t||"Field is required"]}),methods:{applyRules(t){return t?this.rules:[]},buildData(t,e={}){return t.reduce(((t,a)=>(a.options?.length?t[a.name]=this.buildData(a.options,e[a.name]):t[a.name]=e[a.name]??a.default,t)),{})},handleValueChanged(){this.$emit("update:model-value",this.formData)}},created(){this.formData=this.buildData(this.options,this.modelValue)}}),window.app.component("lnbits-dynamic-chips",{template:"#lnbits-dynamic-chips",mixins:[window.windowMixin],props:["modelValue"],data:()=>({chip:"",chips:[]}),methods:{addChip(){this.chip&&(this.chips.push(this.chip),this.chip="",this.$emit("update:model-value",this.chips.join(",")))},removeChip(t){this.chips.splice(t,1),this.$emit("update:model-value",this.chips.join(","))}},created(){"string"==typeof this.modelValue?this.chips=this.modelValue.split(","):this.chips=[...this.modelValue]}}),window.app.component("lnbits-update-balance",{template:"#lnbits-update-balance",mixins:[window.windowMixin],props:["wallet_id","small_btn"],computed:{denomination:()=>LNBITS_DENOMINATION,admin:()=>user.super_user},data:()=>({credit:0}),methods:{updateBalance(t){LNbits.api.updateBalance(t.value,this.wallet_id).then((e=>{if(!0!==e.data.success)throw new Error(e.data);credit=parseInt(t.value),Quasar.Notify.create({type:"positive",message:this.$t("credit_ok",{amount:credit}),icon:null}),this.credit=0,t.value=0,t.set()})).catch(LNbits.utils.notifyApiError)}}}),window.app.component("user-id-only",{template:"#user-id-only",mixins:[window.windowMixin],props:{allowed_new_users:Boolean,authAction:String,authMethod:String,usr:String,wallet:String},data(){return{user:this.usr,walletName:this.wallet}},methods:{showLogin(t){this.$emit("show-login",t)},showRegister(t){this.$emit("show-register",t)},loginUsr(){this.$emit("update:usr",this.user),this.$emit("login-usr")},createWallet(){this.$emit("update:wallet",this.walletName),this.$emit("create-wallet")}},computed:{showInstantLogin(){return"username-password"!==this.authMethod||"register"!==this.authAction}},created(){}}),window.app.component("username-password",{template:"#username-password",mixins:[window.windowMixin],props:{allowed_new_users:Boolean,authMethods:Array,authAction:String,username:String,password_1:String,password_2:String,resetKey:String},data(){return{oauth:["nostr-auth-nip98","google-auth","github-auth","keycloak-auth"],username:this.userName,password:this.password_1,passwordRepeat:this.password_2,reset_key:this.resetKey,keycloakOrg:LNBITS_AUTH_KEYCLOAK_ORG||"Keycloak",keycloakIcon:LNBITS_AUTH_KEYCLOAK_ICON}},methods:{login(){this.$emit("update:userName",this.username),this.$emit("update:password_1",this.password),this.$emit("login")},register(){this.$emit("update:userName",this.username),this.$emit("update:password_1",this.password),this.$emit("update:password_2",this.passwordRepeat),this.$emit("register")},reset(){this.$emit("update:resetKey",this.reset_key),this.$emit("update:password_1",this.password),this.$emit("update:password_2",this.passwordRepeat),this.$emit("reset")},validateUsername:t=>new RegExp("^(?=[a-zA-Z0-9._]{2,20}$)(?!.*[_.]{2})[^_.].*[^_.]$").test(t),async signInWithNostr(){try{const t=await this.createNostrToken();if(!t)return;resp=await LNbits.api.loginByProvider("nostr",{Authorization:t},{}),window.location.href="/wallet"}catch(t){console.warn(t);const e=t?.response?.data?.detail||`${t}`;Quasar.Notify.create({type:"negative",message:"Failed to sign in with Nostr.",caption:e})}},async createNostrToken(){try{if(!window.nostr?.signEvent)return void Quasar.Notify.create({type:"negative",message:"No Nostr signing app detected.",caption:'Is "window.nostr" present?'});const t=`${window.location}nostr`,e="POST",a=await NostrTools.nip98.getToken(t,e,(t=>async function(t){try{const{data:e}=await LNbits.api.getServerHealth();return t.created_at=e.server_time,await window.nostr.signEvent(t)}catch(t){console.error(t),Quasar.Notify.create({type:"negative",message:"Failed to sign nostr event.",caption:`${t}`})}}(t)),!0);if(!await NostrTools.nip98.validateToken(a,t,e))throw new Error("Invalid signed token!");return a}catch(t){console.warn(t),Quasar.Notify.create({type:"negative",message:"Failed create Nostr event.",caption:`${t}`})}}},computed:{showOauth(){return this.oauth.some((t=>this.authMethods.includes(t)))}},created(){}}),window.app.component("separator-text",{template:"#separator-text",props:{text:String,uppercase:{type:Boolean,default:!1},color:{type:String,default:"grey"}}}),window.app.component("lnbits-node-ranks",{props:["ranks"],data:()=>({stats:[{label:"Capacity",key:"capacity"},{label:"Channels",key:"channelcount"},{label:"Age",key:"age"},{label:"Growth",key:"growth"},{label:"Availability",key:"availability"}]}),template:"\n \n
\n
1ml Node Rank
\n
\n
\n
{{ stat.label }}
\n
\n {{ (ranks && ranks[stat.key]) ?? '-' }}\n
\n
\n
\n
\n
\n "}),window.app.component("lnbits-channel-stats",{props:["stats"],data:()=>({states:[{label:"Active",value:"active",color:"green"},{label:"Pending",value:"pending",color:"orange"},{label:"Inactive",value:"inactive",color:"grey"},{label:"Closed",value:"closed",color:"red"}]}),template:"\n \n
\n
Channels
\n
\n
\n
\n {{ state.label }}\n
\n
\n {{ (stats?.counts && stats.counts[state.value]) ?? \"-\" }}\n
\n
\n
\n
\n
\n "}),window.app.component("lnbits-stat",{props:["title","amount","msat","btc"],computed:{value(){return this.amount??(this.btc?LNbits.utils.formatSat(this.btc):LNbits.utils.formatMsat(this.msat))}},template:"\n \n \n
\n {{ title }}\n
\n
\n {{ value }}\n sats\n BTC\n
\n
\n
\n "}),window.app.component("lnbits-node-qrcode",{props:["info"],mixins:[window.windowMixin],template:'\n \n \n
\n
\n \n
\n No addresses available\n
\n
\n
\n
\n \n Public Key Click to copy \n \n \n
\n '}),window.app.component("lnbits-channel-balance",{props:["balance","color"],methods:{formatMsat:t=>LNbits.utils.formatMsat(t)},template:'\n
\n
\n \n Local: {{ formatMsat(balance.local_msat) }}\n sats\n \n \n Remote: {{ formatMsat(balance.remote_msat) }}\n sats\n \n
\n\n \n
\n \n {{ balance.alias }}\n \n
\n \n
\n '}),window.app.component("lnbits-date",{props:["ts"],computed:{date(){return LNbits.utils.formatDate(this.ts)},dateFrom(){return moment.utc(this.date).local().fromNow()}},template:"\n
\n {{ this.date }}\n {{ this.dateFrom }}\n
\n "}),window.app.component("lnbits-node-info",{props:["info"],data:()=>({showDialog:!1}),mixins:[window.windowMixin],methods:{shortenNodeId:t=>t?t.substring(0,5)+"..."+t.substring(t.length-5):"..."},template:"\n
\n
{{ this.info.alias }}
\n
\n
{{ this.info.backend_name }}
\n \n #{{ this.info.color }}\n \n
{{ shortenNodeId(this.info.id) }}
\n \n \n
\n \n \n \n
\n "}),window.app.component("lnbits-stat",{props:["title","amount","msat","btc"],computed:{value(){return this.amount??(this.btc?LNbits.utils.formatSat(this.btc):LNbits.utils.formatMsat(this.msat))}},template:"\n \n \n
\n {{ title }}\n
\n
\n {{ value }}\n sats\n BTC\n
\n
\n
\n "});const DynamicComponent={props:{fetchUrl:{type:String,required:!0},scripts:{type:Array,default:()=>[]}},data:()=>({keys:[]}),async mounted(){await this.loadDynamicContent()},methods:{loadScript:async t=>new Promise(((e,a)=>{const s=document.querySelector(`script[src="${t}"]`);s&&s.remove();const i=document.createElement("script");i.src=t,i.async=!0,i.onload=e,i.onerror=()=>a(new Error(`Failed to load script: ${t}`)),document.head.appendChild(i)})),async loadDynamicContent(){this.$q.loading.show();try{const t=this.fetchUrl.split("#")[0],e=await fetch(t,{credentials:"include",headers:{Accept:"text/html","X-Requested-With":"XMLHttpRequest"}}),a=await e.text(),s=new DOMParser,i=s.parseFromString(a,"text/html").querySelector("#window-vars-script");i&&new Function(i.innerHTML)(),await this.loadScript("/static/js/base.js");for(const t of this.scripts)await this.loadScript(t);const n=this.$router.currentRoute.value.meta.previousRouteName;n&&window.app._context.components[n]&&delete window.app._context.components[n];const o=`${this.$route.name}PageLogic`,l=window[o];if(!l)throw new Error(`Component logic '${o}' not found. Ensure it is defined in the script.`);l.mixins=l.mixins||[],window.windowMixin&&l.mixins.push(window.windowMixin),window.app.component(this.$route.name,{...l,template:a}),delete window[o],this.$forceUpdate()}catch(t){console.error("Error loading dynamic content:",t)}finally{this.$q.loading.hide()}}},watch:{$route(t,e){routes.map((t=>t.name)).includes(t.name)?(this.$router.currentRoute.value.meta.previousRouteName=e.name,this.loadDynamicContent()):console.log(`Route '${t.name}' is not valid. Leave this one to Fastapi.`)}},template:'\n \n '},routes=[{path:"/wallet",name:"Wallet",component:DynamicComponent,props:t=>{let e="/wallet";if(Object.keys(t.query).length>0){e+="?";for(const[a,s]of Object.entries(t.query))e+=`${a}=${s}&`;e=e.slice(0,-1)}return{fetchUrl:e,scripts:["/static/js/wallet.js"]}}},{path:"/extensions",name:"Extensions",component:DynamicComponent,props:{fetchUrl:"/extensions",scripts:["/static/js/extensions.js"]}},{path:"/node",name:"Node",component:PageNode},{path:"/node/public",name:"NodePublic",component:PageNodePublic},{path:"/payments",name:"Payments",component:PagePayments},{path:"/audit",name:"Audit",component:PageAudit},{path:"/wallets",name:"Wallets",component:PageWallets},{path:"/users",name:"Users",component:PageUsers},{path:"/admin",name:"Admin",component:PageAdmin},{path:"/account",name:"Account",component:PageAccount},{path:"/extensions/builder",name:"ExtensionsBuilder",component:PageExtensionBuilder}];window.router=VueRouter.createRouter({history:VueRouter.createWebHistory(),routes:routes}),window.app.mixin({computed:{isVueRoute(){const t=window.location.pathname,e=window.router.resolve(t);return e?.matched?.length>0}}}),window.app.use(VueQrcodeReader),window.app.use(Quasar,{config:{loading:{spinner:Quasar.QSpinnerBars}}}),window.app.use(window.i18n),window.app.provide("g",g),window.app.use(window.router),window.app.component("DynamicComponent",DynamicComponent),window.app.mount("#vue"); diff --git a/lnbits/static/js/init-app.js b/lnbits/static/js/init-app.js index 0b44a785..7165e9f7 100644 --- a/lnbits/static/js/init-app.js +++ b/lnbits/static/js/init-app.js @@ -148,15 +148,6 @@ const routes = [ scripts: ['/static/js/extensions.js'] } }, - { - path: '/extensions/builder', - name: 'ExtensionsBuilder', - component: DynamicComponent, - props: { - fetchUrl: '/extensions/builder', - scripts: ['/static/js/extensions_builder.js'] - } - }, { path: '/node', name: 'Node', @@ -196,6 +187,11 @@ const routes = [ path: '/account', name: 'Account', component: PageAccount + }, + { + path: '/extensions/builder', + name: 'ExtensionsBuilder', + component: PageExtensionBuilder } ] diff --git a/lnbits/static/js/extensions_builder.js b/lnbits/static/js/pages/extensions_builder.js similarity index 98% rename from lnbits/static/js/extensions_builder.js rename to lnbits/static/js/pages/extensions_builder.js index ee2c41ad..39c2276d 100644 --- a/lnbits/static/js/extensions_builder.js +++ b/lnbits/static/js/pages/extensions_builder.js @@ -1,5 +1,7 @@ -window.ExtensionsBuilderPageLogic = { - data: function () { +window.PageExtensionBuilder = { + template: '#page-extension-builder', + mixins: [windowMixin], + data() { return { step: 1, previewStepNames: { @@ -92,7 +94,6 @@ window.ExtensionsBuilderPageLogic = { paymentActionAmountFields() { const amount_source = this.extensionData.public_page.action_fields.amount_source - console.log('### amount_source:', amount_source) if (!amount_source) return [''] if (amount_source === 'owner_data') { @@ -325,7 +326,7 @@ window.ExtensionsBuilderPageLogic = { this.extensionDataCleanString = JSON.stringify(this.extensionData) } }, - created: function () { + created() { this.initBasicData() const extensionData = this.$q.localStorage.getItem( @@ -345,6 +346,5 @@ window.ExtensionsBuilderPageLogic = { setTimeout(() => { this.refreshIframe() }, 1000) - }, - mixins: [windowMixin] + } } diff --git a/lnbits/static/vendor.json b/lnbits/static/vendor.json index 3f1525a7..21f27574 100644 --- a/lnbits/static/vendor.json +++ b/lnbits/static/vendor.json @@ -43,6 +43,7 @@ "js/lnurl.js" ], "components": [ + "js/pages/extensions_builder.js", "js/pages/payments.js", "js/pages/node.js", "js/pages/node-public.js", diff --git a/lnbits/templates/pages.vue b/lnbits/templates/pages.vue index 55810c6d..a26c202b 100644 --- a/lnbits/templates/pages.vue +++ b/lnbits/templates/pages.vue @@ -1,4 +1,4 @@ {% include('pages/payments.vue') %} {% include('pages/node.vue') %} {% include('pages/audit.vue') %} {% include('pages/wallets.vue') %} {% include('pages/users.vue') %} {% include('pages/admin.vue') %} {% -include('pages/account.vue') %} +include('pages/account.vue') %} {% include('pages/extensions_builder.vue') %} diff --git a/lnbits/templates/pages/extensions_builder.vue b/lnbits/templates/pages/extensions_builder.vue new file mode 100644 index 00000000..a53f0954 --- /dev/null +++ b/lnbits/templates/pages/extensions_builder.vue @@ -0,0 +1,878 @@ + diff --git a/package.json b/package.json index 8a3db31a..0f94182d 100644 --- a/package.json +++ b/package.json @@ -95,6 +95,7 @@ "js/lnurl.js" ], "components": [ + "js/pages/extensions_builder.js", "js/pages/payments.js", "js/pages/node.js", "js/pages/node-public.js",