Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ab2ac4813a |
64 changed files with 510 additions and 991 deletions
|
|
@ -92,11 +92,6 @@ function emitIcons(): Plugin {
|
|||
attrs: { name: "apple-mobile-web-app-capable", content: "yes" },
|
||||
injectTo: "head",
|
||||
},
|
||||
{
|
||||
tag: "meta",
|
||||
attrs: { name: "mobile-web-app-capable", content: "yes" },
|
||||
injectTo: "head",
|
||||
},
|
||||
{
|
||||
tag: "meta",
|
||||
attrs: {
|
||||
|
|
|
|||
|
|
@ -20,7 +20,6 @@ pub fn run() {
|
|||
accessibility_backend::accessibility_get_initial_scale,
|
||||
accessibility_backend::accessibility_set_initial_scale,
|
||||
mtp_backend::mtp_request,
|
||||
mtp_backend::mtp_send_sealed_relay,
|
||||
mtp_backend::mtp_status,
|
||||
mtp_backend::mtp_store_credentials,
|
||||
mtp_backend::mtp_has_credentials,
|
||||
|
|
|
|||
|
|
@ -9,12 +9,9 @@ use base64::{
|
|||
Engine as _,
|
||||
};
|
||||
use mtp::client::{ClientConfig, MTPClient, MTPConnection, Policy, SendMode};
|
||||
use mtp::codec::{
|
||||
CommunicationType, CommunicationValue, DataType, DataValue, SealedRelayBuilder, TypeMap,
|
||||
};
|
||||
use mtp::codec::{CommunicationType, CommunicationValue, DataType, DataValue, TypeMap};
|
||||
use mtp::crypto::{
|
||||
derive_encryption_key, AeadDecrypt, ChaCha20Poly1305, DualSigner, HybridKem, Keyring,
|
||||
PublicKeyBundle,
|
||||
derive_encryption_key, AeadDecrypt, ChaCha20Poly1305, HybridKem, Keyring, PublicKeyBundle,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Map, Value};
|
||||
|
|
@ -31,9 +28,6 @@ const CHAT_SECRET_SCHEME: &str = "mtp-chat-secret-kem-chacha20poly1305-hkdf-sha2
|
|||
const INITIAL_SYNC_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
const MAX_BUFFERED_INITIAL_FRAMES: usize = 1_000;
|
||||
const NOTIFICATION_QUEUE_CAPACITY: usize = 32;
|
||||
const ROUTE_TARGET_ID_MASK: u64 = (1_u64 << 48) - 1;
|
||||
const USER_ROUTE_TARGET_KIND: u64 = 0x4000_0000_0000_0000;
|
||||
const IOTA_ROUTE_TARGET_KIND: u64 = 0x8000_0000_0000_0000;
|
||||
#[cfg(target_os = "android")]
|
||||
const ROOT_YE_PEM: &[u8] = b"-----BEGIN CERTIFICATE-----\n\
|
||||
MIIB2TCCAWCgAwIBAgIRAKQCa6LvbHwg1AR+XmWmk4AwCgYIKoZIzj0EAwMwLjEL\n\
|
||||
|
|
@ -85,44 +79,6 @@ pub struct MtpSnapshot {
|
|||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct EncodedKeyMaterial {
|
||||
value: String,
|
||||
encoding: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "lowercase")]
|
||||
enum RelayTargetDto {
|
||||
User { id: u64 },
|
||||
Iota { id: u64 },
|
||||
}
|
||||
|
||||
impl RelayTargetDto {
|
||||
fn wire_id(self) -> Result<u64, String> {
|
||||
let (kind, id) = match self {
|
||||
Self::User { id } => (USER_ROUTE_TARGET_KIND, id),
|
||||
Self::Iota { id } => (IOTA_ROUTE_TARGET_KIND, id),
|
||||
};
|
||||
if id == 0 || id > ROUTE_TARGET_ID_MASK {
|
||||
return Err("relay target ID must be a non-zero 48-bit integer".into());
|
||||
}
|
||||
Ok(kind | id)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SealedRelayRequest {
|
||||
type_name: String,
|
||||
data: Value,
|
||||
next_hop: RelayTargetDto,
|
||||
final_recipient_id: u64,
|
||||
metadata_recipients: Vec<EncodedKeyMaterial>,
|
||||
content_recipients: Vec<EncodedKeyMaterial>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Serialize)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
enum MtpEvent {
|
||||
|
|
@ -739,88 +695,6 @@ async fn resolve_endpoint(config: &MtpConfig) -> Result<(String, String), String
|
|||
))
|
||||
}
|
||||
|
||||
fn decode_key_material(value: EncodedKeyMaterial) -> Result<PublicKeyBundle, String> {
|
||||
let bytes = match value.encoding.as_str() {
|
||||
"base64" => decode_browser_base64(&value.value)?,
|
||||
"hex" => decode_sdk_bytes(&value.value)?,
|
||||
encoding => return Err(format!("unsupported key material encoding: {encoding}")),
|
||||
};
|
||||
let key = PublicKeyBundle::from_bytes(&bytes)
|
||||
.map_err(|error| format!("invalid relay recipient public key: {error}"))?;
|
||||
key.validate()
|
||||
.map_err(|error| format!("invalid relay recipient public key: {error}"))?;
|
||||
Ok(key)
|
||||
}
|
||||
|
||||
async fn send_sealed_relay(request: SealedRelayRequest) -> Result<Value, String> {
|
||||
if request.metadata_recipients.is_empty() || request.content_recipients.is_empty() {
|
||||
return Err("sealed relay requires metadata and content recipients".into());
|
||||
}
|
||||
if request.final_recipient_id == 0 {
|
||||
return Err("sealed relay final recipient ID must be non-zero".into());
|
||||
}
|
||||
let manager = manager();
|
||||
let connection = manager
|
||||
.connection
|
||||
.read()
|
||||
.map_err(|_| "MTP connection lock is unavailable")?
|
||||
.clone()
|
||||
.ok_or_else(|| "MTP is not connected".to_string())?;
|
||||
let config = manager
|
||||
.config
|
||||
.read()
|
||||
.map_err(|_| "MTP configuration lock is unavailable")?
|
||||
.clone()
|
||||
.ok_or_else(|| "MTP credentials are unavailable".to_string())?;
|
||||
let keyring_bytes = decode_browser_base64(&config.keyring)?;
|
||||
let keyring = Keyring::from_bytes(&keyring_bytes)
|
||||
.map_err(|error| format!("invalid MTP keyring: {error}"))?;
|
||||
let signer = DualSigner::new(
|
||||
&keyring.sig_cl_secret_key,
|
||||
&keyring.sig_pq_secret_key,
|
||||
&keyring.sig_pq_public_key,
|
||||
)
|
||||
.map_err(|error| format!("invalid MTP signing key: {error}"))?;
|
||||
let next_hop_id = request.next_hop.wire_id()?;
|
||||
let type_map = TypeMap::latest();
|
||||
let content = json_to_frame(&request.type_name, request.data, 1)?.into_payload();
|
||||
let metadata_recipients = request
|
||||
.metadata_recipients
|
||||
.into_iter()
|
||||
.map(decode_key_material)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let content_recipients = request
|
||||
.content_recipients
|
||||
.into_iter()
|
||||
.map(decode_key_material)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let created_at = mtp::common::unix_time_millis()
|
||||
.map_err(|error| format!("failed to get relay timestamp: {error}"))?;
|
||||
let request_id = connection.next_request_id().await?;
|
||||
let message_id = format!("tensamin-relay-{created_at}-{request_id}");
|
||||
let frame = SealedRelayBuilder::new(
|
||||
request.type_name,
|
||||
content,
|
||||
config.user_id,
|
||||
request.final_recipient_id,
|
||||
next_hop_id,
|
||||
&signer,
|
||||
)
|
||||
.message_id(message_id)
|
||||
.created_at(created_at)
|
||||
.metadata_recipients(metadata_recipients)
|
||||
.content_recipients(content_recipients)
|
||||
.type_map(&type_map)
|
||||
.build()
|
||||
.map_err(|error| format!("failed to build sealed relay: {error}"))?;
|
||||
let response = connection
|
||||
.mtp
|
||||
.request(&frame, None)
|
||||
.await
|
||||
.map_err(|error| format!("sealed relay request failed: {error}"))?;
|
||||
frame_to_json(&response)
|
||||
}
|
||||
|
||||
async fn handle_push(
|
||||
generation: u64,
|
||||
notification_tx: &mpsc::Sender<CommunicationValue>,
|
||||
|
|
@ -1173,8 +1047,7 @@ mod tests {
|
|||
|
||||
use super::{
|
||||
container_value_by_name, decode_browser_base64, decode_sdk_bytes, frame_to_json,
|
||||
jittered_retry_delay, json_to_frame, prepare_initial_state_ack, RelayTargetDto,
|
||||
RequestIdAllocator,
|
||||
jittered_retry_delay, json_to_frame, prepare_initial_state_ack, RequestIdAllocator,
|
||||
};
|
||||
|
||||
#[test]
|
||||
|
|
@ -1197,20 +1070,6 @@ mod tests {
|
|||
assert_eq!(ids.next().unwrap(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iota_relay_target_encodes_its_namespace() {
|
||||
assert_eq!(
|
||||
RelayTargetDto::Iota { id: 42 }.wire_id().unwrap(),
|
||||
0x8000_0000_0000_002a
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relay_target_rejects_raw_or_out_of_range_ids() {
|
||||
assert!(RelayTargetDto::Iota { id: 0 }.wire_id().is_err());
|
||||
assert!(RelayTargetDto::User { id: 1_u64 << 48 }.wire_id().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retry_jitter_stays_within_policy_bounds() {
|
||||
let delay = jittered_retry_delay(std::time::Duration::from_secs(10));
|
||||
|
|
@ -1335,11 +1194,6 @@ pub async fn mtp_request(type_name: String, data: Value) -> Result<Value, String
|
|||
manager().request(&type_name, data).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn mtp_send_sealed_relay(request: SealedRelayRequest) -> Result<Value, String> {
|
||||
send_sealed_relay(request).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn mtp_status() -> MtpSnapshot {
|
||||
manager().snapshot()
|
||||
|
|
|
|||
1
apps/web/.gitignore
vendored
1
apps/web/.gitignore
vendored
|
|
@ -8,7 +8,6 @@ pnpm-debug.log*
|
|||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
.mtp
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
|
|
|||
|
|
@ -24,7 +24,6 @@
|
|||
"@tensamin/chat": "workspace:*",
|
||||
"@tensamin/crypto": "workspace:*",
|
||||
"@tensamin/hotkeys": "workspace:*",
|
||||
"@tensamin/markdown": "workspace:*",
|
||||
"@tensamin/mtp": "workspace:*",
|
||||
"@tensamin/notifications": "workspace:*",
|
||||
"@tensamin/onboarding": "workspace:*",
|
||||
|
|
@ -33,7 +32,7 @@
|
|||
"@tensamin/storage": "workspace:*",
|
||||
"@tensamin/tauri": "workspace:*",
|
||||
"@tensamin/tauth": "workspace:*",
|
||||
"@tensamin/identity": "workspace:*",
|
||||
"@tensamin/user": "workspace:*",
|
||||
"decimal.js-light": "^2.5.1",
|
||||
"eventemitter3": "^5.0.4",
|
||||
"lucide-react": "^1.29.0",
|
||||
|
|
|
|||
|
|
@ -1,8 +0,0 @@
|
|||
import { useCall } from "@tensamin/call/state";
|
||||
import Popout from "@tensamin/call/popout";
|
||||
|
||||
export default function CallPopout() {
|
||||
const active = useCall((state) => state.state !== "closed");
|
||||
|
||||
return active ? <Popout /> : null;
|
||||
}
|
||||
|
|
@ -1,95 +0,0 @@
|
|||
import { useEffect, useState } from "react";
|
||||
|
||||
import { useTheme } from "@methanium/ui";
|
||||
import { useIsSpeaking } from "@tensamin/call/speakingState";
|
||||
import { useCall, useInitializeCall } from "@tensamin/call/store";
|
||||
import { useStorage } from "@tensamin/storage/context";
|
||||
|
||||
function createCallTrayIcon(color: string, speaking: boolean) {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = 32;
|
||||
canvas.height = 32;
|
||||
|
||||
const context = canvas.getContext("2d");
|
||||
if (!context) return undefined;
|
||||
|
||||
context.globalAlpha = speaking ? 1 : 0.55;
|
||||
context.fillStyle = color;
|
||||
context.beginPath();
|
||||
context.arc(16, 16, 13, 0, Math.PI * 2);
|
||||
context.fill();
|
||||
|
||||
if (speaking) {
|
||||
context.globalAlpha = 0.3;
|
||||
context.fillStyle = "#ffffff";
|
||||
context.fill();
|
||||
}
|
||||
|
||||
return canvas.toDataURL("image/png");
|
||||
}
|
||||
|
||||
export default function CallRuntimeInit() {
|
||||
const callInvitePopup = useInitializeCall();
|
||||
const { load } = useStorage();
|
||||
const {
|
||||
themeColor,
|
||||
themePalette,
|
||||
themePrimaryColor,
|
||||
themePolarity,
|
||||
themeTint,
|
||||
themeCustomCss,
|
||||
} = useTheme();
|
||||
const [localUserId, setLocalUserId] = useState(-1);
|
||||
const [primaryColor, setPrimaryColor] = useState("");
|
||||
const inCall = useCall((state) => state.state === "open");
|
||||
const speaking = useIsSpeaking(localUserId);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
|
||||
load("user_id").then((userId) => {
|
||||
if (active) setLocalUserId(userId);
|
||||
});
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [load]);
|
||||
|
||||
useEffect(() => {
|
||||
const frame = requestAnimationFrame(() => {
|
||||
setPrimaryColor(
|
||||
getComputedStyle(document.documentElement)
|
||||
.getPropertyValue("--primary")
|
||||
.trim(),
|
||||
);
|
||||
});
|
||||
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [
|
||||
themeColor,
|
||||
themeCustomCss,
|
||||
themePalette,
|
||||
themePolarity,
|
||||
themePrimaryColor,
|
||||
themeTint,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
const iconDataUrl = primaryColor
|
||||
? createCallTrayIcon(primaryColor, speaking)
|
||||
: undefined;
|
||||
|
||||
void window.tensaminDesktop?.call
|
||||
?.setStatus?.({
|
||||
inCall,
|
||||
speaking: inCall && speaking,
|
||||
iconDataUrl: inCall ? iconDataUrl : undefined,
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
console.error("Failed to update desktop call status", error);
|
||||
});
|
||||
}, [inCall, primaryColor, speaking]);
|
||||
|
||||
return callInvitePopup;
|
||||
}
|
||||
|
|
@ -1,8 +0,0 @@
|
|||
import { useCall } from "@tensamin/call/state";
|
||||
import SidebarBox from "@tensamin/call/sidebarBox";
|
||||
|
||||
export default function CallSidebarBox() {
|
||||
const active = useCall((state) => state.state !== "closed");
|
||||
|
||||
return active ? <SidebarBox /> : null;
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import type { User } from "@tensamin/identity/context";
|
||||
import type { User } from "@tensamin/user/context";
|
||||
import {
|
||||
Avatar,
|
||||
AvatarImage,
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import type { User } from "@tensamin/identity/context";
|
||||
import type { User } from "@tensamin/user/context";
|
||||
import { Avatar, AvatarFallback, AvatarImage, Button } from "@methanium/ui";
|
||||
import Text from "@tensamin/markdown/text";
|
||||
import { Text } from "@methanium/ui/markdown";
|
||||
import { ChevronDown, ChevronUp } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
|
||||
|
|
|
|||
|
|
@ -14,8 +14,8 @@ import {
|
|||
User,
|
||||
} from "lucide-react";
|
||||
import { useLocation, useNavigate, useSearch } from "@tanstack/react-router";
|
||||
import { useCall } from "@tensamin/call/state";
|
||||
import Wrapper from "@tensamin/identity/wrapper";
|
||||
import { joinCall, useCall } from "@tensamin/call/store";
|
||||
import Wrapper from "@tensamin/user/wrapper";
|
||||
import { Skeleton } from "@methanium/ui";
|
||||
import {
|
||||
Select,
|
||||
|
|
@ -27,8 +27,7 @@ import { displayCallId } from "@tensamin/call/utils";
|
|||
import { useState } from "react";
|
||||
import { SidebarTrigger, useSidebar } from "@methanium/ui";
|
||||
import { WindowControls as Controls } from "@methanium/ui";
|
||||
import { useSession } from "@tensamin/identity/session";
|
||||
import { joinCall } from "@tensamin/call/store";
|
||||
import { useSession } from "@tensamin/storage/session";
|
||||
import Profile from "./modals/profile";
|
||||
|
||||
export default function Navbar({ forMobile }: { forMobile: boolean }) {
|
||||
|
|
@ -140,7 +139,9 @@ export default function Navbar({ forMobile }: { forMobile: boolean }) {
|
|||
{currentCalls.length === 0 ? (
|
||||
<Button
|
||||
disabled={callState !== "closed"}
|
||||
onClick={() => void joinCall(id)}
|
||||
onClick={() => {
|
||||
void joinCall(id);
|
||||
}}
|
||||
className="w-9 h-9! aspect-square rounded-lg"
|
||||
variant="outline"
|
||||
>
|
||||
|
|
@ -180,9 +181,9 @@ export default function Navbar({ forMobile }: { forMobile: boolean }) {
|
|||
<SelectItem
|
||||
value={call.CallId}
|
||||
key={call.CallId}
|
||||
onSelect={() =>
|
||||
void joinCall(id, call.CallSecret, call.CallId)
|
||||
}
|
||||
onSelect={() => {
|
||||
void joinCall(id, call.CallSecret, call.CallId);
|
||||
}}
|
||||
>
|
||||
{displayCallId(call.CallId)}
|
||||
</SelectItem>
|
||||
|
|
|
|||
|
|
@ -1,15 +0,0 @@
|
|||
import { Loader2 } from "lucide-react";
|
||||
|
||||
export default function RouteLoader() {
|
||||
return (
|
||||
<div
|
||||
className="flex h-full min-h-40 w-full items-center justify-center bg-background"
|
||||
role="status"
|
||||
>
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="size-5 animate-spin" />
|
||||
<span>Loading...</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,6 +1,5 @@
|
|||
import Wrapper from "@tensamin/identity/wrapper";
|
||||
import Wrapper from "@tensamin/user/wrapper";
|
||||
import { Basic, Loading } from "./modals/basic";
|
||||
import CallSidebarBox from "./callSidebarBox";
|
||||
import List from "@/features/conversation/list/body";
|
||||
|
||||
import {
|
||||
|
|
@ -31,10 +30,11 @@ import {
|
|||
import { useIsMobile } from "@methanium/ui";
|
||||
import { MobileNavbar } from "./navbar";
|
||||
|
||||
import SidebarBox from "@tensamin/call/sidebarBox";
|
||||
import { useShowMobileNavbar } from "@/routes/app/useShowMobileNavbar";
|
||||
import { Ellipsis, Check } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useUser, type User } from "@tensamin/identity/context";
|
||||
import { useUser, type User } from "@tensamin/user/context";
|
||||
import { mtp, userPresencePreferenceSchema } from "@tensamin/shared/data";
|
||||
import { useMTP } from "@tensamin/mtp";
|
||||
import {
|
||||
|
|
@ -285,7 +285,7 @@ export default function Sidebar() {
|
|||
)}
|
||||
{!isMobile && (
|
||||
<SidebarFooter>
|
||||
<CallSidebarBox />
|
||||
<SidebarBox />
|
||||
</SidebarFooter>
|
||||
)}
|
||||
</>
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import Switch from "./switch";
|
|||
import ConversationModal from "../modal/conversation";
|
||||
import CommunityModal from "../modal/community";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { useSession } from "@tensamin/identity/session";
|
||||
import { useSession } from "@tensamin/storage/session";
|
||||
|
||||
export default function List() {
|
||||
const [category, setCategory] = useState<"conversations" | "communities">(
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { Basic, Loading } from "@/components/modals/basic";
|
||||
import Wrapper from "@tensamin/identity/wrapper";
|
||||
import Wrapper from "@tensamin/user/wrapper";
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
|
|
|
|||
|
|
@ -12,26 +12,40 @@ import "./index.css";
|
|||
import "@methanium/ui/index.css";
|
||||
|
||||
import NotFound from "@/routes/404";
|
||||
import RouteLoader from "@/components/routeLoader";
|
||||
import Home from "@/routes/app/home";
|
||||
import AppShell from "@/routes/app/shell";
|
||||
import Login from "@/routes/screens/login";
|
||||
|
||||
import AppLayout from "@/routes/app/layout";
|
||||
import { createSettingsRoute } from "@tensamin/settings";
|
||||
import OnboardingGate from "@tensamin/onboarding";
|
||||
|
||||
import Home from "@/routes/app/home";
|
||||
import ChatScreen from "@tensamin/chat/screen";
|
||||
import CallScreen from "@tensamin/call/screen";
|
||||
import Login from "@/routes/screens/login";
|
||||
|
||||
import DeeplinkContext from "@tensamin/tauri/deeplinkHandler";
|
||||
import ChatContext from "@tensamin/chat/context";
|
||||
import { useCall, useInitializeCall } from "@tensamin/call/store";
|
||||
import { useIsSpeaking } from "@tensamin/call/speakingState";
|
||||
import { Provider as MTPProvider } from "@tensamin/mtp";
|
||||
import UserProvider from "@tensamin/user/context";
|
||||
import DeeplinkContext, { useDeeplinks } from "@tensamin/tauri/deeplinkHandler";
|
||||
import NotificationsProvider from "@tensamin/notifications/context";
|
||||
import PwaRuntime from "@tensamin/pwa/runtime";
|
||||
|
||||
import TAuthWrapper from "@tensamin/tauth/context";
|
||||
|
||||
import { ErrorScreen, ThemeProvider, useTheme } from "@methanium/ui";
|
||||
import z from "zod";
|
||||
|
||||
import { useEffect, useRef, useState, type ReactNode } from "react";
|
||||
|
||||
import Storage from "@tensamin/storage/context";
|
||||
import Session from "@tensamin/storage/session";
|
||||
import Crypto from "@tensamin/crypto/context";
|
||||
import DesktopMediaProvider from "@tensamin/shared/desktopMedia";
|
||||
import { log } from "@tensamin/shared/log";
|
||||
|
||||
import CacheSync from "@tensamin/cache/sync";
|
||||
|
||||
import { useStorage } from "@tensamin/storage/context";
|
||||
import { useLocation, useNavigate } from "@tanstack/react-router";
|
||||
import { useIsMobile, Toaster, TooltipProvider } from "@methanium/ui";
|
||||
|
|
@ -94,7 +108,7 @@ function LoginWrapper({ children }: { children: ReactNode }) {
|
|||
}, [load, location.pathname, navigate, secureStorage]);
|
||||
|
||||
if (loggedIn !== true && location.pathname !== "/login") {
|
||||
return <RouteLoader />;
|
||||
return null;
|
||||
}
|
||||
|
||||
return children;
|
||||
|
|
@ -262,6 +276,155 @@ function RootShell() {
|
|||
);
|
||||
}
|
||||
|
||||
function AppShell() {
|
||||
return (
|
||||
<OnboardingGate>
|
||||
<Crypto>
|
||||
<DesktopMediaProvider>
|
||||
<MTPProvider>
|
||||
<CacheSync />
|
||||
<DeeplinkNavigator />
|
||||
<Session>
|
||||
<UserProvider>
|
||||
<CallInit />
|
||||
<TAuthWrapper>
|
||||
<AppLayout>
|
||||
<ChatContext>
|
||||
<NotificationsProvider>
|
||||
<Outlet />
|
||||
</NotificationsProvider>
|
||||
</ChatContext>
|
||||
</AppLayout>
|
||||
</TAuthWrapper>
|
||||
</UserProvider>
|
||||
</Session>
|
||||
</MTPProvider>
|
||||
</DesktopMediaProvider>
|
||||
</Crypto>
|
||||
</OnboardingGate>
|
||||
);
|
||||
}
|
||||
|
||||
function DeeplinkNavigator() {
|
||||
const { deeplinks } = useDeeplinks();
|
||||
const navigate = useNavigate();
|
||||
const handledCount = useRef(0);
|
||||
|
||||
useEffect(() => {
|
||||
const links = deeplinks.slice(handledCount.current);
|
||||
handledCount.current = deeplinks.length;
|
||||
|
||||
for (const link of links) {
|
||||
try {
|
||||
const url = new URL(link);
|
||||
const id = Number(url.searchParams.get("id"));
|
||||
if (
|
||||
url.protocol === "tensamin:" &&
|
||||
url.hostname === "chat" &&
|
||||
Number.isSafeInteger(id) &&
|
||||
id > 0
|
||||
) {
|
||||
void navigate({ to: "/chat", search: { id } });
|
||||
}
|
||||
} catch {
|
||||
// Ignore malformed URLs delivered by the platform.
|
||||
}
|
||||
}
|
||||
}, [deeplinks, navigate]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function createCallTrayIcon(color: string, speaking: boolean) {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = 32;
|
||||
canvas.height = 32;
|
||||
|
||||
const context = canvas.getContext("2d");
|
||||
if (!context) return undefined;
|
||||
|
||||
context.globalAlpha = speaking ? 1 : 0.55;
|
||||
context.fillStyle = color;
|
||||
context.beginPath();
|
||||
context.arc(16, 16, 13, 0, Math.PI * 2);
|
||||
context.fill();
|
||||
|
||||
if (speaking) {
|
||||
context.globalAlpha = 0.3;
|
||||
context.fillStyle = "#ffffff";
|
||||
context.fill();
|
||||
}
|
||||
|
||||
return canvas.toDataURL("image/png");
|
||||
}
|
||||
|
||||
function CallInit() {
|
||||
const callInvitePopup = useInitializeCall();
|
||||
|
||||
const { load } = useStorage();
|
||||
const {
|
||||
themeColor,
|
||||
themePalette,
|
||||
themePrimaryColor,
|
||||
themePolarity,
|
||||
themeTint,
|
||||
themeCustomCss,
|
||||
} = useTheme();
|
||||
const [localUserId, setLocalUserId] = useState(-1);
|
||||
const [primaryColor, setPrimaryColor] = useState("");
|
||||
const inCall = useCall((state) => state.state === "open");
|
||||
const speaking = useIsSpeaking(localUserId);
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
|
||||
load("user_id").then((userId) => {
|
||||
if (active) setLocalUserId(userId);
|
||||
});
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [load]);
|
||||
|
||||
useEffect(() => {
|
||||
const frame = requestAnimationFrame(() => {
|
||||
setPrimaryColor(
|
||||
getComputedStyle(document.documentElement)
|
||||
.getPropertyValue("--primary")
|
||||
.trim(),
|
||||
);
|
||||
});
|
||||
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [
|
||||
themeColor,
|
||||
themeCustomCss,
|
||||
themePalette,
|
||||
themePolarity,
|
||||
themePrimaryColor,
|
||||
themeTint,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
const iconDataUrl = primaryColor
|
||||
? createCallTrayIcon(primaryColor, speaking)
|
||||
: undefined;
|
||||
|
||||
void window.tensaminDesktop?.call
|
||||
?.setStatus?.({
|
||||
inCall,
|
||||
speaking: inCall && speaking,
|
||||
iconDataUrl: inCall ? iconDataUrl : undefined,
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
console.error("Failed to update desktop call status", error);
|
||||
});
|
||||
}, [inCall, primaryColor, speaking]);
|
||||
|
||||
return callInvitePopup;
|
||||
}
|
||||
|
||||
const rootRoute = createRootRoute({
|
||||
component: RootShell,
|
||||
errorComponent: ({ error }: { error: Error }) => (
|
||||
|
|
|
|||
|
|
@ -11,16 +11,13 @@ import {
|
|||
useIsMobile,
|
||||
} from "@methanium/ui";
|
||||
import z from "zod";
|
||||
import { MTPProtocolError } from "mtp";
|
||||
import { RelayRejectedError, requireRelaySuccess, useMTP } from "@tensamin/mtp";
|
||||
import { log } from "@tensamin/shared/log";
|
||||
import { useMTP } from "@tensamin/mtp";
|
||||
import { useState } from "react";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import { isTauri } from "@tauri-apps/api/core";
|
||||
import { useSession } from "@tensamin/identity/session";
|
||||
import { useSession } from "@tensamin/storage/session";
|
||||
import { useStorage } from "@tensamin/storage/context";
|
||||
import { ShieldAlert } from "lucide-react";
|
||||
import { useUser } from "@tensamin/identity/context";
|
||||
|
||||
// The page
|
||||
export default function Page() {
|
||||
|
|
@ -54,10 +51,8 @@ export default function Page() {
|
|||
|
||||
// Add Conversation Button Component
|
||||
function AddConversationButton() {
|
||||
const { send, sendSealedRelay } = useMTP();
|
||||
const { send } = useMTP();
|
||||
const { contacts, insertContact } = useSession();
|
||||
const { load } = useStorage();
|
||||
const { getIota } = useUser();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
|
@ -69,7 +64,7 @@ function AddConversationButton() {
|
|||
// username check
|
||||
const schema = z
|
||||
.string()
|
||||
.regex(/^[a-z0-9]+$/, "Username must use lowercase letters and numbers")
|
||||
.min(1, "Username is too short")
|
||||
.max(15, "Username is too long");
|
||||
|
||||
const result = schema.safeParse(username?.toLowerCase().trim());
|
||||
|
|
@ -79,27 +74,22 @@ function AddConversationButton() {
|
|||
return;
|
||||
}
|
||||
|
||||
let user;
|
||||
try {
|
||||
user = await send("GetUserData", { Username: result.data });
|
||||
} catch (error) {
|
||||
if (error instanceof MTPProtocolError && error.type === "ErrorNotFound") {
|
||||
setError("User not found");
|
||||
} else if (error instanceof MTPProtocolError) {
|
||||
setError(`User lookup failed: ${error.type}`);
|
||||
} else {
|
||||
setError("User lookup failed: connection error");
|
||||
// user existence check
|
||||
const user = await send("GetUserData", {
|
||||
Username: result.data,
|
||||
})
|
||||
.then((data) => {
|
||||
if (data.type === "ErrorNotFound" || data.data.UserId === 0) {
|
||||
throw new Error();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (user.type === "ErrorNotFound") {
|
||||
|
||||
return data;
|
||||
})
|
||||
.catch(() => {
|
||||
setError("User not found");
|
||||
return;
|
||||
}
|
||||
if (user.type !== "GetUserData") {
|
||||
setError(`User lookup failed: ${user.type}`);
|
||||
return;
|
||||
}
|
||||
});
|
||||
if (!user) return;
|
||||
|
||||
// alrady added check
|
||||
if (contacts.some((contact) => contact.UserId === user.data.UserId)) {
|
||||
|
|
@ -110,36 +100,25 @@ function AddConversationButton() {
|
|||
// add the conv
|
||||
const timeout = setTimeout(() => setLoading(true), 500);
|
||||
|
||||
try {
|
||||
const userId = await load("user_id");
|
||||
const iota = await getIota(userId);
|
||||
const response = await sendSealedRelay(
|
||||
"AddConversation",
|
||||
{ ChatPartnerId: user.data.UserId },
|
||||
{
|
||||
nextHop: { kind: "iota", id: iota.IotaId },
|
||||
finalRecipientId: userId,
|
||||
metadataRecipients: [{ value: iota.PublicKey, encoding: "base64" }],
|
||||
contentRecipients: [{ value: iota.PublicKey, encoding: "base64" }],
|
||||
},
|
||||
);
|
||||
requireRelaySuccess(response);
|
||||
send("AddConversation", {
|
||||
ChatPartnerId: user.data.UserId,
|
||||
})
|
||||
.then(() => {
|
||||
insertContact(user.data.UserId);
|
||||
setOpen(false);
|
||||
} catch (error) {
|
||||
if (error instanceof RelayRejectedError) {
|
||||
setError(
|
||||
`Could not route the request to your Iota: ${error.responseType}`,
|
||||
);
|
||||
} else {
|
||||
log(1, "mtp", "red", "Add conversation failed", error);
|
||||
const detail = error instanceof Error ? error.message : "unknown error";
|
||||
setError(`Add conversation failed: ${detail}`);
|
||||
})
|
||||
.catch((error) => {
|
||||
if (String(error).includes("error_not_found")) {
|
||||
setError("User not found");
|
||||
return;
|
||||
}
|
||||
} finally {
|
||||
|
||||
setError(String(error));
|
||||
})
|
||||
.finally(() => {
|
||||
clearTimeout(timeout);
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -2,8 +2,8 @@ import { type ReactNode } from "react";
|
|||
|
||||
import Sidebar from "@/components/sidebar";
|
||||
import Navbar, { MobileNavbar } from "@/components/navbar";
|
||||
import CallPopout from "@/components/callPopout";
|
||||
import { useShowMobileNavbar } from "./useShowMobileNavbar";
|
||||
import CallPopout from "@tensamin/call/popout";
|
||||
|
||||
import { useIsMobile, cn, SidebarProvider } from "@methanium/ui";
|
||||
|
||||
|
|
|
|||
|
|
@ -1,75 +0,0 @@
|
|||
import { useEffect, useRef } from "react";
|
||||
import { Outlet, useNavigate } from "@tanstack/react-router";
|
||||
|
||||
import AppLayout from "./layout";
|
||||
import CallInit from "@/components/callRuntimeInit";
|
||||
import CacheSync from "@tensamin/cache/sync";
|
||||
import ChatContext from "@tensamin/chat/context";
|
||||
import Crypto from "@tensamin/crypto/context";
|
||||
import UserProvider from "@tensamin/identity/context";
|
||||
import { Provider as MTPProvider } from "@tensamin/mtp";
|
||||
import NotificationsProvider from "@tensamin/notifications/context";
|
||||
import OnboardingGate from "@tensamin/onboarding";
|
||||
import DesktopMediaProvider from "@tensamin/shared/desktopMedia";
|
||||
import Session from "@tensamin/identity/session";
|
||||
import { useDeeplinks } from "@tensamin/tauri/deeplinkHandler";
|
||||
import TAuthWrapper from "@tensamin/tauth/context";
|
||||
|
||||
function DeeplinkNavigator() {
|
||||
const { deeplinks } = useDeeplinks();
|
||||
const navigate = useNavigate();
|
||||
const handledCount = useRef(0);
|
||||
|
||||
useEffect(() => {
|
||||
const links = deeplinks.slice(handledCount.current);
|
||||
handledCount.current = deeplinks.length;
|
||||
|
||||
for (const link of links) {
|
||||
try {
|
||||
const url = new URL(link);
|
||||
const id = Number(url.searchParams.get("id"));
|
||||
if (
|
||||
url.protocol === "tensamin:" &&
|
||||
url.hostname === "chat" &&
|
||||
Number.isSafeInteger(id) &&
|
||||
id > 0
|
||||
) {
|
||||
void navigate({ to: "/chat", search: { id } });
|
||||
}
|
||||
} catch {
|
||||
// Ignore malformed URLs delivered by the platform.
|
||||
}
|
||||
}
|
||||
}, [deeplinks, navigate]);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export default function AppShell() {
|
||||
return (
|
||||
<OnboardingGate>
|
||||
<Crypto>
|
||||
<DesktopMediaProvider>
|
||||
<MTPProvider>
|
||||
<CacheSync />
|
||||
<DeeplinkNavigator />
|
||||
<Session>
|
||||
<UserProvider>
|
||||
<CallInit />
|
||||
<TAuthWrapper>
|
||||
<AppLayout>
|
||||
<ChatContext>
|
||||
<NotificationsProvider>
|
||||
<Outlet />
|
||||
</NotificationsProvider>
|
||||
</ChatContext>
|
||||
</AppLayout>
|
||||
</TAuthWrapper>
|
||||
</UserProvider>
|
||||
</Session>
|
||||
</MTPProvider>
|
||||
</DesktopMediaProvider>
|
||||
</Crypto>
|
||||
</OnboardingGate>
|
||||
);
|
||||
}
|
||||
|
|
@ -65,7 +65,7 @@ export default defineConfig({
|
|||
"@tensamin/settings",
|
||||
"@tensamin/storage",
|
||||
"@tensamin/mtp",
|
||||
"@tensamin/identity",
|
||||
"@tensamin/user",
|
||||
"@tensamin/tauri",
|
||||
"@tensamin/chat",
|
||||
],
|
||||
|
|
@ -118,50 +118,18 @@ export default defineConfig({
|
|||
"@tensamin/storage/context",
|
||||
"@tensamin/tauri",
|
||||
"@tensamin/tauth",
|
||||
"@tensamin/identity",
|
||||
"@tensamin/user",
|
||||
],
|
||||
},
|
||||
build: {
|
||||
minify: !process.env.TAURI_ENV_DEBUG ? "esbuild" : false,
|
||||
sourcemap: !!process.env.TAURI_ENV_DEBUG,
|
||||
chunkSizeWarningLimit: 550,
|
||||
rolldownOptions: {
|
||||
output: {
|
||||
codeSplitting: {
|
||||
groups: [
|
||||
{
|
||||
name: "codemirror-core",
|
||||
test: /node_modules\/.pnpm\/@codemirror\+(?:state|view|language)@/,
|
||||
priority: 20,
|
||||
},
|
||||
{
|
||||
name: "codemirror-editor",
|
||||
test: /node_modules\/.pnpm\/@codemirror\+(?:autocomplete|commands|lang-markdown)@|node_modules\/.pnpm\/codemirror@/,
|
||||
priority: 20,
|
||||
},
|
||||
{
|
||||
name: "livekit-client",
|
||||
test: /node_modules\/.pnpm\/livekit-client@/,
|
||||
priority: 20,
|
||||
},
|
||||
{
|
||||
name: "livekit-support",
|
||||
test: /node_modules\/.pnpm\/@livekit\+/,
|
||||
priority: 20,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [
|
||||
...tensaminPwa(),
|
||||
methaniumUi({ defaultThemeId: "tensamin" }),
|
||||
deepFilterAssetHeaders(resolve(appDir, "public")),
|
||||
mtp({
|
||||
typeMaps: resolve(appDir, "../../mtp-type-maps/type-maps.yaml"),
|
||||
outDir: ".mtp",
|
||||
}),
|
||||
mtp({ typeMaps: resolve(appDir, "../../mtp-type-maps/type-maps.yaml") }),
|
||||
{
|
||||
name: "workspace-realpath-resolution",
|
||||
enforce: "post",
|
||||
|
|
|
|||
|
|
@ -372,7 +372,6 @@
|
|||
git
|
||||
jq
|
||||
curl
|
||||
libsoup_3
|
||||
]
|
||||
++ [
|
||||
android.androidsdk
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@
|
|||
},
|
||||
"dependencies": {
|
||||
"@methanium/ui": "https://git.methanium.net/methanium/ui/releases/download/0.0.29/methanium-ui.tgz",
|
||||
"mtp": "https://git.methanium.net/methanium/mtp/releases/download/0.3.0-dev-c7c7afe/mtp-0.3.0.tgz",
|
||||
"mtp": "https://git.methanium.net/methanium/mtp/releases/download/0.3.0-b331b9f6a3/mtp-0.3.0.tgz",
|
||||
"sonner": "^2.0.8"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,7 +5,6 @@
|
|||
"type": "module",
|
||||
"exports": {
|
||||
"./store": "./src/store.tsx",
|
||||
"./state": "./src/state.ts",
|
||||
"./speakingState": "./src/speakingState.ts",
|
||||
"./screen": "./src/screen.tsx",
|
||||
"./utils": "./src/utils.ts",
|
||||
|
|
@ -25,7 +24,7 @@
|
|||
"@tensamin/mtp": "workspace:*",
|
||||
"@tensamin/shared": "workspace:*",
|
||||
"@tensamin/storage": "workspace:*",
|
||||
"@tensamin/identity": "workspace:*",
|
||||
"@tensamin/user": "workspace:*",
|
||||
"deepfilternet3-noise-filter": "1.3.0",
|
||||
"livekit-client": "^2.21.0",
|
||||
"lucide-react": "^1.29.0",
|
||||
|
|
|
|||
|
|
@ -8,11 +8,11 @@ import {
|
|||
TooltipContent,
|
||||
TooltipTrigger,
|
||||
} from "@methanium/ui";
|
||||
import Wrapper from "@tensamin/identity/wrapper";
|
||||
import Wrapper from "@tensamin/user/wrapper";
|
||||
import { Mail } from "lucide-react";
|
||||
import { sendCallInvite, useCall } from "../../store";
|
||||
import { log, toast } from "@tensamin/shared/log";
|
||||
import { useSession } from "@tensamin/identity/session";
|
||||
import { useSession } from "@tensamin/storage/session";
|
||||
|
||||
export default function InviteButton({
|
||||
className,
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import {
|
|||
Dialog,
|
||||
DialogContent,
|
||||
} from "@methanium/ui";
|
||||
import Wrapper from "@tensamin/identity/wrapper";
|
||||
import Wrapper from "@tensamin/user/wrapper";
|
||||
import { PhoneIncoming, X } from "lucide-react";
|
||||
|
||||
export default function InvitePopup({
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ import {
|
|||
} from "../../store";
|
||||
import { Track, type Participant } from "livekit-client";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { type SelectedUser, useUserFields } from "@tensamin/identity/context";
|
||||
import { type SelectedUser, useUserFields } from "@tensamin/user/context";
|
||||
import { useIsSpeaking } from "../../speakingState";
|
||||
import VideoViewer from "../videoViewer";
|
||||
import { HeadphoneOff, MicOff, Monitor, Plus, Shield } from "lucide-react";
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ import {
|
|||
useSidebar,
|
||||
} from "@methanium/ui";
|
||||
import { ScreenShareOff } from "lucide-react";
|
||||
import { useUserFields } from "@tensamin/identity/context";
|
||||
import { useUserFields } from "@tensamin/user/context";
|
||||
import { useIsSpeaking, useLastSpeakingParticipantId } from "../speakingState";
|
||||
import { getAverageImageColor } from "./modals/base";
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { useUserFields } from "@tensamin/identity/context";
|
||||
import { useUserFields } from "@tensamin/user/context";
|
||||
import { useCall, getRoom } from "../store";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useStorage } from "@tensamin/storage/context";
|
||||
|
|
|
|||
|
|
@ -1,93 +0,0 @@
|
|||
import type { RefObject } from "react";
|
||||
import { create } from "zustand";
|
||||
|
||||
import type { LocalMediaShareSession } from "./mediaShare/controller";
|
||||
|
||||
export type CallView = "preview" | "focused" | "grid";
|
||||
|
||||
export type WrappedCallSecret = {
|
||||
secretId: string;
|
||||
versionNumber: number;
|
||||
encryptedSecret: Uint8Array;
|
||||
kemCiphertext: Uint8Array;
|
||||
wrappingScheme: string;
|
||||
};
|
||||
|
||||
export type CallRuntime = {
|
||||
navigate: (options: {
|
||||
to: string;
|
||||
search?: Record<string, unknown>;
|
||||
}) => Promise<void>;
|
||||
send: (
|
||||
type: string,
|
||||
data: Record<string, unknown>,
|
||||
) => Promise<{ data: unknown }>;
|
||||
load: (key: string) => Promise<unknown>;
|
||||
getPublicKey: (userId: number) => Promise<string>;
|
||||
};
|
||||
|
||||
export const useCall = create<{
|
||||
state: "closed" | "closing" | "connecting" | "open" | "encrypting";
|
||||
view: CallView;
|
||||
invitedUserId: number | null;
|
||||
callId: string | null;
|
||||
incomingCallInvite: {
|
||||
callId: string;
|
||||
callSecret: WrappedCallSecret;
|
||||
senderId: number;
|
||||
} | null;
|
||||
callSecret: string | null;
|
||||
livekitToken: string | null;
|
||||
currentCallData: { UserIds: number[]; exists: boolean } | null;
|
||||
deaf: boolean;
|
||||
micEnabled: boolean;
|
||||
cameraEnabled: boolean;
|
||||
screenShareEnabled: boolean;
|
||||
screenShareSession: LocalMediaShareSession | null;
|
||||
cameraSession: LocalMediaShareSession | null;
|
||||
disabledCameraParticipantIds: number[];
|
||||
focusedParticipantId: number | null;
|
||||
focusedParticipantType: "user" | "stream" | null;
|
||||
usersInFocusedViewHidden: boolean;
|
||||
watchedStreamParticipantIds: number[];
|
||||
pendingWatchedParticipantIds: number[];
|
||||
activeScreenShareParticipantIds: number[];
|
||||
isEncrypted: boolean;
|
||||
ownCallSecretInvitePending: boolean;
|
||||
callIsFullscreen: boolean;
|
||||
callIsPopout: boolean;
|
||||
layoutVersion: number;
|
||||
screenRef: RefObject<HTMLDivElement | null> | null;
|
||||
runtime: CallRuntime | null;
|
||||
lastFocusedParticipantId: number | null;
|
||||
}>(() => ({
|
||||
state: "closed",
|
||||
view: "preview",
|
||||
invitedUserId: null,
|
||||
callId: null,
|
||||
incomingCallInvite: null,
|
||||
callSecret: null,
|
||||
livekitToken: null,
|
||||
currentCallData: null,
|
||||
deaf: false,
|
||||
micEnabled: false,
|
||||
cameraEnabled: false,
|
||||
screenShareEnabled: false,
|
||||
screenShareSession: null,
|
||||
cameraSession: null,
|
||||
disabledCameraParticipantIds: [],
|
||||
focusedParticipantId: null,
|
||||
focusedParticipantType: null,
|
||||
usersInFocusedViewHidden: false,
|
||||
watchedStreamParticipantIds: [],
|
||||
pendingWatchedParticipantIds: [],
|
||||
activeScreenShareParticipantIds: [],
|
||||
isEncrypted: false,
|
||||
ownCallSecretInvitePending: false,
|
||||
callIsFullscreen: false,
|
||||
callIsPopout: false,
|
||||
layoutVersion: 0,
|
||||
screenRef: null,
|
||||
runtime: null,
|
||||
lastFocusedParticipantId: null,
|
||||
}));
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
import { useCallback, useEffect, useMemo, useRef } from "react";
|
||||
import { create } from "zustand";
|
||||
import { useLocation, useNavigate } from "@tanstack/react-router";
|
||||
import { useMTP } from "@tensamin/mtp";
|
||||
import { log, toast } from "@tensamin/shared/log";
|
||||
|
|
@ -12,8 +13,8 @@ import {
|
|||
wrapCallSecret,
|
||||
} from "@tensamin/crypto/callSecret";
|
||||
import { useStorage } from "@tensamin/storage/context";
|
||||
import { useSession } from "@tensamin/identity/session";
|
||||
import { useUser } from "@tensamin/identity/context";
|
||||
import { useSession } from "@tensamin/storage/session";
|
||||
import { useUser } from "@tensamin/user/context";
|
||||
import { DeepFilterNoiseFilterProcessor } from "deepfilternet3-noise-filter";
|
||||
import {
|
||||
ExternalE2EEKeyProvider,
|
||||
|
|
@ -32,6 +33,7 @@ import {
|
|||
import z from "zod";
|
||||
import {
|
||||
createMediaShareController,
|
||||
type LocalMediaShareSession,
|
||||
} from "./mediaShare/controller";
|
||||
import type { MediaShareRequest } from "./mediaShare";
|
||||
import {
|
||||
|
|
@ -39,14 +41,6 @@ import {
|
|||
disposeSpeakingDetector,
|
||||
} from "./speakingIndicator";
|
||||
import InvitePopup from "./components/invitePopup";
|
||||
import {
|
||||
useCall,
|
||||
type CallRuntime as Runtime,
|
||||
type CallView,
|
||||
type WrappedCallSecret,
|
||||
} from "./state";
|
||||
|
||||
export { useCall } from "./state";
|
||||
|
||||
// logging
|
||||
setLogExtension(
|
||||
|
|
@ -57,9 +51,19 @@ setLogExtension(
|
|||
getLogger("tensamin"),
|
||||
);
|
||||
|
||||
type CallView = "preview" | "focused" | "grid";
|
||||
type ProtocolCallSecret = NonNullable<
|
||||
z.infer<typeof mtp.CallInvite.response>["CallSecret"]
|
||||
>;
|
||||
type WrappedCallSecret = {
|
||||
secretId: string;
|
||||
versionNumber: number;
|
||||
encryptedSecret: Uint8Array;
|
||||
kemCiphertext: Uint8Array;
|
||||
wrappingScheme: string;
|
||||
};
|
||||
type CurrentCallData =
|
||||
(z.infer<typeof mtp.CallData.response> & { exists: boolean }) | null;
|
||||
|
||||
type SendFn = (
|
||||
type: string,
|
||||
|
|
@ -68,6 +72,16 @@ type SendFn = (
|
|||
type LoadFn = (key: string) => Promise<unknown>;
|
||||
type RemoteVideoTrackSelector = Track.Kind | Track.Source;
|
||||
|
||||
type Runtime = {
|
||||
navigate: (options: {
|
||||
to: string;
|
||||
search?: Record<string, unknown>;
|
||||
}) => Promise<void>;
|
||||
send: SendFn;
|
||||
load: LoadFn;
|
||||
getPublicKey: (userId: number) => Promise<string>;
|
||||
};
|
||||
|
||||
let _keyProvider: ExternalE2EEKeyProvider | null = null;
|
||||
let _e2eeWorker: Worker | null = null;
|
||||
let _room: Room | null = null;
|
||||
|
|
@ -618,7 +632,7 @@ export function setCallId(callId: string | null) {
|
|||
|
||||
// Cache server call metadata used by the preview screen.
|
||||
export function setCurrentCallData(
|
||||
currentCallData: { UserIds: number[]; exists: boolean },
|
||||
currentCallData: CurrentCallData & { exists: boolean },
|
||||
) {
|
||||
useCall.setState({ currentCallData });
|
||||
}
|
||||
|
|
@ -1139,6 +1153,72 @@ async function ensureNoiseFilter(
|
|||
}
|
||||
}
|
||||
|
||||
export const useCall = create<{
|
||||
state: "closed" | "closing" | "connecting" | "open" | "encrypting";
|
||||
view: CallView;
|
||||
invitedUserId: number | null;
|
||||
callId: string | null;
|
||||
incomingCallInvite: {
|
||||
callId: string;
|
||||
callSecret: WrappedCallSecret;
|
||||
senderId: number;
|
||||
} | null;
|
||||
callSecret: string | null;
|
||||
livekitToken: string | null;
|
||||
currentCallData: CurrentCallData;
|
||||
deaf: boolean;
|
||||
micEnabled: boolean;
|
||||
cameraEnabled: boolean;
|
||||
screenShareEnabled: boolean;
|
||||
screenShareSession: LocalMediaShareSession | null;
|
||||
cameraSession: LocalMediaShareSession | null;
|
||||
disabledCameraParticipantIds: number[];
|
||||
focusedParticipantId: number | null;
|
||||
focusedParticipantType: "user" | "stream" | null;
|
||||
usersInFocusedViewHidden: boolean;
|
||||
watchedStreamParticipantIds: number[];
|
||||
pendingWatchedParticipantIds: number[];
|
||||
activeScreenShareParticipantIds: number[];
|
||||
isEncrypted: boolean;
|
||||
ownCallSecretInvitePending: boolean;
|
||||
callIsFullscreen: boolean;
|
||||
callIsPopout: boolean;
|
||||
layoutVersion: number;
|
||||
screenRef: React.RefObject<HTMLDivElement | null> | null;
|
||||
runtime: Runtime | null;
|
||||
lastFocusedParticipantId: number | null;
|
||||
}>(() => ({
|
||||
state: "closed",
|
||||
view: "preview",
|
||||
invitedUserId: null,
|
||||
callId: null,
|
||||
incomingCallInvite: null,
|
||||
callSecret: null,
|
||||
livekitToken: null,
|
||||
currentCallData: null,
|
||||
deaf: false,
|
||||
micEnabled: false,
|
||||
cameraEnabled: false,
|
||||
screenShareEnabled: false,
|
||||
screenShareSession: null,
|
||||
cameraSession: null,
|
||||
disabledCameraParticipantIds: [],
|
||||
focusedParticipantId: null,
|
||||
focusedParticipantType: null,
|
||||
usersInFocusedViewHidden: false,
|
||||
watchedStreamParticipantIds: [],
|
||||
pendingWatchedParticipantIds: [],
|
||||
activeScreenShareParticipantIds: [],
|
||||
isEncrypted: false,
|
||||
ownCallSecretInvitePending: false,
|
||||
callIsFullscreen: false,
|
||||
callIsPopout: false,
|
||||
layoutVersion: 0,
|
||||
screenRef: null,
|
||||
runtime: null,
|
||||
lastFocusedParticipantId: null,
|
||||
}));
|
||||
|
||||
// Register app-level call listeners and wire React dependencies into the store.
|
||||
export function useInitializeCall() {
|
||||
const navigate = useNavigate();
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { useCall } from "../store";
|
||||
import { useUserFields } from "@tensamin/identity/context";
|
||||
import { useUserFields } from "@tensamin/user/context";
|
||||
|
||||
const USER_FIELDS = ["Display"] as const;
|
||||
|
||||
|
|
|
|||
|
|
@ -24,11 +24,10 @@
|
|||
"@tensamin/cache": "workspace:*",
|
||||
"@tensamin/crypto": "workspace:*",
|
||||
"@tensamin/hotkeys": "workspace:*",
|
||||
"@tensamin/markdown": "workspace:*",
|
||||
"@tensamin/mtp": "workspace:*",
|
||||
"@tensamin/shared": "workspace:*",
|
||||
"@tensamin/storage": "workspace:*",
|
||||
"@tensamin/identity": "workspace:*",
|
||||
"@tensamin/user": "workspace:*",
|
||||
"lucide-react": "^1.29.0",
|
||||
"motion": "^13.0.0",
|
||||
"react": "^19.2.8",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { Button } from "@methanium/ui";
|
||||
import Emoji from "@tensamin/markdown/emoji";
|
||||
import { Emoji } from "@methanium/ui/markdown";
|
||||
import { getRecentEmojis, useEmojiRanks } from "./emojiRanks";
|
||||
|
||||
export default function EmojiPicker({
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { useStorage } from "@tensamin/storage/context";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { normalizeShortcode } from "@tensamin/markdown/emoji";
|
||||
import { normalizeShortcode } from "@methanium/ui/markdown";
|
||||
|
||||
const RANKS_CHANGED_EVENT = "tensamin-reaction-ranks-changed";
|
||||
let recordQueue = Promise.resolve();
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import Input, { type InputController } from "@tensamin/markdown/input";
|
||||
import { Input, type InputController } from "@methanium/ui/markdown";
|
||||
import {
|
||||
Card,
|
||||
CardHeader,
|
||||
|
|
@ -15,19 +15,18 @@ import { Button } from "@methanium/ui";
|
|||
|
||||
import { Plus, Laugh, FileVideo, SendHorizonal } from "lucide-react";
|
||||
import { useChat, useReplyMessage } from "../context";
|
||||
import { requireRelaySuccess, useMTP } from "@tensamin/mtp";
|
||||
import { useMTP } from "@tensamin/mtp";
|
||||
import { log, toast } from "@tensamin/shared/log";
|
||||
import { cn, useIsMobile } from "@methanium/ui";
|
||||
import { encryptChatText } from "@tensamin/crypto/chatSecret";
|
||||
|
||||
import { useSession } from "@tensamin/identity/session";
|
||||
import { useSession } from "@tensamin/storage/session";
|
||||
import EmojiPicker from "./emoji/emojiPicker";
|
||||
import { useEmojiRanks, useRecordEmojiUse } from "./emoji/emojiRanks";
|
||||
import GifPicker from "./media/gifPicker";
|
||||
import ReplyBox from "./replyBox";
|
||||
import { useHotkey } from "@tensamin/hotkeys";
|
||||
import { editLastMessageHotkey } from "../hotkeys";
|
||||
import { useUser } from "@tensamin/identity/context";
|
||||
import EmojiPicker from "./emoji/emojiPicker";
|
||||
import GifPicker from "./media/gifPicker";
|
||||
|
||||
export default function InputComponent({
|
||||
value,
|
||||
|
|
@ -40,8 +39,7 @@ export default function InputComponent({
|
|||
}) {
|
||||
const [invertEnterBehavior, setInvertEnterBehavior] = useState(false);
|
||||
|
||||
const { sendSealedRelay } = useMTP();
|
||||
const { getIota } = useUser();
|
||||
const { send } = useMTP();
|
||||
const {
|
||||
addLiveMessage,
|
||||
chatSecret,
|
||||
|
|
@ -176,43 +174,19 @@ export default function InputComponent({
|
|||
|
||||
log(3, "chat", "purple", "Content encrypted, sending message...");
|
||||
|
||||
try {
|
||||
const [ownIota, peerIota] = await Promise.all([
|
||||
getIota(ownId),
|
||||
getIota(userId),
|
||||
]);
|
||||
const response = await sendSealedRelay(
|
||||
"MessageSend",
|
||||
{
|
||||
send("MessageSend", {
|
||||
Content: encryptedContent,
|
||||
ReceiverId: userId,
|
||||
SendTime: time,
|
||||
...(replyTo && { ReplyId: replyTo }),
|
||||
},
|
||||
{
|
||||
nextHop: { kind: "iota", id: ownIota.IotaId },
|
||||
finalRecipientId: userId,
|
||||
metadataRecipients: [
|
||||
{ value: ownIota.PublicKey, encoding: "base64" },
|
||||
{ value: peerIota.PublicKey, encoding: "base64" },
|
||||
],
|
||||
contentRecipients: [
|
||||
{ value: ownIota.PublicKey, encoding: "base64" },
|
||||
{ value: peerIota.PublicKey, encoding: "base64" },
|
||||
],
|
||||
},
|
||||
);
|
||||
requireRelaySuccess(response);
|
||||
reference.setMessageState("sent");
|
||||
} catch (e) {
|
||||
}).catch((e) => {
|
||||
log(0, "Chat", "red", "Failed to send message", e, {
|
||||
ReceiverId: userId,
|
||||
SendTime: time,
|
||||
});
|
||||
reference.setFailed(true);
|
||||
toast("error", "Failed to send message");
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
if (replyTo) {
|
||||
setReplyTo(undefined);
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import Text from "@tensamin/markdown/text";
|
||||
import { Text } from "@methanium/ui/markdown";
|
||||
import { useStorage } from "@tensamin/storage/context";
|
||||
import {
|
||||
Avatar,
|
||||
|
|
@ -24,7 +24,7 @@ import {
|
|||
} from "lucide-react";
|
||||
import { useState, useMemo, useEffect, useRef, type WheelEvent } from "react";
|
||||
import MediaSaveButton from "./mediaSaveButton";
|
||||
import { useUserFields } from "@tensamin/identity/context";
|
||||
import { useUserFields } from "@tensamin/user/context";
|
||||
|
||||
const zoomLevels = [1, 1.5, 2, 3];
|
||||
|
||||
|
|
|
|||
|
|
@ -1,11 +1,7 @@
|
|||
import type { RawMessage } from "../values";
|
||||
import { AlertTriangle, Check, CheckLine, RefreshCw } from "lucide-react";
|
||||
import { memo, useCallback, useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
type SelectedUser,
|
||||
useUser,
|
||||
useUserFields,
|
||||
} from "@tensamin/identity/context";
|
||||
import { type SelectedUser, useUserFields } from "@tensamin/user/context";
|
||||
|
||||
import {
|
||||
Avatar,
|
||||
|
|
@ -19,13 +15,11 @@ import {
|
|||
import MessageContextMenu from "./messageContextMenu";
|
||||
import Media from "./media/media";
|
||||
import { useStorage } from "@tensamin/storage/context";
|
||||
import { requireRelaySuccess, useMTP } from "@tensamin/mtp";
|
||||
import { useMTP } from "@tensamin/mtp";
|
||||
import { getMessage, useChat } from "../context";
|
||||
import { decryptChatText, encryptChatText } from "@tensamin/crypto/chatSecret";
|
||||
import { log, toast } from "@tensamin/shared/log";
|
||||
import Emoji, { normalizeShortcode } from "@tensamin/markdown/emoji";
|
||||
import Input from "@tensamin/markdown/input";
|
||||
import Text from "@tensamin/markdown/text";
|
||||
import { Emoji, Input, normalizeShortcode, Text } from "@methanium/ui/markdown";
|
||||
import { useRecordEmojiUse } from "./emoji/emojiRanks";
|
||||
import ReplyBox from "./replyBox";
|
||||
import { useHotkey } from "@tensamin/hotkeys";
|
||||
|
|
@ -48,7 +42,6 @@ function MessageComponent({
|
|||
user: SelectedUser<readonly ["UserId", "Avatar", "Display"]> | null;
|
||||
}) {
|
||||
const actuallyFailed =
|
||||
Boolean(message.ErrorType) ||
|
||||
(message.failed && message.MessageState === "awaiting") ||
|
||||
message.decryptionFailed;
|
||||
|
||||
|
|
@ -72,8 +65,7 @@ function MessageComponent({
|
|||
|
||||
// Message states
|
||||
const { load } = useStorage();
|
||||
const { send, sendSealedRelay } = useMTP();
|
||||
const { getIota } = useUser();
|
||||
const { send } = useMTP();
|
||||
const [ownId, setOwnId] = useState(0);
|
||||
useEffect(() => {
|
||||
load("user_id").then(setOwnId);
|
||||
|
|
@ -81,34 +73,22 @@ function MessageComponent({
|
|||
const messageStateReadUpdate = useCallback(async () => {
|
||||
const readConfirmations = await load("settings.read_confirmations");
|
||||
|
||||
if (!user?.UserId || ownId === 0) return;
|
||||
const [ownIota, peerIota] = await Promise.all([
|
||||
getIota(ownId),
|
||||
getIota(user.UserId),
|
||||
]);
|
||||
const response = await sendSealedRelay(
|
||||
"MessageState",
|
||||
{
|
||||
ChatPartnerId: user.UserId,
|
||||
EventAt: Date.now(),
|
||||
MessageState: readConfirmations ? "read" : "received",
|
||||
ReceiverId: user.UserId,
|
||||
},
|
||||
{
|
||||
nextHop: { kind: "iota", id: ownIota.IotaId },
|
||||
finalRecipientId: user.UserId,
|
||||
metadataRecipients: [
|
||||
{ value: ownIota.PublicKey, encoding: "base64" },
|
||||
{ value: peerIota.PublicKey, encoding: "base64" },
|
||||
],
|
||||
contentRecipients: [
|
||||
{ value: ownIota.PublicKey, encoding: "base64" },
|
||||
{ value: peerIota.PublicKey, encoding: "base64" },
|
||||
],
|
||||
},
|
||||
);
|
||||
requireRelaySuccess(response);
|
||||
}, [getIota, load, ownId, sendSealedRelay, user]);
|
||||
if (readConfirmations) {
|
||||
if (!user?.UserId) return;
|
||||
|
||||
await send("MessageState", {
|
||||
ChatPartnerId: user?.UserId,
|
||||
SendTime: message.SendTime,
|
||||
MessageState: "read",
|
||||
});
|
||||
} else {
|
||||
await send("MessageState", {
|
||||
ChatPartnerId: user?.UserId,
|
||||
SendTime: message.SendTime,
|
||||
MessageState: "received",
|
||||
});
|
||||
}
|
||||
}, [load, message.SendTime, user?.UserId, send]);
|
||||
useEffect(() => {
|
||||
if (message.SenderId === ownId || ownId === 0) return;
|
||||
|
||||
|
|
|
|||
|
|
@ -44,7 +44,7 @@ import type {
|
|||
Ref,
|
||||
} from "react";
|
||||
import { useChat } from "../context";
|
||||
import Emoji from "@tensamin/markdown/emoji";
|
||||
import { Emoji } from "@methanium/ui/markdown";
|
||||
import EmojiPicker from "./emoji/emojiPicker";
|
||||
import { getRecentEmojis, useEmojiRanks } from "./emoji/emojiRanks";
|
||||
|
||||
|
|
|
|||
|
|
@ -6,9 +6,9 @@ import {
|
|||
cn,
|
||||
Skeleton,
|
||||
} from "@methanium/ui";
|
||||
import Text from "@tensamin/markdown/text";
|
||||
import type { SelectedUser } from "@tensamin/identity/context";
|
||||
import Wrapper from "@tensamin/identity/wrapper";
|
||||
import { Text } from "@methanium/ui/markdown";
|
||||
import type { SelectedUser } from "@tensamin/user/context";
|
||||
import Wrapper from "@tensamin/user/wrapper";
|
||||
import { Forward, X } from "lucide-react";
|
||||
|
||||
type ReplyUserData = SelectedUser<readonly ["Avatar", "Display"]>;
|
||||
|
|
|
|||
|
|
@ -23,10 +23,10 @@ import {
|
|||
wrapChatSecret,
|
||||
} from "@tensamin/crypto/chatSecret";
|
||||
import { useStorage } from "@tensamin/storage/context";
|
||||
import { requireRelaySuccess, useMTP } from "@tensamin/mtp";
|
||||
import { useMTP } from "@tensamin/mtp";
|
||||
import { log, toast } from "@tensamin/shared/log";
|
||||
import { useSession } from "@tensamin/identity/session";
|
||||
import { useUser } from "@tensamin/identity/context";
|
||||
import { useSession } from "@tensamin/storage/session";
|
||||
import { useUser } from "@tensamin/user/context";
|
||||
import { createCache, type ChatDraft } from "@tensamin/cache";
|
||||
import { secureValueCodec } from "@tensamin/storage/secure";
|
||||
|
||||
|
|
@ -69,14 +69,6 @@ type MessageEdit = Partial<
|
|||
>
|
||||
>;
|
||||
|
||||
const messageStateRank: Record<RawMessage["MessageState"], number> = {
|
||||
awaiting: 0,
|
||||
sending: 0,
|
||||
sent: 1,
|
||||
received: 2,
|
||||
read: 3,
|
||||
};
|
||||
|
||||
function updateMessagesBySendTime<T extends EditableMessage>(
|
||||
messages: T[],
|
||||
sendTime: number,
|
||||
|
|
@ -89,13 +81,6 @@ function updateMessagesBySendTime<T extends EditableMessage>(
|
|||
return item;
|
||||
}
|
||||
|
||||
if (
|
||||
edit.MessageState !== undefined &&
|
||||
messageStateRank[edit.MessageState] < messageStateRank[item.MessageState]
|
||||
) {
|
||||
return item;
|
||||
}
|
||||
|
||||
const entries = Object.entries(edit) as Array<
|
||||
[keyof MessageEdit, MessageEdit[keyof MessageEdit]]
|
||||
>;
|
||||
|
|
@ -241,8 +226,8 @@ export async function fetchReplyMessage({
|
|||
|
||||
export default function Provider({ children }: { children: ReactNode }) {
|
||||
const { load } = useStorage();
|
||||
const { send, sendSealedRelay, subscribe } = useMTP();
|
||||
const { get: getUser, getIota } = useUser();
|
||||
const { send, subscribe } = useMTP();
|
||||
const { get: getUser } = useUser();
|
||||
const { moveUserIdToTop } = useSession();
|
||||
|
||||
const [error, setError] = useState("");
|
||||
|
|
@ -484,11 +469,9 @@ export default function Provider({ children }: { children: ReactNode }) {
|
|||
version: CHAT_SECRET_VERSION,
|
||||
});
|
||||
|
||||
const ownIota = await getIota(ownUserId);
|
||||
const peerIota = await getIota(userIdValue);
|
||||
const response = await sendSealedRelay(
|
||||
assertProtocolSuccess(
|
||||
"SetChatSecret",
|
||||
{
|
||||
await send("SetChatSecret", {
|
||||
ChatId: chatId,
|
||||
SecretId: secretId,
|
||||
VersionNumber: CHAT_SECRET_VERSION,
|
||||
|
|
@ -506,21 +489,8 @@ export default function Provider({ children }: { children: ReactNode }) {
|
|||
KemCiphertext: protocolBytes(peerWrapped.kemCiphertext),
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
nextHop: { kind: "iota", id: ownIota.IotaId },
|
||||
finalRecipientId: userIdValue,
|
||||
metadataRecipients: [
|
||||
{ value: ownIota.PublicKey, encoding: "base64" },
|
||||
{ value: peerIota.PublicKey, encoding: "base64" },
|
||||
],
|
||||
contentRecipients: [
|
||||
{ value: ownIota.PublicKey, encoding: "base64" },
|
||||
{ value: peerIota.PublicKey, encoding: "base64" },
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
requireRelaySuccess(response);
|
||||
|
||||
if (active) {
|
||||
setCurrentChatSecretState({ userId: userIdValue, value: rawSecret });
|
||||
|
|
@ -538,7 +508,7 @@ export default function Provider({ children }: { children: ReactNode }) {
|
|||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [getIota, getUser, load, send, sendSealedRelay, userIdValue]);
|
||||
}, [getUser, load, send, userIdValue]);
|
||||
|
||||
const getChatSecret = useCallback(
|
||||
async (userId: number): Promise<Uint8Array | null> => {
|
||||
|
|
@ -931,9 +901,6 @@ export default function Provider({ children }: { children: ReactNode }) {
|
|||
setFailed: (failed: boolean) => {
|
||||
editMessage(message.SendTime, { failed });
|
||||
},
|
||||
setMessageState: (MessageState: RawMessage["MessageState"]) => {
|
||||
editMessage(message.SendTime, { MessageState });
|
||||
},
|
||||
};
|
||||
},
|
||||
[editMessage, userIdValue, moveUserIdToTop, ownId],
|
||||
|
|
@ -998,7 +965,9 @@ export default function Provider({ children }: { children: ReactNode }) {
|
|||
);
|
||||
return;
|
||||
}
|
||||
editMessage(data.SendTime, { MessageState: data.MessageState });
|
||||
editMessage(data.SendTime, {
|
||||
MessageState: data.MessageState,
|
||||
});
|
||||
});
|
||||
return () => {
|
||||
unsubscribeEdit();
|
||||
|
|
@ -1052,7 +1021,6 @@ type contextType = {
|
|||
liveMessages: () => LiveMessage[];
|
||||
addLiveMessage: (message: RawMessage) => {
|
||||
setFailed: (failed: boolean) => void;
|
||||
setMessageState: (messageState: RawMessage["MessageState"]) => void;
|
||||
};
|
||||
editMessage: (sendTime: number, edit: MessageEdit) => void;
|
||||
deleteMessage: (sendTime: number) => void;
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ import {
|
|||
type LiveMessage,
|
||||
type RawMessage,
|
||||
} from "./values";
|
||||
import Wrapper from "@tensamin/identity/wrapper";
|
||||
import Wrapper from "@tensamin/user/wrapper";
|
||||
|
||||
function shouldFetchPreviousPage({
|
||||
entry,
|
||||
|
|
|
|||
|
|
@ -9,7 +9,6 @@ import {
|
|||
export type TextProps = {
|
||||
value: string;
|
||||
fontSize?: CSSProperties["fontSize"];
|
||||
showEditedIndicator?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
|
|
@ -26,9 +25,6 @@ export default function Text(props: TextProps) {
|
|||
return (
|
||||
<div className="tm-md-root" style={{ fontSize: props.fontSize }}>
|
||||
{renderedBlocks}
|
||||
{props.showEditedIndicator && (
|
||||
<span className="ml-1 text-xs text-muted-foreground">(edited)</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,6 @@
|
|||
import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { toast as sonnerToast } from "@methanium/ui";
|
||||
import {
|
||||
base64ToBytes,
|
||||
ConnectionState,
|
||||
MTPClient,
|
||||
} from "mtp";
|
||||
import { base64ToBytes, ConnectionState, MTPClient } from "mtp";
|
||||
import createAsyncQueue from "@tensamin/shared/asyncQueue";
|
||||
import {
|
||||
mtp as mtpSchemas,
|
||||
|
|
@ -21,7 +17,6 @@ import {
|
|||
type MTPContextType,
|
||||
type ProtocolMessage,
|
||||
removeMissingContacts,
|
||||
type SealedRelaySend,
|
||||
useMessageHandlers,
|
||||
} from "./mtpContext";
|
||||
import {
|
||||
|
|
@ -206,20 +201,6 @@ export function BrowserProvider(props: {
|
|||
},
|
||||
[],
|
||||
);
|
||||
const sendSealedRelay: SealedRelaySend = useMemo(
|
||||
() => async (type, data, options) => {
|
||||
const client = clientRef.current;
|
||||
if (!client) throw new Error("mtp is not connected");
|
||||
await client.sendSealedRelay(type, data, {
|
||||
nextHopId: options.nextHop.id,
|
||||
finalRecipientId: options.finalRecipientId,
|
||||
metadataRecipients: options.metadataRecipients,
|
||||
contentRecipients: options.contentRecipients,
|
||||
});
|
||||
return { type: "Success", data: {} };
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const resolveConnectionRef = useRef(() => {});
|
||||
useEffect(() => {
|
||||
|
|
@ -357,7 +338,6 @@ export function BrowserProvider(props: {
|
|||
hostPublicKey: { value: omikronPublicKey, encoding: "base64" },
|
||||
descriptor: "client",
|
||||
pings: true,
|
||||
securityProfile: { protectedSignatureSuite: "dual" },
|
||||
logger: (event) => {
|
||||
if (event.type === "state") {
|
||||
if (generation !== connectionGeneration) return;
|
||||
|
|
@ -532,7 +512,6 @@ export function BrowserProvider(props: {
|
|||
<MTPContext.Provider
|
||||
value={{
|
||||
send: sendQueued,
|
||||
sendSealedRelay,
|
||||
subscribe,
|
||||
addInterceptor,
|
||||
readyState,
|
||||
|
|
|
|||
|
|
@ -1,12 +1,7 @@
|
|||
export { Provider, useMTP } from "./context";
|
||||
export { RelayRejectedError, requireRelaySuccess } from "./mtpContext";
|
||||
export type {
|
||||
BoundSendFn,
|
||||
MTPExchange,
|
||||
MTPInterceptor,
|
||||
ProtocolMessage,
|
||||
RelayTarget,
|
||||
SealedRelayOptions,
|
||||
SealedRelayResult,
|
||||
SealedRelaySend,
|
||||
} from "./mtpContext";
|
||||
|
|
|
|||
|
|
@ -1,8 +1,5 @@
|
|||
import { createContext, useCallback, useRef } from "react";
|
||||
import type {
|
||||
MTPDataValueInput,
|
||||
MTPEncodedBytesInput,
|
||||
MTPFrame,
|
||||
MTPRequestFunction,
|
||||
MTPResponseFrame,
|
||||
MTPSubscriptionFunction,
|
||||
|
|
@ -22,56 +19,6 @@ export type ProtocolMessage<
|
|||
|
||||
export type BoundSendFn = MTPRequestFunction<typeof mtpSchemas>;
|
||||
|
||||
export type RelayTarget =
|
||||
| { kind: "user"; id: number }
|
||||
| { kind: "iota"; id: number };
|
||||
|
||||
export type SealedRelayOptions = {
|
||||
nextHop: RelayTarget;
|
||||
finalRecipientId: number;
|
||||
metadataRecipients: MTPEncodedBytesInput[];
|
||||
contentRecipients: MTPEncodedBytesInput[];
|
||||
};
|
||||
|
||||
export type SealedRelayResult = {
|
||||
type: string;
|
||||
data: Record<string, unknown>;
|
||||
};
|
||||
|
||||
export function sealedRelayResultFromFrame(frame: MTPFrame): SealedRelayResult {
|
||||
return {
|
||||
type: frame.type,
|
||||
data:
|
||||
typeof frame.data === "object" &&
|
||||
frame.data !== null &&
|
||||
!Array.isArray(frame.data)
|
||||
? (frame.data as Record<string, unknown>)
|
||||
: {},
|
||||
};
|
||||
}
|
||||
|
||||
export class RelayRejectedError extends Error {
|
||||
public readonly responseType: string;
|
||||
|
||||
constructor(responseType: string) {
|
||||
super(`Relay rejected with ${responseType}`);
|
||||
this.responseType = responseType;
|
||||
this.name = "RelayRejectedError";
|
||||
}
|
||||
}
|
||||
|
||||
export function requireRelaySuccess(response: SealedRelayResult): void {
|
||||
if (response.type !== "Success") {
|
||||
throw new RelayRejectedError(response.type);
|
||||
}
|
||||
}
|
||||
|
||||
export type SealedRelaySend = (
|
||||
type: string,
|
||||
data: MTPDataValueInput,
|
||||
options: SealedRelayOptions,
|
||||
) => Promise<SealedRelayResult>;
|
||||
|
||||
export type MTPExchange = {
|
||||
type: keyof typeof mtpSchemas & string;
|
||||
data: unknown;
|
||||
|
|
@ -82,7 +29,6 @@ export type MTPInterceptor = (exchange: MTPExchange) => void | Promise<void>;
|
|||
|
||||
export type MTPContextType = {
|
||||
send: BoundSendFn;
|
||||
sendSealedRelay: SealedRelaySend;
|
||||
subscribe: MTPSubscriptionFunction<typeof mtpSchemas>;
|
||||
addInterceptor: (interceptor: MTPInterceptor) => () => void;
|
||||
readyState: number;
|
||||
|
|
|
|||
|
|
@ -26,8 +26,6 @@ import {
|
|||
MTPContext,
|
||||
type ProtocolMessage,
|
||||
removeMissingContacts,
|
||||
type SealedRelayResult,
|
||||
type SealedRelaySend,
|
||||
useMessageHandlers,
|
||||
} from "./mtpContext";
|
||||
|
||||
|
|
@ -235,26 +233,12 @@ export function TauriProvider(props: {
|
|||
},
|
||||
[connection, interceptorsRef],
|
||||
);
|
||||
const sendSealedRelay = useCallback<SealedRelaySend>(
|
||||
async (type, data, options) => {
|
||||
return invoke<SealedRelayResult>("mtp_send_sealed_relay", {
|
||||
typeName: type,
|
||||
data,
|
||||
nextHop: options.nextHop,
|
||||
finalRecipientId: options.finalRecipientId,
|
||||
metadataRecipients: options.metadataRecipients,
|
||||
contentRecipients: options.contentRecipients,
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
const connected = snapshot.readyState === ConnectionState.Connected;
|
||||
|
||||
return (
|
||||
<MTPContext.Provider
|
||||
value={{
|
||||
send,
|
||||
sendSealedRelay,
|
||||
subscribe,
|
||||
addInterceptor,
|
||||
readyState: snapshot.readyState,
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@
|
|||
"@tensamin/mtp": "workspace:*",
|
||||
"@tensamin/shared": "workspace:*",
|
||||
"@tensamin/storage": "workspace:*",
|
||||
"@tensamin/identity": "workspace:*",
|
||||
"@tensamin/user": "workspace:*",
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8",
|
||||
"sonner": "^2.0.7"
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { useStorage } from "@tensamin/storage/context";
|
||||
import { useUser } from "@tensamin/identity/context";
|
||||
import { useUser } from "@tensamin/user/context";
|
||||
import { useChat } from "@tensamin/chat/context";
|
||||
import { useMTP } from "@tensamin/mtp";
|
||||
import { createContext, useEffect, useContext } from "react";
|
||||
|
|
@ -11,7 +11,7 @@ import {
|
|||
requestPermission as requestTauriNotificationPermission,
|
||||
sendNotification as sendTauriNotification,
|
||||
} from "@tauri-apps/plugin-notification";
|
||||
import { useSession } from "@tensamin/identity/session";
|
||||
import { useSession } from "@tensamin/storage/session";
|
||||
import { useLocation, useNavigate } from "@tanstack/react-router";
|
||||
import { decryptChatText } from "@tensamin/crypto/chatSecret";
|
||||
import { log } from "@tensamin/shared/log";
|
||||
|
|
@ -29,7 +29,7 @@ async function requestNotificationPermission() {
|
|||
}
|
||||
|
||||
export default function Provider(props: { children: React.ReactNode }) {
|
||||
const { subscribe } = useMTP();
|
||||
const { subscribe, send } = useMTP();
|
||||
const { load } = useStorage();
|
||||
const { get } = useUser();
|
||||
const { addLiveMessage, chatSecret, getChatSecret, userId } = useChat();
|
||||
|
|
@ -79,6 +79,11 @@ export default function Provider(props: { children: React.ReactNode }) {
|
|||
// todo: add notification symbol to conversation cards (incl. message start)
|
||||
moveUserIdToTop(data.SenderId);
|
||||
|
||||
if (await load("settings.receive_confirmations")) {
|
||||
void send("MessageState", {
|
||||
MessageState: "received",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const user = await get(data.SenderId, [
|
||||
|
|
@ -175,6 +180,7 @@ export default function Provider(props: { children: React.ReactNode }) {
|
|||
load,
|
||||
location.pathname,
|
||||
navigate,
|
||||
send,
|
||||
moveUserIdToTop,
|
||||
subscribe,
|
||||
getChatSecret,
|
||||
|
|
|
|||
|
|
@ -17,11 +17,10 @@
|
|||
"@tauri-apps/api": "^2.11.1",
|
||||
"@tensamin/cache": "workspace:*",
|
||||
"@tensamin/hotkeys": "workspace:*",
|
||||
"@tensamin/markdown": "workspace:*",
|
||||
"@tensamin/mtp": "workspace:*",
|
||||
"@tensamin/shared": "workspace:*",
|
||||
"@tensamin/storage": "workspace:*",
|
||||
"@tensamin/identity": "workspace:*",
|
||||
"@tensamin/user": "workspace:*",
|
||||
"lucide-react": "^1.29.0",
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8"
|
||||
|
|
|
|||
|
|
@ -1,15 +1,14 @@
|
|||
import { settingsNavigation } from "./navigation";
|
||||
|
||||
import SettingsIndex from "./pages/index";
|
||||
import Accessibility from "./pages/accessibility";
|
||||
import Cache from "./pages/cache";
|
||||
import Call from "./pages/call";
|
||||
import Chat from "./pages/chat";
|
||||
import Index from "./pages/index";
|
||||
import Licenses from "./pages/licenses";
|
||||
import Profile from "./pages/profile";
|
||||
import Security from "./pages/security";
|
||||
import Chat from "./pages/chat";
|
||||
import Call from "./pages/call";
|
||||
import Cache from "./pages/cache";
|
||||
import Theme from "./pages/theme";
|
||||
import Accessibility from "./pages/accessibility";
|
||||
import Hotkeys from "./pages/hotkeys";
|
||||
import Licenses from "./pages/licenses";
|
||||
import { settingsNavigation } from "./navigation";
|
||||
|
||||
const pageComponents = {
|
||||
profile: Profile,
|
||||
|
|
@ -24,7 +23,7 @@ const pageComponents = {
|
|||
} as const;
|
||||
|
||||
export const settingsPages = [
|
||||
{ path: "/", component: SettingsIndex },
|
||||
{ path: "/", component: Index },
|
||||
...settingsNavigation.map((page) => ({
|
||||
...page,
|
||||
component: pageComponents[page.path],
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import MDInput from "@tensamin/markdown/input";
|
||||
import { Input as MDInput } from "@methanium/ui/markdown";
|
||||
import { useMTP } from "@tensamin/mtp";
|
||||
import { mtp } from "@tensamin/shared/data";
|
||||
import { useStorage } from "@tensamin/storage/context";
|
||||
|
|
@ -15,7 +15,7 @@ import {
|
|||
useUser,
|
||||
useUserFields,
|
||||
type SelectedUser,
|
||||
} from "@tensamin/identity/context";
|
||||
} from "@tensamin/user/context";
|
||||
import { Check } from "lucide-react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
|
|
|
|||
|
|
@ -70,7 +70,6 @@ const callSecretEnvelopeRequest = z.object({
|
|||
export const Reaction = z.object({
|
||||
Reaction: z.string(),
|
||||
SenderId: z.number(),
|
||||
RelayMessageId: z.string().optional(),
|
||||
});
|
||||
|
||||
export const Message = z.object({
|
||||
|
|
@ -83,8 +82,6 @@ export const Message = z.object({
|
|||
Avatar: z.boolean().optional(),
|
||||
Display: z.boolean().optional(),
|
||||
ReplyId: z.number().optional(),
|
||||
UpdatedAt: z.number().optional(),
|
||||
ErrorType: z.string().optional(),
|
||||
MessageState: z
|
||||
.enum(["read", "received", "sent", "sending", "awaiting"]) // awaiting for 'internal' use
|
||||
.default("received"),
|
||||
|
|
@ -110,7 +107,6 @@ const authPayload = z.object({
|
|||
.array(
|
||||
z.object({
|
||||
LastMessageAt: z.number().default(0),
|
||||
CreatedAt: z.number().optional(),
|
||||
UserId: z.number(),
|
||||
LastMessage: z
|
||||
.object({
|
||||
|
|
@ -152,7 +148,7 @@ const userFields = {
|
|||
About: z.string().max(255).optional(),
|
||||
Avatar: z.string().optional(),
|
||||
Display: z.string().min(1).max(15),
|
||||
IotaId: z.number().optional(),
|
||||
IotaId: z.number(),
|
||||
OmikronConnections: z.array(z.number()),
|
||||
OmikronId: z.number().optional(),
|
||||
PublicKey: z.base64(),
|
||||
|
|
@ -244,27 +240,6 @@ export const mtp = {
|
|||
}),
|
||||
response: userSchema,
|
||||
},
|
||||
GetIotaData: {
|
||||
request: z
|
||||
.object({
|
||||
IotaId: z.number().int().positive().optional(),
|
||||
UserId: z.number().int().positive().optional(),
|
||||
Username: z.string().min(1).max(15).optional(),
|
||||
})
|
||||
.refine(
|
||||
({ IotaId, UserId, Username }) =>
|
||||
[IotaId, UserId, Username].filter((value) => value !== undefined)
|
||||
.length === 1,
|
||||
"GetIotaData requires exactly one selector",
|
||||
),
|
||||
response: z.object({
|
||||
IotaId: z.number().int().positive(),
|
||||
PublicKey: z.base64(),
|
||||
OmikronConnections: z.array(z.number().int().positive()).optional(),
|
||||
UserId: z.number().int().positive().optional(),
|
||||
Username: z.string().optional(),
|
||||
}),
|
||||
},
|
||||
GetStates: {
|
||||
request: z.object({
|
||||
SessionId: z.number().int().positive(),
|
||||
|
|
@ -401,12 +376,17 @@ export const mtp = {
|
|||
response: z.object({}),
|
||||
},
|
||||
MessageState: {
|
||||
request: z.object({
|
||||
request: z
|
||||
.object({
|
||||
ChatPartnerId: z.number(),
|
||||
RelayMessageId: z.string(),
|
||||
EventAt: z.number(),
|
||||
MessageState: z.enum(["received", "read"]),
|
||||
SendTime: z.number(),
|
||||
MessageState: Message.shape.MessageState,
|
||||
})
|
||||
.or(
|
||||
z.object({
|
||||
MessageState: Message.shape.MessageState,
|
||||
}),
|
||||
),
|
||||
response: z.object({
|
||||
ChatPartnerId: z.number(),
|
||||
MessageState: Message.shape.MessageState,
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@
|
|||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
"./session": "./src/session.tsx",
|
||||
"./context": "./src/context.tsx",
|
||||
"./secure": "./src/secure.ts",
|
||||
"./browserSecure": "./src/browserSecure.ts",
|
||||
|
|
@ -17,6 +18,8 @@
|
|||
"dependencies": {
|
||||
"@methanium/ui": "*",
|
||||
"@tauri-apps/api": "^2.11.1",
|
||||
"@tensamin/cache": "workspace:*",
|
||||
"@tensamin/mtp": "workspace:*",
|
||||
"@tensamin/shared": "workspace:*",
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8"
|
||||
|
|
|
|||
|
|
@ -6,10 +6,10 @@ import {
|
|||
useContext,
|
||||
useEffect,
|
||||
} from "react";
|
||||
import { useStorage } from "@tensamin/storage/context";
|
||||
import { useStorage } from "./context";
|
||||
import type { Contacts, Communities, Calls } from "@tensamin/shared/data";
|
||||
import { createCache } from "@tensamin/cache";
|
||||
import { secureValueCodec } from "@tensamin/storage/secure";
|
||||
import { secureValueCodec } from "./secure";
|
||||
|
||||
interface SessionContextType {
|
||||
contacts: Contacts;
|
||||
|
|
@ -19,7 +19,7 @@
|
|||
"@tensamin/shared": "workspace:*",
|
||||
"@tensamin/storage": "workspace:*",
|
||||
"@tensamin/tauri": "workspace:*",
|
||||
"@tensamin/identity": "workspace:*",
|
||||
"@tensamin/user": "workspace:*",
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { type ReactNode } from "react";
|
||||
/**
|
||||
import { useEffect, useState, type ReactNode } from "react";
|
||||
import { useUser } from "@tensamin/identity/context";
|
||||
import { useUser } from "@tensamin/user/context";
|
||||
import { useStorage } from "@tensamin/storage/context";
|
||||
import {
|
||||
Button,
|
||||
|
|
|
|||
|
|
@ -1,11 +1,10 @@
|
|||
{
|
||||
"name": "@tensamin/identity",
|
||||
"name": "@tensamin/user",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
"./context": "./src/context.tsx",
|
||||
"./session": "./src/session.tsx",
|
||||
"./wrapper": "./src/wrapper.tsx",
|
||||
"./values": "./src/values.ts"
|
||||
},
|
||||
|
|
@ -19,13 +19,12 @@ import {
|
|||
import type z from "zod";
|
||||
import { createCache } from "@tensamin/cache";
|
||||
import { useStorage } from "@tensamin/storage/context";
|
||||
import { useSession } from "./session";
|
||||
import { useSession } from "@tensamin/storage/session";
|
||||
import { getChangedUserFields, selectUserFields } from "./selection";
|
||||
|
||||
export { getChangedUserFields, selectUserFields } from "./selection";
|
||||
|
||||
export type User = z.infer<typeof schemas.GetUserData.response>;
|
||||
export type Iota = z.infer<typeof schemas.GetIotaData.response>;
|
||||
type ClientUserState = z.infer<typeof clientUserStateSchema>;
|
||||
export type UserField = keyof User;
|
||||
export type UserFields = readonly [UserField, ...UserField[]];
|
||||
|
|
@ -45,7 +44,7 @@ export function mergeTransientPresence<T extends { UserId: number }>(
|
|||
return state === undefined ? user : ({ ...user, OnlineStatus: state } as T);
|
||||
}
|
||||
|
||||
const DATA_CACHE_MAX_AGE = 5 * 60 * 1000;
|
||||
const USER_CACHE_MAX_AGE = 5 * 60 * 1000;
|
||||
|
||||
interface contextValue {
|
||||
get<const Fields extends UserFields>(
|
||||
|
|
@ -62,7 +61,6 @@ interface contextValue {
|
|||
listener: () => void,
|
||||
): () => void;
|
||||
getVersion(userId: number, fields: readonly UserField[]): string;
|
||||
getIota(userId: number): Promise<Iota>;
|
||||
updateProfile(userId: number, patch: UserProfilePatch): Promise<void>;
|
||||
updateState(userId: number, state: ClientUserState): void;
|
||||
}
|
||||
|
|
@ -77,9 +75,6 @@ const UserContext = createContext<contextValue | undefined>(undefined);
|
|||
export default function UserProvider(props: { children: ReactNode }) {
|
||||
const storageRef = useRef<Record<number, User>>({});
|
||||
const pendingRef = useRef<Record<number, Promise<User> | undefined>>({});
|
||||
const iotaStorageRef = useRef<Record<number, Iota>>({});
|
||||
const pendingIotaRef = useRef<Record<number, Promise<Iota> | undefined>>({});
|
||||
const iotaCheckedAtRef = useRef<Record<number, number>>({});
|
||||
const profileUpdateQueuesRef = useRef(new Map<number, Promise<void>>());
|
||||
const profileGenerationsRef = useRef(new Map<number, number>());
|
||||
const checkedAtRef = useRef<Record<number, number>>({});
|
||||
|
|
@ -235,7 +230,7 @@ export default function UserProvider(props: { children: ReactNode }) {
|
|||
if (cached) {
|
||||
installProfile(cached);
|
||||
const checkedAt = checkedAtRef.current[userId];
|
||||
if (!checkedAt || Date.now() - checkedAt < DATA_CACHE_MAX_AGE) {
|
||||
if (!checkedAt || Date.now() - checkedAt < USER_CACHE_MAX_AGE) {
|
||||
checkedAtRef.current[userId] = Date.now();
|
||||
return storageRef.current[userId];
|
||||
}
|
||||
|
|
@ -294,52 +289,6 @@ export default function UserProvider(props: { children: ReactNode }) {
|
|||
[loadUser],
|
||||
);
|
||||
|
||||
const getIota = useCallback(
|
||||
async (userId: number): Promise<Iota> => {
|
||||
if (userId == null) {
|
||||
throw new Error("userId is required");
|
||||
}
|
||||
|
||||
const pendingIota = pendingIotaRef.current[userId];
|
||||
if (pendingIota !== undefined) {
|
||||
return pendingIota;
|
||||
}
|
||||
|
||||
const cached = iotaStorageRef.current[userId];
|
||||
const checkedAt = iotaCheckedAtRef.current[userId];
|
||||
if (cached && checkedAt && Date.now() - checkedAt < DATA_CACHE_MAX_AGE) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const request = (async () => {
|
||||
try {
|
||||
const response = await send("GetIotaData", { UserId: userId });
|
||||
if (response.type !== "GetIotaData") {
|
||||
throw new Error(`GetIotaData failed: ${response.type}`);
|
||||
}
|
||||
const iota = schemas.GetIotaData.response.parse(response.data);
|
||||
iotaStorageRef.current[userId] = iota;
|
||||
iotaCheckedAtRef.current[userId] = Date.now();
|
||||
return iota;
|
||||
} catch (error) {
|
||||
if (cached) {
|
||||
iotaCheckedAtRef.current[userId] = Date.now();
|
||||
return cached;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
})();
|
||||
|
||||
pendingIotaRef.current[userId] = request;
|
||||
try {
|
||||
return await request;
|
||||
} finally {
|
||||
delete pendingIotaRef.current[userId];
|
||||
}
|
||||
},
|
||||
[send],
|
||||
);
|
||||
|
||||
const peek = useCallback(
|
||||
<const Fields extends UserFields>(userId: number, fields: Fields) => {
|
||||
const user = storageRef.current[userId];
|
||||
|
|
@ -438,14 +387,13 @@ export default function UserProvider(props: { children: ReactNode }) {
|
|||
const value = useMemo(
|
||||
() => ({
|
||||
get,
|
||||
getIota,
|
||||
peek,
|
||||
subscribe,
|
||||
getVersion,
|
||||
updateProfile,
|
||||
updateState,
|
||||
}),
|
||||
[get, getIota, getVersion, peek, subscribe, updateProfile, updateState],
|
||||
[get, getVersion, peek, subscribe, updateProfile, updateState],
|
||||
);
|
||||
|
||||
return (
|
||||
28
packages/user/src/selection.test.ts
Normal file
28
packages/user/src/selection.test.ts
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { User } from "./context";
|
||||
import { getChangedUserFields, selectUserFields } from "./selection";
|
||||
|
||||
const user = {
|
||||
Avatar: undefined,
|
||||
Display: "Alice",
|
||||
IotaId: 1,
|
||||
OmikronConnections: [],
|
||||
OnlineStatus: "user_online",
|
||||
PublicKey: "AA==",
|
||||
SubEnd: 0,
|
||||
SubLevel: 0,
|
||||
UserId: 1,
|
||||
Username: "alice",
|
||||
} satisfies User;
|
||||
|
||||
describe("presence selection", () => {
|
||||
it("notifies OnlineStatus selections when presence changes", () => {
|
||||
const next = { ...user, OnlineStatus: "user_dnd" as const };
|
||||
|
||||
expect(getChangedUserFields(user, next)).toEqual(["OnlineStatus"]);
|
||||
expect(selectUserFields(next, ["OnlineStatus"])).toEqual({
|
||||
OnlineStatus: "user_dnd",
|
||||
});
|
||||
});
|
||||
});
|
||||
99
pnpm-lock.yaml
generated
99
pnpm-lock.yaml
generated
|
|
@ -198,12 +198,6 @@ importers:
|
|||
'@tensamin/hotkeys':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/hotkeys
|
||||
'@tensamin/identity':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/identity
|
||||
'@tensamin/markdown':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/markdown
|
||||
'@tensamin/mtp':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/mtp
|
||||
|
|
@ -231,6 +225,9 @@ importers:
|
|||
'@tensamin/tauth':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/tauth
|
||||
'@tensamin/user':
|
||||
specifier: workspace:*
|
||||
version: link:../../packages/user
|
||||
decimal.js-light:
|
||||
specifier: ^2.5.1
|
||||
version: 2.5.1
|
||||
|
|
@ -337,9 +334,6 @@ importers:
|
|||
'@tensamin/crypto':
|
||||
specifier: workspace:*
|
||||
version: link:../crypto
|
||||
'@tensamin/identity':
|
||||
specifier: workspace:*
|
||||
version: link:../identity
|
||||
'@tensamin/mtp':
|
||||
specifier: workspace:*
|
||||
version: link:../mtp
|
||||
|
|
@ -349,6 +343,9 @@ importers:
|
|||
'@tensamin/storage':
|
||||
specifier: workspace:*
|
||||
version: link:../storage
|
||||
'@tensamin/user':
|
||||
specifier: workspace:*
|
||||
version: link:../user
|
||||
deepfilternet3-noise-filter:
|
||||
specifier: 1.3.0
|
||||
version: 1.3.0(livekit-client@2.21.0(@types/dom-mediacapture-record@1.0.22))
|
||||
|
|
@ -403,12 +400,6 @@ importers:
|
|||
'@tensamin/hotkeys':
|
||||
specifier: workspace:*
|
||||
version: link:../hotkeys
|
||||
'@tensamin/identity':
|
||||
specifier: workspace:*
|
||||
version: link:../identity
|
||||
'@tensamin/markdown':
|
||||
specifier: workspace:*
|
||||
version: link:../markdown
|
||||
'@tensamin/mtp':
|
||||
specifier: workspace:*
|
||||
version: link:../mtp
|
||||
|
|
@ -418,6 +409,9 @@ importers:
|
|||
'@tensamin/storage':
|
||||
specifier: workspace:*
|
||||
version: link:../storage
|
||||
'@tensamin/user':
|
||||
specifier: workspace:*
|
||||
version: link:../user
|
||||
lucide-react:
|
||||
specifier: ^1.29.0
|
||||
version: 1.30.0(react@19.2.8)
|
||||
|
|
@ -465,30 +459,6 @@ importers:
|
|||
specifier: ^8.2.1
|
||||
version: 8.2.1(@types/node@26.2.0)(esbuild@0.28.1)(jiti@2.7.0)(terser@5.50.0)(yaml@2.9.0)
|
||||
|
||||
packages/identity:
|
||||
dependencies:
|
||||
'@tensamin/cache':
|
||||
specifier: workspace:*
|
||||
version: link:../cache
|
||||
'@tensamin/mtp':
|
||||
specifier: workspace:*
|
||||
version: link:../mtp
|
||||
'@tensamin/shared':
|
||||
specifier: workspace:*
|
||||
version: link:../shared
|
||||
'@tensamin/storage':
|
||||
specifier: workspace:*
|
||||
version: link:../storage
|
||||
react:
|
||||
specifier: ^19.2.8
|
||||
version: 19.2.8
|
||||
react-dom:
|
||||
specifier: ^19.2.8
|
||||
version: 19.2.8(react@19.2.8)
|
||||
zod:
|
||||
specifier: ^4.4.3
|
||||
version: 4.4.3
|
||||
|
||||
packages/markdown:
|
||||
dependencies:
|
||||
'@codemirror/autocomplete':
|
||||
|
|
@ -573,9 +543,6 @@ importers:
|
|||
'@tensamin/crypto':
|
||||
specifier: workspace:*
|
||||
version: link:../crypto
|
||||
'@tensamin/identity':
|
||||
specifier: workspace:*
|
||||
version: link:../identity
|
||||
'@tensamin/mtp':
|
||||
specifier: workspace:*
|
||||
version: link:../mtp
|
||||
|
|
@ -585,6 +552,9 @@ importers:
|
|||
'@tensamin/storage':
|
||||
specifier: workspace:*
|
||||
version: link:../storage
|
||||
'@tensamin/user':
|
||||
specifier: workspace:*
|
||||
version: link:../user
|
||||
react:
|
||||
specifier: ^19.2.8
|
||||
version: 19.2.8
|
||||
|
|
@ -642,12 +612,6 @@ importers:
|
|||
'@tensamin/hotkeys':
|
||||
specifier: workspace:*
|
||||
version: link:../hotkeys
|
||||
'@tensamin/identity':
|
||||
specifier: workspace:*
|
||||
version: link:../identity
|
||||
'@tensamin/markdown':
|
||||
specifier: workspace:*
|
||||
version: link:../markdown
|
||||
'@tensamin/mtp':
|
||||
specifier: workspace:*
|
||||
version: link:../mtp
|
||||
|
|
@ -657,6 +621,9 @@ importers:
|
|||
'@tensamin/storage':
|
||||
specifier: workspace:*
|
||||
version: link:../storage
|
||||
'@tensamin/user':
|
||||
specifier: workspace:*
|
||||
version: link:../user
|
||||
lucide-react:
|
||||
specifier: ^1.29.0
|
||||
version: 1.30.0(react@19.2.8)
|
||||
|
|
@ -697,6 +664,12 @@ importers:
|
|||
'@tauri-apps/api':
|
||||
specifier: ^2.11.1
|
||||
version: 2.11.1
|
||||
'@tensamin/cache':
|
||||
specifier: workspace:*
|
||||
version: link:../cache
|
||||
'@tensamin/mtp':
|
||||
specifier: workspace:*
|
||||
version: link:../mtp
|
||||
'@tensamin/shared':
|
||||
specifier: workspace:*
|
||||
version: link:../shared
|
||||
|
|
@ -718,9 +691,6 @@ importers:
|
|||
'@tensamin/crypto':
|
||||
specifier: workspace:*
|
||||
version: link:../crypto
|
||||
'@tensamin/identity':
|
||||
specifier: workspace:*
|
||||
version: link:../identity
|
||||
'@tensamin/mtp':
|
||||
specifier: workspace:*
|
||||
version: link:../mtp
|
||||
|
|
@ -733,6 +703,9 @@ importers:
|
|||
'@tensamin/tauri':
|
||||
specifier: workspace:*
|
||||
version: link:../../apps/tauri
|
||||
'@tensamin/user':
|
||||
specifier: workspace:*
|
||||
version: link:../user
|
||||
react:
|
||||
specifier: ^19.2.8
|
||||
version: 19.2.8
|
||||
|
|
@ -740,6 +713,30 @@ importers:
|
|||
specifier: ^19.2.8
|
||||
version: 19.2.8(react@19.2.8)
|
||||
|
||||
packages/user:
|
||||
dependencies:
|
||||
'@tensamin/cache':
|
||||
specifier: workspace:*
|
||||
version: link:../cache
|
||||
'@tensamin/mtp':
|
||||
specifier: workspace:*
|
||||
version: link:../mtp
|
||||
'@tensamin/shared':
|
||||
specifier: workspace:*
|
||||
version: link:../shared
|
||||
'@tensamin/storage':
|
||||
specifier: workspace:*
|
||||
version: link:../storage
|
||||
react:
|
||||
specifier: ^19.2.8
|
||||
version: 19.2.8
|
||||
react-dom:
|
||||
specifier: ^19.2.8
|
||||
version: 19.2.8(react@19.2.8)
|
||||
zod:
|
||||
specifier: ^4.4.3
|
||||
version: 4.4.3
|
||||
|
||||
packages:
|
||||
|
||||
'@apideck/better-ajv-errors@0.3.7':
|
||||
|
|
|
|||
|
|
@ -5,8 +5,6 @@ allowBuilds:
|
|||
electron: true
|
||||
electron-winstaller: true
|
||||
esbuild: true
|
||||
ffi: false
|
||||
ref: false
|
||||
overrides:
|
||||
"@methanium/ui": "https://git.methanium.net/methanium/ui/releases/download/0.0.29/methanium-ui.tgz"
|
||||
mtp: "https://git.methanium.net/methanium/mtp/releases/download/0.3.0-dev-c7c7afe/mtp-0.3.0.tgz"
|
||||
|
|
|
|||
Loading…
Reference in a new issue