From 5289f747e7932b79f7bd3d6ad65d4abec1e5189e Mon Sep 17 00:00:00 2001 From: Niko PLP Date: Tue, 1 Aug 2023 15:44:56 +0300 Subject: [PATCH] wallet creation and login working on native app tauri --- Cargo.lock | 2 +- ng-app/src-tauri/src/lib.rs | 183 ++++++++++++++++-- ng-app/src-tauri/tauri.conf.json | 6 +- ng-app/src/App.svelte | 37 +++- ng-app/src/api.ts | 56 +++++- ng-app/src/lib/Home.svelte | 12 +- ng-app/src/lib/Login.svelte | 65 +------ ng-app/src/lib/{Greet.svelte => Test.svelte} | 8 +- ng-app/src/routes/Home.svelte | 2 +- ng-app/src/routes/Test.svelte | 4 +- ng-app/src/routes/UserRegistered.svelte | 2 - ng-app/src/routes/WalletCreate.svelte | 123 ++++++++---- ng-app/src/routes/WalletLogin.svelte | 6 +- ng-app/src/store.ts | 10 +- ng-sdk-js/Cargo.toml | 1 - ng-sdk-js/index.html | 5 +- ng-sdk-js/js/browser.js | 18 +- ng-sdk-js/src/lib.rs | 133 +++---------- ng-wallet/Cargo.toml | 3 +- ng-wallet/src/lib.rs | 37 +++- ng-wallet/src/types.rs | 92 +++++++-- ngaccount/README.md | 3 +- ngaccount/src/main.rs | 71 ++++--- ngaccount/web/package.json | 15 +- ngaccount/web/pnpm-lock.yaml | 8 + ngaccount/web/src/routes/Create.svelte | 55 ++++-- ngaccount/web/src/routes/Delete.svelte | 3 +- p2p-broker/src/lib.rs | 2 +- .../src/{storage.rs => server_storage.rs} | 12 +- p2p-broker/src/server_ws.rs | 8 +- p2p-net/src/actors/add_invitation.rs | 2 +- p2p-net/src/actors/add_user.rs | 2 +- p2p-net/src/actors/del_user.rs | 2 +- p2p-net/src/actors/list_invitations.rs | 2 +- p2p-net/src/actors/list_users.rs | 6 +- p2p-net/src/broker.rs | 46 +++-- p2p-net/src/lib.rs | 2 +- .../{broker_storage.rs => server_storage.rs} | 2 +- p2p-repo/src/types.rs | 2 +- 39 files changed, 688 insertions(+), 360 deletions(-) rename ng-app/src/lib/{Greet.svelte => Test.svelte} (97%) rename p2p-broker/src/{storage.rs => server_storage.rs} (97%) rename p2p-net/src/{broker_storage.rs => server_storage.rs} (95%) diff --git a/Cargo.lock b/Cargo.lock index 9f74304..b0432d0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2785,7 +2785,6 @@ version = "0.1.0" dependencies = [ "async-std", "base64-url", - "crypto_box", "futures", "getrandom 0.1.16", "gloo-timers", @@ -2816,6 +2815,7 @@ dependencies = [ "async-std", "base64-url", "chacha20poly1305", + "crypto_box", "getrandom 0.1.16", "image", "lazy_static", diff --git a/ng-app/src-tauri/src/lib.rs b/ng-app/src-tauri/src/lib.rs index 1efac7a..39a1db4 100644 --- a/ng-app/src-tauri/src/lib.rs +++ b/ng-app/src-tauri/src/lib.rs @@ -1,3 +1,6 @@ +use std::collections::HashMap; +use std::fs::{read, write}; + // Copyright (c) 2022-2023 Niko Bonnieure, Par le Peuple, NextGraph.org developers // All rights reserved. // Licensed under the Apache License, Version 2.0 @@ -10,11 +13,13 @@ use async_std::stream::StreamExt; use ng_wallet::types::*; use ng_wallet::*; use p2p_net::broker::*; -use p2p_net::types::CreateAccountBSP; -use p2p_net::utils::{spawn_and_log_error, Receiver, ResultSend}; +use p2p_net::types::{CreateAccountBSP, Invitation}; +use p2p_net::utils::{decode_invitation_string, spawn_and_log_error, Receiver, ResultSend}; use p2p_repo::log::*; use p2p_repo::types::*; -use tauri::{App, Manager, Window}; +use tauri::ipc::RemoteDomainAccessScope; +use tauri::utils::config::WindowConfig; +use tauri::{path::BaseDirectory, App, Manager, Window}; #[cfg(mobile)] mod mobile; @@ -61,19 +66,132 @@ async fn wallet_open_wallet_with_pazzle( } #[tauri::command(rename_all = "snake_case")] -async fn wallet_create_wallet(mut params: CreateWalletV0) -> Result { +async fn wallet_create_wallet( + mut params: CreateWalletV0, + app: tauri::AppHandle, +) -> Result<(CreateWalletResultV0, Option), String> { //log_debug!("wallet_create_wallet from rust {:?}", params); - params.result_with_wallet_file = false; + params.result_with_wallet_file = !params.local_save; let local_save = params.local_save; let res = create_wallet_v0(params).await.map_err(|e| e.to_string()); + if res.is_ok() { + let mut cwr = res.unwrap(); + if local_save { + // save in local store + + let session = save_wallet_locally(&cwr, app).await; + if session.is_err() { + return Err("Cannot save wallet locally".to_string()); + } + return Ok((cwr, Some(session.unwrap()))); + } else { + // save wallet file to Downloads folder + let path = app + .path() + .resolve( + format!("wallet-{}.ngw", cwr.wallet_name), + BaseDirectory::Download, + ) + .unwrap(); + let _r = write(path, &cwr.wallet_file); + cwr.wallet_file = vec![]; + return Ok((cwr, None)); + } + } + Err(res.unwrap_err()) +} + +async fn save_wallet_locally( + res: &CreateWalletResultV0, + app: tauri::AppHandle, +) -> Result { + let path = app + .path() + .resolve("wallets", BaseDirectory::AppLocalData) + .map_err(|_| ())?; + let sws = save_new_session(&res.wallet_name, res.wallet.id(), res.user, app.clone())?; + let mut wallets: HashMap = get_wallets_from_localstorage(app) + .await + .unwrap_or(Some(HashMap::new())) + .unwrap_or(HashMap::new()); + // TODO: check that the wallet is not already present in localStorage + let lws: LocalWalletStorageV0 = res.into(); + wallets.insert(res.wallet_name.clone(), lws); + let lws_ser = LocalWalletStorage::v0_to_vec(wallets); + let r = write(path.clone(), &lws_ser); + if r.is_err() { + log_debug!("write {:?} {}", path, r.unwrap_err()); + return Err(()); + } + Ok(sws) +} + +#[tauri::command(rename_all = "snake_case")] +async fn get_wallets_from_localstorage( + app: tauri::AppHandle, +) -> Result>, ()> { + let path = app + .path() + .resolve("wallets", BaseDirectory::AppLocalData) + .map_err(|_| ())?; + let map_ser = read(path); + if map_ser.is_ok() { + let wallets = LocalWalletStorage::v0_from_vec(&map_ser.unwrap()); + let LocalWalletStorage::V0(v0) = wallets; + return Ok(Some(v0)); + } + Ok(None) +} + +fn save_new_session( + wallet_name: &String, + wallet_id: PubKey, + user: PubKey, + app: tauri::AppHandle, +) -> Result { + let mut path = app + .path() + .resolve("sessions", BaseDirectory::AppLocalData) + .map_err(|_| ())?; + let session_v0 = create_new_session(wallet_id, user); + if session_v0.is_err() { + log_debug!("create_new_session {}", session_v0.unwrap_err()); + return Err(()); + } + let sws = session_v0.unwrap(); + std::fs::create_dir_all(path.clone()).unwrap(); + path.push(wallet_name); + let res = write(path.clone(), &sws.1); + if res.is_err() { + log_debug!("write {:?} {}", path, res.unwrap_err()); + return Err(()); + } + Ok(sws.0) +} - if local_save { - // TODO save in user store - } else { - // TODO save wallet file to Downloads folder +#[tauri::command(rename_all = "snake_case")] +async fn get_local_session( + id: String, + key: PrivKey, + user: PubKey, + app: tauri::AppHandle, +) -> Result { + let path = app + .path() + .resolve(format!("sessions/{id}"), BaseDirectory::AppLocalData) + .map_err(|_| ())?; + let res = read(path.clone()); + if res.is_ok() { + log_debug!("RESUMING SESSION"); + let v0 = dec_session(key, &res.unwrap()); + if v0.is_ok() { + return Ok(v0.unwrap()); + } } - res + // create a new session + let wallet_id: PubKey = id.as_str().try_into().unwrap(); + save_new_session(&id, wallet_id, user, app) } #[tauri::command(rename_all = "snake_case")] @@ -82,6 +200,34 @@ async fn encode_create_account(payload: CreateAccountBSP) -> Result payload.encode().ok_or(()) } +#[tauri::command(rename_all = "snake_case")] +async fn open_window( + url: String, + label: String, + title: String, + app: tauri::AppHandle, +) -> Result<(), ()> { + log_debug!("open window url {:?}", url); + let already_exists = app.get_window(&label); + if (already_exists.is_some()) { + let _ = already_exists.unwrap().close(); + std::thread::sleep(std::time::Duration::from_secs(1)); + } + let mut config = WindowConfig::default(); + config.label = label; + config.url = tauri::WindowUrl::External(url.parse().unwrap()); + config.title = title; + let _register_window = tauri::WindowBuilder::from_config(&app, config) + .build() + .unwrap(); + Ok(()) +} + +#[tauri::command(rename_all = "snake_case")] +async fn decode_invitation(invite: String) -> Option { + decode_invitation_string(invite) +} + #[tauri::command(rename_all = "snake_case")] async fn doc_sync_branch(nuri: &str, stream_id: &str, app: tauri::AppHandle) -> Result<(), ()> { log_debug!("doc_sync_branch {} {}", nuri, stream_id); @@ -157,6 +303,11 @@ pub struct AppBuilder { setup: Option, } +#[cfg(debug_assertions)] +const ALLOWED_BSP_DOMAINS: [&str; 2] = ["account-dev.nextgraph.eu", "account-dev.nextgraph.net"]; +#[cfg(not(debug_assertions))] +const ALLOWED_BSP_DOMAINS: [&str; 2] = ["account.nextgraph.eu", "account.nextgraph.net"]; + impl AppBuilder { pub fn new() -> Self { Self::default() @@ -178,7 +329,13 @@ impl AppBuilder { if let Some(setup) = setup { (setup)(app)?; } - + for domain in ALLOWED_BSP_DOMAINS { + app.ipc_scope().configure_remote_access( + RemoteDomainAccessScope::new(domain) + .add_window("registration") + .add_plugins(["window", "event"]), + ); + } Ok(()) }) .plugin(tauri_plugin_window::init()) @@ -192,6 +349,10 @@ impl AppBuilder { wallet_open_wallet_with_pazzle, wallet_create_wallet, encode_create_account, + get_local_session, + get_wallets_from_localstorage, + open_window, + decode_invitation, ]) .run(tauri::generate_context!()) .expect("error while running tauri application"); diff --git a/ng-app/src-tauri/tauri.conf.json b/ng-app/src-tauri/tauri.conf.json index 49473ae..55ef0ca 100644 --- a/ng-app/src-tauri/tauri.conf.json +++ b/ng-app/src-tauri/tauri.conf.json @@ -11,7 +11,6 @@ "version": "0.1.0" }, "tauri": { - "bundle": { "active": true, "icon": [ @@ -21,7 +20,7 @@ "icons/icon.icns", "icons/icon.ico" ], - "identifier": "org.nextgraph.dev", + "identifier": "org.nextgraph.app", "targets": "all", "iOS": { "developmentTeam": "test" @@ -42,7 +41,8 @@ "resizable": true, "title": "NextGraph", "width": 800, - "height": 980 + "height": 1040, + "contentProtected": true } ] } diff --git a/ng-app/src/App.svelte b/ng-app/src/App.svelte index dee103e..a4ae8a9 100644 --- a/ng-app/src/App.svelte +++ b/ng-app/src/App.svelte @@ -46,30 +46,44 @@ let unsubscribe = () => {}; let wallet_channel; + let unsub_main_close; onMount(async () => { let tauri_platform = import.meta.env.TAURI_PLATFORM; - if (!tauri_platform) { + if (tauri_platform) { + let walls = await ng.get_wallets_from_localstorage(); + wallets.set(walls); + + let window_api = await import("@tauri-apps/plugin-window"); + let event_api = await import("@tauri-apps/api/event"); + let main = window_api.WebviewWindow.getByLabel("main"); + unsub_main_close = await main.onCloseRequested(async (event) => { + console.log("onCloseRequested main"); + await event_api.emit("close_all", {}); + let registration = window_api.WebviewWindow.getByLabel("registration"); + if (registration) { + await registration.close(); + } + let viewer = window_api.WebviewWindow.getByLabel("viewer"); + if (viewer) { + await viewer.close(); + } + }); + } else { window.addEventListener("storage", async (event) => { if (event.storageArea != localStorage) return; if (event.key === "ng_wallets") { - wallets.set( - Object.fromEntries(await ng.get_wallets_from_localstorage()) - ); + wallets.set(await ng.get_wallets_from_localstorage()); } }); - wallets.set( - Object.fromEntries((await ng.get_wallets_from_localstorage()) || []) - ); + wallets.set(await ng.get_wallets_from_localstorage()); wallet_channel = new BroadcastChannel("ng_wallet"); wallet_channel.postMessage({ cmd: "is_opened" }, location.href); wallet_channel.onmessage = (event) => { console.log(event); if (!location.href.startsWith(event.origin)) return; - console.log("ng_wallet", event.data); switch (event.data.cmd) { case "is_opened": - console.log($active_wallet); if ($active_wallet && $active_wallet.wallet) { wallet_channel.postMessage( { cmd: "opened", wallet: $active_wallet }, @@ -128,7 +142,10 @@ } }); - onDestroy(unsubscribe); + onDestroy(() => { + unsubscribe(); + if (unsub_main_close) unsub_main_close(); + });
diff --git a/ng-app/src/api.ts b/ng-app/src/api.ts index 3ea221f..35db3e5 100644 --- a/ng-app/src/api.ts +++ b/ng-app/src/api.ts @@ -19,6 +19,10 @@ const mapping = { "wallet_open_wallet_with_pazzle": ["wallet","pazzle","pin"], "wallet_create_wallet": ["params"], "encode_create_account": ["payload"], + "get_local_session": ["id","key","user"], + "get_wallets_from_localstorage": [], + "open_window": ["url","label","title"], + "decode_invitation": ["invite"], "test": [ ] } @@ -34,6 +38,23 @@ const handler = { client_info.version=version; //console.log(client_info); return client_info; + } else if (path[0] === "get_wallets_from_localstorage") { + let wallets = await Reflect.apply(sdk[path], caller, args); + return Object.fromEntries(wallets || []); + } else if (path[0] === "get_local_session") { + let res = await Reflect.apply(sdk[path], caller, args); + let v = res.users.values().next().value; + v.branches_last_seq = Object.fromEntries(v.branches_last_seq); + res.users = Object.fromEntries(res.users); + return res; + } else if (path[0] === "wallet_create_wallet") { + let res = await Reflect.apply(sdk[path], caller, args); + if (res[1]) { + let v = res[1].users.values().next().value; + v.branches_last_seq = Object.fromEntries(v.branches_last_seq); + res[1].users = Object.fromEntries(res[1].users); + } + return res; } else { return Reflect.apply(sdk[path], caller, args) } @@ -88,17 +109,29 @@ const handler = { let res = await tauri.invoke(path[0],arg); res['File'].V0.content = Uint8Array.from(res['File'].V0.content); res['File'].V0.metadata = Uint8Array.from(res['File'].V0.metadata); - return res + return res; + } else if (path[0] === "get_wallets_from_localstorage") { + let res = await tauri.invoke(path[0],{}); + for (let e of Object.entries(res)) { + e[1].wallet.V0.content.security_img = Uint8Array.from(e[1].wallet.V0.content.security_img); + } + return res; + } else if (path[0] === "wallet_create_wallet") { let params = args[0]; params.result_with_wallet_file = false; params.security_img = Array.from(new Uint8Array(params.security_img)); return await tauri.invoke(path[0],{params}) - } else if (path[0].starts_with("get_local_bootstrap")) { + } else if (path[0] && path[0].startsWith("get_local_bootstrap")) { return false; - } else if (path[0].starts_with("get_local_url")) { + } else if (path[0] === "get_local_url") { return false; - } + } else if (path[0] === "wallet_open_wallet_with_pazzle") { + let arg = {}; + args.map((el,ix) => arg[mapping[path[0]][ix]]=el) + arg.wallet.V0.content.security_img = Array.from(new Uint8Array(arg.wallet.V0.content.security_img)); + return tauri.invoke(path[0],arg) + } else { let arg = {}; args.map((el,ix) => arg[mapping[path[0]][ix]]=el) @@ -111,15 +144,20 @@ const handler = { const api = createAsyncProxy({}, handler); export const NG_EU_BSP = "https://nextgraph.eu"; -export const NG_EU_BSP_REGISTER = "https://account.nextgraph.eu/#/create"; -export const NG_EU_BSP_REGISTERED = "https://nextgraph.eu/#/user/registered"; +export const NG_EU_BSP_REGISTER = import.meta.env.PROD +? "https://account.nextgraph.eu/#/create" +: "http://account-dev.nextgraph.eu:5173/#/create"; + +export const NG_NET_BSP = "https://nextgraph.net"; +export const NG_NET_BSP_REGISTER = import.meta.env.PROD +? "https://account.nextgraph.net/#/create" +: "http://account-dev.nextgraph.net:5173/#/create"; export const APP_ACCOUNT_REGISTERED_SUFFIX = "/#/user/registered"; export const APP_WALLET_CREATE_SUFFIX = "/#/wallet/create"; -export const NG_NET_BSP = "https://nextgraph.net"; -export const NG_NET_BSP_REGISTER = "https://account.nextgraph.net/#/create"; -export const NG_NET_BSP_REGISTERED = "https://nextgraph.net/#/user/registered"; +export const LINK_NG_BOX = "https://nextgraph.org/ng-box/"; +export const LINK_SELF_HOST = "https://nextgraph.org/self-host/"; export default api; \ No newline at end of file diff --git a/ng-app/src/lib/Home.svelte b/ng-app/src/lib/Home.svelte index 0fe0394..7811417 100644 --- a/ng-app/src/lib/Home.svelte +++ b/ng-app/src/lib/Home.svelte @@ -14,13 +14,14 @@ import { link } from "svelte-spa-router"; // @ts-ignore import Logo from "../assets/nextgraph.svg?component"; - import { has_wallets } from "../store"; + import Test from "./Test.svelte"; + import { has_wallets, active_wallet } from "../store"; import { onMount } from "svelte"; export let display_login_create = false; -{#if !$has_wallets || display_login_create} +{#if !$has_wallets || !$active_wallet || display_login_create}
+{:else} +
+

Welcome to test

+
+ +
+
{/if} diff --git a/ng-app/src/lib/Login.svelte b/ng-app/src/lib/Login.svelte index d99405e..3ad467e 100644 --- a/ng-app/src/lib/Login.svelte +++ b/ng-app/src/lib/Login.svelte @@ -20,56 +20,8 @@ onMount(async () => { await load_svg(); - + console.log(wallet); await init(); - - //console.log(JSON.stringify(await ng.test_create_wallet())); - //console.log(await ng.test_create_wallet()); - - // let ref = { - // id: { - // Blake3Digest32: [ - // 228, 228, 181, 117, 36, 206, 41, 223, 130, 96, 85, 195, 104, 137, 78, - // 145, 42, 176, 58, 244, 111, 97, 246, 39, 11, 76, 135, 150, 188, 111, - // 66, 33, - // ], - // }, - // key: { - // ChaCha20Key: [ - // 100, 243, 39, 242, 203, 131, 102, 50, 9, 54, 248, 113, 4, 160, 28, 45, - // 73, 56, 217, 112, 95, 150, 144, 137, 9, 57, 106, 5, 39, 202, 146, 94, - // ], - // }, - // }; - - // let img = await ng.doc_get_file_from_store_with_object_ref("ng:", ref); - - // let c = { - // security_img: img["File"].V0.content, - // security_txt: " know yourself ", - // pin: [5, 2, 9, 1], - // pazzle_length: 9, - // send_bootstrap: false, - // send_wallet: false, - // result_with_wallet_file: true, - // local_save: false, - // }; - - // try { - // let res = await ng.wallet_create_wallet(c); - // console.log(res); - // wallet = res.wallet; - - // for (const emoji of res.pazzle) { - // let cat = (emoji & 240) >> 4; - // let idx = emoji & 15; - // console.log(emoji_cat[cat], emojis[emoji_cat[cat]][idx].code); - // } - // } catch (e) { - // console.error(e); - // } - - //await start_pin(); }); async function init() { @@ -159,6 +111,7 @@ } console.log(pazzle); + console.log(wallet); // open the wallet try { @@ -168,7 +121,6 @@ pin_code ); step = "end"; - console.log(secret_wallet); dispatch("opened", { wallet: secret_wallet, id: secret_wallet.V0.wallet_id, @@ -239,7 +191,7 @@ {:else if step == "pazzle"} -
+
{#each [0, 1, 2, 3, 4] as row}
{#each emojis2[display]?.slice(0 + row * 3, 3 + row * 3) || [] as emoji, i} @@ -258,7 +210,7 @@
{:else if step == "order"} -
+
{#each [0, 1, 2] as row}
{#each selection.slice(0 + row * 3, 3 + row * 3) || [] as emoji, i} @@ -401,14 +353,17 @@ } .sel { - position: relative; - top: -56%; + position: absolute; + width: 100%; + top: 45%; + left: 0; font-size: 100px; font-weight: 700; } .sel-emoji { - overflow: hidden; + /* overflow: hidden; */ + position: relative; } .emoji { diff --git a/ng-app/src/lib/Greet.svelte b/ng-app/src/lib/Test.svelte similarity index 97% rename from ng-app/src/lib/Greet.svelte rename to ng-app/src/lib/Test.svelte index 5fb3470..ab49793 100644 --- a/ng-app/src/lib/Greet.svelte +++ b/ng-app/src/lib/Test.svelte @@ -27,7 +27,7 @@ try { //console.log(JSON.stringify(ref)); let file = await ng.doc_get_file_from_store_with_object_ref("ng:", ref); - console.log(file); + //console.log(file); var blob = new Blob([file["File"].V0.content], { type: file["File"].V0.content_type, }); @@ -75,10 +75,10 @@
-
+
-

{greetMsg}

+ {#await commits.load()}

Currently loading...

{:then} diff --git a/ng-app/src/routes/Home.svelte b/ng-app/src/routes/Home.svelte index afedb38..d68ca79 100644 --- a/ng-app/src/routes/Home.svelte +++ b/ng-app/src/routes/Home.svelte @@ -31,7 +31,7 @@ $s2, ]); unsubscribe = combined.subscribe((value) => { - console.log(value); + //console.log(value); if (!value[0] && value[1]) { push("#/wallet/login"); } diff --git a/ng-app/src/routes/Test.svelte b/ng-app/src/routes/Test.svelte index ba29f10..45dce3b 100644 --- a/ng-app/src/routes/Test.svelte +++ b/ng-app/src/routes/Test.svelte @@ -10,14 +10,14 @@ -->

Welcome to test

- +
diff --git a/ng-app/src/routes/UserRegistered.svelte b/ng-app/src/routes/UserRegistered.svelte index 081afc3..a763ccc 100644 --- a/ng-app/src/routes/UserRegistered.svelte +++ b/ng-app/src/routes/UserRegistered.svelte @@ -20,8 +20,6 @@ import { NG_EU_BSP, NG_NET_BSP, - NG_EU_BSP_REGISTER, - NG_EU_BSP_REGISTERED, APP_ACCOUNT_REGISTERED_SUFFIX, default as ng, } from "../api"; diff --git a/ng-app/src/routes/WalletCreate.svelte b/ng-app/src/routes/WalletCreate.svelte index 0a2e9eb..61ee36c 100644 --- a/ng-app/src/routes/WalletCreate.svelte +++ b/ng-app/src/routes/WalletCreate.svelte @@ -19,14 +19,16 @@ import { NG_EU_BSP, NG_NET_BSP, + LINK_NG_BOX, + LINK_SELF_HOST, NG_EU_BSP_REGISTER, - NG_EU_BSP_REGISTERED, + NG_NET_BSP_REGISTER, APP_WALLET_CREATE_SUFFIX, default as ng, } from "../api"; import { display_pazzle } from "../wallet_emojis"; - import { onMount, tick } from "svelte"; + import { onMount, onDestroy, tick } from "svelte"; import { wallets, set_active_session, has_wallets } from "../store"; const param = new URLSearchParams($querystring); @@ -108,6 +110,10 @@ let animateDownload = true; let invitation; + let unsub_register_accepted; + let unsub_register_error; + let unsub_register_close; + function scrollToTop() { top.scrollIntoView(); } @@ -202,7 +208,7 @@ pazzle_length: 9, send_bootstrap: false, //options.cloud || options.bootstrap ? : undefined, send_wallet: options.cloud, - local_save: options.trusted, // this is only used for tauri apps + local_save: options.trusted, result_with_wallet_file: false, // this will be automatically changed to true for browser app core_bootstrap: invitation.V0.bootstrap, core_registration, @@ -211,10 +217,8 @@ console.log(params); try { let res = await ng.wallet_create_wallet(params); - console.log(res); - wallets.set( - Object.fromEntries((await ng.get_wallets_from_localstorage()) || []) - ); + let walls = await ng.get_wallets_from_localstorage(); + wallets.set(walls); if (res[1]) { set_active_session(res[1]); } @@ -227,26 +231,9 @@ if (ready.wallet_file.length) { const blob = new Blob([ready.wallet_file]); download_link = URL.createObjectURL(blob); - - // we also save the wallet to localStorage here, and only if options.trusted is true - // indeed if a wallet_file is sent in the result, it means we are not on tauri app - // therefor we are on a web-browser. - if (options.trusted) { - //TODO save in localStorage - } } } catch (e) { console.log(e); - if ( - e == "The operation is insecure." || - e == - "Failed to read the 'sessionStorage' property from 'Window': Access is denied for this document." || - e == - "Failed to read the 'localStorage' property from 'Window': Access is denied for this document." - ) { - e = - "Please allow this website to store cookies, session and local storage."; - } error = e; } } @@ -276,16 +263,32 @@ // }, // }; - const selectEU = async (event) => { + const unsub_register = () => { + if (unsub_register_accepted) unsub_register_accepted(); + if (unsub_register_error) unsub_register_error(); + if (unsub_register_close) unsub_register_close(); + unsub_register_close = undefined; + unsub_register_error = undefined; + unsub_register_accepted = undefined; + }; + + onDestroy(() => { + unsub_register(); + }); + + const select_bsp = async (bsp_url, bsp_name) => { if (!tauri_platform) { let local_url = await ng.get_local_url(location.href); + if (!import.meta.env.PROD) { + local_url = "http://localhost:1421"; + } let create = { V0: { redirect_url: local_url + APP_WALLET_CREATE_SUFFIX, }, }; let ca = await ng.encode_create_account(create); - window.location.href = NG_EU_BSP_REGISTER + "?ca=" + ca; + window.location.href = bsp_url + "?ca=" + ca; //window.open(), "_self").focus(); } else { let create = { @@ -294,14 +297,60 @@ }, }; let ca = await ng.encode_create_account(create); - // TODO: open window with registration URL : NG_EU_BSP_REGISTER + "?ca=" + ca; + await ng.open_window( + bsp_url + "?ca=" + ca, + "registration", + "Registration at a Broker" + ); + let window_api = await import("@tauri-apps/plugin-window"); + let event_api = await import("@tauri-apps/api/event"); + let reg_popup = window_api.WebviewWindow.getByLabel("registration"); + unsub_register_accepted = await event_api.listen( + "accepted", + async (event) => { + console.log("got accepted with payload", event.payload); + unsub_register(); + await reg_popup.close(); + registration_success = bsp_name; + invitation = await ng.decode_invitation(event.payload.invite); + } + ); + unsub_register_error = await event_api.listen("error", async (event) => { + console.log("got error with payload", event.payload); + if (event.payload) registration_error = event.payload.error; + else intro = true; + unsub_register(); + await reg_popup.close(); + }); + unsub_register_close = await reg_popup.onCloseRequested(async (event) => { + console.log("onCloseRequested"); + intro = true; + unsub_register(); + }); } }; - const selectNET = (event) => {}; + const selectEU = async (event) => { + await select_bsp(NG_EU_BSP_REGISTER, "nextgraph.eu"); + }; + const selectNET = async (event) => { + await select_bsp(NG_NET_BSP_REGISTER, "nextgraph.net"); + }; const enterINVITE = (event) => {}; const enterQRcode = (event) => {}; - const displayNGbox = (event) => {}; - const displaySelfHost = (event) => {}; + const displayNGbox = async (event) => { + if (!tauri_platform) { + window.open(LINK_NG_BOX, "_blank").focus(); + } else { + await ng.open_window(LINK_NG_BOX, "viewer", "Own your NG-Box"); + } + }; + const displaySelfHost = async (event) => { + if (!tauri_platform) { + window.open(LINK_SELF_HOST, "_blank").focus(); + } else { + await ng.open_window(LINK_SELF_HOST, "viewer", "Self-host a broker"); + } + };
@@ -869,7 +918,7 @@ {/if}