timesafari
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

364 lines
12 KiB

<template>
<!-- QUICK NAV -->
<nav id="QuickNav" class="fixed bottom-0 left-0 right-0 bg-slate-200">
<ul class="flex text-2xl p-2 gap-2">
<!-- Home Feed -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link :to="{ name: 'home' }" class="block text-center py-3 px-1"
><fa icon="house-chimney" class="fa-fw"></fa
></router-link>
</li>
<!-- Search -->
<li class="basis-1/5 rounded-md bg-slate-400 text-white">
<router-link
:to="{ name: 'discover' }"
class="block text-center py-3 px-1"
><fa icon="magnifying-glass" class="fa-fw"></fa
></router-link>
</li>
<!-- Contacts -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'contacts' }"
class="block text-center py-3 px-1"
><fa icon="folder-open" class="fa-fw"></fa
></router-link>
</li>
<!-- Commitments -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link :to="{ name: '' }" class="block text-center py-3 px-1"
><fa icon="hand" class="fa-fw"></fa
></router-link>
</li>
<!-- Profile -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'account' }"
class="block text-center py-3 px-1"
><fa icon="circle-user" class="fa-fw"></fa
></router-link>
</li>
</ul>
</nav>
<section id="Content" class="p-6 pb-24">
<!-- Heading -->
<h1 id="ViewHeading" class="text-4xl text-center font-light pt-4 mb-8">
My Contacts
</h1>
<div>
{{ errorMessage }}
</div>
<!-- New Contact -->
<div class="mb-4 flex">
<input
type="text"
placeholder="DID, Name, Public Key"
class="block w-full rounded-l border border-r-0 border-slate-400 px-3 py-2"
v-model="contactInput"
/>
<button
class="px-4 rounded-r bg-slate-200 border border-l-0 border-slate-400"
@click="onClickNewContact()"
>
<fa icon="plus" class="fa-fw"></fa>
</button>
</div>
<!-- eslint-disable-next-line -->
<div
class="flex justify-between"
>
<!-- eslint-disable-next-line -->
<div class="w-1/2 text-left">
<button
href=""
class="left text-md uppercase bg-slate-500 text-white px-1.5 py-2 rounded-md mb-6"
v-if="showGiveTotals"
@click="loadGives()"
>
Load Totals
</button>
</div>
<div class="w-1/2 text-right">
Hours to Add:
<input
class="border border rounded border-slate-400 w-24 text-right"
type="text"
placeholder="1"
v-model="hourInput"
/>
</div>
</div>
<!-- Results List -->
<ul class="">
<li
class="border-b border-slate-300"
v-for="contact in contacts"
:key="contact.did"
>
<div class="grow overflow-hidden">
<h2 class="text-base font-semibold">
{{ contact.name || "(no name)" }}
</h2>
<div class="text-sm truncate">{{ contact.did }}</div>
<div class="text-sm truncate">{{ contact.publicKeyBase64 }}</div>
<div v-if="showGiveTotals" class="float-right">
<div class="float-right">
to: {{ givenByMeTotals[contact.did] || 0 }}
<button
class="text-md uppercase bg-slate-500 text-white px-1.5 py-2 rounded-md mb-6"
@click="onClickAddGive(identity.did, contact.did)"
>
+
</button>
by: {{ givenToMeTotals[contact.did] || 0 }}
<button
class="text-md uppercase bg-slate-500 text-white px-1.5 py-2 rounded-md mb-6"
@click="onClickAddGive(contact.did, identity.did)"
>
+
</button>
</div>
</div>
</div>
</li>
</ul>
</section>
</template>
<script lang="ts">
import { AxiosError } from "axios";
import * as didJwt from "did-jwt";
import { Options, Vue } from "vue-class-component";
import { AppString } from "@/constants/app";
import { accessToken, SimpleSigner } from "@/libs/crypto";
import { IIdentifier } from "@veramo/core";
import { db } from "../db";
import { Contact } from "../db/tables/contacts.ts";
export interface GiveVerifiableCredential {
"@context": string;
"@type": string;
agent: { identifier: string };
recipient: { identifier: string };
object: { amountOfThisGood: number; unitCode: string };
}
@Options({
components: {},
})
export default class ContactsView extends Vue {
contacts: Contact[] = [];
contactInput = "";
// { "did:...": amount } entry for each contact
givenByMeTotals = {};
// { "did:...": amount } entry for each contact
givenToMeTotals = {};
hourInput = 0;
identity: IIdentifier = null;
errorMessage = "";
showGiveTotals = false;
// 'created' hook runs when the Vue instance is first created
async created() {
await db.open();
this.contacts = await db.contacts.toArray();
const params = new URLSearchParams(window.location.search);
this.showGiveTotals = params.get("showGiveTotals") == "true";
const accounts = await db.accounts.toArray();
this.identity = JSON.parse(accounts[0].identity);
}
async onClickNewContact(): void {
let did = this.contactInput;
let name, publicKeyBase64;
const commaPos1 = this.contactInput.indexOf(",");
if (commaPos1 > -1) {
did = this.contactInput.substring(0, commaPos1).trim();
name = this.contactInput.substring(commaPos1 + 1).trim();
const commaPos2 = this.contactInput.indexOf(",", commaPos1 + 1);
if (commaPos2 > -1) {
name = this.contactInput.substring(commaPos1 + 1, commaPos2).trim();
publicKeyBase64 = this.contactInput.substring(commaPos2 + 1).trim();
}
}
const newContact = { did, name, publicKeyBase64 };
await db.contacts.add(newContact);
this.contacts = this.contacts.concat([newContact]);
}
async loadGives() {
const endorserApiServer = AppString.DEFAULT_ENDORSER_API_SERVER;
// load all the time I have given
try {
const url =
endorserApiServer +
"/api/v2/report/gives?agentId=" +
encodeURIComponent(this.identity.did);
const token = await accessToken(this.identity);
const headers = {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
};
const resp = await this.axios.get(url, { headers });
//console.log("Server response", resp.status, resp.data);
if (resp.status === 200) {
const contactTotals = {};
for (const give of resp.data.data) {
if (give.unit == "HUR") {
const prevAmount = contactTotals[give.recipientDid] || 0;
contactTotals[give.recipientDid] = prevAmount + give.amount;
}
}
//console.log("Done retrieving gives", contactTotals);
this.givenByMeTotals = contactTotals;
}
} catch (error) {
this.errorMessage = "" + error;
}
// load all the time I have received
try {
const url =
endorserApiServer +
"/api/v2/report/gives?recipientId=" +
encodeURIComponent(this.identity.did);
const token = await accessToken(this.identity);
const headers = {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
};
const resp = await this.axios.get(url, { headers });
//console.log("Server response", resp.status, resp.data);
if (resp.status === 200) {
const contactTotals = {};
for (const give of resp.data.data) {
if (give.unit == "HUR") {
const prevAmount = contactTotals[give.agentDid] || 0;
contactTotals[give.agentDid] = prevAmount + give.amount;
}
}
//console.log("Done retrieving receipts", contactTotals);
this.givenToMeTotals = contactTotals;
}
} catch (error) {
this.errorMessage = "" + error;
}
}
// from https://stackoverflow.com/a/175787/845494
private isNumeric(str): boolean {
return !isNaN(str) && !isNaN(parseFloat(str));
}
async onClickAddGive(fromDid: string, toDid: string): void {
if (!this.hourInput) {
this.errorMessage = "Giving 0 hours does nothing.";
} else if (!this.isNumeric(this.hourInput)) {
this.errorMessage =
"This is not a valid number of hours: " + this.hourInput;
} else {
this.errorMessage = "";
this.createAndSubmitGive(fromDid, toDid, parseFloat(this.hourInput));
}
}
private async createAndSubmitGive(
fromDid: string,
toDid: string,
amount: number
): void {
// Make a claim
const vcClaim: GiveVerifiableCredential = {
"@context": "https://schema.org",
"@type": "GiveAction",
agent: { identifier: fromDid },
recipient: { identifier: toDid },
object: { amountOfThisGood: amount, unitCode: "HUR" },
};
// Make a payload for the claim
const vcPayload = {
vc: {
"@context": ["https://www.w3.org/2018/credentials/v1"],
type: ["VerifiableCredential"],
credentialSubject: vcClaim,
},
};
// Create a signature using private key of identity
if (this.identity.keys[0].privateKeyHex !== null) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const privateKeyHex: string = this.identity.keys[0].privateKeyHex!;
const signer = await SimpleSigner(privateKeyHex);
const alg = undefined;
// Create a JWT for the request
const vcJwt: string = await didJwt.createJWT(vcPayload, {
alg: alg,
issuer: this.identity.did,
signer: signer,
});
// Make the xhr request payload
const payload = JSON.stringify({ jwtEncoded: vcJwt });
const endorserApiServer = AppString.DEFAULT_ENDORSER_API_SERVER;
const url = endorserApiServer + "/api/v2/claim";
const token = await accessToken(this.identity);
const headers = {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
};
try {
const resp = await this.axios.post(url, payload, { headers });
console.log("Got resp data:", resp.data);
if (resp.data?.success?.handleId) {
this.errorMessage = "";
this.alertTitle = "";
this.alertMessage = "";
if (fromDid === this.identity.did) {
this.givenByMeTotals[toDid] = this.givenByMeTotals[toDid] + amount;
// do this to update the UI
// eslint-disable-next-line no-self-assign
this.givenByMeTotals = this.givenByMeTotals;
} else {
this.givenToMeTotals[fromDid] =
this.givenToMeTotals[fromDid] + amount;
// do this to update the UI
// eslint-disable-next-line no-self-assign
this.givenToMeTotals = this.givenToMeTotals;
}
}
} catch (error) {
let userMessage = "There was an error. See logs for more info.";
const serverError = error as AxiosError;
if (serverError) {
this.isAlertVisible = true;
if (serverError.message) {
this.alertTitle = "User Message";
userMessage = serverError.message; // This is info for the user.
this.alertMessage = userMessage;
} else {
this.alertTitle = "Server Message";
this.alertMessage = JSON.stringify(serverError.toJSON());
}
} else {
console.log("Here's the full error trying to save the claim:", error);
this.alertTitle = "Claim Error";
this.alertMessage = error as string;
}
// Now set that error for the user to see.
this.errorMessage = userMessage;
}
}
}
}
</script>