pretiffy code

This commit is contained in:
AnisHADJARAB 2024-11-07 09:46:16 +00:00
parent c2ac42ae54
commit 896de5aca4
12 changed files with 315 additions and 351 deletions

View File

@ -7,7 +7,7 @@ let notifications = [];
export async function unpair() { export async function unpair() {
const service = await Services.getInstance(); const service = await Services.getInstance();
await service.unpairDevice(); await service.unpairDevice();
navigate('home') navigate('home');
} }
(window as any).unpair = unpair; (window as any).unpair = unpair;
@ -27,7 +27,7 @@ function toggleMenu() {
async function getNotifications() { async function getNotifications() {
const service = await Services.getInstance(); const service = await Services.getInstance();
notifications = service.getNotifications(); notifications = service.getNotifications();
return notifications return notifications;
} }
function openCloseNotifications() { function openCloseNotifications() {
const notifications = document.querySelector('.notification-board') as HTMLDivElement; const notifications = document.querySelector('.notification-board') as HTMLDivElement;
@ -40,7 +40,7 @@ export async function initHeader() {
if (currentRoute === 'home') { if (currentRoute === 'home') {
hideSomeFunctionnalities(); hideSomeFunctionnalities();
} else { } else {
fetchNotifications() fetchNotifications();
setInterval(fetchNotifications, 2 * 60 * 1000); setInterval(fetchNotifications, 2 * 60 * 1000);
} }
} }
@ -82,8 +82,7 @@ async function setNotification(notifications: INotification[]): Promise<void> {
} }
async function fetchNotifications() { async function fetchNotifications() {
const service = await Services.getInstance() const service = await Services.getInstance();
const data = service.getNotifications(); const data = service.getNotifications();
setNotification(data) setNotification(data);
} }

View File

@ -1,13 +1,13 @@
import ModalService from "../../services/modal.service"; import ModalService from '../../services/modal.service';
const modalService = await ModalService.getInstance(); const modalService = await ModalService.getInstance();
export async function confirm() { export async function confirm() {
modalService.confirmPairing() modalService.confirmPairing();
} }
export async function closeConfirmationModal() { export async function closeConfirmationModal() {
modalService.closeConfirmationModal() modalService.closeConfirmationModal();
} }
(window as any).confirm = confirm; (window as any).confirm = confirm;
(window as any).closeConfirmationModal = closeConfirmationModal; (window as any).closeConfirmationModal = closeConfirmationModal;

View File

@ -17,16 +17,16 @@ export async function initHomePage(): Promise<void> {
document.querySelectorAll('.tab-content').forEach((content) => content.classList.remove('active')); document.querySelectorAll('.tab-content').forEach((content) => content.classList.remove('active'));
document.getElementById(tab.getAttribute('data-tab') as string)?.classList.add('active'); document.getElementById(tab.getAttribute('data-tab') as string)?.classList.add('active');
}) });
}); });
const service = await Services.getInstance(); const service = await Services.getInstance();
const spAddress = await service.getDeviceAddress() const spAddress = await service.getDeviceAddress();
generateQRCode(spAddress) generateQRCode(spAddress);
displayEmojis(spAddress) displayEmojis(spAddress);
const notifBell = document.getElementById('notification-bell') const notifBell = document.getElementById('notification-bell');
if(notifBell) addSubscription(notifBell, 'click', openCloseNotifications) if (notifBell) addSubscription(notifBell, 'click', openCloseNotifications);
var html5QrcodeScanner = new Html5QrcodeScanner('qr-reader', { fps: 10, qrbox: 250 }, undefined); var html5QrcodeScanner = new Html5QrcodeScanner('qr-reader', { fps: 10, qrbox: 250 }, undefined);
html5QrcodeScanner.render(onScanSuccess, undefined); html5QrcodeScanner.render(onScanSuccess, undefined);

View File

