From ffd2a62c3f7df94365980302fef3bc3376b48182 Mon Sep 17 00:00:00 2001 From: Florian Dold Date: Mon, 3 Aug 2020 13:00:48 +0530 Subject: modularize repo, use pnpm, improve typechecking --- .../taler-wallet-webextension/src/pages/pay.tsx | 180 ++++++++ .../src/pages/payback.tsx | 30 ++ .../taler-wallet-webextension/src/pages/popup.tsx | 502 +++++++++++++++++++++ .../taler-wallet-webextension/src/pages/refund.tsx | 89 ++++ .../src/pages/reset-required.tsx | 93 ++++ .../src/pages/return-coins.tsx | 30 ++ .../taler-wallet-webextension/src/pages/tip.tsx | 103 +++++ .../src/pages/welcome.tsx | 190 ++++++++ .../src/pages/withdraw.tsx | 229 ++++++++++ 9 files changed, 1446 insertions(+) create mode 100644 packages/taler-wallet-webextension/src/pages/pay.tsx create mode 100644 packages/taler-wallet-webextension/src/pages/payback.tsx create mode 100644 packages/taler-wallet-webextension/src/pages/popup.tsx create mode 100644 packages/taler-wallet-webextension/src/pages/refund.tsx create mode 100644 packages/taler-wallet-webextension/src/pages/reset-required.tsx create mode 100644 packages/taler-wallet-webextension/src/pages/return-coins.tsx create mode 100644 packages/taler-wallet-webextension/src/pages/tip.tsx create mode 100644 packages/taler-wallet-webextension/src/pages/welcome.tsx create mode 100644 packages/taler-wallet-webextension/src/pages/withdraw.tsx (limited to 'packages/taler-wallet-webextension/src/pages') diff --git a/packages/taler-wallet-webextension/src/pages/pay.tsx b/packages/taler-wallet-webextension/src/pages/pay.tsx new file mode 100644 index 000000000..2abd423bd --- /dev/null +++ b/packages/taler-wallet-webextension/src/pages/pay.tsx @@ -0,0 +1,180 @@ +/* + This file is part of TALER + (C) 2015 GNUnet e.V. + + TALER is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + TALER is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + TALER; see the file COPYING. If not, see + */ + +/** + * Page shown to the user to confirm entering + * a contract. + */ + +/** + * Imports. + */ +import * as i18n from "../i18n"; + + +import { renderAmount, ProgressButton } from "../renderHtml"; +import * as wxApi from "../wxApi"; + +import React, { useState, useEffect } from "react"; + +import { Amounts, AmountJson, walletTypes, talerTypes } from "taler-wallet-core"; + +function TalerPayDialog({ talerPayUri }: { talerPayUri: string }): JSX.Element { + const [payStatus, setPayStatus] = useState(); + const [payErrMsg, setPayErrMsg] = useState(""); + const [numTries, setNumTries] = useState(0); + const [loading, setLoading] = useState(false); + let amountEffective: AmountJson | undefined = undefined; + + useEffect(() => { + const doFetch = async (): Promise => { + const p = await wxApi.preparePay(talerPayUri); + setPayStatus(p); + }; + doFetch(); + }, [numTries, talerPayUri]); + + if (!payStatus) { + return Loading payment information ...; + } + + let insufficientBalance = false; + if (payStatus.status == "insufficient-balance") { + insufficientBalance = true; + } + + if (payStatus.status === "payment-possible") { + amountEffective = Amounts.parseOrThrow(payStatus.amountEffective); + } + + if (payStatus.status === walletTypes.PreparePayResultType.AlreadyConfirmed && numTries === 0) { + return ( + + You have already paid for this article. Click{" "} + here to view it again. + + ); + } + + let contractTerms: talerTypes.ContractTerms; + + try { + contractTerms = talerTypes.codecForContractTerms().decode(payStatus.contractTerms); + } catch (e) { + // This should never happen, as the wallet is supposed to check the contract terms + // before storing them. + console.error(e); + console.log("raw contract terms were", payStatus.contractTerms); + return Invalid contract terms.; + } + + if (!contractTerms) { + return ( + + Error: did not get contract terms from merchant or wallet backend. + + ); + } + + let merchantName: React.ReactElement; + if (contractTerms.merchant && contractTerms.merchant.name) { + merchantName = {contractTerms.merchant.name}; + } else { + merchantName = (pub: {contractTerms.merchant_pub}); + } + + const amount = ( + {renderAmount(Amounts.parseOrThrow(contractTerms.amount))} + ); + + const doPayment = async (): Promise => { + if (payStatus.status !== "payment-possible") { + throw Error(`invalid state: ${payStatus.status}`); + } + const proposalId = payStatus.proposalId; + setNumTries(numTries + 1); + try { + setLoading(true); + const res = await wxApi.confirmPay(proposalId, undefined); + document.location.href = res.nextUrl; + } catch (e) { + console.error(e); + setPayErrMsg(e.message); + } + }; + + return ( +
+

+ + The merchant {merchantName} offers you to purchase: + +

+ {contractTerms.summary} +
+ {amountEffective ? ( + + The total price is {amount} + (plus {renderAmount(amountEffective)} fees). + + ) : ( + + The total price is {amount}. + + )} +

+ + {insufficientBalance ? ( +
+

+ Unable to pay: Your balance is insufficient. +

+
+ ) : null} + + {payErrMsg ? ( +
+

Payment failed: {payErrMsg}

+ +
+ ) : ( +
+ doPayment()} + > + {i18n.str`Confirm payment`} + +
+ )} +
+ ); +} + +export function createPayPage(): JSX.Element { + const url = new URL(document.location.href); + const talerPayUri = url.searchParams.get("talerPayUri"); + if (!talerPayUri) { + throw Error("invalid parameter"); + } + return ; +} diff --git a/packages/taler-wallet-webextension/src/pages/payback.tsx b/packages/taler-wallet-webextension/src/pages/payback.tsx new file mode 100644 index 000000000..5d42f5f47 --- /dev/null +++ b/packages/taler-wallet-webextension/src/pages/payback.tsx @@ -0,0 +1,30 @@ +/* + This file is part of TALER + (C) 2017 Inria + + TALER is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + TALER is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + TALER; see the file COPYING. If not, see + */ + +/** + * View and edit auditors. + * + * @author Florian Dold + */ + +/** + * Imports. + */ +import * as React from "react"; + +export function makePaybackPage(): JSX.Element { + return
not implemented
; +} diff --git a/packages/taler-wallet-webextension/src/pages/popup.tsx b/packages/taler-wallet-webextension/src/pages/popup.tsx new file mode 100644 index 000000000..72c9f4bcb --- /dev/null +++ b/packages/taler-wallet-webextension/src/pages/popup.tsx @@ -0,0 +1,502 @@ +/* + This file is part of TALER + (C) 2016 GNUnet e.V. + + TALER is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + TALER is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + TALER; see the file COPYING. If not, see + */ + +/** + * Popup shown to the user when they click + * the Taler browser action button. + * + * @author Florian Dold + */ + +/** + * Imports. + */ +import * as i18n from "../i18n"; + +import { + AmountJson, + Amounts, + time, + taleruri, + walletTypes, +} from "taler-wallet-core"; + + +import { abbrev, renderAmount, PageLink } from "../renderHtml"; +import * as wxApi from "../wxApi"; + +import React, { Fragment, useState, useEffect } from "react"; + +import moment from "moment"; +import { PermissionsCheckbox } from "./welcome"; + +// FIXME: move to newer react functions +/* eslint-disable react/no-deprecated */ + +class Router extends React.Component { + static setRoute(s: string): void { + window.location.hash = s; + } + + static getRoute(): string { + // Omit the '#' at the beginning + return window.location.hash.substring(1); + } + + static onRoute(f: any): () => void { + Router.routeHandlers.push(f); + return () => { + const i = Router.routeHandlers.indexOf(f); + this.routeHandlers = this.routeHandlers.splice(i, 1); + }; + } + + private static routeHandlers: any[] = []; + + componentWillMount(): void { + console.log("router mounted"); + window.onhashchange = () => { + this.setState({}); + for (const f of Router.routeHandlers) { + f(); + } + }; + } + + render(): JSX.Element { + const route = window.location.hash.substring(1); + console.log("rendering route", route); + let defaultChild: React.ReactChild | null = null; + let foundChild: React.ReactChild | null = null; + React.Children.forEach(this.props.children, (child) => { + const childProps: any = (child as any).props; + if (!childProps) { + return; + } + if (childProps.default) { + defaultChild = child as React.ReactChild; + } + if (childProps.route === route) { + foundChild = child as React.ReactChild; + } + }); + const c: React.ReactChild | null = foundChild || defaultChild; + if (!c) { + throw Error("unknown route"); + } + Router.setRoute((c as any).props.route); + return
{c}
; + } +} + +interface TabProps { + target: string; + children?: React.ReactNode; +} + +function Tab(props: TabProps): JSX.Element { + let cssClass = ""; + if (props.target === Router.getRoute()) { + cssClass = "active"; + } + const onClick = (e: React.MouseEvent): void => { + Router.setRoute(props.target); + e.preventDefault(); + }; + return ( + + {props.children} + + ); +} + +class WalletNavBar extends React.Component { + private cancelSubscription: any; + + componentWillMount(): void { + this.cancelSubscription = Router.onRoute(() => { + this.setState({}); + }); + } + + componentWillUnmount(): void { + if (this.cancelSubscription) { + this.cancelSubscription(); + } + } + + render(): JSX.Element { + console.log("rendering nav bar"); + return ( + + ); + } +} + +/** + * Render an amount as a large number with a small currency symbol. + */ +function bigAmount(amount: AmountJson): JSX.Element { + const v = amount.value + amount.fraction / Amounts.fractionalBase; + return ( + + {v}{" "} + {amount.currency} + + ); +} + +function EmptyBalanceView(): JSX.Element { + return ( + + You have no balance to show. Need some{" "} + help getting started? + + ); +} + +class WalletBalanceView extends React.Component { + private balance?: walletTypes.BalancesResponse; + private gotError = false; + private canceler: (() => void) | undefined = undefined; + private unmount = false; + private updateBalanceRunning = false; + + componentWillMount(): void { + this.canceler = wxApi.onUpdateNotification(() => this.updateBalance()); + this.updateBalance(); + } + + componentWillUnmount(): void { + console.log("component WalletBalanceView will unmount"); + if (this.canceler) { + this.canceler(); + } + this.unmount = true; + } + + async updateBalance(): Promise { + if (this.updateBalanceRunning) { + return; + } + this.updateBalanceRunning = true; + let balance: walletTypes.BalancesResponse; + try { + balance = await wxApi.getBalance(); + } catch (e) { + if (this.unmount) { + return; + } + this.gotError = true; + console.error("could not retrieve balances", e); + this.setState({}); + return; + } finally { + this.updateBalanceRunning = false; + } + if (this.unmount) { + return; + } + this.gotError = false; + console.log("got balance", balance); + this.balance = balance; + this.setState({}); + } + + formatPending(entry: walletTypes.Balance): JSX.Element { + let incoming: JSX.Element | undefined; + let payment: JSX.Element | undefined; + + const available = Amounts.parseOrThrow(entry.available); + const pendingIncoming = Amounts.parseOrThrow(entry.pendingIncoming); + const pendingOutgoing = Amounts.parseOrThrow(entry.pendingOutgoing); + + console.log( + "available: ", + entry.pendingIncoming ? renderAmount(entry.available) : null, + ); + console.log( + "incoming: ", + entry.pendingIncoming ? renderAmount(entry.pendingIncoming) : null, + ); + + if (!Amounts.isZero(pendingIncoming)) { + incoming = ( + + + {"+"} + {renderAmount(entry.pendingIncoming)} + {" "} + incoming + + ); + } + + const l = [incoming, payment].filter((x) => x !== undefined); + if (l.length === 0) { + return ; + } + + if (l.length === 1) { + return ({l}); + } + return ( + + ({l[0]}, {l[1]}) + + ); + } + + render(): JSX.Element { + const wallet = this.balance; + if (this.gotError) { + return ( +
+

{i18n.str`Error: could not retrieve balance information.`}

+

+ Click here for help and + diagnostics. +

+
+ ); + } + if (!wallet) { + return ; + } + console.log(wallet); + const listing = wallet.balances.map((entry) => { + const av = Amounts.parseOrThrow(entry.available); + return ( +

+ {bigAmount(av)} {this.formatPending(entry)} +

+ ); + }); + return listing.length > 0 ? ( +
{listing}
+ ) : ( + + ); + } +} + +function Icon({ l }: { l: string }): JSX.Element { + return
{l}
; +} + +function formatAndCapitalize(text: string): string { + text = text.replace("-", " "); + text = text.replace(/^./, text[0].toUpperCase()); + return text; +} + +const HistoryComponent = (props: any): JSX.Element => { + return TBD; +}; + +class WalletSettings extends React.Component { + render(): JSX.Element { + return ( +
+

Permissions

+ +
+ ); + } +} + +function reload(): void { + try { + chrome.runtime.reload(); + window.close(); + } catch (e) { + // Functionality missing in firefox, ignore! + } +} + +function confirmReset(): void { + if ( + confirm( + "Do you want to IRREVOCABLY DESTROY everything inside your" + + " wallet and LOSE ALL YOUR COINS?", + ) + ) { + wxApi.resetDb(); + window.close(); + } +} + +function WalletDebug(props: any): JSX.Element { + return ( +
+

Debug tools:

+ + + + +
+ + +
+ ); +} + +function openExtensionPage(page: string) { + return () => { + chrome.tabs.create({ + url: chrome.extension.getURL(page), + }); + }; +} + +function openTab(page: string) { + return (evt: React.SyntheticEvent) => { + evt.preventDefault(); + chrome.tabs.create({ + url: page, + }); + }; +} + +function makeExtensionUrlWithParams( + url: string, + params?: { [name: string]: string | undefined }, +): string { + const innerUrl = new URL(chrome.extension.getURL("/" + url)); + if (params) { + for (const key in params) { + const p = params[key]; + if (p) { + innerUrl.searchParams.set(key, p); + } + } + } + return innerUrl.href; +} + +function actionForTalerUri(talerUri: string): string | undefined { + const uriType = taleruri.classifyTalerUri(talerUri); + switch (uriType) { + case taleruri.TalerUriType.TalerWithdraw: + return makeExtensionUrlWithParams("withdraw.html", { + talerWithdrawUri: talerUri, + }); + case taleruri.TalerUriType.TalerPay: + return makeExtensionUrlWithParams("pay.html", { + talerPayUri: talerUri, + }); + case taleruri.TalerUriType.TalerTip: + return makeExtensionUrlWithParams("tip.html", { + talerTipUri: talerUri, + }); + case taleruri.TalerUriType.TalerRefund: + return makeExtensionUrlWithParams("refund.html", { + talerRefundUri: talerUri, + }); + case taleruri.TalerUriType.TalerNotifyReserve: + // FIXME: implement + break; + default: + console.warn( + "Response with HTTP 402 has Taler header, but header value is not a taler:// URI.", + ); + break; + } + return undefined; +} + +async function findTalerUriInActiveTab(): Promise { + return new Promise((resolve, reject) => { + chrome.tabs.executeScript( + { + code: ` + (() => { + let x = document.querySelector("a[href^='taler://'"); + return x ? x.href.toString() : null; + })(); + `, + allFrames: false, + }, + (result) => { + if (chrome.runtime.lastError) { + console.error(chrome.runtime.lastError); + resolve(undefined); + return; + } + console.log("got result", result); + resolve(result[0]); + }, + ); + }); +} + +function WalletPopup(): JSX.Element { + const [talerActionUrl, setTalerActionUrl] = useState( + undefined, + ); + const [dismissed, setDismissed] = useState(false); + useEffect(() => { + async function check(): Promise { + const talerUri = await findTalerUriInActiveTab(); + if (talerUri) { + const actionUrl = actionForTalerUri(talerUri); + setTalerActionUrl(actionUrl); + } + } + check(); + }); + if (talerActionUrl && !dismissed) { + return ( +
+

Taler Action

+

This page has a Taler action.

+

+ +

+

+ +

+
+ ); + } + return ( +
+ +
+ + + + + +
+
+ ); +} + +export function createPopup(): JSX.Element { + return ; +} diff --git a/packages/taler-wallet-webextension/src/pages/refund.tsx b/packages/taler-wallet-webextension/src/pages/refund.tsx new file mode 100644 index 000000000..7326dfc88 --- /dev/null +++ b/packages/taler-wallet-webextension/src/pages/refund.tsx @@ -0,0 +1,89 @@ +/* + This file is part of TALER + (C) 2015-2016 GNUnet e.V. + + TALER is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + TALER is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + TALER; see the file COPYING. If not, see + */ + +/** + * Page that shows refund status for purchases. + * + * @author Florian Dold + */ + +import React, { useEffect, useState } from "react"; + +import * as wxApi from "../wxApi"; +import { AmountView } from "../renderHtml"; +import { walletTypes } from "taler-wallet-core"; + +function RefundStatusView(props: { talerRefundUri: string }): JSX.Element { + const [applied, setApplied] = useState(false); + const [purchaseDetails, setPurchaseDetails] = useState< + walletTypes.PurchaseDetails | undefined + >(undefined); + const [errMsg, setErrMsg] = useState(undefined); + + useEffect(() => { + const doFetch = async (): Promise => { + try { + const result = await wxApi.applyRefund(props.talerRefundUri); + setApplied(true); + const r = await wxApi.getPurchaseDetails(result.proposalId); + setPurchaseDetails(r); + } catch (e) { + console.error(e); + setErrMsg(e.message); + console.log("err message", e.message); + } + }; + doFetch(); + }, [props.talerRefundUri]); + + console.log("rendering"); + + if (errMsg) { + return Error: {errMsg}; + } + + if (!applied || !purchaseDetails) { + return Updating refund status; + } + + return ( + <> +

Refund Status

+

+ The product {purchaseDetails.contractTerms.summary} has + received a total refund of{" "} + . +

+

Note that additional fees from the exchange may apply.

+ + ); +} + +export function createRefundPage(): JSX.Element { + const url = new URL(document.location.href); + + const container = document.getElementById("container"); + if (!container) { + throw Error("fatal: can't mount component, container missing"); + } + + const talerRefundUri = url.searchParams.get("talerRefundUri"); + if (!talerRefundUri) { + throw Error("taler refund URI requred"); + } + + return ; +} diff --git a/packages/taler-wallet-webextension/src/pages/reset-required.tsx b/packages/taler-wallet-webextension/src/pages/reset-required.tsx new file mode 100644 index 000000000..0ef5fe8b7 --- /dev/null +++ b/packages/taler-wallet-webextension/src/pages/reset-required.tsx @@ -0,0 +1,93 @@ +/* + This file is part of TALER + (C) 2017 GNUnet e.V. + + TALER is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + TALER is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + TALER; see the file COPYING. If not, see + */ + +/** + * Page to inform the user when a database reset is required. + * + * @author Florian Dold + */ + +import * as React from "react"; + +import * as wxApi from "../wxApi"; + +interface State { + /** + * Did the user check the confirmation check box? + */ + checked: boolean; + + /** + * Do we actually need to reset the db? + */ + resetRequired: boolean; +} + +class ResetNotification extends React.Component { + constructor(props: any) { + super(props); + this.state = { checked: false, resetRequired: true }; + setInterval(() => this.update(), 500); + } + async update(): Promise { + const res = await wxApi.checkUpgrade(); + this.setState({ resetRequired: res.dbResetRequired }); + } + render(): JSX.Element { + if (this.state.resetRequired) { + return ( +
+

Manual Reset Reqired

+

+ The wallet's database in your browser is incompatible with the{" "} + currently installed wallet. Please reset manually. +

+

+ Once the database format has stabilized, we will provide automatic + upgrades. +

+ this.setState({ checked: e.target.checked })} + />{" "} + +
+ +
+ ); + } + return ( +
+

Everything is fine!

A reset is not required anymore, you can + close this page. +
+ ); + } +} + +export function createResetRequiredPage(): JSX.Element { + return ; +} diff --git a/packages/taler-wallet-webextension/src/pages/return-coins.tsx b/packages/taler-wallet-webextension/src/pages/return-coins.tsx new file mode 100644 index 000000000..e8cf8c9dd --- /dev/null +++ b/packages/taler-wallet-webextension/src/pages/return-coins.tsx @@ -0,0 +1,30 @@ +/* + This file is part of TALER + (C) 2017 Inria + + TALER is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + TALER is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + TALER; see the file COPYING. If not, see + */ + +/** + * Return coins to own bank account. + * + * @author Florian Dold + */ + +/** + * Imports. + */ +import * as React from "react"; + +export function createReturnCoinsPage(): JSX.Element { + return Not implemented yet.; +} diff --git a/packages/taler-wallet-webextension/src/pages/tip.tsx b/packages/taler-wallet-webextension/src/pages/tip.tsx new file mode 100644 index 000000000..6cf4e1875 --- /dev/null +++ b/packages/taler-wallet-webextension/src/pages/tip.tsx @@ -0,0 +1,103 @@ +/* + This file is part of TALER + (C) 2017 GNUnet e.V. + + TALER is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + TALER is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + TALER; see the file COPYING. If not, see + */ + +/** + * Page shown to the user to confirm creation + * of a reserve, usually requested by the bank. + * + * @author Florian Dold + */ + +import * as React from "react"; + +import { acceptTip, getTipStatus } from "../wxApi"; + +import { renderAmount, ProgressButton } from "../renderHtml"; + +import { useState, useEffect } from "react"; +import { walletTypes } from "taler-wallet-core"; + +function TipDisplay(props: { talerTipUri: string }): JSX.Element { + const [tipStatus, setTipStatus] = useState(undefined); + const [discarded, setDiscarded] = useState(false); + const [loading, setLoading] = useState(false); + const [finished, setFinished] = useState(false); + + useEffect(() => { + const doFetch = async (): Promise => { + const ts = await getTipStatus(props.talerTipUri); + setTipStatus(ts); + }; + doFetch(); + }, [props.talerTipUri]); + + if (discarded) { + return You've discarded the tip.; + } + + if (finished) { + return Tip has been accepted!; + } + + if (!tipStatus) { + return Loading ...; + } + + const discard = (): void => { + setDiscarded(true); + }; + + const accept = async (): Promise => { + setLoading(true); + await acceptTip(tipStatus.tipId); + setFinished(true); + }; + + return ( +
+

Tip Received!

+

+ You received a tip of {renderAmount(tipStatus.amount)}{" "} + from + {tipStatus.merchantOrigin}. +

+

+ The tip is handled by the exchange{" "} + {tipStatus.exchangeUrl}. This exchange will charge fees + of {renderAmount(tipStatus.totalFees)} for this + operation. +

+
+ accept()}> + Accept Tip + {" "} + +
+
+ ); +} + +export function createTipPage(): JSX.Element { + const url = new URL(document.location.href); + const talerTipUri = url.searchParams.get("talerTipUri"); + if (typeof talerTipUri !== "string") { + throw Error("talerTipUri must be a string"); + } + + return ; +} diff --git a/packages/taler-wallet-webextension/src/pages/welcome.tsx b/packages/taler-wallet-webextension/src/pages/welcome.tsx new file mode 100644 index 000000000..ff5de572c --- /dev/null +++ b/packages/taler-wallet-webextension/src/pages/welcome.tsx @@ -0,0 +1,190 @@ +/* + This file is part of GNU Taler + (C) 2019 Taler Systems SA + + GNU Taler is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + GNU Taler; see the file COPYING. If not, see + */ + +/** + * Welcome page, shown on first installs. + * + * @author Florian Dold + */ + +import React, { useState, useEffect } from "react"; +import { getDiagnostics } from "../wxApi"; +import { PageLink } from "../renderHtml"; +import * as wxApi from "../wxApi"; +import { getPermissionsApi } from "../compat"; +import { extendedPermissions } from "../permissions"; +import { walletTypes } from "taler-wallet-core"; + +function Diagnostics(): JSX.Element | null { + const [timedOut, setTimedOut] = useState(false); + const [diagnostics, setDiagnostics] = useState( + undefined, + ); + + useEffect(() => { + let gotDiagnostics = false; + setTimeout(() => { + if (!gotDiagnostics) { + console.error("timed out"); + setTimedOut(true); + } + }, 1000); + const doFetch = async (): Promise => { + const d = await getDiagnostics(); + console.log("got diagnostics", d); + gotDiagnostics = true; + setDiagnostics(d); + }; + console.log("fetching diagnostics"); + doFetch(); + }, []); + + if (timedOut) { + return

Diagnostics timed out. Could not talk to the wallet backend.

; + } + + if (diagnostics) { + if (diagnostics.errors.length === 0) { + return null; + } else { + return ( +
+

Problems detected:

+
    + {diagnostics.errors.map((errMsg) => ( +
  1. {errMsg}
  2. + ))} +
+ {diagnostics.firefoxIdbProblem ? ( +

+ Please check in your about:config settings that you + have IndexedDB enabled (check the preference name{" "} + dom.indexedDB.enabled). +

+ ) : null} + {diagnostics.dbOutdated ? ( +

+ Your wallet database is outdated. Currently automatic migration is + not supported. Please go{" "} + here to reset + the wallet database. +

+ ) : null} +
+ ); + } + } + + return

Running diagnostics ...

; +} + +export function PermissionsCheckbox(): JSX.Element { + const [extendedPermissionsEnabled, setExtendedPermissionsEnabled] = useState( + false, + ); + async function handleExtendedPerm(requestedVal: boolean): Promise { + let nextVal: boolean | undefined; + if (requestedVal) { + const granted = await new Promise((resolve, reject) => { + // We set permissions here, since apparently FF wants this to be done + // as the result of an input event ... + getPermissionsApi().request(extendedPermissions, (granted: boolean) => { + if (chrome.runtime.lastError) { + console.error("error requesting permissions"); + console.error(chrome.runtime.lastError); + reject(chrome.runtime.lastError); + return; + } + console.log("permissions granted:", granted); + resolve(granted); + }); + }); + const res = await wxApi.setExtendedPermissions(granted); + console.log(res); + nextVal = res.newValue; + } else { + const res = await wxApi.setExtendedPermissions(false); + console.log(res); + nextVal = res.newValue; + } + console.log("new permissions applied:", nextVal); + setExtendedPermissionsEnabled(nextVal ?? false); + } + useEffect(() => { + async function getExtendedPermValue(): Promise { + const res = await wxApi.getExtendedPermissions(); + setExtendedPermissionsEnabled(res.newValue); + } + getExtendedPermValue(); + }); + return ( +
+ handleExtendedPerm(x.target.checked)} + type="checkbox" + id="checkbox-perm" + style={{ width: "1.5em", height: "1.5em", verticalAlign: "middle" }} + /> + + + (Enabling this option below will make using the wallet faster, but + requires more permissions from your browser.) + +
+ ); +} + +function Welcome(): JSX.Element { + return ( + <> +

Thank you for installing the wallet.

+ +

Permissions

+ +

Next Steps

+ + Try the demo » + + + Learn how to top up your wallet balance » + + + ); +} + +export function createWelcomePage(): JSX.Element { + return ; +} diff --git a/packages/taler-wallet-webextension/src/pages/withdraw.tsx b/packages/taler-wallet-webextension/src/pages/withdraw.tsx new file mode 100644 index 000000000..4a92704b3 --- /dev/null +++ b/packages/taler-wallet-webextension/src/pages/withdraw.tsx @@ -0,0 +1,229 @@ +/* + This file is part of TALER + (C) 2015-2016 GNUnet e.V. + + TALER is free software; you can redistribute it and/or modify it under the + terms of the GNU General Public License as published by the Free Software + Foundation; either version 3, or (at your option) any later version. + + TALER is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + A PARTICULAR PURPOSE. See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along with + TALER; see the file COPYING. If not, see + */ + +/** + * Page shown to the user to confirm creation + * of a reserve, usually requested by the bank. + * + * @author Florian Dold + */ + +import * as i18n from "../i18n"; + +import { WithdrawDetailView, renderAmount } from "../renderHtml"; + +import React, { useState, useEffect } from "react"; +import { + acceptWithdrawal, + onUpdateNotification, +} from "../wxApi"; + +function WithdrawalDialog(props: { talerWithdrawUri: string }): JSX.Element { + const [details, setDetails] = useState< + any | undefined + >(); + const [selectedExchange, setSelectedExchange] = useState< + string | undefined + >(); + const talerWithdrawUri = props.talerWithdrawUri; + const [cancelled, setCancelled] = useState(false); + const [selecting, setSelecting] = useState(false); + const [customUrl, setCustomUrl] = useState(""); + const [errMsg, setErrMsg] = useState(""); + const [updateCounter, setUpdateCounter] = useState(1); + + useEffect(() => { + return onUpdateNotification(() => { + setUpdateCounter(updateCounter + 1); + }); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + useEffect(() => { + const fetchData = async (): Promise => { + // FIXME: re-implement with new API + // console.log("getting from", talerWithdrawUri); + // let d: WithdrawalDetailsResponse | undefined = undefined; + // try { + // d = await getWithdrawDetails(talerWithdrawUri, selectedExchange); + // } catch (e) { + // console.error( + // `error getting withdraw details for uri ${talerWithdrawUri}, exchange ${selectedExchange}`, + // e, + // ); + // setErrMsg(e.message); + // return; + // } + // console.log("got withdrawDetails", d); + // if (!selectedExchange && d.bankWithdrawDetails.suggestedExchange) { + // console.log("setting selected exchange"); + // setSelectedExchange(d.bankWithdrawDetails.suggestedExchange); + // } + // setDetails(d); + }; + fetchData(); + }, [selectedExchange, errMsg, selecting, talerWithdrawUri, updateCounter]); + + if (errMsg) { + return ( +
+ + Could not get details for withdraw operation: + +

{errMsg}

+

+ { + setSelecting(true); + setErrMsg(undefined); + setSelectedExchange(undefined); + setDetails(undefined); + }} + > + {i18n.str`Chose different exchange provider`} + +

+
+ ); + } + + if (!details) { + return Loading...; + } + + if (cancelled) { + return Withdraw operation has been cancelled.; + } + + if (selecting) { + const bankSuggestion = + details && details.bankWithdrawDetails.suggestedExchange; + return ( +
+ {i18n.str`Please select an exchange. You can review the details before after your selection.`} + {bankSuggestion && ( +
+

Bank Suggestion

+ +
+ )} +

Custom Selection

+

+ setCustomUrl(e.target.value)} + value={customUrl} + /> +

+ +
+ ); + } + + const accept = async (): Promise => { + if (!selectedExchange) { + throw Error("can't accept, no exchange selected"); + } + console.log("accepting exchange", selectedExchange); + const res = await acceptWithdrawal(talerWithdrawUri, selectedExchange); + console.log("accept withdrawal response", res); + if (res.confirmTransferUrl) { + document.location.href = res.confirmTransferUrl; + } + }; + + return ( +
+

Digital Cash Withdrawal

+ + You are about to withdraw{" "} + {renderAmount(details.bankWithdrawDetails.amount)} from + your bank account into your wallet. + + {selectedExchange ? ( +

+ The exchange {selectedExchange} will be used as the + Taler payment service provider. +

+ ) : null} + +
+ +

+ setSelecting(true)} + > + {i18n.str`Chose different exchange provider`} + +
+ setCancelled(true)} + > + {i18n.str`Cancel withdraw operation`} + +

+ + {details.exchangeWithdrawDetails ? ( + + ) : null} +
+
+ ); +} + +export function createWithdrawPage(): JSX.Element { + const url = new URL(document.location.href); + const talerWithdrawUri = url.searchParams.get("talerWithdrawUri"); + if (!talerWithdrawUri) { + throw Error("withdraw URI required"); + } + return ; +} -- cgit v1.2.3