Compare commits
No commits in common. "create-account" and "working-chat" have entirely different histories.
create-acc
...
working-ch
@ -5,7 +5,7 @@
|
|||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "echo \"Error: no test specified\" && exit 1",
|
"test": "echo \"Error: no test specified\" && exit 1",
|
||||||
"build_wasm": "wasm-pack build --out-dir ../ihm_client_dev1/pkg ../sdk_client --target bundler --dev",
|
"build_wasm": "wasm-pack build --out-dir ../ihm_client/pkg ../sdk_client --target bundler --dev",
|
||||||
"start": "vite --host 0.0.0.0",
|
"start": "vite --host 0.0.0.0",
|
||||||
"build": "tsc && vite build",
|
"build": "tsc && vite build",
|
||||||
"deploy": "sudo cp -r dist/* /var/www/html/",
|
"deploy": "sudo cp -r dist/* /var/www/html/",
|
||||||
|
@ -599,7 +599,7 @@ body {
|
|||||||
margin-top: 9vh;
|
margin-top: 9vh;
|
||||||
margin-left: -1%;
|
margin-left: -1%;
|
||||||
text-align: left;
|
text-align: left;
|
||||||
width: 100vw;
|
width: 209vh;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Liste des information sur l'account */
|
/* Liste des information sur l'account */
|
||||||
@ -1364,62 +1364,3 @@ body {
|
|||||||
border-radius: 50%;
|
border-radius: 50%;
|
||||||
border: 2px solid white;
|
border: 2px solid white;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ---------------------Style pour le QR code--------------------- */
|
|
||||||
|
|
||||||
.qr-code {
|
|
||||||
width: 50px;
|
|
||||||
height: 50px;
|
|
||||||
cursor: pointer;
|
|
||||||
transition: transform 0.2s ease;
|
|
||||||
}
|
|
||||||
|
|
||||||
.qr-code:hover {
|
|
||||||
transform: scale(1.5);
|
|
||||||
}
|
|
||||||
|
|
||||||
.qr-modal {
|
|
||||||
position: fixed;
|
|
||||||
top: 0;
|
|
||||||
left: 0;
|
|
||||||
width: 100%;
|
|
||||||
height: 100%;
|
|
||||||
background-color: rgba(0, 0, 0, 0.7);
|
|
||||||
display: flex;
|
|
||||||
justify-content: center;
|
|
||||||
align-items: center;
|
|
||||||
z-index: 1000;
|
|
||||||
}
|
|
||||||
|
|
||||||
.qr-modal-content {
|
|
||||||
background-color: white;
|
|
||||||
padding: 20px;
|
|
||||||
border-radius: 8px;
|
|
||||||
position: relative;
|
|
||||||
text-align: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
.close-qr-modal {
|
|
||||||
position: absolute;
|
|
||||||
right: 10px;
|
|
||||||
top: 5px;
|
|
||||||
font-size: 24px;
|
|
||||||
cursor: pointer;
|
|
||||||
color: #666;
|
|
||||||
}
|
|
||||||
|
|
||||||
.close-qr-modal:hover {
|
|
||||||
color: #000;
|
|
||||||
}
|
|
||||||
|
|
||||||
.qr-code-large {
|
|
||||||
max-width: 300px;
|
|
||||||
margin: 10px 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.qr-address {
|
|
||||||
margin-top: 10px;
|
|
||||||
word-break: break-all;
|
|
||||||
font-size: 12px;
|
|
||||||
color: #666;
|
|
||||||
}
|
|
||||||
|
@ -186,28 +186,6 @@ body {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
.group-list .member-container {
|
|
||||||
position: relative;
|
|
||||||
}
|
|
||||||
|
|
||||||
.group-list .member-container button {
|
|
||||||
margin-left: 40px;
|
|
||||||
padding: 5px;
|
|
||||||
cursor: pointer;
|
|
||||||
background: var(--primary-color);
|
|
||||||
color: white;
|
|
||||||
border: 0px solid var(--primary-color);
|
|
||||||
border-radius: 50px;
|
|
||||||
position: absolute;
|
|
||||||
top: -25px;
|
|
||||||
right: -25px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.group-list .member-container button:hover {
|
|
||||||
background: var(--accent-color)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/* Zone de chat */
|
/* Zone de chat */
|
||||||
.chat-area {
|
.chat-area {
|
||||||
display: flex;
|
display: flex;
|
||||||
@ -575,23 +553,3 @@ body {
|
|||||||
margin: 0;
|
margin: 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
::-webkit-scrollbar {
|
|
||||||
width: 5px;
|
|
||||||
height: 5px;
|
|
||||||
}
|
|
||||||
|
|
||||||
::-webkit-scrollbar-track {
|
|
||||||
background: var(--primary-color);
|
|
||||||
border-radius: 5px;
|
|
||||||
}
|
|
||||||
|
|
||||||
::-webkit-scrollbar-thumb {
|
|
||||||
background: var(--secondary-color);
|
|
||||||
border-radius: 5px;
|
|
||||||
}
|
|
||||||
|
|
||||||
::-webkit-scrollbar-thumb:hover {
|
|
||||||
background: var(--accent-color);
|
|
||||||
}
|
|
40
src/4nk.css
40
src/4nk.css
@ -316,7 +316,7 @@ h1 {
|
|||||||
margin-top: 0px;
|
margin-top: 0px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.create-btn {
|
.sp-address-btn {
|
||||||
margin-bottom: 2em;
|
margin-bottom: 2em;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
background-color: #d0d0d7;
|
background-color: #d0d0d7;
|
||||||
@ -778,41 +778,3 @@ select[data-multi-select-plugin] {
|
|||||||
.process-card-action {
|
.process-card-action {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**************************************** Select Member Home Page ******************************************************/
|
|
||||||
.custom-select {
|
|
||||||
width: 100%;
|
|
||||||
max-height: 150px;
|
|
||||||
overflow-y: auto;
|
|
||||||
direction: ltr;
|
|
||||||
background-color: white;
|
|
||||||
border: 1px solid #ccc;
|
|
||||||
border-radius: 4px;
|
|
||||||
margin: 10px 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.custom-select option {
|
|
||||||
padding: 8px 12px;
|
|
||||||
cursor: pointer;
|
|
||||||
}
|
|
||||||
|
|
||||||
.custom-select option:hover {
|
|
||||||
background-color: #f0f0f0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.custom-select::-webkit-scrollbar {
|
|
||||||
width: 8px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.custom-select::-webkit-scrollbar-track {
|
|
||||||
background: #f1f1f1;
|
|
||||||
}
|
|
||||||
|
|
||||||
.custom-select::-webkit-scrollbar-thumb {
|
|
||||||
background: #888;
|
|
||||||
border-radius: 4px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.custom-select::-webkit-scrollbar-thumb:hover {
|
|
||||||
background: #555;
|
|
||||||
}
|
|
@ -29,7 +29,7 @@
|
|||||||
<a onclick="navigate('chat')">Chat</a>
|
<a onclick="navigate('chat')">Chat</a>
|
||||||
<a onclick="navigate('signature')">Signatures</a>
|
<a onclick="navigate('signature')">Signatures</a>
|
||||||
<a onclick="navigate('process')">Process</a>
|
<a onclick="navigate('process')">Process</a>
|
||||||
<a onclick="disconnect()">Disconnect</a>
|
<a onclick="navigate('home')">Disconnect</a>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
@ -181,40 +181,3 @@ async function createBackUp() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
(window as any).createBackUp = createBackUp;
|
(window as any).createBackUp = createBackUp;
|
||||||
|
|
||||||
async function disconnect() {
|
|
||||||
console.log('Disconnecting...');
|
|
||||||
try {
|
|
||||||
localStorage.clear();
|
|
||||||
|
|
||||||
await new Promise<void>((resolve, reject) => {
|
|
||||||
const request = indexedDB.deleteDatabase('4nk');
|
|
||||||
request.onsuccess = () => {
|
|
||||||
console.log('IndexedDB deleted successfully');
|
|
||||||
resolve();
|
|
||||||
};
|
|
||||||
request.onerror = () => reject(request.error);
|
|
||||||
request.onblocked = () => {
|
|
||||||
console.log('Database deletion was blocked');
|
|
||||||
resolve();
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
const registrations = await navigator.serviceWorker.getRegistrations();
|
|
||||||
await Promise.all(registrations.map(registration => registration.unregister()));
|
|
||||||
console.log('Service worker unregistered');
|
|
||||||
|
|
||||||
navigate('home');
|
|
||||||
|
|
||||||
setTimeout(() => {
|
|
||||||
window.location.href = window.location.origin;
|
|
||||||
}, 100);
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error during disconnect:', error);
|
|
||||||
// force reload
|
|
||||||
window.location.href = window.location.origin;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
(window as any).disconnect = disconnect;
|
|
@ -1,14 +0,0 @@
|
|||||||
<div id="creation-modal" class="modal">
|
|
||||||
<div class="modal-content">
|
|
||||||
<div class="modal-title">Login</div>
|
|
||||||
<div class="message">
|
|
||||||
Do you want to create a 4NK member?<br />
|
|
||||||
Attempting to create a member with address <br />
|
|
||||||
<strong>{{device1}}</strong> <br />
|
|
||||||
</div>
|
|
||||||
<div class="confirmation-box">
|
|
||||||
<a class="btn confirmation-btn" onclick="confirm()">Confirm</a>
|
|
||||||
<a class="btn refusal-btn" onclick="closeConfirmationModal()">Refuse</a>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
@ -2,7 +2,7 @@ declare global {
|
|||||||
interface Window {
|
interface Window {
|
||||||
initAccount: () => void;
|
initAccount: () => void;
|
||||||
showContractPopup: (contractId: string) => void;
|
showContractPopup: (contractId: string) => void;
|
||||||
showPairing: () => Promise<void>;
|
showPairing: () => void;
|
||||||
showWallet: () => void;
|
showWallet: () => void;
|
||||||
showData: () => void;
|
showData: () => void;
|
||||||
addWalletRow: () => void;
|
addWalletRow: () => void;
|
||||||
@ -36,7 +36,6 @@ declare global {
|
|||||||
generateRecoveryWords: () => string[];
|
generateRecoveryWords: () => string[];
|
||||||
exportUserData: () => void;
|
exportUserData: () => void;
|
||||||
updateActionButtons: () => void;
|
updateActionButtons: () => void;
|
||||||
showQRCodeModal: (address: string) => void;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -46,7 +45,6 @@ import { Row, WalletRow, DataRow, Notification, Contract, NotificationMessage }
|
|||||||
import { addressToEmoji } from '../../utils/sp-address.utils';
|
import { addressToEmoji } from '../../utils/sp-address.utils';
|
||||||
import { getCorrectDOM } from '../../utils/document.utils';
|
import { getCorrectDOM } from '../../utils/document.utils';
|
||||||
import accountStyle from '../../../public/style/account.css?inline';
|
import accountStyle from '../../../public/style/account.css?inline';
|
||||||
import Services from '../../services/service';
|
|
||||||
|
|
||||||
let isAddingRow = false;
|
let isAddingRow = false;
|
||||||
let currentRow: HTMLTableRowElement | null = null;
|
let currentRow: HTMLTableRowElement | null = null;
|
||||||
@ -199,7 +197,6 @@ class AccountElement extends HTMLElement {
|
|||||||
window.updateActionButtons = () => this.updateActionButtons();
|
window.updateActionButtons = () => this.updateActionButtons();
|
||||||
window.openAvatarPopup = () => this.openAvatarPopup();
|
window.openAvatarPopup = () => this.openAvatarPopup();
|
||||||
window.closeAvatarPopup = () => this.closeAvatarPopup();
|
window.closeAvatarPopup = () => this.closeAvatarPopup();
|
||||||
window.showQRCodeModal = (address: string) => this.showQRCodeModal(address);
|
|
||||||
|
|
||||||
if (!localStorage.getItem('rows')) {
|
if (!localStorage.getItem('rows')) {
|
||||||
localStorage.setItem('rows', JSON.stringify(defaultRows));
|
localStorage.setItem('rows', JSON.stringify(defaultRows));
|
||||||
@ -555,13 +552,6 @@ private updateTableContent(rows: Row[]): void {
|
|||||||
<td>${row.column1}</td>
|
<td>${row.column1}</td>
|
||||||
<td class="device-name" onclick="window.editDeviceName(this)">${row.column2}</td>
|
<td class="device-name" onclick="window.editDeviceName(this)">${row.column2}</td>
|
||||||
<td>${row.column3}</td>
|
<td>${row.column3}</td>
|
||||||
<td>
|
|
||||||
<img src="https://api.qrserver.com/v1/create-qr-code/?size=50x50&data=${encodeURIComponent(row.column1)}"
|
|
||||||
alt="QR Code"
|
|
||||||
title="${row.column1}"
|
|
||||||
class="qr-code"
|
|
||||||
onclick="window.showQRCodeModal('${encodeURIComponent(row.column1)}')">
|
|
||||||
</td>
|
|
||||||
<td>
|
<td>
|
||||||
<button class="delete-button" onclick="window.deleteRow(this)">
|
<button class="delete-button" onclick="window.deleteRow(this)">
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" width="16" height="16" fill="red">
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" width="16" height="16" fill="red">
|
||||||
@ -637,26 +627,29 @@ private deleteRow(button: HTMLButtonElement): void {
|
|||||||
const table = row.closest('tbody');
|
const table = row.closest('tbody');
|
||||||
if (!table) return;
|
if (!table) return;
|
||||||
|
|
||||||
|
// Vérifier le nombre de lignes restantes
|
||||||
const remainingRows = table.getElementsByTagName('tr').length;
|
const remainingRows = table.getElementsByTagName('tr').length;
|
||||||
if (remainingRows <= 2) {
|
if (remainingRows <= 2) {
|
||||||
this.showAlert('You must keep at least 2 devices paired');
|
this.showAlert('You must keep at least 2 devices paired');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const index = Array.from(table.children).indexOf(row);
|
// Animation de suppression
|
||||||
row.style.transition = 'opacity 0.3s, transform 0.3s';
|
row.style.transition = 'opacity 0.3s';
|
||||||
row.style.opacity = '0';
|
row.style.opacity = '0';
|
||||||
row.style.transform = 'translateX(-100%)';
|
|
||||||
|
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
|
// Obtenir l'index avant la suppression
|
||||||
|
const index = Array.from(table.children).indexOf(row);
|
||||||
|
|
||||||
|
// Supprimer la ligne du DOM
|
||||||
row.remove();
|
row.remove();
|
||||||
|
|
||||||
|
// Mettre à jour le localStorage
|
||||||
const storageKey = STORAGE_KEYS[currentMode];
|
const storageKey = STORAGE_KEYS[currentMode];
|
||||||
const rows = JSON.parse(localStorage.getItem(storageKey) || '[]');
|
const rows = JSON.parse(localStorage.getItem(storageKey) || '[]');
|
||||||
if (index > -1) {
|
|
||||||
rows.splice(index, 1);
|
rows.splice(index, 1);
|
||||||
localStorage.setItem(storageKey, JSON.stringify(rows));
|
localStorage.setItem(storageKey, JSON.stringify(rows));
|
||||||
}
|
|
||||||
}, 300);
|
}, 300);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -894,6 +887,9 @@ private showContractPopup(contractId: string) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Ajouter à l'objet window
|
||||||
|
|
||||||
|
|
||||||
// Fonction utilitaire pour cacher tous les contenus
|
// Fonction utilitaire pour cacher tous les contenus
|
||||||
private hideAllContent(): void {
|
private hideAllContent(): void {
|
||||||
const contents = ['pairing-content', 'wallet-content', 'process-content', 'data-content'];
|
const contents = ['pairing-content', 'wallet-content', 'process-content', 'data-content'];
|
||||||
@ -906,22 +902,25 @@ private hideAllContent(): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Fonctions d'affichage des sections
|
// Fonctions d'affichage des sections
|
||||||
private async showPairing(): Promise<void> {
|
private showPairing(): void {
|
||||||
const service = await Services.getInstance();
|
|
||||||
const spAddress = await service.getDeviceAddress();
|
|
||||||
|
|
||||||
isAddingRow = false;
|
isAddingRow = false;
|
||||||
currentRow = null;
|
currentRow = null;
|
||||||
currentMode = 'pairing';
|
|
||||||
|
|
||||||
|
currentMode = 'pairing';
|
||||||
|
// Cacher tous les contenus
|
||||||
this.hideAllContent();
|
this.hideAllContent();
|
||||||
|
|
||||||
|
// Mettre à jour le titre
|
||||||
const headerElement = this.shadowRoot?.getElementById('parameter-header');
|
const headerElement = this.shadowRoot?.getElementById('parameter-header');
|
||||||
if (headerElement) {
|
if (headerElement) {
|
||||||
headerElement.textContent = 'Pairing';
|
headerElement.textContent = 'Pairing';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Afficher le contenu de pairing
|
||||||
const pairingContent = this.shadowRoot?.getElementById('pairing-content');
|
const pairingContent = this.shadowRoot?.getElementById('pairing-content');
|
||||||
|
|
||||||
if (pairingContent) {
|
if (pairingContent) {
|
||||||
pairingContent.style.display = 'block';
|
pairingContent.style.display = 'block';
|
||||||
pairingContent.innerHTML = `
|
pairingContent.innerHTML = `
|
||||||
@ -933,8 +932,7 @@ private async showPairing(): Promise<void> {
|
|||||||
<th>SP Address</th>
|
<th>SP Address</th>
|
||||||
<th>Device Name</th>
|
<th>Device Name</th>
|
||||||
<th>SP Emojis</th>
|
<th>SP Emojis</th>
|
||||||
<th>QR Code</th>
|
<th></th>
|
||||||
<th>Actions</th>
|
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody></tbody>
|
<tbody></tbody>
|
||||||
@ -945,46 +943,8 @@ private async showPairing(): Promise<void> {
|
|||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
let rows = JSON.parse(localStorage.getItem(STORAGE_KEYS.pairing) || '[]');
|
// Mettre à jour le contenu du tableau
|
||||||
|
const rows = JSON.parse(localStorage.getItem(STORAGE_KEYS.pairing) || '[]');
|
||||||
const deviceExists = rows.some((row: Row) => row.column1 === spAddress);
|
|
||||||
|
|
||||||
if (!deviceExists && spAddress) {
|
|
||||||
const emojis = await addressToEmoji(spAddress);
|
|
||||||
|
|
||||||
try {
|
|
||||||
// Déboguer le processus de pairing
|
|
||||||
const pairingProcessId = await service.getPairingProcessId();
|
|
||||||
console.log('Pairing Process ID:', pairingProcessId);
|
|
||||||
|
|
||||||
const pairingProcess = await service.getProcess(pairingProcessId);
|
|
||||||
console.log('Pairing Process:', pairingProcess);
|
|
||||||
|
|
||||||
const userName = pairingProcess?.states?.[0]?.metadata?.userName
|
|
||||||
|| pairingProcess?.states?.[0]?.metadata?.name
|
|
||||||
|| localStorage.getItem('userName')
|
|
||||||
|
|
||||||
console.log('Username found:', userName);
|
|
||||||
|
|
||||||
const newRow = {
|
|
||||||
column1: spAddress,
|
|
||||||
column2: userName,
|
|
||||||
column3: emojis
|
|
||||||
};
|
|
||||||
rows = [newRow, ...rows];
|
|
||||||
localStorage.setItem(STORAGE_KEYS.pairing, JSON.stringify(rows));
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error getting pairing process:', error);
|
|
||||||
const newRow = {
|
|
||||||
column1: spAddress,
|
|
||||||
column2: 'This Device',
|
|
||||||
column3: emojis
|
|
||||||
};
|
|
||||||
rows = [newRow, ...rows];
|
|
||||||
localStorage.setItem(STORAGE_KEYS.pairing, JSON.stringify(rows));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
this.updateTableContent(rows);
|
this.updateTableContent(rows);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -1459,28 +1419,6 @@ private initializeEventListeners() {
|
|||||||
avatarInput.addEventListener('change', this.handleAvatarUpload.bind(this));
|
avatarInput.addEventListener('change', this.handleAvatarUpload.bind(this));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private showQRCodeModal(address: string): void {
|
|
||||||
const modal = document.createElement('div');
|
|
||||||
modal.className = 'qr-modal';
|
|
||||||
modal.innerHTML = `
|
|
||||||
<div class="qr-modal-content">
|
|
||||||
<span class="close-qr-modal">×</span>
|
|
||||||
<img src="https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=${address}"
|
|
||||||
alt="QR Code Large"
|
|
||||||
class="qr-code-large">
|
|
||||||
<div class="qr-address">${decodeURIComponent(address)}</div>
|
|
||||||
</div>
|
|
||||||
`;
|
|
||||||
|
|
||||||
this.shadowRoot?.appendChild(modal);
|
|
||||||
|
|
||||||
const closeBtn = modal.querySelector('.close-qr-modal');
|
|
||||||
closeBtn?.addEventListener('click', () => modal.remove());
|
|
||||||
modal.addEventListener('click', (e) => {
|
|
||||||
if (e.target === modal) modal.remove();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
customElements.define('account-element', AccountElement);
|
customElements.define('account-element', AccountElement);
|
||||||
|
File diff suppressed because it is too large
Load Diff
@ -4,23 +4,24 @@
|
|||||||
|
|
||||||
<div class="tab-container">
|
<div class="tab-container">
|
||||||
<div class="tabs">
|
<div class="tabs">
|
||||||
<div class="tab active" data-tab="tab1">Create an account</div>
|
<div class="tab active" data-tab="tab1">Scan QR Code</div>
|
||||||
<div class="tab" data-tab="tab2">Add a device for an existing memeber</div>
|
<div class="tab" data-tab="tab2">Scan other device</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="page-container">
|
<div class="page-container">
|
||||||
<div id="tab1" class="card tab-content active">
|
<div id="tab1" class="card tab-content active">
|
||||||
<div class="card-description">Create an account :</div>
|
<div class="card-description">Scan with your other device :</div>
|
||||||
<div class="pairing-request"></div>
|
<div class="pairing-request"></div>
|
||||||
<!-- <div class="card-image qr-code">
|
<div class="card-image qr-code">
|
||||||
<img src="assets/qr_code.png" alt="QR Code" width="150" height="150" />
|
<img src="assets/qr_code.png" alt="QR Code" width="150" height="150" />
|
||||||
</div> -->
|
</div>
|
||||||
<button id="createButton" class="create-btn"></button>
|
<button id="copyBtn" class="sp-address-btn"></button>
|
||||||
|
<div class="card-image emoji-display" id="emoji-display"></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="separator"></div>
|
<div class="separator"></div>
|
||||||
<div id="tab2" class="card tab-content">
|
<div id="tab2" class="card tab-content">
|
||||||
<div class="card-description">Add a device for an existing member :</div>
|
<div class="card-description">Scan your other device :</div>
|
||||||
<div class="card-image camera-card">
|
<div class="card-image camera-card">
|
||||||
<img id="scanner" src="assets/camera.jpg" alt="QR Code" width="150" height="150" />
|
<img id="scanner" src="assets/camera.jpg" alt="QR Code" width="150" height="150" />
|
||||||
<button id="scan-btn" onclick="scanDevice()">Scan</button>
|
<button id="scan-btn" onclick="scanDevice()">Scan</button>
|
||||||
@ -30,13 +31,8 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<p>Or</p>
|
<p>Or</p>
|
||||||
<!-- <input type="text" id="addressInput" placeholder="Paste address" />
|
<input type="text" id="addressInput" placeholder="Paste address" />
|
||||||
<div id="emoji-display-2"></div> -->
|
<div id="emoji-display-2"></div>
|
||||||
<div class="card-description">Chose a member :</div>
|
|
||||||
<select name="memberSelect" id="memberSelect" size="5" class="custom-select">
|
|
||||||
<!-- Options -->
|
|
||||||
</select>
|
|
||||||
|
|
||||||
<button id="okButton" style="display: none">OK</button>
|
<button id="okButton" style="display: none">OK</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
import Routing from '../../services/modal.service';
|
import Routing from '../../services/modal.service';
|
||||||
import Services from '../../services/service';
|
import Services from '../../services/service';
|
||||||
import { addSubscription } from '../../utils/subscription.utils';
|
import { addSubscription } from '../../utils/subscription.utils';
|
||||||
import { displayEmojis, generateQRCode, generateCreateBtn, addressToEmoji } from '../../utils/sp-address.utils';
|
import { displayEmojis, generateQRCode } from '../../utils/sp-address.utils';
|
||||||
import { getCorrectDOM } from '../../utils/html.utils';
|
import { getCorrectDOM } from '../../utils/html.utils';
|
||||||
import QrScannerComponent from '../../components/qrcode-scanner/qrcode-scanner-component';
|
import QrScannerComponent from '../../components/qrcode-scanner/qrcode-scanner-component';
|
||||||
export { QrScannerComponent };
|
export { QrScannerComponent };
|
||||||
@ -20,12 +20,8 @@ export async function initHomePage(): Promise<void> {
|
|||||||
|
|
||||||
const service = await Services.getInstance();
|
const service = await Services.getInstance();
|
||||||
const spAddress = await service.getDeviceAddress();
|
const spAddress = await service.getDeviceAddress();
|
||||||
// generateQRCode(spAddress);
|
generateQRCode(spAddress);
|
||||||
generateCreateBtn ();
|
|
||||||
displayEmojis(spAddress);
|
displayEmojis(spAddress);
|
||||||
|
|
||||||
// Add this line to populate the select when the page loads
|
|
||||||
await populateMemberSelect();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//// Modal
|
//// Modal
|
||||||
@ -49,46 +45,4 @@ function scanDevice() {
|
|||||||
if (reader) reader.innerHTML = '<qr-scanner></qr-scanner>';
|
if (reader) reader.innerHTML = '<qr-scanner></qr-scanner>';
|
||||||
}
|
}
|
||||||
|
|
||||||
async function populateMemberSelect() {
|
|
||||||
const container = getCorrectDOM('login-4nk-component') as HTMLElement;
|
|
||||||
const memberSelect = container.querySelector('#memberSelect') as HTMLSelectElement;
|
|
||||||
|
|
||||||
if (!memberSelect) {
|
|
||||||
console.error('Could not find memberSelect element');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const service = await Services.getInstance();
|
|
||||||
const members = service.getAllMembersSorted();
|
|
||||||
|
|
||||||
for (const [processId, member] of Object.entries(members)) {
|
|
||||||
const process = await service.getProcess(processId);
|
|
||||||
let memberPublicName;
|
|
||||||
|
|
||||||
if (process) {
|
|
||||||
const publicMemberData = service.getPublicData(process);
|
|
||||||
if (publicMemberData) {
|
|
||||||
const extractedName = publicMemberData['memberPublicName'];
|
|
||||||
if (extractedName !== undefined && extractedName !== null) {
|
|
||||||
memberPublicName = extractedName;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!memberPublicName) {
|
|
||||||
memberPublicName = 'Unnamed Member';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Récupérer les emojis pour ce processId
|
|
||||||
const emojis = await addressToEmoji(processId);
|
|
||||||
|
|
||||||
const option = document.createElement('option');
|
|
||||||
option.value = processId;
|
|
||||||
option.textContent = `${memberPublicName} (${emojis})`;
|
|
||||||
memberSelect.appendChild(option);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
(window as any).populateMemberSelect = populateMemberSelect;
|
|
||||||
|
|
||||||
(window as any).scanDevice = scanDevice;
|
(window as any).scanDevice = scanDevice;
|
||||||
|
@ -2,12 +2,9 @@ import { addSubscription } from '../../utils/subscription.utils';
|
|||||||
import Services from '../../services/service';
|
import Services from '../../services/service';
|
||||||
import { getCorrectDOM } from '~/utils/html.utils';
|
import { getCorrectDOM } from '~/utils/html.utils';
|
||||||
import { Process } from 'pkg/sdk_client';
|
import { Process } from 'pkg/sdk_client';
|
||||||
import chatStyle from '../../../public/style/chat.css?inline';
|
|
||||||
import { Database } from '../../services/database.service';
|
|
||||||
|
|
||||||
// Initialize function, create initial tokens with itens that are already selected by the user
|
// Initialize function, create initial tokens with itens that are already selected by the user
|
||||||
export async function init() {
|
export async function init() {
|
||||||
|
|
||||||
const container = getCorrectDOM('process-list-4nk-component') as HTMLElement;
|
const container = getCorrectDOM('process-list-4nk-component') as HTMLElement;
|
||||||
const element = container.querySelector('select') as HTMLSelectElement;
|
const element = container.querySelector('select') as HTMLSelectElement;
|
||||||
// Create div that wroaps all the elements inside (select, elements selected, search div) to put select inside
|
// Create div that wroaps all the elements inside (select, elements selected, search div) to put select inside
|
||||||
@ -158,39 +155,62 @@ function clearAutocompleteList(select: HTMLSelectElement) {
|
|||||||
if (autocomplete_list) autocomplete_list.innerHTML = '';
|
if (autocomplete_list) autocomplete_list.innerHTML = '';
|
||||||
}
|
}
|
||||||
|
|
||||||
async function populateAutocompleteList(select: HTMLSelectElement, query: string, dropdown = false) {
|
// Populate the autocomplete list following a given query from the user
|
||||||
|
function populateAutocompleteList(select: HTMLSelectElement, query: string, dropdown = false) {
|
||||||
const { autocomplete_options } = getOptions(select);
|
const { autocomplete_options } = getOptions(select);
|
||||||
|
|
||||||
let options_to_show = [];
|
let options_to_show;
|
||||||
|
|
||||||
const service = await Services.getInstance();
|
if (dropdown) {
|
||||||
const mineArray: string[] = await service.getMyProcesses();
|
let messagingCounter = 1;
|
||||||
const allProcesses = await service.getProcesses();
|
const messagingOptions = select.querySelectorAll('option[value="messaging"]');
|
||||||
const allArray: string[] = Object.keys(allProcesses).filter(x => !mineArray.includes(x));
|
|
||||||
|
options_to_show = autocomplete_options.map(option => {
|
||||||
|
if (option === 'messaging') {
|
||||||
|
// Récupérer l'élément option correspondant au compteur actuel
|
||||||
|
const currentOption = messagingOptions[messagingCounter - 1];
|
||||||
|
const processId = currentOption?.getAttribute('data-process-id');
|
||||||
|
console.log(`Mapping messaging ${messagingCounter} with processId:`, processId);
|
||||||
|
|
||||||
|
const optionText = `messaging ${messagingCounter}`;
|
||||||
|
messagingCounter++;
|
||||||
|
|
||||||
|
// Stocker le processId dans un attribut data sur le select
|
||||||
|
select.setAttribute(`data-messaging-id-${messagingCounter - 1}`, processId || '');
|
||||||
|
|
||||||
|
return optionText;
|
||||||
|
}
|
||||||
|
return option;
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
options_to_show = autocomplete(query, autocomplete_options);
|
||||||
|
}
|
||||||
|
|
||||||
const wrapper = select.parentNode;
|
const wrapper = select.parentNode;
|
||||||
const input_search = wrapper?.querySelector('.search-container');
|
const input_search = wrapper?.querySelector('.search-container');
|
||||||
const autocomplete_list = wrapper?.querySelector('.autocomplete-list');
|
const autocomplete_list = wrapper?.querySelector('.autocomplete-list');
|
||||||
if (autocomplete_list) autocomplete_list.innerHTML = '';
|
if (autocomplete_list) autocomplete_list.innerHTML = '';
|
||||||
|
const result_size = options_to_show.length;
|
||||||
|
|
||||||
const addProcessToList = (processId:string, isMine: boolean) => {
|
if (result_size == 1) {
|
||||||
const li = document.createElement('li');
|
const li = document.createElement('li');
|
||||||
li.innerText = processId;
|
li.innerText = options_to_show[0];
|
||||||
li.setAttribute("data-value", processId);
|
li.setAttribute('data-value', options_to_show[0]);
|
||||||
|
|
||||||
if (isMine) {
|
|
||||||
li.classList.add("my-process");
|
|
||||||
li.style.cssText = `color: var(--accent-color)`;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (li) addSubscription(li, 'click', selectOption);
|
if (li) addSubscription(li, 'click', selectOption);
|
||||||
autocomplete_list?.appendChild(li);
|
autocomplete_list?.appendChild(li);
|
||||||
};
|
if (query.length == options_to_show[0].length) {
|
||||||
|
const event = new Event('click');
|
||||||
mineArray.forEach(processId => addProcessToList(processId, true));
|
li.dispatchEvent(event);
|
||||||
allArray.forEach(processId => addProcessToList(processId, false));
|
}
|
||||||
|
} else if (result_size > 1) {
|
||||||
if (mineArray.length === 0 && allArray.length === 0) {
|
for (let i = 0; i < result_size; i++) {
|
||||||
|
const li = document.createElement('li');
|
||||||
|
li.innerText = options_to_show[i];
|
||||||
|
li.setAttribute('data-value', options_to_show[i]);
|
||||||
|
if (li) addSubscription(li, 'click', selectOption);
|
||||||
|
autocomplete_list?.appendChild(li);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
const li = document.createElement('li');
|
const li = document.createElement('li');
|
||||||
li.classList.add('not-cursor');
|
li.classList.add('not-cursor');
|
||||||
li.innerText = 'No options found';
|
li.innerText = 'No options found';
|
||||||
@ -479,7 +499,7 @@ async function createMessagingProcess(): Promise<void> {
|
|||||||
await service.handleApiReturn(createProcessReturn);
|
await service.handleApiReturn(createProcessReturn);
|
||||||
const createPrdReturn = await service.createPrdUpdate(processId, stateId);
|
const createPrdReturn = await service.createPrdUpdate(processId, stateId);
|
||||||
await service.handleApiReturn(createPrdReturn);
|
await service.handleApiReturn(createPrdReturn);
|
||||||
const approveChangeReturn = await service.approveChange(processId, stateId);
|
const approveChangeReturn = service.approveChange(processId, stateId);
|
||||||
await service.handleApiReturn(approveChangeReturn);
|
await service.handleApiReturn(approveChangeReturn);
|
||||||
}, 500)
|
}, 500)
|
||||||
}
|
}
|
||||||
@ -518,3 +538,15 @@ async function getDescription(processId: string, process: Process): Promise<stri
|
|||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function getProcesses(): Promise<any[]> {
|
||||||
|
const service = await Services.getInstance();
|
||||||
|
const processes = await service.getProcesses();
|
||||||
|
|
||||||
|
const res = Object.entries(processes).map(([key, value]) => ({
|
||||||
|
key,
|
||||||
|
value,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
@ -148,7 +148,7 @@ export async function init(): Promise<void> {
|
|||||||
await services.restoreSecretsFromDB();
|
await services.restoreSecretsFromDB();
|
||||||
|
|
||||||
if (services.isPaired()) {
|
if (services.isPaired()) {
|
||||||
await navigate('chat');
|
await navigate('process');
|
||||||
} else {
|
} else {
|
||||||
const queryString = window.location.search;
|
const queryString = window.location.search;
|
||||||
const urlParams = new URLSearchParams(queryString);
|
const urlParams = new URLSearchParams(queryString);
|
||||||
|
@ -1,5 +1,3 @@
|
|||||||
const EMPTY32BYTES = String('').padStart(64, '0');
|
|
||||||
|
|
||||||
self.addEventListener('install', (event) => {
|
self.addEventListener('install', (event) => {
|
||||||
event.waitUntil(self.skipWaiting()); // Activate worker immediately
|
event.waitUntil(self.skipWaiting()); // Activate worker immediately
|
||||||
});
|
});
|
||||||
@ -11,24 +9,25 @@ self.addEventListener('activate', (event) => {
|
|||||||
// Event listener for messages from clients
|
// Event listener for messages from clients
|
||||||
self.addEventListener('message', async (event) => {
|
self.addEventListener('message', async (event) => {
|
||||||
const data = event.data;
|
const data = event.data;
|
||||||
console.log(data);
|
if (data.type === 'START') {
|
||||||
|
const fetchNotifications = async () => {
|
||||||
|
const itemsWithFlag = await getAllItemsWithFlag();
|
||||||
|
|
||||||
if (data.type === 'SCAN') {
|
// Process items with the specific flag
|
||||||
try {
|
itemsWithFlag?.forEach((item) => {
|
||||||
const myProcessesId = data.payload;
|
console.log(item); // Do something with each flagged item
|
||||||
if (myProcessesId && myProcessesId.length != 0) {
|
});
|
||||||
const toDownload = await scanMissingData(myProcessesId);
|
|
||||||
if (toDownload.length != 0) {
|
event.ports[0].postMessage({
|
||||||
console.log('Sending TO_DOWNLOAD message');
|
type: 'NOTIFICATIONS',
|
||||||
event.source.postMessage({ type: 'TO_DOWNLOAD', data: toDownload});
|
data: itemsWithFlag,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
fetchNotifications();
|
||||||
|
setInterval(fetchNotifications, 2 * 60 * 1000);
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
event.source.postMessage({ status: 'error', message: 'Empty lists' });
|
if (data.type === 'ADD_OBJECT') {
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
event.source.postMessage({ status: 'error', message: error.message });
|
|
||||||
}
|
|
||||||
} else if (data.type === 'ADD_OBJECT') {
|
|
||||||
try {
|
try {
|
||||||
const { storeName, object, key } = data.payload;
|
const { storeName, object, key } = data.payload;
|
||||||
const db = await openDatabase();
|
const db = await openDatabase();
|
||||||
@ -48,44 +47,6 @@ self.addEventListener('message', async (event) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
async function scanMissingData(processesToScan) {
|
|
||||||
console.log('Scanning for missing data...');
|
|
||||||
const myProcesses = await getProcesses(processesToScan);
|
|
||||||
|
|
||||||
let toDownload = new Set();
|
|
||||||
// Iterate on each process
|
|
||||||
if (myProcesses && myProcesses.length != 0) {
|
|
||||||
for (const process of myProcesses) {
|
|
||||||
// Iterate on states
|
|
||||||
const firstState = process.states[0];
|
|
||||||
const processId = firstState.commited_in;
|
|
||||||
for (const state of process.states) {
|
|
||||||
if (state.state_id === EMPTY32BYTES) continue;
|
|
||||||
// iterate on pcd_commitment
|
|
||||||
for (const [field, hash] of Object.entries(state.pcd_commitment)) {
|
|
||||||
// Skip public fields
|
|
||||||
if (state.public_data[field] !== undefined || field === 'roles') continue;
|
|
||||||
// Check if we have the data in db
|
|
||||||
const existingData = await getBlob(hash);
|
|
||||||
if (!existingData) {
|
|
||||||
toDownload.add(hash);
|
|
||||||
// We also add an entry in diff, in case it doesn't already exist
|
|
||||||
await addDiff(processId, state.state_id, hash, state.roles, field);
|
|
||||||
} else {
|
|
||||||
// We remove it if we have it in the set
|
|
||||||
if (toDownload.delete(hash)) {
|
|
||||||
console.log(`Removing ${hash} from the set`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log(toDownload);
|
|
||||||
return Array.from(toDownload);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function openDatabase() {
|
async function openDatabase() {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const request = indexedDB.open('4nk', 1);
|
const request = indexedDB.open('4nk', 1);
|
||||||
@ -104,58 +65,32 @@ async function openDatabase() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Function to get all processes because it is asynchronous
|
async function getAllItemsWithFlag() {
|
||||||
async function getAllProcesses() {
|
|
||||||
const db = await openDatabase();
|
const db = await openDatabase();
|
||||||
|
|
||||||
|
// Function to get all processes because it is asynchronous
|
||||||
|
const getAllProcesses = () => {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
if (!db) {
|
|
||||||
reject(new Error('Database is not available'));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const tx = db.transaction('processes', 'readonly');
|
const tx = db.transaction('processes', 'readonly');
|
||||||
const store = tx.objectStore('processes');
|
const store = tx.objectStore('processes');
|
||||||
const request = store.getAll();
|
const request = store.openCursor();
|
||||||
|
const processes = [];
|
||||||
|
|
||||||
request.onsuccess = () => {
|
request.onsuccess = (event) => {
|
||||||
resolve(request.result);
|
const cursor = event.target.result;
|
||||||
};
|
if (cursor) {
|
||||||
|
processes.push({ key: cursor.key, ...cursor.value });
|
||||||
request.onerror = () => {
|
cursor.continue();
|
||||||
reject(request.error);
|
} else {
|
||||||
};
|
resolve(processes);
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
async function getProcesses(processIds) {
|
|
||||||
if (!processIds || processIds.length === 0) {
|
|
||||||
return [];
|
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const db = await openDatabase();
|
request.onerror = (event) => {
|
||||||
if (!db) {
|
reject(event.target.error);
|
||||||
throw new Error('Database is not available');
|
|
||||||
}
|
|
||||||
|
|
||||||
const tx = db.transaction('processes', 'readonly');
|
|
||||||
const store = tx.objectStore('processes');
|
|
||||||
|
|
||||||
const requests = Array.from(processIds).map((processId) => {
|
|
||||||
return new Promise((resolve) => {
|
|
||||||
const request = store.get(processId);
|
|
||||||
request.onsuccess = () => resolve(request.result);
|
|
||||||
request.onerror = () => {
|
|
||||||
console.error(`Error fetching process ${processId}:`, request.error);
|
|
||||||
resolve(undefined);
|
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
});
|
};
|
||||||
|
|
||||||
const results = await Promise.all(requests);
|
|
||||||
return results.filter(result => result !== undefined);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function getAllDiffsNeedValidation() {
|
|
||||||
const db = await openDatabase();
|
|
||||||
|
|
||||||
const allProcesses = await getAllProcesses();
|
const allProcesses = await getAllProcesses();
|
||||||
const tx = db.transaction('diffs', 'readonly');
|
const tx = db.transaction('diffs', 'readonly');
|
||||||
@ -211,56 +146,3 @@ async function getAllDiffsNeedValidation() {
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getBlob(hash) {
|
|
||||||
const db = await openDatabase();
|
|
||||||
const storeName = 'data';
|
|
||||||
const tx = db.transaction(storeName, 'readonly');
|
|
||||||
const store = tx.objectStore(storeName);
|
|
||||||
const result = await new Promise((resolve, reject) => {
|
|
||||||
const getRequest = store.get(hash);
|
|
||||||
getRequest.onsuccess = () => resolve(getRequest.result);
|
|
||||||
getRequest.onerror = () => reject(getRequest.error);
|
|
||||||
});
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function addDiff(processId, stateId, hash, roles, field) {
|
|
||||||
const db = await openDatabase();
|
|
||||||
const storeName = 'diffs';
|
|
||||||
const tx = db.transaction(storeName, 'readwrite');
|
|
||||||
const store = tx.objectStore(storeName);
|
|
||||||
|
|
||||||
// Check if the diff already exists
|
|
||||||
const existingDiff = await new Promise((resolve, reject) => {
|
|
||||||
const getRequest = store.get(hash);
|
|
||||||
getRequest.onsuccess = () => resolve(getRequest.result);
|
|
||||||
getRequest.onerror = () => reject(getRequest.error);
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!existingDiff) {
|
|
||||||
const newDiff = {
|
|
||||||
process_id: processId,
|
|
||||||
state_id: stateId,
|
|
||||||
value_commitment: hash,
|
|
||||||
roles: roles,
|
|
||||||
field: field,
|
|
||||||
description: null,
|
|
||||||
previous_value: null,
|
|
||||||
new_value: null,
|
|
||||||
notify_user: false,
|
|
||||||
need_validation: false,
|
|
||||||
validation_status: 'None'
|
|
||||||
};
|
|
||||||
|
|
||||||
const insertResult = await new Promise((resolve, reject) => {
|
|
||||||
const putRequest = store.put(newDiff);
|
|
||||||
putRequest.onsuccess = () => resolve(putRequest.result);
|
|
||||||
putRequest.onerror = () => reject(putRequest.error);
|
|
||||||
});
|
|
||||||
|
|
||||||
return insertResult;
|
|
||||||
}
|
|
||||||
|
|
||||||
return existingDiff;
|
|
||||||
}
|
|
||||||
|
@ -1,14 +1,13 @@
|
|||||||
import Services from './service';
|
import Services from './service';
|
||||||
|
|
||||||
export class Database {
|
class Database {
|
||||||
private static instance: Database;
|
private static instance: Database;
|
||||||
private db: IDBDatabase | null = null;
|
private db: IDBDatabase | null = null;
|
||||||
private dbName: string = '4nk';
|
private dbName: string = '4nk';
|
||||||
private dbVersion: number = 1;
|
private dbVersion: number = 1;
|
||||||
private serviceWorkerRegistration: ServiceWorkerRegistration | null = null;
|
private serviceWorkerRegistration: ServiceWorkerRegistration | null = null;
|
||||||
private messageChannel: MessageChannel | null = null;
|
private messageChannel: MessageChannel = new MessageChannel();
|
||||||
private messageChannelForGet: MessageChannel | null = null;
|
private messageChannelForGet: MessageChannel = new MessageChannel();
|
||||||
private serviceWorkerCheckIntervalId: number | null = null;
|
|
||||||
private storeDefinitions = {
|
private storeDefinitions = {
|
||||||
AnkLabels: {
|
AnkLabels: {
|
||||||
name: 'labels',
|
name: 'labels',
|
||||||
@ -44,11 +43,6 @@ export class Database {
|
|||||||
{ name: 'byStatus', keyPath: 'validation_status', options: { unique: false } },
|
{ name: 'byStatus', keyPath: 'validation_status', options: { unique: false } },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
AnkData: {
|
|
||||||
name: 'data',
|
|
||||||
options: {},
|
|
||||||
indices: [],
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Private constructor to prevent direct instantiation from outside
|
// Private constructor to prevent direct instantiation from outside
|
||||||
@ -82,10 +76,12 @@ export class Database {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
request.onsuccess = async () => {
|
request.onsuccess = () => {
|
||||||
|
setTimeout(() => {
|
||||||
this.db = request.result;
|
this.db = request.result;
|
||||||
await this.initServiceWorker();
|
this.initServiceWorker();
|
||||||
resolve();
|
resolve();
|
||||||
|
}, 500);
|
||||||
};
|
};
|
||||||
|
|
||||||
request.onerror = () => {
|
request.onerror = () => {
|
||||||
@ -110,67 +106,35 @@ export class Database {
|
|||||||
return objectList;
|
return objectList;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async initServiceWorker() {
|
private createMessageChannel(responseHandler: (event: MessageEvent) => void): MessageChannel {
|
||||||
if (!('serviceWorker' in navigator)) return; // Ensure service workers are supported
|
const messageChannel = new MessageChannel();
|
||||||
|
messageChannel.port1.onmessage = responseHandler;
|
||||||
try {
|
return messageChannel;
|
||||||
// Get existing service worker registrations
|
|
||||||
const registrations = await navigator.serviceWorker.getRegistrations();
|
|
||||||
if (registrations.length === 0) {
|
|
||||||
// No existing workers: register a new one.
|
|
||||||
this.serviceWorkerRegistration = await navigator.serviceWorker.register('/src/service-workers/database.worker.js', { type: 'module' });
|
|
||||||
console.log('Service Worker registered with scope:', this.serviceWorkerRegistration.scope);
|
|
||||||
} else if (registrations.length === 1) {
|
|
||||||
// One existing worker: update it (restart it) without unregistering.
|
|
||||||
this.serviceWorkerRegistration = registrations[0];
|
|
||||||
await this.serviceWorkerRegistration.update();
|
|
||||||
console.log('Service Worker updated');
|
|
||||||
} else {
|
|
||||||
// More than one existing worker: unregister them all and register a new one.
|
|
||||||
console.log('Multiple Service Worker(s) detected. Unregistering all...');
|
|
||||||
await Promise.all(registrations.map(reg => reg.unregister()));
|
|
||||||
console.log('All previous Service Workers unregistered.');
|
|
||||||
this.serviceWorkerRegistration = await navigator.serviceWorker.register('/src/service-workers/database.worker.js', { type: 'module' });
|
|
||||||
console.log('Service Worker registered with scope:', this.serviceWorkerRegistration.scope);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async initServiceWorker() {
|
||||||
|
if ('serviceWorker' in navigator) {
|
||||||
|
try {
|
||||||
|
const registration = await navigator.serviceWorker.register('/src/service-workers/database.worker.js', { type: 'module' });
|
||||||
|
console.log('Service Worker registered with scope:', registration.scope);
|
||||||
|
|
||||||
|
this.serviceWorkerRegistration = registration
|
||||||
await this.checkForUpdates();
|
await this.checkForUpdates();
|
||||||
|
|
||||||
// Set up a global message listener for responses from the service worker.
|
// Set up the message channels
|
||||||
navigator.serviceWorker.addEventListener('message', async (event) => {
|
this.messageChannel.port1.onmessage = this.handleAddObjectResponse;
|
||||||
console.log('Received message from service worker:', event.data);
|
this.messageChannelForGet.port1.onmessage = this.handleGetObjectResponse;
|
||||||
await this.handleServiceWorkerMessage(event.data);
|
registration.active?.postMessage(
|
||||||
});
|
{
|
||||||
|
type: 'START',
|
||||||
// Set up a periodic check to ensure the service worker is active and to send a SYNC message.
|
},
|
||||||
this.serviceWorkerCheckIntervalId = window.setInterval(async () => {
|
[this.messageChannel.port2],
|
||||||
const activeWorker = this.serviceWorkerRegistration.active || (await this.waitForServiceWorkerActivation(this.serviceWorkerRegistration));
|
);
|
||||||
const service = await Services.getInstance();
|
// Optionally, initialize service worker with some data
|
||||||
const payload = await service.getMyProcesses();
|
|
||||||
if (payload.length != 0) {
|
|
||||||
activeWorker?.postMessage({ type: 'SCAN', payload });
|
|
||||||
}
|
|
||||||
}, 5000);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Service Worker registration failed:', error);
|
console.error('Service Worker registration failed:', error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Helper function to wait for service worker activation
|
|
||||||
private async waitForServiceWorkerActivation(registration: ServiceWorkerRegistration): Promise<ServiceWorker | null> {
|
|
||||||
return new Promise((resolve) => {
|
|
||||||
if (registration.active) {
|
|
||||||
resolve(registration.active);
|
|
||||||
} else {
|
|
||||||
const listener = () => {
|
|
||||||
if (registration.active) {
|
|
||||||
navigator.serviceWorker.removeEventListener('controllerchange', listener);
|
|
||||||
resolve(registration.active);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
navigator.serviceWorker.addEventListener('controllerchange', listener);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async checkForUpdates() {
|
private async checkForUpdates() {
|
||||||
@ -189,92 +153,12 @@ export class Database {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async handleServiceWorkerMessage(message: any) {
|
|
||||||
switch (message.type) {
|
|
||||||
case 'TO_DOWNLOAD':
|
|
||||||
await this.handleDownloadList(message.data);
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
console.warn('Unknown message type received from service worker:', message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async handleDownloadList(downloadList: string[]): void {
|
|
||||||
// Download the missing data
|
|
||||||
let requestedStateId = [];
|
|
||||||
const service = await Services.getInstance();
|
|
||||||
for (const hash of downloadList) {
|
|
||||||
const diff = await service.getDiffByValue(hash);
|
|
||||||
if (!diff) {
|
|
||||||
// This should never happen
|
|
||||||
console.warn(`Missing a diff for hash ${hash}`);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const processId = diff.process_id;
|
|
||||||
const stateId = diff.state_id;
|
|
||||||
const roles = diff.roles;
|
|
||||||
try {
|
|
||||||
const valueBytes = await service.fetchValueFromStorage(hash);
|
|
||||||
if (valueBytes) {
|
|
||||||
// Save data to db
|
|
||||||
const blob = new Blob([valueBytes], {type: "application/octet-stream"});
|
|
||||||
await service.saveBlobToDb(hash, blob);
|
|
||||||
document.dispatchEvent(new CustomEvent('newDataReceived', {
|
|
||||||
detail: {
|
|
||||||
processId,
|
|
||||||
stateId,
|
|
||||||
hash,
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
} else {
|
|
||||||
// We first request the data from managers
|
|
||||||
console.log('Request data from managers of the process');
|
|
||||||
// get the diff from db
|
|
||||||
if (!requestedStateId.includes(stateId)) {
|
|
||||||
await service.requestDataFromPeers(processId, [stateId], [roles]);
|
|
||||||
requestedStateId.push(stateId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
console.error(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private handleAddObjectResponse = async (event: MessageEvent) => {
|
private handleAddObjectResponse = async (event: MessageEvent) => {
|
||||||
const data = event.data;
|
const data = event.data;
|
||||||
console.log('Received response from service worker (ADD_OBJECT):', data);
|
console.log('Received response from service worker (ADD_OBJECT):', data);
|
||||||
const service = await Services.getInstance();
|
|
||||||
if (data.type === 'NOTIFICATIONS') {
|
if (data.type === 'NOTIFICATIONS') {
|
||||||
|
const service = await Services.getInstance();
|
||||||
service.setNotifications(data.data);
|
service.setNotifications(data.data);
|
||||||
} else if (data.type === 'TO_DOWNLOAD') {
|
|
||||||
console.log(`Received missing data ${data}`);
|
|
||||||
// Download the missing data
|
|
||||||
let requestedStateId = [];
|
|
||||||
for (const hash of data.data) {
|
|
||||||
try {
|
|
||||||
const valueBytes = await service.fetchValueFromStorage(hash);
|
|
||||||
if (valueBytes) {
|
|
||||||
// Save data to db
|
|
||||||
const blob = new Blob([valueBytes], {type: "application/octet-stream"});
|
|
||||||
await service.saveBlobToDb(hash, blob);
|
|
||||||
} else {
|
|
||||||
// We first request the data from managers
|
|
||||||
console.log('Request data from managers of the process');
|
|
||||||
// get the diff from db
|
|
||||||
const diff = await service.getDiffByValue(hash);
|
|
||||||
const processId = diff.process_id;
|
|
||||||
const stateId = diff.state_id;
|
|
||||||
const roles = diff.roles;
|
|
||||||
if (!requestedStateId.includes(stateId)) {
|
|
||||||
await service.requestDataFromPeers(processId, [stateId], [roles]);
|
|
||||||
requestedStateId.push(stateId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
console.error(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -283,15 +167,13 @@ export class Database {
|
|||||||
};
|
};
|
||||||
|
|
||||||
public addObject(payload: { storeName: string; object: any; key: any }): Promise<void> {
|
public addObject(payload: { storeName: string; object: any; key: any }): Promise<void> {
|
||||||
return new Promise(async (resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
// Check if the service worker is active
|
// Check if the service worker is active
|
||||||
if (!this.serviceWorkerRegistration) {
|
if (!this.serviceWorkerRegistration?.active) {
|
||||||
// console.warn('Service worker registration is not ready. Waiting...');
|
reject(new Error('Service worker is not active'));
|
||||||
this.serviceWorkerRegistration = await navigator.serviceWorker.ready;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const activeWorker = await this.waitForServiceWorkerActivation(this.serviceWorkerRegistration);
|
|
||||||
|
|
||||||
// Create a message channel for communication
|
// Create a message channel for communication
|
||||||
const messageChannel = new MessageChannel();
|
const messageChannel = new MessageChannel();
|
||||||
|
|
||||||
@ -307,7 +189,7 @@ export class Database {
|
|||||||
|
|
||||||
// Send the add object request to the service worker
|
// Send the add object request to the service worker
|
||||||
try {
|
try {
|
||||||
activeWorker?.postMessage(
|
this.serviceWorkerRegistration.active.postMessage(
|
||||||
{
|
{
|
||||||
type: 'ADD_OBJECT',
|
type: 'ADD_OBJECT',
|
||||||
payload,
|
payload,
|
||||||
|
@ -14,7 +14,6 @@ export default class ModalService {
|
|||||||
private processId: string | null = null;
|
private processId: string | null = null;
|
||||||
private constructor() {}
|
private constructor() {}
|
||||||
private paired_addresses: string[] = [];
|
private paired_addresses: string[] = [];
|
||||||
private modal: HTMLElement | null = null;
|
|
||||||
|
|
||||||
// Method to access the singleton instance of Services
|
// Method to access the singleton instance of Services
|
||||||
public static async getInstance(): Promise<ModalService> {
|
public static async getInstance(): Promise<ModalService> {
|
||||||
@ -55,21 +54,6 @@ export default class ModalService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async injectCreationModal(members: any[]) {
|
|
||||||
const container = document.querySelector('#containerId');
|
|
||||||
if (container) {
|
|
||||||
let html = await fetch('/src/components/modal/creation-modal.html').then((res) => res.text());
|
|
||||||
html = html.replace('{{device1}}', await addressToEmoji(members[0]['sp_addresses'][0]));
|
|
||||||
container.innerHTML += html;
|
|
||||||
|
|
||||||
// Dynamically load the header JS
|
|
||||||
const script = document.createElement('script');
|
|
||||||
script.src = '/src/components/modal/confirmation-modal.ts';
|
|
||||||
script.type = 'module';
|
|
||||||
document.head.appendChild(script);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Device 1 wait Device 2
|
// Device 1 wait Device 2
|
||||||
async injectWaitingModal() {
|
async injectWaitingModal() {
|
||||||
const container = document.querySelector('#containerId');
|
const container = document.querySelector('#containerId');
|
||||||
@ -111,48 +95,43 @@ export default class ModalService {
|
|||||||
|
|
||||||
public async openPairingConfirmationModal(roleDefinition: Record<string, RoleDefinition>, processId: string, stateId: string) {
|
public async openPairingConfirmationModal(roleDefinition: Record<string, RoleDefinition>, processId: string, stateId: string) {
|
||||||
let members;
|
let members;
|
||||||
if (roleDefinition['pairing']) {
|
if (roleDefinition['owner']) {
|
||||||
const owner = roleDefinition['pairing'];
|
const owner = roleDefinition['owner'];
|
||||||
members = owner.members;
|
members = owner.members;
|
||||||
} else {
|
} else {
|
||||||
throw new Error('No "pairing" role');
|
throw new Error('No "owner" role');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (members.length != 1) {
|
if (members.length != 1) {
|
||||||
throw new Error('Must have exactly 1 member');
|
throw new Error('Must have exactly 1 member');
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log("MEMBERS:", members);
|
|
||||||
// We take all the addresses except our own
|
// We take all the addresses except our own
|
||||||
const service = await Services.getInstance();
|
const service = await Services.getInstance();
|
||||||
const localAddress = await service.getDeviceAddress();
|
const localAddress = await service.getDeviceAddress();
|
||||||
for (const member of members) {
|
for (const member of members) {
|
||||||
if (member.sp_addresses) {
|
for (const address of member['sp_addresses']) {
|
||||||
for (const address of member.sp_addresses) {
|
|
||||||
if (address !== localAddress) {
|
if (address !== localAddress) {
|
||||||
this.paired_addresses.push(address);
|
this.paired_addresses.push(address);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
this.processId = processId;
|
this.processId = processId;
|
||||||
this.stateId = stateId;
|
this.stateId = stateId;
|
||||||
|
|
||||||
if (members[0].sp_addresses.length === 1) {
|
|
||||||
await this.injectCreationModal(members);
|
|
||||||
this.modal = document.getElementById('creation-modal');
|
|
||||||
console.log("LENGTH:", members[0].sp_addresses.length);
|
|
||||||
} else {
|
|
||||||
await this.injectModal(members);
|
await this.injectModal(members);
|
||||||
this.modal = document.getElementById('modal');
|
const modal = document.getElementById('modal');
|
||||||
console.log("LENGTH:", members[0].sp_addresses.length);
|
if (modal) modal.style.display = 'flex';
|
||||||
}
|
// const newScript = document.createElement('script');
|
||||||
|
// newScript.setAttribute('type', 'module');
|
||||||
|
// newScript.textContent = confirmationModalScript;
|
||||||
|
// document.head.appendChild(newScript).parentNode?.removeChild(newScript);
|
||||||
|
|
||||||
if (this.modal) this.modal.style.display = 'flex';
|
// Add correct text
|
||||||
|
|
||||||
// Close modal when clicking outside of it
|
// Close modal when clicking outside of it
|
||||||
window.onclick = (event) => {
|
window.onclick = (event) => {
|
||||||
if (event.target === this.modal) {
|
const modal = document.getElementById('modal');
|
||||||
|
if (event.target === modal) {
|
||||||
this.closeConfirmationModal();
|
this.closeConfirmationModal();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -161,12 +140,14 @@ export default class ModalService {
|
|||||||
console.log('=============> Confirm Login');
|
console.log('=============> Confirm Login');
|
||||||
}
|
}
|
||||||
async closeLoginModal() {
|
async closeLoginModal() {
|
||||||
if (this.modal) this.modal.style.display = 'none';
|
const modal = document.getElementById('login-modal');
|
||||||
|
if (modal) modal.style.display = 'none';
|
||||||
}
|
}
|
||||||
|
|
||||||
async confirmPairing() {
|
async confirmPairing() {
|
||||||
const service = await Services.getInstance();
|
const service = await Services.getInstance();
|
||||||
if (this.modal) this.modal.style.display = 'none';
|
const modal = document.getElementById('modal');
|
||||||
|
if (modal) modal.style.display = 'none';
|
||||||
|
|
||||||
if (service.device1) {
|
if (service.device1) {
|
||||||
console.log("Device 1 detected");
|
console.log("Device 1 detected");
|
||||||
@ -185,7 +166,7 @@ export default class ModalService {
|
|||||||
|
|
||||||
// We send confirmation that we validate the change
|
// We send confirmation that we validate the change
|
||||||
try {
|
try {
|
||||||
const approveChangeReturn = await service.approveChange(this.processId!, this.stateId!);
|
const approveChangeReturn = service.approveChange(this.processId!, this.stateId!);
|
||||||
await service.handleApiReturn(approveChangeReturn);
|
await service.handleApiReturn(approveChangeReturn);
|
||||||
|
|
||||||
await this.injectWaitingModal();
|
await this.injectWaitingModal();
|
||||||
@ -205,7 +186,7 @@ export default class ModalService {
|
|||||||
const newDevice = service.dumpDeviceFromMemory();
|
const newDevice = service.dumpDeviceFromMemory();
|
||||||
console.log(newDevice);
|
console.log(newDevice);
|
||||||
await service.saveDeviceInDatabase(newDevice);
|
await service.saveDeviceInDatabase(newDevice);
|
||||||
navigate('chat');
|
navigate('process');
|
||||||
service.resetState();
|
service.resetState();
|
||||||
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@ -234,7 +215,7 @@ export default class ModalService {
|
|||||||
|
|
||||||
// We send confirmation that we validate the change
|
// We send confirmation that we validate the change
|
||||||
try {
|
try {
|
||||||
const approveChangeReturn = await service.approveChange(this.processId!, this.stateId!);
|
const approveChangeReturn = service.approveChange(this.processId!, this.stateId!);
|
||||||
await service.handleApiReturn(approveChangeReturn);
|
await service.handleApiReturn(approveChangeReturn);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
throw e;
|
throw e;
|
||||||
@ -248,13 +229,14 @@ export default class ModalService {
|
|||||||
const newDevice = service.dumpDeviceFromMemory();
|
const newDevice = service.dumpDeviceFromMemory();
|
||||||
console.log(newDevice);
|
console.log(newDevice);
|
||||||
await service.saveDeviceInDatabase(newDevice);
|
await service.saveDeviceInDatabase(newDevice);
|
||||||
navigate('chat');
|
navigate('process');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async closeConfirmationModal() {
|
async closeConfirmationModal() {
|
||||||
const service = await Services.getInstance();
|
const service = await Services.getInstance();
|
||||||
await service.unpairDevice();
|
await service.unpairDevice();
|
||||||
if (this.modal) this.modal.style.display = 'none';
|
const modal = document.getElementById('modal');
|
||||||
|
if (modal) modal.style.display = 'none';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -6,24 +6,25 @@ import { initWebsocket, sendMessage } from '../websockets';
|
|||||||
import { ApiReturn, Device, HandshakeMessage, Member, Process, RoleDefinition, SecretsStore, UserDiff } from '../../pkg/sdk_client';
|
import { ApiReturn, Device, HandshakeMessage, Member, Process, RoleDefinition, SecretsStore, UserDiff } from '../../pkg/sdk_client';
|
||||||
import ModalService from './modal.service';
|
import ModalService from './modal.service';
|
||||||
import Database from './database.service';
|
import Database from './database.service';
|
||||||
import { storeData, retrieveData, testData } from './storage.service';
|
import { storeData, retrieveData } from './storage.service';
|
||||||
import { BackUp } from '~/models/backup.model';
|
import { BackUp } from '~/models/backup.model';
|
||||||
|
|
||||||
export const U32_MAX = 4294967295;
|
export const U32_MAX = 4294967295;
|
||||||
|
|
||||||
const BASEURL = `https://demo.4nkweb.com`;
|
const storageUrl = `/storage`;
|
||||||
const BOOTSTRAPURL = [`${BASEURL}/ws/`];
|
const BOOTSTRAPURL = [`https://demo.4nkweb.com/ws/`];
|
||||||
const STORAGEURL = `${BASEURL}/storage`
|
|
||||||
const DEFAULTAMOUNT = 1000n;
|
const DEFAULTAMOUNT = 1000n;
|
||||||
const EMPTY32BYTES = String('').padStart(64, '0');
|
|
||||||
|
|
||||||
export default class Services {
|
export default class Services {
|
||||||
private static initializing: Promise<Services> | null = null;
|
private static initializing: Promise<Services> | null = null;
|
||||||
private static instance: Services;
|
private static instance: Services;
|
||||||
private currentProcess: string | null = null;
|
private currentProcess: string | null = null;
|
||||||
|
private pendingUpdates: any | null = null;
|
||||||
private currentUpdateMerkleRoot: string | null = null;
|
private currentUpdateMerkleRoot: string | null = null;
|
||||||
|
private localAddress: string | null = null;
|
||||||
|
private pairedAddresses: string[] = [];
|
||||||
private sdkClient: any;
|
private sdkClient: any;
|
||||||
private myProcesses: Set = new Set();
|
private processes: IProcess[] | null = null;
|
||||||
private notifications: any[] | null = null;
|
private notifications: any[] | null = null;
|
||||||
private subscriptions: { element: Element; event: string; eventHandler: string }[] = [];
|
private subscriptions: { element: Element; event: string; eventHandler: string }[] = [];
|
||||||
private database: any;
|
private database: any;
|
||||||
@ -209,8 +210,8 @@ export default class Services {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async ensureSufficientAmount(): Promise<void> {
|
private async ensureSufficientAmount(): Promise<void> {
|
||||||
const availableAmt = this.getAmount();
|
let availableAmt = this.getAmount();
|
||||||
const target: BigInt = DEFAULTAMOUNT * BigInt(10);
|
const target: BigInt = DEFAULTAMOUNT * BigInt(2);
|
||||||
|
|
||||||
if (availableAmt < target) {
|
if (availableAmt < target) {
|
||||||
const faucetMsg = this.createFaucetMessage();
|
const faucetMsg = this.createFaucetMessage();
|
||||||
@ -238,40 +239,91 @@ export default class Services {
|
|||||||
throw new Error('Amount is still 0 after 3 attempts');
|
throw new Error('Amount is still 0 after 3 attempts');
|
||||||
}
|
}
|
||||||
|
|
||||||
public async createPairingProcess(userName: string, pairWith: string[], relayAddress: string, feeRate: number): Promise<ApiReturn> {
|
public async createMessagingProcess(otherMembers: Member[],relayAddress: string, feeRate: number): Promise<ApiReturn> {
|
||||||
|
if (!this.isPaired()) {
|
||||||
|
throw new Error('Device not paired');
|
||||||
|
}
|
||||||
|
const me = await this.getMemberFromDevice();
|
||||||
|
if (!me) {
|
||||||
|
throw new Error('No paired member in device');
|
||||||
|
}
|
||||||
|
const allMembers: Member[] = otherMembers;
|
||||||
|
const meAndOne = [{ sp_addresses: me }, otherMembers.pop()!];
|
||||||
|
allMembers.push({ sp_addresses: me });
|
||||||
|
const everyOneElse = otherMembers;
|
||||||
|
const messagingTemplate = {
|
||||||
|
description: 'messaging',
|
||||||
|
roles: {
|
||||||
|
public: {
|
||||||
|
members: allMembers,
|
||||||
|
validation_rules: [
|
||||||
|
{
|
||||||
|
quorum: 0.0,
|
||||||
|
fields: ['description', 'roles'],
|
||||||
|
min_sig_member: 0.0,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
storages: [storageUrl]
|
||||||
|
},
|
||||||
|
owner: {
|
||||||
|
members: meAndOne,
|
||||||
|
validation_rules: [
|
||||||
|
{
|
||||||
|
quorum: 1.0,
|
||||||
|
fields: ['description', 'roles'],
|
||||||
|
min_sig_member: 1.0,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
storages: [storageUrl]
|
||||||
|
},
|
||||||
|
users: {
|
||||||
|
members: everyOneElse,
|
||||||
|
validation_rules: [
|
||||||
|
{
|
||||||
|
quorum: 0.0,
|
||||||
|
fields: ['description', 'roles'],
|
||||||
|
min_sig_member: 0.0,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
storages: [storageUrl]
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
return this.sdkClient.create_new_process(JSON.stringify(messagingTemplate), null, relayAddress, feeRate);
|
||||||
|
} catch (e) {
|
||||||
|
throw new Error(`Creating process failed: ${e}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async createPairingProcess(pairWith: string[], relayAddress: string, feeRate: number): Promise<ApiReturn> {
|
||||||
if (this.sdkClient.is_paired()) {
|
if (this.sdkClient.is_paired()) {
|
||||||
throw new Error('Device already paired');
|
throw new Error('Device already paired');
|
||||||
}
|
}
|
||||||
const myAddress: string = this.sdkClient.get_address();
|
const myAddress: string = this.sdkClient.get_address();
|
||||||
pairWith.push(myAddress);
|
pairWith.push(myAddress);
|
||||||
const roles: Record<string, RoleDefinition> = {
|
const newKey = this.sdkClient.get_new_keypair();
|
||||||
pairing: {
|
const pairingTemplate = {
|
||||||
|
description: 'pairing',
|
||||||
|
roles: {
|
||||||
|
owner: {
|
||||||
members: [{ sp_addresses: pairWith }],
|
members: [{ sp_addresses: pairWith }],
|
||||||
validation_rules: [
|
validation_rules: [
|
||||||
{
|
{
|
||||||
quorum: 1.0,
|
quorum: 1.0,
|
||||||
fields: ['description', 'counter', 'roles', 'memberPublicName'],
|
fields: ['description', 'roles', 'session_privkey', 'session_pubkey', 'key_parity'],
|
||||||
min_sig_member: 1.0,
|
min_sig_member: 1.0,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
storages: [STORAGEURL]
|
storages: [storageUrl]
|
||||||
},
|
},
|
||||||
|
},
|
||||||
|
session_privkey: newKey['private_key'],
|
||||||
|
session_pubkey: newKey['x_only_public_key'],
|
||||||
|
key_parity: newKey['key_parity'],
|
||||||
};
|
};
|
||||||
const pairingTemplate = {
|
|
||||||
description: 'pairing',
|
|
||||||
counter: 0,
|
|
||||||
};
|
|
||||||
const publicData = {
|
|
||||||
memberPublicName: userName
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
return this.sdkClient.create_new_process(
|
return this.sdkClient.create_new_process(JSON.stringify(pairingTemplate), null, relayAddress, feeRate);
|
||||||
pairingTemplate,
|
|
||||||
roles,
|
|
||||||
publicData,
|
|
||||||
relayAddress,
|
|
||||||
feeRate
|
|
||||||
);
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
throw new Error(`Creating process failed:, ${e}`);
|
throw new Error(`Creating process failed:, ${e}`);
|
||||||
}
|
}
|
||||||
@ -298,20 +350,10 @@ export default class Services {
|
|||||||
throw new Error('No paired member found');
|
throw new Error('No paired member found');
|
||||||
}
|
}
|
||||||
|
|
||||||
const roles = {
|
const dmTemplate = {
|
||||||
demiurge: {
|
description: 'dm',
|
||||||
members: [
|
message: '',
|
||||||
{ sp_addresses: myAddresses },
|
roles: {
|
||||||
],
|
|
||||||
validation_rules: [
|
|
||||||
{
|
|
||||||
quorum: 0.01,
|
|
||||||
fields: ['message', 'description', 'roles'],
|
|
||||||
min_sig_member: 0.01,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
storages: [STORAGEURL]
|
|
||||||
}
|
|
||||||
dm: {
|
dm: {
|
||||||
members: [
|
members: [
|
||||||
{ sp_addresses: myAddresses },
|
{ sp_addresses: myAddresses },
|
||||||
@ -320,31 +362,26 @@ export default class Services {
|
|||||||
validation_rules: [
|
validation_rules: [
|
||||||
{
|
{
|
||||||
quorum: 0.01,
|
quorum: 0.01,
|
||||||
fields: ['message', 'description'],
|
fields: ['message', 'description', 'roles'],
|
||||||
min_sig_member: 0.01,
|
min_sig_member: 0.01,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
storages: [STORAGEURL]
|
storages: [storageUrl]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const dmTemplate = {
|
|
||||||
description: 'dm',
|
|
||||||
message: '',
|
|
||||||
};
|
};
|
||||||
|
|
||||||
console.log('📋 Template final:', JSON.stringify(dmTemplate, null, 2));
|
console.log('📋 Template final:', JSON.stringify(dmTemplate, null, 2));
|
||||||
|
|
||||||
const relayAddress = this.getAllRelays()[0]['spAddress'];
|
const relayAddress = this.getAllRelays()[0]['spAddress'];
|
||||||
const feeRate = 1;
|
const feeRate = 1;
|
||||||
const publicData = {};
|
const initState = JSON.stringify(dmTemplate);
|
||||||
|
|
||||||
await this.checkConnections ([{ sp_addresses: otherMember }]);
|
await this.checkConnections ([{ sp_addresses: otherMember}]);
|
||||||
|
|
||||||
const result = this.sdkClient.create_new_process (
|
const result = this.sdkClient.create_new_process(
|
||||||
dmTemplate,
|
initState,
|
||||||
roles,
|
null,
|
||||||
publicData,
|
|
||||||
relayAddress,
|
relayAddress,
|
||||||
feeRate
|
feeRate
|
||||||
);
|
);
|
||||||
@ -357,26 +394,9 @@ export default class Services {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async updateProcess(process: Process, new_state: any, roles: Record<string, RoleDefinition> | null): Promise<ApiReturn> {
|
public updateProcess(processId: string, new_state: any): ApiReturn {
|
||||||
// If roles is null, we just take the last commited state roles
|
|
||||||
if (!roles) {
|
|
||||||
roles = this.getRoles(process);
|
|
||||||
} else {
|
|
||||||
// We should check that we have the right to change the roles here, or maybe it's better leave it to the wasm
|
|
||||||
console.log('Provided new roles:', JSON.stringify(roles));
|
|
||||||
}
|
|
||||||
console.log(roles);
|
|
||||||
let members = new Set();
|
|
||||||
for (const role of Object.values(roles)) {
|
|
||||||
for (const member of role.members) {
|
|
||||||
members.add(member)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
console.log(members);
|
|
||||||
await this.checkConnections([...members]);
|
|
||||||
try {
|
try {
|
||||||
console.log(process);
|
return this.sdkClient.update_process(processId, JSON.stringify(new_state));
|
||||||
return this.sdkClient.update_process(process, new_state, roles, {});
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
throw new Error(`Failed to update process: ${e}`);
|
throw new Error(`Failed to update process: ${e}`);
|
||||||
}
|
}
|
||||||
@ -403,25 +423,21 @@ export default class Services {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async approveChange(processId: string, stateId: string): Promise<ApiReturn> {
|
public approveChange(processId: string, stateId: string): ApiReturn {
|
||||||
const process = await this.getProcess(processId);
|
|
||||||
if (!process) {
|
|
||||||
throw new Error('Failed to get process from db');
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
return this.sdkClient.validate_state(process, stateId);
|
return this.sdkClient.validate_state(processId, stateId);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
throw new Error(`Failed to create prd response: ${e}`);
|
throw new Error(`Failed to create prd response: ${e}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async rejectChange(processId: string, stateId: string): Promise<ApiReturn> {
|
public rejectChange(): ApiReturn {
|
||||||
const process = await this.getProcess(processId);
|
if (!this.currentProcess || !this.currentUpdateMerkleRoot) {
|
||||||
if (!process) {
|
throw new Error('No current process and/or current update defined');
|
||||||
throw new Error('Failed to get process from db');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
return this.sdkClient.refuse_state(process, stateId);
|
return this.sdkClient.refuse_state(this.currentProcess, this.currentUpdateMerkleRoot);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
throw new Error(`Failed to create prd response: ${e}`);
|
throw new Error(`Failed to create prd response: ${e}`);
|
||||||
}
|
}
|
||||||
@ -494,8 +510,38 @@ export default class Services {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async tryFetchDiffValue(diffs: UserDiff[]): Promise<[UserDiff[], Record<string, string>]>{
|
||||||
|
if (diffs.length === 0) {
|
||||||
|
return [[], {}];
|
||||||
|
}
|
||||||
|
|
||||||
|
// We check if we have the value in diffs
|
||||||
|
let retrievedValues: Record<string, string> = {};
|
||||||
|
for (const diff of diffs) {
|
||||||
|
// Check if `new_value` is missing
|
||||||
|
if (diff.new_value === null) {
|
||||||
|
const hash = diff.value_commitment;
|
||||||
|
if (!hash) {
|
||||||
|
console.error('No commitment for diff');
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const res = await this.fetchValueFromStorage(hash);
|
||||||
|
if (!res) {
|
||||||
|
console.error('Failed to fetch value for hash', hash);
|
||||||
|
} else {
|
||||||
|
diff.new_value = res['value'];
|
||||||
|
retrievedValues[hash] = res['value'];
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Failed to fetch new_value for diff: ${JSON.stringify(diff)}`, error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return [diffs, retrievedValues];
|
||||||
|
}
|
||||||
|
|
||||||
public async handleApiReturn(apiReturn: ApiReturn) {
|
public async handleApiReturn(apiReturn: ApiReturn) {
|
||||||
console.log(apiReturn);
|
|
||||||
if (apiReturn.new_tx_to_send && apiReturn.new_tx_to_send.transaction.length != 0) {
|
if (apiReturn.new_tx_to_send && apiReturn.new_tx_to_send.transaction.length != 0) {
|
||||||
await this.sendNewTxMessage(JSON.stringify(apiReturn.new_tx_to_send));
|
await this.sendNewTxMessage(JSON.stringify(apiReturn.new_tx_to_send));
|
||||||
await new Promise(r => setTimeout(r, 500));
|
await new Promise(r => setTimeout(r, 500));
|
||||||
@ -530,50 +576,46 @@ export default class Services {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
setTimeout(async () => {
|
||||||
if (apiReturn.updated_process) {
|
if (apiReturn.updated_process) {
|
||||||
const updatedProcess = apiReturn.updated_process;
|
const updatedProcess = apiReturn.updated_process;
|
||||||
|
|
||||||
const processId: string = updatedProcess.process_id;
|
const processId: string = updatedProcess.commitment_tx;
|
||||||
|
|
||||||
if (updatedProcess.encrypted_data && Object.keys(updatedProcess.encrypted_data).length != 0) {
|
// Save process to storage
|
||||||
for (const [hash, cipher] of Object.entries(updatedProcess.encrypted_data)) {
|
|
||||||
console.log(hash);
|
|
||||||
console.log(cipher);
|
|
||||||
const blob = this.hexToBlob(cipher);
|
|
||||||
try {
|
try {
|
||||||
await this.saveBlobToDb(hash, blob);
|
await this.saveProcess(processId, updatedProcess.current_process);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
throw e;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Save process to db
|
|
||||||
await this.saveProcessToDb(processId, updatedProcess.current_process);
|
|
||||||
|
|
||||||
const isPaired = this.isPaired();
|
const isPaired = this.isPaired();
|
||||||
|
|
||||||
if (updatedProcess.diffs && updatedProcess.diffs.length != 0) {
|
if (updatedProcess.new_diffs.length != 0) {
|
||||||
|
const [updatedDiffs, retrievedValues] = await this.tryFetchDiffValue(updatedProcess.new_diffs);
|
||||||
|
if (Object.entries(retrievedValues).length != 0) {
|
||||||
|
const stateId = updatedDiffs[0].state_id;
|
||||||
|
const processId = updatedDiffs[0].process_id;
|
||||||
|
// We update the process with the value we retrieved
|
||||||
|
const hashToValues = JSON.stringify(retrievedValues);
|
||||||
|
const apiReturn = this.sdkClient.update_process_state(processId, stateId, hashToValues);
|
||||||
|
await this.handleApiReturn(apiReturn);
|
||||||
|
} else {
|
||||||
try {
|
try {
|
||||||
await this.saveDiffsToDb(updatedProcess.diffs);
|
await this.saveDiffs(updatedDiffs);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('Failed to save diffs to db:', e);
|
throw e;
|
||||||
}
|
}
|
||||||
if (!isPaired) {
|
if (!isPaired) {
|
||||||
console.log(updatedProcess);
|
await this.openPairingConfirmationModal(updatedDiffs);
|
||||||
await this.openPairingConfirmationModal(updatedProcess.current_process.states[0]);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (apiReturn.push_to_storage && apiReturn.push_to_storage.length != 0) {
|
|
||||||
for (const hash of apiReturn.push_to_storage) {
|
if (updatedProcess.modified_state) {
|
||||||
const blob = await this.getBlobFromDb(hash);
|
const responsePrdReturn = this.sdkClient.create_response_prd(processId, updatedProcess.modified_state);
|
||||||
if (blob) {
|
await this.handleApiReturn(responsePrdReturn);
|
||||||
await this.saveDataToStorage(hash, blob, null);
|
|
||||||
} else {
|
|
||||||
console.error('Failed to get data from db');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -585,16 +627,20 @@ export default class Services {
|
|||||||
if (apiReturn.ciphers_to_send && apiReturn.ciphers_to_send.length != 0) {
|
if (apiReturn.ciphers_to_send && apiReturn.ciphers_to_send.length != 0) {
|
||||||
await this.sendCipherMessages(apiReturn.ciphers_to_send);
|
await this.sendCipherMessages(apiReturn.ciphers_to_send);
|
||||||
}
|
}
|
||||||
|
}, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async openPairingConfirmationModal(firstState: ProcessState) {
|
public async openPairingConfirmationModal(diffs: UserDiff[]) {
|
||||||
const roles = firstState.roles;
|
const rolesDiff = diffs.find((diff) => diff.field === 'roles');
|
||||||
const processId = firstState.commited_in;
|
if (!rolesDiff) {
|
||||||
const stateId = firstState.state_id;
|
throw new Error('Pairing process must have roles');
|
||||||
|
}
|
||||||
|
const processId = rolesDiff.process_id;
|
||||||
|
const stateId = rolesDiff.state_id;
|
||||||
try {
|
try {
|
||||||
await this.routingInstance.openPairingConfirmationModal(roles, processId, stateId);
|
await this.routingInstance.openPairingConfirmationModal(rolesDiff.new_value, processId, stateId);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
throw new Error(`${e}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -623,15 +669,6 @@ export default class Services {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public dumpNeuteredDevice(): Device | null {
|
|
||||||
try {
|
|
||||||
return this.sdkClient.dump_neutered_device();
|
|
||||||
} catch (e) {
|
|
||||||
console.error(`Failed to dump device: ${e}`);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public getPairingProcessId(): string {
|
public getPairingProcessId(): string {
|
||||||
try {
|
try {
|
||||||
return this.sdkClient.get_pairing_process_id();
|
return this.sdkClient.get_pairing_process_id();
|
||||||
@ -700,27 +737,26 @@ export default class Services {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
rolesContainsUs(roles: Record<string, RoleDefinition>): boolean {
|
rolesContainsUs(roles: any): boolean {
|
||||||
let us;
|
|
||||||
try {
|
try {
|
||||||
us = this.sdkClient.get_member();
|
this.sdkClient.roles_contains_us(JSON.stringify(roles));
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
throw e;
|
console.error(e);
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
return this.rolesContainsMember(roles, us.sp_addresses);
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
rolesContainsMember(roles: Record<string, RoleDefinition>, member: string[]): boolean {
|
rolesContainsMember(roles: any, member: string[]): boolean {
|
||||||
let res = false;
|
try {
|
||||||
for (const [roleName, roleDef] of Object.entries(roles)) {
|
this.sdkClient.roles_contains_member(JSON.stringify(roles), member);
|
||||||
for (const otherMember of roleDef.members) {
|
} catch (e) {
|
||||||
if (res) { return true }
|
console.error(e);
|
||||||
res = this.compareMembers(member, otherMember.sp_addresses);
|
return false;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return res;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
async dumpWallet() {
|
async dumpWallet() {
|
||||||
@ -758,75 +794,46 @@ export default class Services {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async removeProcess(processId: string): Promise<void> {
|
public async saveProcess(commitedIn: string, process: Process) {
|
||||||
const db = await Database.getInstance();
|
|
||||||
const storeName = 'processes';
|
|
||||||
|
|
||||||
try {
|
|
||||||
await db.deleteObject(storeName, processId);
|
|
||||||
} catch (e) {
|
|
||||||
console.error(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async saveProcessToDb(processId: string, process: Process) {
|
|
||||||
const db = await Database.getInstance();
|
const db = await Database.getInstance();
|
||||||
try {
|
try {
|
||||||
await db.addObject({
|
await db.addObject({
|
||||||
storeName: 'processes',
|
storeName: 'processes',
|
||||||
object: process,
|
object: process,
|
||||||
key: processId,
|
key: commitedIn,
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(`Failed to save process ${processId}: ${e}`);
|
throw new Error(`Failed to save process: ${e}`);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async saveBlobToDb(hash: string, data: Blob) {
|
// We check how many copies in storage nodes
|
||||||
const db = await Database.getInstance();
|
// We check the storage nodes in the process itself
|
||||||
try {
|
// this.sdkClient.get_storages(commitedIn);
|
||||||
await db.addObject({
|
const storages = [storageUrl];
|
||||||
storeName: 'data',
|
|
||||||
object: data,
|
|
||||||
key: hash,
|
|
||||||
});
|
|
||||||
} catch (e) {
|
|
||||||
console.error(`Failed to save data to db: ${e}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async getBlobFromDb(hash: string): Promise<Blob | null> {
|
for (const state of process.states) {
|
||||||
const db = await Database.getInstance();
|
if (state.state_id === "") {
|
||||||
try {
|
continue;
|
||||||
return await db.getObject('data', hash);
|
|
||||||
} catch (e) {
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
if (!state.encrypted_pcd) {
|
||||||
|
console.warn('Empty encrypted pcd, skipping...');
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (const [field, hash] of Object.entries(state.pcd_commitment)) {
|
||||||
|
// get the encrypted value with the field name
|
||||||
|
const value = state.encrypted_pcd[field];
|
||||||
|
await storeData(storages, hash, value, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async saveDataToStorage(hash: string, data: Blob, ttl: number | null) {
|
|
||||||
const storages = [STORAGEURL];
|
|
||||||
|
|
||||||
try {
|
|
||||||
await storeData(storages, hash, data, ttl);
|
|
||||||
} catch (e) {
|
|
||||||
console.error(`Failed to store data with hash ${hash}: ${e}`);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async fetchValueFromStorage(hash: string): Promise<any | null> {
|
public async fetchValueFromStorage(hash: string): Promise<any | null> {
|
||||||
const storages = [STORAGEURL];
|
const storages = [storageUrl];
|
||||||
|
|
||||||
return await retrieveData(storages, hash);
|
return await retrieveData(storages, hash);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async testDataInStorage(hash: string): Promise<Record<string, boolean | null> | null> {
|
public async saveDiffs(diffs: UserDiff[]) {
|
||||||
const storages = [STORAGEURL];
|
|
||||||
|
|
||||||
return await testData(storages, hash);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async saveDiffsToDb(diffs: UserDiff[]) {
|
|
||||||
const db = await Database.getInstance();
|
const db = await Database.getInstance();
|
||||||
try {
|
try {
|
||||||
for (const diff of diffs) {
|
for (const diff of diffs) {
|
||||||
@ -883,6 +890,24 @@ export default class Services {
|
|||||||
await this.restoreProcessesFromDB();
|
await this.restoreProcessesFromDB();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async updateProcessesFromRelay(processes: Record<string, Process>) {
|
||||||
|
const db = await Database.getInstance();
|
||||||
|
for (const [processId, process] of Object.entries(processes)) {
|
||||||
|
const processFromDb = await this.getProcess(processId);
|
||||||
|
if (!processFromDb) {
|
||||||
|
console.log(`Unknown process ${processId}, adding to db`);
|
||||||
|
await db.addObject({ storeName: 'processes', object: process, key: processId});
|
||||||
|
} else {
|
||||||
|
const missingStates = process.states.length - processFromDb.states.length;
|
||||||
|
if (missingStates < 0) {
|
||||||
|
// We are missing one or more states for a known process
|
||||||
|
// TODO send a request to process managers to get the missing states
|
||||||
|
console.log(`Missing ${missingStates} for process ${processId}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Restore process in wasm with persistent storage
|
// Restore process in wasm with persistent storage
|
||||||
public async restoreProcessesFromDB() {
|
public async restoreProcessesFromDB() {
|
||||||
const db = await Database.getInstance();
|
const db = await Database.getInstance();
|
||||||
@ -947,41 +972,40 @@ export default class Services {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async decryptAttribute(processId: string, state: ProcessState, attribute: string): Promise<string | null> {
|
async getDescription(processId: string, process: Process): Promise<string | null> {
|
||||||
let hash = state.pcd_commitment[attribute];
|
const service = await Services.getInstance();
|
||||||
let key = state.keys[attribute];
|
// Get the `commited_in` value of the last state and remove it from the array
|
||||||
|
const currentCommitedIn = process.states.at(-1)?.commited_in;
|
||||||
|
console.log('Current CommitedIn:' currentCommitedIn)
|
||||||
|
|
||||||
// If hash or key is missing, request an update and then retry
|
if (currentCommitedIn === undefined) {
|
||||||
if (!hash || !key) {
|
return null; // No states available
|
||||||
await this.requestDataFromPeers(processId, [state.state_id], [state.roles]);
|
|
||||||
|
|
||||||
const maxRetries = 5;
|
|
||||||
const retryDelay = 500; // delay in milliseconds
|
|
||||||
let retries = 0;
|
|
||||||
|
|
||||||
while ((!hash || !key) && retries < maxRetries) {
|
|
||||||
await new Promise(resolve => setTimeout(resolve, retryDelay));
|
|
||||||
// Re-read hash and key after waiting
|
|
||||||
hash = state.pcd_commitment[attribute];
|
|
||||||
key = state.keys[attribute];
|
|
||||||
retries++;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (hash && key) {
|
// Find the last state where `commited_in` is different
|
||||||
const blob = await this.getBlobFromDb(hash);
|
let lastDifferentState = process.states.findLast(
|
||||||
if (blob) {
|
state => state.commited_in !== currentCommitedIn
|
||||||
// Decrypt the data
|
);
|
||||||
const buf = await blob.arrayBuffer();
|
|
||||||
const cipher = new Uint8Array(buf);
|
|
||||||
const keyBlob = this.hexToBlob(key);
|
|
||||||
const keyBuf = await keyBlob.arrayBuffer();
|
|
||||||
|
|
||||||
const clear = this.sdkClient.decrypt_data(new Uint8Array(keyBuf), cipher);
|
if (!lastDifferentState) {
|
||||||
if (clear) {
|
// It means that we only have one state that is not commited yet, that can happen with process we just created
|
||||||
// Parse the stringified JSON
|
// let's assume that the right description is in the last concurrent state and not handle the (arguably rare) case where we have multiple concurrent states on a creation
|
||||||
return JSON.parse(clear);
|
lastDifferentState = process.states.at(-1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!lastDifferentState.pcd_commitment) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Take the description out of the state, if any
|
||||||
|
const description = lastDifferentState!.pcd_commitment['description'];
|
||||||
|
if (description) {
|
||||||
|
const userDiff = await service.getDiffByValue(description);
|
||||||
|
if (userDiff) {
|
||||||
|
console.log("Successfully retrieved userDiff:", userDiff);
|
||||||
|
return userDiff.new_value;
|
||||||
|
} else {
|
||||||
|
console.log("Failed to retrieve a non-null userDiff.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1072,57 +1096,23 @@ export default class Services {
|
|||||||
this.device2Ready = false;
|
this.device2Ready = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Handle the handshake message
|
|
||||||
public async handleHandshakeMsg(url: string, parsedMsg: any) {
|
public async handleHandshakeMsg(url: string, parsedMsg: any) {
|
||||||
try {
|
try {
|
||||||
const handshakeMsg: HandshakeMessage = JSON.parse(parsedMsg);
|
const handshakeMsg: HandshakeMessage = JSON.parse(parsedMsg);
|
||||||
this.updateRelay(url, handshakeMsg.sp_address);
|
this.updateRelay(url, handshakeMsg.sp_address);
|
||||||
const members = handshakeMsg.peers_list;
|
const members = handshakeMsg.peers_list;
|
||||||
if (this.membersList && Object.keys(this.membersList).length === 0) {
|
if (this.membersList && Object.keys(this.membersList).length === 0) {
|
||||||
// We start from an empty list, just copy it over
|
|
||||||
this.membersList = handshakeMsg.peers_list;
|
this.membersList = handshakeMsg.peers_list;
|
||||||
} else {
|
} else {
|
||||||
// We are incrementing our list
|
|
||||||
for (const [processId, member] of Object.entries(handshakeMsg.peers_list)) {
|
for (const [processId, member] of Object.entries(handshakeMsg.peers_list)) {
|
||||||
this.membersList[processId] = member as Member;
|
this.membersList[processId] = member;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
setTimeout(async () => {
|
setTimeout(async () => {
|
||||||
const newProcesses = handshakeMsg.processes_list;
|
const newProcesses = handshakeMsg.processes_list;
|
||||||
if (newProcesses && Object.keys(newProcesses).length !== 0) {
|
if (newProcesses && Object.keys(newProcesses).length !== 0) {
|
||||||
for (const [processId, process] of Object.entries(newProcesses)) {
|
await this.updateProcessesFromRelay(newProcesses);
|
||||||
const existing = await this.getProcess(processId);
|
|
||||||
if (existing) {
|
|
||||||
// Look for state id we don't know yet
|
|
||||||
let new_states = [];
|
|
||||||
let roles = [];
|
|
||||||
for (const state of process.states) {
|
|
||||||
if (!state.state_id || state.state_id === EMPTY32BYTES) { continue; }
|
|
||||||
if (!this.lookForStateId(existing, state.state_id)) {
|
|
||||||
new_states.push(state.state_id);
|
|
||||||
roles.push(state.roles);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (new_states.length != 0) {
|
|
||||||
// We request the new states
|
|
||||||
await this.requestDataFromPeers(processId, new_states, roles);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Otherwise we're probably just in the initial loading at page initialization
|
|
||||||
|
|
||||||
// We may learn an update for this process
|
|
||||||
// TODO maybe actually check if what the relay is sending us contains more information than what we have
|
|
||||||
// relay should always have more info than us, but we never know
|
|
||||||
// For now let's keep it simple and let the worker do the job
|
|
||||||
} else {
|
|
||||||
// We add it to db
|
|
||||||
console.log(`Saving ${processId} to db`);
|
|
||||||
await this.saveProcessToDb(processId, process as Process);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}, 500)
|
}, 500)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@ -1130,162 +1120,18 @@ export default class Services {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private lookForStateId(process: Process, stateId: string): boolean {
|
|
||||||
for (const state of process.states) {
|
|
||||||
if (state.state_id === stateId) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retourne la liste de tous les membres ordonnés par leur process id
|
* Retourne la liste de tous les membres
|
||||||
* @returns Un tableau contenant tous les membres
|
* @returns Un tableau contenant tous les membres
|
||||||
*/
|
*/
|
||||||
public getAllMembersSorted(): Record<string, Member> {
|
public getAllMembers(): Record<string, Member> {
|
||||||
return Object.fromEntries(
|
return Object.fromEntries(
|
||||||
Object.entries(this.membersList).sort(([keyA], [keyB]) => keyA.localeCompare(keyB))
|
Object.entries(this.membersList).sort(([keyA], [keyB]) => keyA.localeCompare(keyB))
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public getAllMembers(): Record<string, Member> {
|
|
||||||
return this.membersList;
|
|
||||||
}
|
|
||||||
|
|
||||||
public getAddressesForMemberId(memberId: string): string[] | null {
|
public getAddressesForMemberId(memberId: string): string[] | null {
|
||||||
return this.membersList[memberId];
|
return this.membersList[memberId];
|
||||||
}
|
}
|
||||||
|
|
||||||
public compareMembers(memberA: string[], memberB: string[]): boolean {
|
|
||||||
if (!memberA || !memberB) { return false }
|
|
||||||
if (memberA.length !== memberB.length) { return false }
|
|
||||||
|
|
||||||
const res = memberA.every(item => memberB.includes(item)) && memberB.every(item => memberA.includes(item));
|
|
||||||
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async handleCommitError(response: string) {
|
|
||||||
const content = JSON.parse(response);
|
|
||||||
const error = content.error;
|
|
||||||
const errorMsg = error['GenericError'];
|
|
||||||
if (errorMsg === 'State is identical to the previous state') {
|
|
||||||
return;
|
|
||||||
} else if (errorMsg === 'Not enough valid proofs') { return; }
|
|
||||||
// Wait and retry
|
|
||||||
setTimeout(async () => {
|
|
||||||
await this.sendCommitMessage(JSON.stringify(content));
|
|
||||||
}, 1000)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
public getRoles(process: Process): Record<string, RoleDefinition> | null {
|
|
||||||
const lastCommitedState = this.getLastCommitedState(process);
|
|
||||||
if (lastCommitedState && lastCommitedState.roles && Object.keys(lastCommitedState.roles).length != 0) {
|
|
||||||
return lastCommitedState!.roles;
|
|
||||||
} else {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public getPublicData(process: Process): Record<string, any> | null {
|
|
||||||
const lastCommitedState = this.getLastCommitedState(process);
|
|
||||||
if (lastCommitedState && lastCommitedState.public_data) {
|
|
||||||
return lastCommitedState.public_data;
|
|
||||||
} else {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public getProcessName(process: Process): string | null {
|
|
||||||
const lastCommitedState = this.getLastCommitedState(process);
|
|
||||||
if (lastCommitedState && lastCommitedState.public_data) {
|
|
||||||
const processName = lastCommitedState!.public_data['processName'];
|
|
||||||
if (processName) { return processName }
|
|
||||||
else { return null }
|
|
||||||
} else {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async getMyProcesses(): Promise<string[]> {
|
|
||||||
try {
|
|
||||||
const processes = await this.getProcesses();
|
|
||||||
|
|
||||||
for (const [processId, process] of Object.entries(processes)) {
|
|
||||||
// We use myProcesses attribute to not reevaluate all processes everytime
|
|
||||||
if (this.myProcesses && this.myProcesses.has(processId)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const roles = this.getRoles(process);
|
|
||||||
|
|
||||||
if (roles && this.rolesContainsUs(roles)) {
|
|
||||||
this.myProcesses.add(processId);
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
console.error(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return Array.from(this.myProcesses);
|
|
||||||
} catch (e) {
|
|
||||||
console.error("Failed to get processes:", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async requestDataFromPeers(processId: string, stateIds: string[], roles: Record<string, RoleDefinition>[]) {
|
|
||||||
console.log('Requesting data from peers');
|
|
||||||
console.log(roles);
|
|
||||||
try {
|
|
||||||
const res = this.sdkClient.request_data(processId, stateIds, roles);
|
|
||||||
await this.handleApiReturn(res);
|
|
||||||
} catch (e) {
|
|
||||||
console.error(e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public hexToBlob(hexString: string): Blob {
|
|
||||||
if (hexString.length % 2 !== 0) {
|
|
||||||
throw new Error("Invalid hex string: length must be even");
|
|
||||||
}
|
|
||||||
const uint8Array = new Uint8Array(hexString.length / 2);
|
|
||||||
for (let i = 0; i < hexString.length; i += 2) {
|
|
||||||
uint8Array[i / 2] = parseInt(hexString.substr(i, 2), 16);
|
|
||||||
}
|
|
||||||
|
|
||||||
return new Blob([uint8Array], { type: "application/octet-stream" });
|
|
||||||
}
|
|
||||||
|
|
||||||
public async blobToHex(blob: Blob): Promise<string> {
|
|
||||||
const buffer = await blob.arrayBuffer();
|
|
||||||
const bytes = new Uint8Array(buffer);
|
|
||||||
return Array.from(bytes)
|
|
||||||
.map(byte => byte.toString(16).padStart(2, '0'))
|
|
||||||
.join('');
|
|
||||||
}
|
|
||||||
|
|
||||||
public getLastCommitedState(process: Process): ProcessState {
|
|
||||||
if (process.states.length === 0) return null;
|
|
||||||
const processTip = process.states[process.states.length - 1].commited_in;
|
|
||||||
const lastCommitedState = process.states.findLast(state => state.commited_in !== processTip);
|
|
||||||
if (lastCommitedState) {
|
|
||||||
return lastCommitedState;
|
|
||||||
} else {
|
|
||||||
console.error('Can\'t find last commited state');
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public isPairingProcess(roles: Record<string, RoleDefinition>): boolean {
|
|
||||||
if (Object.keys(roles).length != 1) { return false }
|
|
||||||
const pairingRole = roles['pairing'];
|
|
||||||
if (pairingRole) {
|
|
||||||
// For now that's enough, we should probably test more things
|
|
||||||
return true;
|
|
||||||
} else {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
@ -1,49 +1,32 @@
|
|||||||
import axios, { AxiosResponse } from 'axios';
|
import axios, { AxiosResponse } from 'axios';
|
||||||
|
|
||||||
export async function storeData(servers: string[], key: string, value: Blob, ttl: number | null): Promise<AxiosResponse | null> {
|
export async function storeData(servers: string[], key: string, value: any, ttl: number | null): Promise<AxiosResponse | null> {
|
||||||
for (const server of servers) {
|
for (const server of servers) {
|
||||||
try {
|
try {
|
||||||
// Append key and ttl as query parameters
|
const response = await axios.post(`${server}/store`, { key, value, ttl });
|
||||||
const url = new URL(`${server}/store`);
|
console.log('Data stored successfully:', response.data);
|
||||||
url.searchParams.append('key', key);
|
|
||||||
if (ttl !== null) {
|
|
||||||
url.searchParams.append('ttl', ttl.toString());
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send the encrypted ArrayBuffer as the raw request body.
|
|
||||||
const response = await axios.post(url.toString(), value, {
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/octet-stream'
|
|
||||||
},
|
|
||||||
});
|
|
||||||
console.log('Data stored successfully:', key);
|
|
||||||
if (response.status !== 200) {
|
if (response.status !== 200) {
|
||||||
console.error('Received response status', response.status);
|
console.error('Received response status', response.status);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
console.log('Stored data:', response.data);
|
||||||
return response;
|
return response;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error?.response?.status === 409) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
console.error('Error storing data:', error);
|
console.error('Error storing data:', error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function retrieveData(servers: string[], key: string): Promise<ArrayBuffer | null> {
|
export async function retrieveData(servers: string[], key: string): Promise<any | null> {
|
||||||
for (const server of servers) {
|
for (const server of servers) {
|
||||||
try {
|
try {
|
||||||
// When fetching the data from the server:
|
const response = await axios.get(`${server}/retrieve/${key}`);
|
||||||
const response = await axios.get(`${server}/retrieve/${key}`, {
|
|
||||||
responseType: 'arraybuffer'
|
|
||||||
});
|
|
||||||
if (response.status !== 200) {
|
if (response.status !== 200) {
|
||||||
console.error('Received response status', response.status);
|
console.error('Received response status', response.status);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
// console.log('Retrieved data:', response.data);
|
console.log('Retrieved data:', response.data);
|
||||||
return response.data;
|
return response.data;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error retrieving data:', error);
|
console.error('Error retrieving data:', error);
|
||||||
@ -51,31 +34,3 @@ export async function retrieveData(servers: string[], key: string): Promise<Arra
|
|||||||
}
|
}
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
interface TestResponse {
|
|
||||||
key: string;
|
|
||||||
value: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function testData(servers: string[], key: string): Promise<Record<string, boolean | null> | null> {
|
|
||||||
const res = {};
|
|
||||||
for (const server of servers) {
|
|
||||||
res[server] = null;
|
|
||||||
try {
|
|
||||||
const response = await axios.get(`${server}/test/${key}`);
|
|
||||||
if (response.status !== 200) {
|
|
||||||
console.error(`${server}: Test response status: ${response.status}`);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const data: TestResponse = response.data;
|
|
||||||
|
|
||||||
res[server] = data.value;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error retrieving data:', error);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
|
@ -104,7 +104,6 @@ export function initAddressInput() {
|
|||||||
const addressInput = container.querySelector('#addressInput') as HTMLInputElement;
|
const addressInput = container.querySelector('#addressInput') as HTMLInputElement;
|
||||||
const emojiDisplay = container.querySelector('#emoji-display-2');
|
const emojiDisplay = container.querySelector('#emoji-display-2');
|
||||||
const okButton = container.querySelector('#okButton') as HTMLButtonElement;
|
const okButton = container.querySelector('#okButton') as HTMLButtonElement;
|
||||||
const createButton = container.querySelector('#createButton') as HTMLButtonElement;
|
|
||||||
addSubscription(addressInput, 'input', async () => {
|
addSubscription(addressInput, 'input', async () => {
|
||||||
let address = addressInput.value;
|
let address = addressInput.value;
|
||||||
|
|
||||||
@ -146,12 +145,6 @@ export function initAddressInput() {
|
|||||||
onOkButtonClick();
|
onOkButtonClick();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (createButton) {
|
|
||||||
addSubscription(createButton, 'click', () => {
|
|
||||||
onCreateButtonClick();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function onOkButtonClick() {
|
async function onOkButtonClick() {
|
||||||
@ -165,46 +158,21 @@ async function onOkButtonClick() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function onCreateButtonClick() {
|
export async function prepareAndSendPairingTx(secondDeviceAddress: string) {
|
||||||
try {
|
|
||||||
await prepareAndSendPairingTx();
|
|
||||||
} catch (e) {
|
|
||||||
console.error(`onCreateButtonClick error: ${e}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function prepareAndSendPairingTx(promptName: boolean = false) {
|
|
||||||
const service = await Services.getInstance();
|
const service = await Services.getInstance();
|
||||||
|
|
||||||
// Device 1 wait Device 2
|
// Device 1 wait Device 2
|
||||||
// service.device1 = true;
|
service.device1 = true;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await service.checkConnections([]);
|
await service.checkConnections([{ sp_addresses: [secondDeviceAddress] }]);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
throw e;
|
throw e;
|
||||||
}
|
}
|
||||||
|
// Create the process
|
||||||
// Prompt the user for a username.
|
|
||||||
let userName;
|
|
||||||
if (promptName) {
|
|
||||||
userName = prompt("Please enter your user name:");
|
|
||||||
} else {
|
|
||||||
userName = "";
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create the process after a delay.
|
|
||||||
setTimeout(async () => {
|
setTimeout(async () => {
|
||||||
const relayAddress = service.getAllRelays();
|
const relayAddress = service.getAllRelays();
|
||||||
|
const createPairingProcessReturn = await service.createPairingProcess([secondDeviceAddress], relayAddress[0].spAddress, 1);
|
||||||
// Pass the userName as an additional parameter.
|
|
||||||
const createPairingProcessReturn = await service.createPairingProcess(
|
|
||||||
userName,
|
|
||||||
[],
|
|
||||||
relayAddress[0].spAddress,
|
|
||||||
1,
|
|
||||||
userName
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!createPairingProcessReturn.updated_process) {
|
if (!createPairingProcessReturn.updated_process) {
|
||||||
throw new Error('createPairingProcess returned an empty new process'); // This should never happen
|
throw new Error('createPairingProcess returned an empty new process'); // This should never happen
|
||||||
@ -221,21 +189,17 @@ export async function generateQRCode(spAddress: string) {
|
|||||||
const url = await QRCode.toDataURL(currentUrl + '?sp_address=' + spAddress);
|
const url = await QRCode.toDataURL(currentUrl + '?sp_address=' + spAddress);
|
||||||
const qrCode = container?.querySelector('.qr-code img');
|
const qrCode = container?.querySelector('.qr-code img');
|
||||||
qrCode?.setAttribute('src', url);
|
qrCode?.setAttribute('src', url);
|
||||||
|
|
||||||
|
//Generate Address CopyBtn
|
||||||
|
const address = container?.querySelector('.sp-address-btn');
|
||||||
|
if (address) {
|
||||||
|
address.textContent = 'Copy address';
|
||||||
|
}
|
||||||
|
const copyBtn = container.querySelector('#copyBtn');
|
||||||
|
if (copyBtn) {
|
||||||
|
addSubscription(copyBtn, 'click', () => copyToClipboard(currentUrl + '?sp_address=' + spAddress));
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function generateCreateBtn() {
|
|
||||||
try{
|
|
||||||
//Generate CreateBtn
|
|
||||||
const container = getCorrectDOM('login-4nk-component') as HTMLElement
|
|
||||||
const createBtn = container?.querySelector('.create-btn');
|
|
||||||
if (createBtn) {
|
|
||||||
createBtn.textContent = 'CREATE';
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.error(err);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -5,15 +5,12 @@ export function cleanSubscriptions(): void {
|
|||||||
for (const sub of subscriptions) {
|
for (const sub of subscriptions) {
|
||||||
const el = sub.element;
|
const el = sub.element;
|
||||||
const eventHandler = sub.eventHandler;
|
const eventHandler = sub.eventHandler;
|
||||||
if (el) {
|
|
||||||
el.removeEventListener(sub.event, eventHandler);
|
el.removeEventListener(sub.event, eventHandler);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
subscriptions = [];
|
subscriptions = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function addSubscription(element: Element | Document, event: any, eventHandler: EventListenerOrEventListenerObject): void {
|
export function addSubscription(element: Element | Document, event: any, eventHandler: EventListenerOrEventListenerObject): void {
|
||||||
if (!element) return;
|
|
||||||
subscriptions.push({ element, event, eventHandler });
|
subscriptions.push({ element, event, eventHandler });
|
||||||
element.addEventListener(event, eventHandler);
|
element.addEventListener(event, eventHandler);
|
||||||
}
|
}
|
||||||
|
@ -38,10 +38,6 @@ export async function initWebsocket(url: string) {
|
|||||||
case 'Cipher':
|
case 'Cipher':
|
||||||
await services.parseCipher(parsedMessage.content);
|
await services.parseCipher(parsedMessage.content);
|
||||||
break;
|
break;
|
||||||
case 'Commit':
|
|
||||||
// Basically if we see this it means we have an error
|
|
||||||
await services.handleCommitError(parsedMessage.content);
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Received an invalid message:', error);
|
console.error('Received an invalid message:', error);
|
||||||
|
Loading…
x
Reference in New Issue
Block a user