@ -1,3 +1,4 @@
import { interpolate } from '../../utils/html.utils';
import Services from '../../services/service'; import Services from '../../services/service';
let currentPageStyle: HTMLStyleElement | null = null; let currentPageStyle: HTMLStyleElement | null = null;
@ -13,10 +14,6 @@ export async function initProcessElement(id: string, zone: string) {
} }
} }
function interpolate(template: string, data: { [key: string]: string }) {
return template.replace(/{{(.*?)}}/g, (_, key) => data[key.trim()]);
}
async function loadPage(data?: any) { async function loadPage(data?: any) {
const content = document.getElementById('containerId'); const content = document.getElementById('containerId');
if (content && data) { if (content && data) {

View File

@ -7,7 +7,7 @@ export async function init() {
const element = document.querySelector('select') as HTMLSelectElement; const element = document.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
const wrapper = document.createElement('div'); const wrapper = document.createElement('div');
if(wrapper) addSubscription(wrapper, 'click', clickOnWrapper) if (wrapper) addSubscription(wrapper, 'click', clickOnWrapper);
wrapper.classList.add('multi-select-component'); wrapper.classList.add('multi-select-component');
wrapper.classList.add('input-field'); wrapper.classList.add('input-field');
@ -18,16 +18,16 @@ export async function init() {
input.classList.add('selected-input'); input.classList.add('selected-input');
input.setAttribute('autocomplete', 'off'); input.setAttribute('autocomplete', 'off');
input.setAttribute('tabindex', '0'); input.setAttribute('tabindex', '0');
if(input) { if (input) {
addSubscription(input, 'keyup', inputChange) addSubscription(input, 'keyup', inputChange);
addSubscription(input, 'keydown', deletePressed) addSubscription(input, 'keydown', deletePressed);
addSubscription(input, 'click', openOptions) addSubscription(input, 'click', openOptions);
} }
const dropdown_icon = document.createElement('a'); const dropdown_icon = document.createElement('a');
dropdown_icon.classList.add('dropdown-icon'); dropdown_icon.classList.add('dropdown-icon');
if(dropdown_icon) addSubscription(dropdown_icon, 'click', clickDropdown) if (dropdown_icon) addSubscription(dropdown_icon, 'click', clickDropdown);
const autocomplete_list = document.createElement('ul'); const autocomplete_list = document.createElement('ul');
autocomplete_list.classList.add('autocomplete-list'); autocomplete_list.classList.add('autocomplete-list');
search_div.appendChild(input); search_div.appendChild(input);
@ -131,7 +131,7 @@ function createToken(wrapper: HTMLElement, value: any) {
close.setAttribute('data-option', value); close.setAttribute('data-option', value);
close.setAttribute('data-hits', '0'); close.setAttribute('data-hits', '0');
close.innerText = 'x'; close.innerText = 'x';
if(close) addSubscription(close, 'click', removeToken) if (close) addSubscription(close, 'click', removeToken);
token.appendChild(token_span); token.appendChild(token_span);
token.appendChild(close); token.appendChild(close);
inputInderline?.appendChild(token); inputInderline?.appendChild(token);
@ -188,7 +188,7 @@ function populateAutocompleteList(select: HTMLSelectElement, query: string, drop
const li = document.createElement('li'); const li = document.createElement('li');
li.innerText = options_to_show[0]; li.innerText = options_to_show[0];
li.setAttribute('data-value', options_to_show[0]); li.setAttribute('data-value', options_to_show[0]);
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) { if (query.length == options_to_show[0].length) {
const event = new Event('click'); const event = new Event('click');
@ -199,7 +199,7 @@ function populateAutocompleteList(select: HTMLSelectElement, query: string, drop
const li = document.createElement('li'); const li = document.createElement('li');
li.innerText = options_to_show[i]; li.innerText = options_to_show[i];
li.setAttribute('data-value', options_to_show[i]); li.setAttribute('data-value', options_to_show[i]);
if(li) addSubscription(li, 'click', selectOption) if (li) addSubscription(li, 'click', selectOption);
autocomplete_list?.appendChild(li); autocomplete_list?.appendChild(li);
} }
} else { } else {
@ -348,7 +348,7 @@ addSubscription(document, 'click', () => {
} }
} }
} }
}) });
async function showSelectedProcess(elem: MouseEvent) { async function showSelectedProcess(elem: MouseEvent) {
if (elem) { if (elem) {

View File

@ -12,7 +12,7 @@ const routes: { [key: string]: string } = {
export let currentRoute = ''; export let currentRoute = '';
export async function navigate(path: string) { export async function navigate(path: string) {
cleanSubscriptions() cleanSubscriptions();
path = path.replace(/^\//, ''); path = path.replace(/^\//, '');
if (path.includes('/')) { if (path.includes('/')) {
const parsedPath = path.split('/')[0]; const parsedPath = path.split('/')[0];
@ -29,7 +29,7 @@ async function handleLocation(path: string) {
if (path.includes('/')) { if (path.includes('/')) {
path = parsedPath[0]; path = parsedPath[0];
} }
currentRoute = path currentRoute = path;
const routeHtml = routes[path] || routes['home']; const routeHtml = routes[path] || routes['home'];
const content = document.getElementById('containerId'); const content = document.getElementById('containerId');
@ -57,10 +57,10 @@ async function handleLocation(path: string) {
window.onpopstate = async () => { window.onpopstate = async () => {
const services = await Services.getInstance(); const services = await Services.getInstance();
if(!services.isPaired()) { if (!services.isPaired()) {
handleLocation('home') handleLocation('home');
} else { } else {
handleLocation('process') handleLocation('process');
} }
}; };
@ -108,7 +108,7 @@ async function injectHeader() {
script.src = '/src/components/header/header.ts'; script.src = '/src/components/header/header.ts';
script.type = 'module'; script.type = 'module';
document.head.appendChild(script); document.head.appendChild(script);
initHeader() initHeader();
} }
} }

View File

@ -41,8 +41,8 @@ export default class ModalService {
let html = await fetch('/src/components/modal/confirmation-modal.html').then((res) => res.text()); let html = await fetch('/src/components/modal/confirmation-modal.html').then((res) => res.text());
html = html.replace('{{device1}}', await addressToEmoji(members[0]['sp_addresses'][0])); html = html.replace('{{device1}}', await addressToEmoji(members[0]['sp_addresses'][0]));
html = html.replace('{{device2}}', await addressToEmoji(members[0]['sp_addresses'][1])); html = html.replace('{{device2}}', await addressToEmoji(members[0]['sp_addresses'][1]));
container.innerHTML += html; container.innerHTML += html;
// Dynamically load the header JS // Dynamically load the header JS
const script = document.createElement('script'); const script = document.createElement('script');
script.src = '/src/components/modal/confirmation-modal.ts'; script.src = '/src/components/modal/confirmation-modal.ts';
@ -57,7 +57,7 @@ export default class ModalService {
let members = roles['owner']['members']; let members = roles['owner']['members'];
console.log(members); console.log(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();
console.log('🚀 ~ Routing ~ openConfirmationModal ~ pcd:', pcd); console.log('🚀 ~ Routing ~ openConfirmationModal ~ pcd:', pcd);
for (const address of members[0]['sp_addresses']) { for (const address of members[0]['sp_addresses']) {
@ -65,7 +65,7 @@ export default class ModalService {
this.paired_addresses.push(address); this.paired_addresses.push(address);
} }
} }
await this.injectModal(members) await this.injectModal(members);
const modal = document.getElementById('modal'); const modal = document.getElementById('modal');
if (modal) modal.style.display = 'flex'; if (modal) modal.style.display = 'flex';
// const newScript = document.createElement('script'); // const newScript = document.createElement('script');

View File

@ -37,7 +37,7 @@ export default class Services {
Services.initializing = (async () => { Services.initializing = (async () => {
const instance = new Services(); const instance = new Services();
await instance.init(); await instance.init();
instance.routingInstance = await ModalService.getInstance() instance.routingInstance = await ModalService.getInstance();
return instance; return instance;
})(); })();
} }
@ -57,8 +57,8 @@ export default class Services {
public async addWebsocketConnection(url: string): Promise<void> { public async addWebsocketConnection(url: string): Promise<void> {
// const services = await Services.getInstance(); // const services = await Services.getInstance();
console.log('Opening new websocket connection'); console.log('Opening new websocket connection');
const newClient = initWebsocket(url); const newClient = initWebsocket(url);
} }
public isPaired(): boolean | undefined { public isPaired(): boolean | undefined {
@ -330,7 +330,7 @@ export default class Services {
console.log('🚀 ~ Services ~ createFaucetMessage ~ message:', message); console.log('🚀 ~ Services ~ createFaucetMessage ~ message:', message);
return message; return message;
} }
async createNewDevice() { async createNewDevice() {
let spAddress = ''; let spAddress = '';
try { try {

3
src/utils/html.utils.ts Normal file
View File

@ -0,0 +1,3 @@
export function interpolate(template: string, data: { [key: string]: string }) {
return template.replace(/{{(.*?)}}/g, (_, key) => data[key.trim()]);
}

View File

@ -1,175 +1,174 @@
import Services from "../services/service"; import Services from '../services/service';
import { addSubscription } from "./subscription.utils"; import { addSubscription } from './subscription.utils';
import QRCode from 'qrcode'; import QRCode from 'qrcode';
//Copy Address //Copy Address
export async function copyToClipboard(fullAddress: string) { export async function copyToClipboard(fullAddress: string) {
try { try {
await navigator.clipboard.writeText(fullAddress); await navigator.clipboard.writeText(fullAddress);
alert('Adresse copiée dans le presse-papiers !'); alert('Adresse copiée dans le presse-papiers !');
} catch (err) { } catch (err) {
console.error('Failed to copy the address: ', err); console.error('Failed to copy the address: ', err);
} }
} }
//Generate emojis list //Generate emojis list
export function generateEmojiList(): string[] { export function generateEmojiList(): string[] {
const emojiRanges = [ const emojiRanges = [
[0x1f600, 0x1f64f], [0x1f600, 0x1f64f],
[0x1f300, 0x1f5ff], [0x1f300, 0x1f5ff],
[0x1f680, 0x1f6ff], [0x1f680, 0x1f6ff],
[0x1f700, 0x1f77f], [0x1f700, 0x1f77f],
]; ];
const emojiList: string[] = []; const emojiList: string[] = [];
for (const range of emojiRanges) { for (const range of emojiRanges) {
const [start, end] = range; const [start, end] = range;
for (let i = start; i <= end && emojiList.length < 256; i++) { for (let i = start; i <= end && emojiList.length < 256; i++) {
emojiList.push(String.fromCodePoint(i)); emojiList.push(String.fromCodePoint(i));
} }
if (emojiList.length >= 256) { if (emojiList.length >= 256) {
break; break;
} }
} }
return emojiList.slice(0, 256); return emojiList.slice(0, 256);
} }
//Adress to emojis //Adress to emojis
export async function addressToEmoji(text: string): Promise<string> { export async function addressToEmoji(text: string): Promise<string> {
//Adress to Hash //Adress to Hash
const encoder = new TextEncoder(); const encoder = new TextEncoder();
const data = encoder.encode(text); const data = encoder.encode(text);
const hashBuffer = await crypto.subtle.digest('SHA-256', data); const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const hash = new Uint8Array(hashBuffer); const hash = new Uint8Array(hashBuffer);
const bytes = hash.slice(-4); const bytes = hash.slice(-4);
//Hash slice to emojis //Hash slice to emojis
const emojiList = generateEmojiList(); const emojiList = generateEmojiList();
const emojis = Array.from(bytes) const emojis = Array.from(bytes)
.map((byte) => emojiList[byte]) .map((byte) => emojiList[byte])
.join(''); .join('');
return emojis; return emojis;
}; }
//Get emojis from other device
//Get emojis from other device async function emojisPairingRequest() {
async function emojisPairingRequest() { try {
try { const container = document.getElementById('containerId');
const container = document.getElementById('containerId');
const urlParams: URLSearchParams = new URLSearchParams(window.location.search);
const urlParams: URLSearchParams = new URLSearchParams(window.location.search); const sp_adress: string | null = urlParams.get('sp_address');
const sp_adress: string | null = urlParams.get('sp_address');
if (!sp_adress) {
if (!sp_adress) { // console.error("No 'sp_adress' parameter found in the URL.");
// console.error("No 'sp_adress' parameter found in the URL."); return;
return; }
}
const emojis = await addressToEmoji(sp_adress);
const emojis = await addressToEmoji(sp_adress); const emojiDisplay = container?.querySelector('.pairing-request');
const emojiDisplay = container?.querySelector('.pairing-request');
if (emojiDisplay) {
if (emojiDisplay) { emojiDisplay.textContent = '(Request from: ' + emojis + ')';
emojiDisplay.textContent = '(Request from: ' + emojis + ')'; }
} } catch (err) {
} catch (err) { console.error(err);
console.error(err); }
} }
}
// Display address emojis and other device emojis
// Display address emojis and other device emojis export async function displayEmojis(text: string) {
export async function displayEmojis(text: string) { console.log('🚀 ~ Services ~ adressToEmoji');
console.log('🚀 ~ Services ~ adressToEmoji'); try {
try { const container = document.getElementById('containerId');
const container = document.getElementById('containerId'); const emojis = await addressToEmoji(text);
const emojis = await addressToEmoji(text); const emojiDisplay = container?.querySelector('.emoji-display');
const emojiDisplay = container?.querySelector('.emoji-display');
if (emojiDisplay) {
if (emojiDisplay) { emojiDisplay.textContent = emojis;
emojiDisplay.textContent = emojis; }
}
emojisPairingRequest();
emojisPairingRequest();
initAddressInput();
initAddressInput(); } catch (err) {
} catch (err) { console.error(err);
console.error(err); }
} }
};
// Verify Other address
// Verify Other address export function initAddressInput() {
export function initAddressInput() { const addressInput = document.getElementById('addressInput') as HTMLInputElement;
const addressInput = document.getElementById('addressInput') as HTMLInputElement; const emojiDisplay = document.getElementById('emoji-display-2');
const emojiDisplay = document.getElementById('emoji-display-2'); const okButton = document.getElementById('okButton');
const okButton = document.getElementById('okButton'); addSubscription(addressInput, 'input', async () => {
addSubscription(addressInput, 'input', async () => { let address = addressInput.value;
let address = addressInput.value;
// Vérifie si l'adresse est une URL
// Vérifie si l'adresse est une URL try {
try { const url = new URL(address);
const url = new URL(address); // Si c'est une URL valide, extraire le paramètre sp_address
// Si c'est une URL valide, extraire le paramètre sp_address const urlParams = new URLSearchParams(url.search);
const urlParams = new URLSearchParams(url.search); const extractedAddress = urlParams.get('sp_address') || ''; // Prend sp_address ou une chaîne vide
const extractedAddress = urlParams.get('sp_address') || ''; // Prend sp_address ou une chaîne vide
if (extractedAddress) {
if (extractedAddress) { address = extractedAddress;
address = extractedAddress; addressInput.value = address; // Met à jour l'input pour afficher uniquement l'adresse extraite
addressInput.value = address; // Met à jour l'input pour afficher uniquement l'adresse extraite }
} } catch (e) {
} catch (e) { // Si ce n'est pas une URL valide, on garde l'adresse originale
// Si ce n'est pas une URL valide, on garde l'adresse originale console.log("Ce n'est pas une URL valide, on garde l'adresse originale.");
console.log("Ce n'est pas une URL valide, on garde l'adresse originale."); }
} if (address) {
if (address) { const emojis = await addressToEmoji(address);
const emojis = await addressToEmoji(address); if (emojiDisplay) {
if (emojiDisplay) { emojiDisplay.innerHTML = emojis;
emojiDisplay.innerHTML = emojis; }
} if (okButton) {
if (okButton) { okButton.style.display = 'inline-block';
okButton.style.display = 'inline-block'; }
} } else {
} else { if (emojiDisplay) {
if (emojiDisplay) { emojiDisplay.innerHTML = '';
emojiDisplay.innerHTML = ''; }
} if (okButton) {
if (okButton) { okButton.style.display = 'none';
okButton.style.display = 'none'; }
} }
} });
})
if (okButton) {
if (okButton) { addSubscription(okButton, 'click', () => {
addSubscription(okButton, 'click', () => { onOkButtonClick();
onOkButtonClick(); });
}); }
} }
}
async function onOkButtonClick() {
async function onOkButtonClick() { const service = await Services.getInstance();
const service = await Services.getInstance() const addressInput = (document.getElementById('addressInput') as HTMLInputElement).value;
const addressInput = (document.getElementById('addressInput') as HTMLInputElement).value; await service.sendPairingTx(addressInput);
await service.sendPairingTx(addressInput); }
}
export async function generateQRCode(spAddress: string) {
export async function generateQRCode(spAddress: string) { try {
try { const container = document.getElementById('containerId');
const container = document.getElementById('containerId'); const currentUrl = 'https://' + window.location.host;
const currentUrl = 'https://' + window.location.host; 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
//Generate Address CopyBtn const address = container?.querySelector('.sp-address-btn');
const address = container?.querySelector('.sp-address-btn'); if (address) {
if (address) { address.textContent = 'Copy address';
address.textContent = 'Copy address'; }
} const copyBtn = document.getElementById('copyBtn');
const copyBtn = document.getElementById('copyBtn'); if (copyBtn) {
if (copyBtn) { addSubscription(copyBtn, 'click', () => copyToClipboard(currentUrl + '?sp_address=' + spAddress));
addSubscription(copyBtn, 'click', () => copyToClipboard(currentUrl + '?sp_address=' + spAddress)) }
} } catch (err) {
} catch (err) { console.error(err);
console.error(err); }
} }
};

View File

@ -1,16 +1,16 @@
let subscriptions: { element: Element | Document, event: any, eventHandler: EventListenerOrEventListenerObject }[] = []; let subscriptions: { element: Element | Document; event: any; eventHandler: EventListenerOrEventListenerObject }[] = [];
export function cleanSubscriptions(): void { export function cleanSubscriptions(): void {
console.log("🚀 ~ cleanSubscriptions ~ sub:", subscriptions) console.log('🚀 ~ cleanSubscriptions ~ sub:', subscriptions);
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;
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 {
subscriptions.push({ element, event, eventHandler }); subscriptions.push({ element, event, eventHandler });
element.addEventListener(event, eventHandler); element.addEventListener(event, eventHandler);
} }

View File

@ -3,127 +3,93 @@ import Services from './services/service';
let ws: WebSocket; let ws: WebSocket;
let messageQueue: string[] = []; let messageQueue: string[] = [];
let services: Services let services: Services;
export async function initWebsocket(url: string) { export async function initWebsocket(url: string) {
ws = new WebSocket(url); ws = new WebSocket(url);
services = await Services.getInstance() services = await Services.getInstance();
if (ws !== null) { if (ws !== null) {
ws.onopen = async (event) => { ws.onopen = async (event) => {
console.log('WebSocket connection established'); console.log('WebSocket connection established');
const amount = await services.getAmount(); const amount = await services.getAmount();
if (amount === 0n) { if (amount === 0n) {
const faucetMsg = await services.createFaucetMessage(); const faucetMsg = await services.createFaucetMessage();
await services.sendFaucetMessage(faucetMsg); await services.sendFaucetMessage(faucetMsg);
}
while (messageQueue.length > 0) {
const message = messageQueue.shift();
if (message) {
ws.send(message);
} }
while (messageQueue.length > 0) { }
const message = messageQueue.shift(); };
if (message) {
ws.send(message);
}
}
};
// Listen for messages // Listen for messages
ws.onmessage = (event) => { ws.onmessage = (event) => {
const msgData = event.data; const msgData = event.data;
// console.log("Received text message: ", msgData); // console.log("Received text message: ", msgData);
(async () => { (async () => {
if (typeof msgData === 'string') { if (typeof msgData === 'string') {
try { try {
const feeRate = 0.0001; const feeRate = 0.0001;
const parsedMessage = JSON.parse(msgData); const parsedMessage = JSON.parse(msgData);
// console.log("🚀 ~ WebSocketClient ~ parsedMessage:", parsedMessage) switch (parsedMessage.flag) {
switch (parsedMessage.flag) { case 'NewTx':
case 'NewTx': await services.parseNewTx(parsedMessage.content);
await services.parseNewTx(parsedMessage.content); break;
break; case 'Cipher':
case 'Cipher': await services.parseCipher(parsedMessage.content);
await services.parseCipher(parsedMessage.content); break;
// device = await services.dumpWallet()
// console.log("🚀 ~ WebSocketClient ~ device:", device)
// await services.saveDevice(device)
break;
}
// By parsing the message, we can link it with existing cached message and return the updated version of the message
// if (res.status === 'FaucetComplete') {
// // we received a faucet tx, there's nothing else to do
// window.alert(`New faucet output\n${res.commited_in}`);
// } else if (res.status === 'TxWaitingCipher') {
// // we received a tx but we don't have the cipher
// console.debug(`received notification in output ${res.commited_in}, waiting for cipher message`);
// } else if (res.status === 'CipherWaitingTx') {
// // we received a cipher but we don't have the key
// console.debug(`received a cipher`);
// } else if (res.status === 'SentWaitingConfirmation') {
// // We are sender and we're waiting for the challenge that will confirm recipient got the transaction and the message
// } else if (res.status === 'MustSpendConfirmation') {
// // we received a challenge for a notification we made
// // that means we can stop rebroadcasting the tx and we must spend the challenge to confirm
// window.alert(`Spending ${res.confirmed_by} to prove our identity`);
// console.debug(`sending confirm message to ${res.recipient}`);
// } else if (res.status === 'ReceivedMustConfirm') {
// // we found a notification and decrypted the cipher
// window.alert(`Received message from ${res.sender}\n${res.plaintext}`);
// // we must spend the commited_in output to sender
// } else if (res.status === 'Complete') {
// window.alert(`Received confirmation that ${res.sender} is the author of message ${res.plaintext}`)
// } else {
// console.debug('Received an unimplemented valid message');
// }
} catch (error) {
console.error('Received an invalid message:', error);
} }
} else { } catch (error) {
console.error('Received a non-string message'); console.error('Received an invalid message:', error);
} }
})(); } else {
}; console.error('Received a non-string message');
}
})();
};
// Listen for possible errors // Listen for possible errors
ws.onerror = (event) => { ws.onerror = (event) => {
console.error('WebSocket error:', event); console.error('WebSocket error:', event);
}; };
// Listen for when the connection is closed // Listen for when the connection is closed
ws.onclose = (event) => { ws.onclose = (event) => {
console.log('WebSocket is closed now.'); console.log('WebSocket is closed now.');
}; };
}
} }
}
// Method to send messages // Method to send messages
export async function sendMessage(flag: AnkFlag, message: string): Promise<void> { export async function sendMessage(flag: AnkFlag, message: string): Promise<void> {
if (ws.readyState === WebSocket.OPEN) { if (ws.readyState === WebSocket.OPEN) {
const networkMessage = { const networkMessage = {
flag: flag, flag: flag,
content: message, content: message,
}; };
// if(flag === 'Cipher') { console.log('Sending message:', JSON.stringify(networkMessage));
// const services = await Services.getInstance(); ws.send(JSON.stringify(networkMessage));
// services.parseCipher(JSON.stringify(networkMessage)) } else {
// } console.error('WebSocket is not open. ReadyState:', ws.readyState);
console.log('Sending message:', JSON.stringify(networkMessage)); messageQueue.push(message);
ws.send(JSON.stringify(networkMessage));
} else {
console.error('WebSocket is not open. ReadyState:', ws.readyState);
messageQueue.push(message);
}
} }
}
export function getUrl(): string { export function getUrl(): string {
return ws.url; return ws.url;
} }
export function sendNormalMessage(message: string) { export function sendNormalMessage(message: string) {
ws.send(message); ws.send(message);
console.log('Sending message:', JSON.stringify(message)); console.log('Sending message:', JSON.stringify(message));
} }
// Method to close the WebSocket connection // Method to close the WebSocket connection
export function close(): void { export function close(): void {
ws.close(); ws.close();
} }