minecraft skins!
This commit is contained in:
Generated
+1
@@ -6280,6 +6280,7 @@ dependencies = [
|
||||
"objc2-foundation",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"specta",
|
||||
"specta-typescript",
|
||||
"sqlx",
|
||||
|
||||
+51
-5
@@ -1,17 +1,26 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
pub const VERSION: u8 = 2;
|
||||
pub const VERSION: u8 = 3;
|
||||
pub const MAX_INTERACTION_PAYLOAD_BYTES: usize = 160 * 1024;
|
||||
pub const MAX_IMAGE_B64_SIZE: usize = 150 * 1024;
|
||||
pub const MAX_SKIN_B64_SIZE: usize = 96 * 1024;
|
||||
pub const MAX_IMAGE_DIMENSION: u32 = 480;
|
||||
pub const MAX_TEXT_CHARS: usize = 500;
|
||||
|
||||
pub fn is_skin_hash(hash: &str) -> bool {
|
||||
hash.len() == 64
|
||||
&& hash
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Profile {
|
||||
pub id: String,
|
||||
pub display_name: String,
|
||||
pub skin_hash: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
@@ -36,6 +45,17 @@ pub enum ClientMessage {
|
||||
request_id: String,
|
||||
user_id: String,
|
||||
},
|
||||
RequestSkin {
|
||||
request_id: String,
|
||||
user_id: String,
|
||||
skin_hash: String,
|
||||
},
|
||||
ProvideSkin {
|
||||
request_id: String,
|
||||
requester_id: String,
|
||||
skin_hash: String,
|
||||
data: Option<String>,
|
||||
},
|
||||
Signed {
|
||||
payload: String,
|
||||
signature: String,
|
||||
@@ -115,6 +135,17 @@ pub enum ServerMessage {
|
||||
request_id: String,
|
||||
profile: Option<Profile>,
|
||||
},
|
||||
SkinRequested {
|
||||
request_id: String,
|
||||
requester_id: String,
|
||||
skin_hash: String,
|
||||
},
|
||||
SkinResolved {
|
||||
request_id: String,
|
||||
user_id: String,
|
||||
skin_hash: String,
|
||||
data: Option<String>,
|
||||
},
|
||||
FriendStatusChanged {
|
||||
friend_id: String,
|
||||
online: bool,
|
||||
@@ -139,9 +170,10 @@ pub enum ServerMessage {
|
||||
|
||||
pub fn register_bytes(challenge: &str, profile: &Profile, friends: &[String]) -> Vec<u8> {
|
||||
format!(
|
||||
"wyd-register-v{VERSION}\n{challenge}\n{}\n{}\n{}",
|
||||
"wyd-register-v{VERSION}\n{challenge}\n{}\n{}\n{}\n{}",
|
||||
profile.id,
|
||||
profile.display_name,
|
||||
profile.skin_hash.as_deref().unwrap_or(""),
|
||||
friends.join("\n")
|
||||
)
|
||||
.into_bytes()
|
||||
@@ -166,8 +198,10 @@ pub fn interaction_bytes(interaction_id: &str, recipient_id: &str, payload: &str
|
||||
|
||||
pub fn profile_bytes(profile: &Profile) -> Vec<u8> {
|
||||
format!(
|
||||
"wyd-profile-v{VERSION}\n{}\n{}",
|
||||
profile.id, profile.display_name
|
||||
"wyd-profile-v{VERSION}\n{}\n{}\n{}",
|
||||
profile.id,
|
||||
profile.display_name,
|
||||
profile.skin_hash.as_deref().unwrap_or("")
|
||||
)
|
||||
.into_bytes()
|
||||
}
|
||||
@@ -178,7 +212,7 @@ pub fn friends_bytes(friends: &[String]) -> Vec<u8> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{InteractionContent, MAX_TEXT_CHARS, interaction_bytes};
|
||||
use super::{InteractionContent, MAX_TEXT_CHARS, Profile, interaction_bytes, profile_bytes};
|
||||
|
||||
#[test]
|
||||
fn interaction_signature_bytes_are_length_delimited() {
|
||||
@@ -211,4 +245,16 @@ mod tests {
|
||||
);
|
||||
assert!(serde_json::from_str::<InteractionContent>(r#"{"type":"unknown"}"#).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_signature_bytes_include_the_skin_hash() {
|
||||
let mut profile = Profile {
|
||||
id: "id".to_owned(),
|
||||
display_name: "Name".to_owned(),
|
||||
skin_hash: None,
|
||||
};
|
||||
let without_skin = profile_bytes(&profile);
|
||||
profile.skin_hash = Some("a".repeat(64));
|
||||
assert_ne!(without_skin, profile_bytes(&profile));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,6 +161,7 @@ mod tests {
|
||||
profile: Profile {
|
||||
id: public_key.clone(),
|
||||
display_name: "Source".to_owned(),
|
||||
skin_hash: None,
|
||||
},
|
||||
friends: vec!["target".to_owned(), "one-sided".to_owned()],
|
||||
sender: source_sender,
|
||||
@@ -174,6 +175,7 @@ mod tests {
|
||||
profile: Profile {
|
||||
id: "target".to_owned(),
|
||||
display_name: "Target".to_owned(),
|
||||
skin_hash: None,
|
||||
},
|
||||
friends: vec![public_key.clone()],
|
||||
sender: target_sender.clone(),
|
||||
@@ -187,6 +189,7 @@ mod tests {
|
||||
profile: Profile {
|
||||
id: "one-sided".to_owned(),
|
||||
display_name: "One-sided".to_owned(),
|
||||
skin_hash: None,
|
||||
},
|
||||
friends: Vec::new(),
|
||||
sender: one_sided_sender,
|
||||
@@ -305,6 +308,7 @@ mod tests {
|
||||
profile: Profile {
|
||||
id: public_key.clone(),
|
||||
display_name: "Source".to_owned(),
|
||||
skin_hash: None,
|
||||
},
|
||||
friends: vec!["target".to_owned()],
|
||||
sender: source_sender,
|
||||
@@ -318,6 +322,7 @@ mod tests {
|
||||
profile: Profile {
|
||||
id: "target".to_owned(),
|
||||
display_name: "Target".to_owned(),
|
||||
skin_hash: None,
|
||||
},
|
||||
friends: vec![public_key.clone()],
|
||||
sender: target_sender,
|
||||
|
||||
@@ -18,6 +18,7 @@ use wyd_common::{ClientMessage, Profile, ServerMessage, message_bytes, register_
|
||||
mod interactions;
|
||||
mod presence;
|
||||
mod profiles;
|
||||
mod skins;
|
||||
|
||||
type Clients = Arc<Mutex<HashMap<String, Client>>>;
|
||||
|
||||
@@ -70,6 +71,13 @@ async fn connected(mut socket: WebSocket, clients: Clients) {
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if profile
|
||||
.skin_hash
|
||||
.as_deref()
|
||||
.is_some_and(|hash| !wyd_common::is_skin_hash(hash))
|
||||
{
|
||||
return;
|
||||
}
|
||||
let Ok(key) = key(&profile.id) else { return };
|
||||
if !verify(
|
||||
&key,
|
||||
@@ -208,6 +216,42 @@ async fn connected(mut socket: WebSocket, clients: Clients) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(ClientMessage::RequestSkin { request_id, user_id, skin_hash }) => {
|
||||
match skins::request(
|
||||
&clients,
|
||||
&public_key,
|
||||
connection_id,
|
||||
request_id,
|
||||
user_id,
|
||||
skin_hash,
|
||||
).await {
|
||||
skins::RequestOutcome::StaleSession => break,
|
||||
skins::RequestOutcome::Forwarded => {}
|
||||
skins::RequestOutcome::Unavailable(response) => {
|
||||
if writer.send(response).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(ClientMessage::ProvideSkin {
|
||||
request_id,
|
||||
requester_id,
|
||||
skin_hash,
|
||||
data,
|
||||
}) => {
|
||||
if !skins::provide(
|
||||
&clients,
|
||||
&public_key,
|
||||
connection_id,
|
||||
request_id,
|
||||
requester_id,
|
||||
skin_hash,
|
||||
data,
|
||||
).await {
|
||||
break;
|
||||
}
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
Some(Ok(Message::Ping(data))) => {
|
||||
@@ -301,6 +345,7 @@ mod tests {
|
||||
let profile = Profile {
|
||||
id: URL_SAFE_NO_PAD.encode(signing_key.verifying_key().to_bytes()),
|
||||
display_name: "Wind".to_owned(),
|
||||
skin_hash: None,
|
||||
};
|
||||
let friends = vec!["friend".to_owned()];
|
||||
let registration = register_bytes("challenge", &profile, &friends);
|
||||
@@ -347,6 +392,7 @@ mod tests {
|
||||
profile: Profile {
|
||||
id: public_key.clone(),
|
||||
display_name: "Wind".to_owned(),
|
||||
skin_hash: None,
|
||||
},
|
||||
friends: Vec::new(),
|
||||
sender,
|
||||
@@ -390,6 +436,7 @@ mod tests {
|
||||
profile: Profile {
|
||||
id: "source".to_owned(),
|
||||
display_name: "Source".to_owned(),
|
||||
skin_hash: None,
|
||||
},
|
||||
friends: vec!["mutual".to_owned()],
|
||||
sender: source_sender,
|
||||
@@ -403,6 +450,7 @@ mod tests {
|
||||
profile: Profile {
|
||||
id: "mutual".to_owned(),
|
||||
display_name: "Mutual".to_owned(),
|
||||
skin_hash: None,
|
||||
},
|
||||
friends: vec!["source".to_owned()],
|
||||
sender: mutual_sender,
|
||||
@@ -416,6 +464,7 @@ mod tests {
|
||||
profile: Profile {
|
||||
id: "one-way".to_owned(),
|
||||
display_name: "One way".to_owned(),
|
||||
skin_hash: None,
|
||||
},
|
||||
friends: vec!["source".to_owned()],
|
||||
sender: one_way_sender,
|
||||
@@ -494,6 +543,7 @@ mod tests {
|
||||
profile: Profile {
|
||||
id: public_key.clone(),
|
||||
display_name: "Source".to_owned(),
|
||||
skin_hash: None,
|
||||
},
|
||||
friends: vec!["mutual".to_owned(), "sender-only".to_owned()],
|
||||
sender: source_sender,
|
||||
@@ -516,6 +566,7 @@ mod tests {
|
||||
profile: Profile {
|
||||
id: id.to_owned(),
|
||||
display_name: id.to_owned(),
|
||||
skin_hash: None,
|
||||
},
|
||||
friends,
|
||||
sender,
|
||||
|
||||
@@ -19,7 +19,13 @@ pub(super) async fn update(
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
if profile.id != public_key || !verify(&client.key, &profile_bytes(&profile), signature) {
|
||||
if profile.id != public_key
|
||||
|| profile
|
||||
.skin_hash
|
||||
.as_deref()
|
||||
.is_some_and(|hash| !wyd_common::is_skin_hash(hash))
|
||||
|| !verify(&client.key, &profile_bytes(&profile), signature)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
client.profile = profile.clone();
|
||||
@@ -122,6 +128,7 @@ mod tests {
|
||||
profile: Profile {
|
||||
id: id.to_owned(),
|
||||
display_name: display_name.to_owned(),
|
||||
skin_hash: None,
|
||||
},
|
||||
friends,
|
||||
sender,
|
||||
@@ -164,6 +171,7 @@ mod tests {
|
||||
let profile = Profile {
|
||||
id: public_key.clone(),
|
||||
display_name: "New".to_owned(),
|
||||
skin_hash: Some("a".repeat(64)),
|
||||
};
|
||||
let signature =
|
||||
URL_SAFE_NO_PAD.encode(signing_key.sign(&profile_bytes(&profile)).to_bytes());
|
||||
@@ -179,6 +187,17 @@ mod tests {
|
||||
.display_name,
|
||||
"New"
|
||||
);
|
||||
assert_eq!(
|
||||
clients
|
||||
.lock()
|
||||
.await
|
||||
.get(&public_key)
|
||||
.unwrap()
|
||||
.profile
|
||||
.skin_hash
|
||||
.as_deref(),
|
||||
Some("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
|
||||
);
|
||||
let Message::Text(announcement) = friend_receiver
|
||||
.recv()
|
||||
.await
|
||||
@@ -197,6 +216,7 @@ mod tests {
|
||||
let stale_profile = Profile {
|
||||
id: public_key.clone(),
|
||||
display_name: "Stale".to_owned(),
|
||||
skin_hash: None,
|
||||
};
|
||||
let stale_signature =
|
||||
URL_SAFE_NO_PAD.encode(signing_key.sign(&profile_bytes(&stale_profile)).to_bytes());
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
use axum::extract::ws::Message;
|
||||
use uuid::Uuid;
|
||||
use wyd_common::{MAX_SKIN_B64_SIZE, ServerMessage};
|
||||
|
||||
use super::{Clients, are_mutual_friends};
|
||||
|
||||
pub(super) enum RequestOutcome {
|
||||
StaleSession,
|
||||
Forwarded,
|
||||
Unavailable(Message),
|
||||
}
|
||||
|
||||
pub(super) async fn request(
|
||||
clients: &Clients,
|
||||
requester_id: &str,
|
||||
connection_id: Uuid,
|
||||
request_id: String,
|
||||
user_id: String,
|
||||
skin_hash: String,
|
||||
) -> RequestOutcome {
|
||||
let clients = clients.lock().await;
|
||||
let Some(requester) = clients
|
||||
.get(requester_id)
|
||||
.filter(|client| client.connection_id == connection_id)
|
||||
else {
|
||||
return RequestOutcome::StaleSession;
|
||||
};
|
||||
let target = clients.get(&user_id).filter(|target| {
|
||||
are_mutual_friends(requester_id, requester, &user_id, target)
|
||||
&& target.profile.skin_hash.as_deref() == Some(&skin_hash)
|
||||
});
|
||||
|
||||
let Some(target) = target else {
|
||||
return RequestOutcome::Unavailable(resolved(request_id, user_id, skin_hash, None));
|
||||
};
|
||||
let request = Message::Text(
|
||||
serde_json::to_string(&ServerMessage::SkinRequested {
|
||||
request_id: request_id.clone(),
|
||||
requester_id: requester_id.to_owned(),
|
||||
skin_hash: skin_hash.clone(),
|
||||
})
|
||||
.expect("skin request serializes")
|
||||
.into(),
|
||||
);
|
||||
match target.sender.try_send(request) {
|
||||
Ok(()) => RequestOutcome::Forwarded,
|
||||
Err(_) => RequestOutcome::Unavailable(resolved(request_id, user_id, skin_hash, None)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn provide(
|
||||
clients: &Clients,
|
||||
provider_id: &str,
|
||||
connection_id: Uuid,
|
||||
request_id: String,
|
||||
requester_id: String,
|
||||
skin_hash: String,
|
||||
data: Option<String>,
|
||||
) -> bool {
|
||||
if data
|
||||
.as_ref()
|
||||
.is_some_and(|data| data.len() > MAX_SKIN_B64_SIZE)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
let clients = clients.lock().await;
|
||||
let Some(provider) = clients
|
||||
.get(provider_id)
|
||||
.filter(|client| client.connection_id == connection_id)
|
||||
.filter(|client| client.profile.skin_hash.as_deref() == Some(&skin_hash))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let Some(requester) = clients
|
||||
.get(&requester_id)
|
||||
.filter(|requester| are_mutual_friends(provider_id, provider, &requester_id, requester))
|
||||
else {
|
||||
return true;
|
||||
};
|
||||
let _ = requester.sender.try_send(resolved(
|
||||
request_id,
|
||||
provider_id.to_owned(),
|
||||
skin_hash,
|
||||
data,
|
||||
));
|
||||
true
|
||||
}
|
||||
|
||||
fn resolved(
|
||||
request_id: String,
|
||||
user_id: String,
|
||||
skin_hash: String,
|
||||
data: Option<String>,
|
||||
) -> Message {
|
||||
Message::Text(
|
||||
serde_json::to_string(&ServerMessage::SkinResolved {
|
||||
request_id,
|
||||
user_id,
|
||||
skin_hash,
|
||||
data,
|
||||
})
|
||||
.expect("skin response serializes")
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use ed25519_dalek::SigningKey;
|
||||
use tokio::sync::mpsc;
|
||||
use wyd_common::Profile;
|
||||
|
||||
use super::*;
|
||||
use crate::network::Client;
|
||||
|
||||
fn client(
|
||||
id: &str,
|
||||
connection_id: Uuid,
|
||||
friends: Vec<String>,
|
||||
skin_hash: Option<String>,
|
||||
sender: mpsc::Sender<Message>,
|
||||
) -> Client {
|
||||
let signing_key = SigningKey::from_bytes(&[7; 32]);
|
||||
Client {
|
||||
connection_id,
|
||||
key: signing_key.verifying_key(),
|
||||
profile: Profile {
|
||||
id: id.to_owned(),
|
||||
display_name: id.to_owned(),
|
||||
skin_hash,
|
||||
},
|
||||
friends,
|
||||
sender,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mutual_friends_can_round_trip_the_advertised_skin() {
|
||||
let requester_id = URL_SAFE_NO_PAD.encode([1_u8; 32]);
|
||||
let provider_id = URL_SAFE_NO_PAD.encode([2_u8; 32]);
|
||||
let skin_hash = "a".repeat(64);
|
||||
let requester_connection = Uuid::new_v4();
|
||||
let provider_connection = Uuid::new_v4();
|
||||
let (requester_sender, mut requester_receiver) = mpsc::channel(2);
|
||||
let (provider_sender, mut provider_receiver) = mpsc::channel(2);
|
||||
let clients = Clients::default();
|
||||
{
|
||||
let mut clients = clients.lock().await;
|
||||
clients.insert(
|
||||
requester_id.clone(),
|
||||
client(
|
||||
&requester_id,
|
||||
requester_connection,
|
||||
vec![provider_id.clone()],
|
||||
None,
|
||||
requester_sender,
|
||||
),
|
||||
);
|
||||
clients.insert(
|
||||
provider_id.clone(),
|
||||
client(
|
||||
&provider_id,
|
||||
provider_connection,
|
||||
vec![requester_id.clone()],
|
||||
Some(skin_hash.clone()),
|
||||
provider_sender,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
assert!(matches!(
|
||||
request(
|
||||
&clients,
|
||||
&requester_id,
|
||||
requester_connection,
|
||||
"request".to_owned(),
|
||||
provider_id.clone(),
|
||||
skin_hash.clone(),
|
||||
)
|
||||
.await,
|
||||
RequestOutcome::Forwarded
|
||||
));
|
||||
let Message::Text(requested) = provider_receiver.recv().await.unwrap() else {
|
||||
panic!("expected skin request")
|
||||
};
|
||||
assert!(matches!(
|
||||
serde_json::from_str(&requested).unwrap(),
|
||||
ServerMessage::SkinRequested { request_id, .. } if request_id == "request"
|
||||
));
|
||||
|
||||
assert!(
|
||||
provide(
|
||||
&clients,
|
||||
&provider_id,
|
||||
provider_connection,
|
||||
"request".to_owned(),
|
||||
requester_id,
|
||||
skin_hash,
|
||||
Some("png".to_owned()),
|
||||
)
|
||||
.await
|
||||
);
|
||||
let Message::Text(resolved) = requester_receiver.recv().await.unwrap() else {
|
||||
panic!("expected skin response")
|
||||
};
|
||||
assert!(matches!(
|
||||
serde_json::from_str(&resolved).unwrap(),
|
||||
ServerMessage::SkinResolved { data: Some(data), .. } if data == "png"
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn request_requires_the_exact_advertised_hash() {
|
||||
let (requester_sender, _requester_receiver) = mpsc::channel(1);
|
||||
let (provider_sender, mut provider_receiver) = mpsc::channel(1);
|
||||
let requester_connection = Uuid::new_v4();
|
||||
let requester_id = "requester".to_owned();
|
||||
let provider_id = "provider".to_owned();
|
||||
let clients = Clients::default();
|
||||
{
|
||||
let mut clients = clients.lock().await;
|
||||
clients.insert(
|
||||
requester_id.clone(),
|
||||
client(
|
||||
&requester_id,
|
||||
requester_connection,
|
||||
vec![provider_id.clone()],
|
||||
None,
|
||||
requester_sender,
|
||||
),
|
||||
);
|
||||
clients.insert(
|
||||
provider_id.clone(),
|
||||
client(
|
||||
&provider_id,
|
||||
Uuid::new_v4(),
|
||||
vec![requester_id.clone()],
|
||||
Some("a".repeat(64)),
|
||||
provider_sender,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
let response = request(
|
||||
&clients,
|
||||
&requester_id,
|
||||
requester_connection,
|
||||
"request".to_owned(),
|
||||
provider_id,
|
||||
"b".repeat(64),
|
||||
)
|
||||
.await;
|
||||
assert!(matches!(response, RequestOutcome::Unavailable(_)));
|
||||
assert!(provider_receiver.try_recv().is_err());
|
||||
}
|
||||
|
||||
async fn request_with_provider_sender(
|
||||
provider_sender: mpsc::Sender<Message>,
|
||||
) -> RequestOutcome {
|
||||
let (requester_sender, _requester_receiver) = mpsc::channel(1);
|
||||
let requester_connection = Uuid::new_v4();
|
||||
let requester_id = "requester".to_owned();
|
||||
let provider_id = "provider".to_owned();
|
||||
let skin_hash = "a".repeat(64);
|
||||
let clients = Clients::default();
|
||||
{
|
||||
let mut clients = clients.lock().await;
|
||||
clients.insert(
|
||||
requester_id.clone(),
|
||||
client(
|
||||
&requester_id,
|
||||
requester_connection,
|
||||
vec![provider_id.clone()],
|
||||
None,
|
||||
requester_sender,
|
||||
),
|
||||
);
|
||||
clients.insert(
|
||||
provider_id.clone(),
|
||||
client(
|
||||
&provider_id,
|
||||
Uuid::new_v4(),
|
||||
vec![requester_id.clone()],
|
||||
Some(skin_hash.clone()),
|
||||
provider_sender,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
request(
|
||||
&clients,
|
||||
&requester_id,
|
||||
requester_connection,
|
||||
"request".to_owned(),
|
||||
provider_id,
|
||||
skin_hash,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn closed_target_queue_returns_an_immediate_response() {
|
||||
let (provider_sender, provider_receiver) = mpsc::channel(1);
|
||||
drop(provider_receiver);
|
||||
|
||||
assert!(matches!(
|
||||
request_with_provider_sender(provider_sender).await,
|
||||
RequestOutcome::Unavailable(_)
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn full_target_queue_returns_an_immediate_response() {
|
||||
let (provider_sender, _provider_receiver) = mpsc::channel(1);
|
||||
provider_sender
|
||||
.try_send(Message::Text("occupied".into()))
|
||||
.unwrap();
|
||||
|
||||
assert!(matches!(
|
||||
request_with_provider_sender(provider_sender).await,
|
||||
RequestOutcome::Unavailable(_)
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,7 @@ tauri-plugin-opener = "2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
base64 = "0.22.1"
|
||||
sha2 = "0.10"
|
||||
image = { version = "0.25", default-features = false, features = ["gif", "jpeg", "png", "webp"] }
|
||||
lazy_static = "1.5.0"
|
||||
ed25519-dalek = "3.0.0"
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE profile ADD COLUMN skin_hash TEXT;
|
||||
ALTER TABLE friends ADD COLUMN skin_hash TEXT;
|
||||
@@ -13,6 +13,7 @@ use crate::keypair::AppKeypair;
|
||||
pub struct Friend {
|
||||
pub id: String,
|
||||
pub display_name: Option<String>,
|
||||
pub skin_hash: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Type, Event)]
|
||||
@@ -23,7 +24,7 @@ pub struct FriendsChanged {
|
||||
|
||||
pub(crate) async fn all(database: &AppDatabase) -> Result<Vec<Friend>, sqlx::Error> {
|
||||
sqlx::query_as::<_, Friend>(
|
||||
"SELECT id, display_name FROM friends \
|
||||
"SELECT id, display_name, skin_hash FROM friends \
|
||||
ORDER BY display_name IS NULL, display_name COLLATE NOCASE, id",
|
||||
)
|
||||
.fetch_all(database.pool())
|
||||
@@ -38,17 +39,26 @@ async fn emit_changed(handle: &AppHandle, database: &AppDatabase) -> Result<(),
|
||||
.map_err(db::command_error)
|
||||
}
|
||||
|
||||
async fn update_display_names(
|
||||
async fn update_profiles(
|
||||
database: &AppDatabase,
|
||||
profiles: &[wyd_common::Profile],
|
||||
) -> Result<bool, sqlx::Error> {
|
||||
let mut transaction = database.pool().begin().await?;
|
||||
let mut changed = false;
|
||||
for profile in profiles {
|
||||
if profile
|
||||
.skin_hash
|
||||
.as_deref()
|
||||
.is_some_and(|hash| !wyd_common::is_skin_hash(hash))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let result = sqlx::query(
|
||||
"UPDATE friends SET display_name = ?1 WHERE id = ?2 AND display_name IS NOT ?1",
|
||||
"UPDATE friends SET display_name = ?1, skin_hash = ?2 \
|
||||
WHERE id = ?3 AND (display_name IS NOT ?1 OR skin_hash IS NOT ?2)",
|
||||
)
|
||||
.bind(&profile.display_name)
|
||||
.bind(&profile.skin_hash)
|
||||
.bind(&profile.id)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
@@ -71,7 +81,7 @@ pub(crate) async fn apply_profile_sync(
|
||||
database: &AppDatabase,
|
||||
profiles: Vec<wyd_common::Profile>,
|
||||
) -> Result<bool, String> {
|
||||
let changed = update_display_names(database, &profiles)
|
||||
let changed = update_profiles(database, &profiles)
|
||||
.await
|
||||
.map_err(db::command_error)?;
|
||||
if changed {
|
||||
@@ -97,6 +107,7 @@ pub async fn create_friend(
|
||||
let friend = Friend {
|
||||
id,
|
||||
display_name: None,
|
||||
skin_hash: None,
|
||||
};
|
||||
sqlx::query("INSERT INTO friends (id, display_name) VALUES (?1, NULL)")
|
||||
.bind(&friend.id)
|
||||
@@ -132,7 +143,7 @@ pub async fn get_friend(
|
||||
database: State<'_, AppDatabase>,
|
||||
id: String,
|
||||
) -> Result<Option<Friend>, String> {
|
||||
sqlx::query_as::<_, Friend>("SELECT id, display_name FROM friends WHERE id = ?1")
|
||||
sqlx::query_as::<_, Friend>("SELECT id, display_name, skin_hash FROM friends WHERE id = ?1")
|
||||
.bind(id)
|
||||
.fetch_optional(database.pool())
|
||||
.await
|
||||
@@ -191,16 +202,18 @@ mod tests {
|
||||
.unwrap();
|
||||
|
||||
assert!(
|
||||
update_display_names(
|
||||
update_profiles(
|
||||
&database,
|
||||
&[
|
||||
wyd_common::Profile {
|
||||
id: "friend-id".to_owned(),
|
||||
display_name: "New".to_owned(),
|
||||
skin_hash: Some("a".repeat(64)),
|
||||
},
|
||||
wyd_common::Profile {
|
||||
id: "missing".to_owned(),
|
||||
display_name: "Name".to_owned(),
|
||||
skin_hash: None,
|
||||
},
|
||||
],
|
||||
)
|
||||
@@ -208,11 +221,12 @@ mod tests {
|
||||
.unwrap()
|
||||
);
|
||||
assert!(
|
||||
!update_display_names(
|
||||
!update_profiles(
|
||||
&database,
|
||||
&[wyd_common::Profile {
|
||||
id: "friend-id".to_owned(),
|
||||
display_name: "New".to_owned(),
|
||||
skin_hash: Some("a".repeat(64)),
|
||||
}],
|
||||
)
|
||||
.await
|
||||
@@ -223,6 +237,7 @@ mod tests {
|
||||
[Friend {
|
||||
id: "friend-id".to_owned(),
|
||||
display_name: Some("New".to_owned()),
|
||||
skin_hash: Some("a".repeat(64)),
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ mod network;
|
||||
mod profile;
|
||||
mod puppet;
|
||||
mod remotes;
|
||||
mod skins;
|
||||
mod ufa;
|
||||
mod ui;
|
||||
mod user;
|
||||
@@ -76,6 +77,7 @@ fn specta_builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
network::list_statuses,
|
||||
network::list_friend_statuses,
|
||||
network::resolve_friend_display_name,
|
||||
skins::resolve_skin,
|
||||
images::pick_and_send_image,
|
||||
images::send_image_bytes,
|
||||
interactions::send_interaction,
|
||||
|
||||
@@ -0,0 +1,392 @@
|
||||
use std::collections::HashMap;
|
||||
use std::time::Duration;
|
||||
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use tauri::{AppHandle, Manager};
|
||||
use tokio::sync::{mpsc, oneshot, watch};
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
use wyd_common::{
|
||||
ClientMessage, InteractionDeliveryStatus, Profile, ServerMessage, friends_bytes,
|
||||
interaction_bytes, message_bytes, profile_bytes, register_bytes,
|
||||
};
|
||||
|
||||
use super::presence::FriendPresence;
|
||||
use super::{
|
||||
ConnectionState, Statuses, apply_friend_presence_change, changed, update_friend_presence,
|
||||
};
|
||||
use crate::db::AppDatabase;
|
||||
use crate::friends;
|
||||
use crate::interactions;
|
||||
use crate::keypair::AppKeypair;
|
||||
use crate::live_data::LiveData;
|
||||
use crate::remotes::Remote;
|
||||
|
||||
pub(super) struct InteractionRequest {
|
||||
pub(super) interaction_id: String,
|
||||
pub(super) recipient_id: String,
|
||||
pub(super) payload: String,
|
||||
pub(super) response: oneshot::Sender<InteractionDeliveryStatus>,
|
||||
}
|
||||
|
||||
pub(super) struct ProfileLookupRequest {
|
||||
pub(super) request_id: String,
|
||||
pub(super) user_id: String,
|
||||
pub(super) response: oneshot::Sender<Option<String>>,
|
||||
}
|
||||
|
||||
pub(super) struct SkinLookupRequest {
|
||||
pub(super) request_id: String,
|
||||
pub(super) user_id: String,
|
||||
pub(super) skin_hash: String,
|
||||
pub(super) response: oneshot::Sender<Option<String>>,
|
||||
}
|
||||
|
||||
pub(super) struct ConnectionInputs {
|
||||
pub(super) profiles: watch::Receiver<crate::user::User>,
|
||||
pub(super) friends: watch::Receiver<Vec<String>>,
|
||||
pub(super) keypair: AppKeypair,
|
||||
pub(super) live_data: mpsc::Receiver<String>,
|
||||
pub(super) interactions: mpsc::Receiver<InteractionRequest>,
|
||||
pub(super) profile_lookups: mpsc::Receiver<ProfileLookupRequest>,
|
||||
pub(super) skin_lookups: mpsc::Receiver<SkinLookupRequest>,
|
||||
}
|
||||
|
||||
pub(super) async fn run(
|
||||
handle: AppHandle,
|
||||
statuses: Statuses,
|
||||
friend_presence: std::sync::Arc<FriendPresence>,
|
||||
remote: Remote,
|
||||
generation: u64,
|
||||
mut inputs: ConnectionInputs,
|
||||
) {
|
||||
loop {
|
||||
changed(
|
||||
&handle,
|
||||
&statuses,
|
||||
&remote,
|
||||
generation,
|
||||
ConnectionState::Connecting,
|
||||
);
|
||||
if let Err(error) = connect(
|
||||
&handle,
|
||||
&statuses,
|
||||
&friend_presence,
|
||||
&remote,
|
||||
generation,
|
||||
&mut inputs,
|
||||
)
|
||||
.await
|
||||
{
|
||||
eprintln!("remote {} disconnected: {error}", remote.id);
|
||||
}
|
||||
apply_friend_presence_change(&handle, friend_presence.remove(&remote.id));
|
||||
changed(
|
||||
&handle,
|
||||
&statuses,
|
||||
&remote,
|
||||
generation,
|
||||
ConnectionState::Disconnected,
|
||||
);
|
||||
tokio::time::sleep(Duration::from_secs(5)).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn connect(
|
||||
handle: &AppHandle,
|
||||
statuses: &Statuses,
|
||||
friend_presence: &FriendPresence,
|
||||
remote: &Remote,
|
||||
generation: u64,
|
||||
inputs: &mut ConnectionInputs,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
let ConnectionInputs {
|
||||
profiles,
|
||||
friends,
|
||||
keypair,
|
||||
live_data,
|
||||
interactions: active_outgoing,
|
||||
profile_lookups,
|
||||
skin_lookups,
|
||||
} = inputs;
|
||||
let (socket, _) = tokio_tungstenite::connect_async(url(remote)).await?;
|
||||
let (mut writer, mut reader) = socket.split();
|
||||
|
||||
let challenge = match recv(&mut reader).await? {
|
||||
ServerMessage::Challenge { version, challenge } if version == wyd_common::VERSION => {
|
||||
challenge
|
||||
}
|
||||
_ => return Err("server did not send a compatible challenge".into()),
|
||||
};
|
||||
let current = profiles.borrow_and_update().clone();
|
||||
let registration_profile = Profile {
|
||||
id: current.id,
|
||||
display_name: current.display_name,
|
||||
skin_hash: current.skin_hash,
|
||||
};
|
||||
let registration_friends = friends.borrow_and_update().clone();
|
||||
send(
|
||||
&mut writer,
|
||||
&ClientMessage::Register {
|
||||
signature: keypair.sign(®ister_bytes(
|
||||
&challenge,
|
||||
®istration_profile,
|
||||
®istration_friends,
|
||||
)),
|
||||
profile: registration_profile,
|
||||
friends: registration_friends,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
if !matches!(recv(&mut reader).await?, ServerMessage::Registered) {
|
||||
return Err("server rejected registration".into());
|
||||
}
|
||||
while live_data.try_recv().is_ok() {}
|
||||
while let Ok(request) = active_outgoing.try_recv() {
|
||||
let _ = request
|
||||
.response
|
||||
.send(InteractionDeliveryStatus::Unavailable);
|
||||
}
|
||||
send(&mut writer, &ClientMessage::SyncFriendProfiles).await?;
|
||||
send(&mut writer, &ClientMessage::SyncFriendStatuses).await?;
|
||||
changed(
|
||||
handle,
|
||||
statuses,
|
||||
remote,
|
||||
generation,
|
||||
ConnectionState::Connected,
|
||||
);
|
||||
|
||||
let mut pending_interactions = HashMap::new();
|
||||
let mut pending_profile_lookups: HashMap<String, (String, oneshot::Sender<Option<String>>)> =
|
||||
HashMap::new();
|
||||
let mut pending_skin_lookups: HashMap<
|
||||
String,
|
||||
(String, String, oneshot::Sender<Option<String>>),
|
||||
> = HashMap::new();
|
||||
loop {
|
||||
tokio::select! {
|
||||
payload = live_data.recv() => {
|
||||
let payload = payload.ok_or("network sender closed")?;
|
||||
send(&mut writer, &ClientMessage::Signed {
|
||||
signature: keypair.sign(&message_bytes(&payload)),
|
||||
payload,
|
||||
}).await?;
|
||||
}
|
||||
request = active_outgoing.recv() => {
|
||||
let request = request.ok_or("interaction sender closed")?;
|
||||
let signature = keypair.sign(&interaction_bytes(
|
||||
&request.interaction_id,
|
||||
&request.recipient_id,
|
||||
&request.payload,
|
||||
));
|
||||
send(&mut writer, &ClientMessage::Interaction {
|
||||
interaction_id: request.interaction_id.clone(),
|
||||
recipient_id: request.recipient_id,
|
||||
payload: request.payload,
|
||||
signature,
|
||||
}).await?;
|
||||
pending_interactions.insert(request.interaction_id, request.response);
|
||||
}
|
||||
request = profile_lookups.recv() => {
|
||||
let request = request.ok_or("profile lookup sender closed")?;
|
||||
if request.response.is_closed() {
|
||||
continue;
|
||||
}
|
||||
pending_profile_lookups.retain(|_, (_, response)| !response.is_closed());
|
||||
send(&mut writer, &ClientMessage::ResolveProfile {
|
||||
request_id: request.request_id.clone(),
|
||||
user_id: request.user_id.clone(),
|
||||
}).await?;
|
||||
pending_profile_lookups.insert(
|
||||
request.request_id,
|
||||
(request.user_id, request.response),
|
||||
);
|
||||
}
|
||||
request = skin_lookups.recv() => {
|
||||
let request = request.ok_or("skin lookup sender closed")?;
|
||||
if request.response.is_closed() {
|
||||
continue;
|
||||
}
|
||||
pending_skin_lookups.retain(|_, (_, _, response)| !response.is_closed());
|
||||
send(&mut writer, &ClientMessage::RequestSkin {
|
||||
request_id: request.request_id.clone(),
|
||||
user_id: request.user_id.clone(),
|
||||
skin_hash: request.skin_hash.clone(),
|
||||
}).await?;
|
||||
pending_skin_lookups.insert(
|
||||
request.request_id,
|
||||
(request.user_id, request.skin_hash, request.response),
|
||||
);
|
||||
}
|
||||
changed = profiles.changed() => {
|
||||
changed.map_err(|_| "profile sender closed")?;
|
||||
let current = profiles.borrow_and_update().clone();
|
||||
let profile = Profile {
|
||||
id: current.id,
|
||||
display_name: current.display_name,
|
||||
skin_hash: current.skin_hash,
|
||||
};
|
||||
send(&mut writer, &ClientMessage::ProfileUpdated {
|
||||
signature: keypair.sign(&profile_bytes(&profile)),
|
||||
profile,
|
||||
}).await?;
|
||||
}
|
||||
changed = friends.changed() => {
|
||||
changed.map_err(|_| "friends sender closed")?;
|
||||
let friends = friends.borrow_and_update().clone();
|
||||
send(&mut writer, &ClientMessage::FriendsUpdated {
|
||||
signature: keypair.sign(&friends_bytes(&friends)),
|
||||
friends,
|
||||
}).await?;
|
||||
}
|
||||
message = reader.next() => match message.ok_or("server closed the socket")?? {
|
||||
Message::Text(text) => match serde_json::from_str(&text)? {
|
||||
ServerMessage::FriendProfileUpdated { profile } => {
|
||||
let database = handle.state::<AppDatabase>();
|
||||
if let Err(error) = friends::apply_profile_update(handle, &database, profile).await {
|
||||
eprintln!("failed to update friend profile: {error}");
|
||||
}
|
||||
}
|
||||
ServerMessage::FriendProfiles { profiles } => {
|
||||
let database = handle.state::<AppDatabase>();
|
||||
if let Err(error) = friends::apply_profile_sync(handle, &database, profiles).await {
|
||||
eprintln!("failed to synchronize friend profiles: {error}");
|
||||
}
|
||||
}
|
||||
ServerMessage::FriendStatusChanged { friend_id, online } => {
|
||||
update_friend_presence(
|
||||
handle,
|
||||
friend_presence,
|
||||
&remote.id,
|
||||
friend_id,
|
||||
online,
|
||||
);
|
||||
}
|
||||
ServerMessage::FriendStatuses { friend_ids } => {
|
||||
apply_friend_presence_change(
|
||||
handle,
|
||||
friend_presence.replace(&remote.id, friend_ids),
|
||||
);
|
||||
}
|
||||
ServerMessage::FriendLiveData { friend_id, payload } => {
|
||||
match serde_json::from_str(&payload) {
|
||||
Ok(LiveData::Cursor { positions }) => {
|
||||
crate::cursor::emit_position(handle, friend_id, positions);
|
||||
}
|
||||
Ok(LiveData::ForegroundApp { meta }) => {
|
||||
crate::ufa::emit_friend_app(handle, friend_id, meta);
|
||||
}
|
||||
Err(error) => {
|
||||
eprintln!("failed to decode friend live data: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
ServerMessage::FriendInteraction {
|
||||
interaction_id,
|
||||
friend_id,
|
||||
payload,
|
||||
} => {
|
||||
interactions::receive(handle, interaction_id, friend_id, &payload);
|
||||
}
|
||||
ServerMessage::InteractionDelivery { interaction_id, status } => {
|
||||
if let Some(response) = pending_interactions.remove(&interaction_id) {
|
||||
let _ = response.send(status);
|
||||
}
|
||||
}
|
||||
ServerMessage::ProfileResolved { request_id, profile } => {
|
||||
if let Some((user_id, response)) = pending_profile_lookups.remove(&request_id) {
|
||||
let display_name = profile
|
||||
.filter(|profile| profile.id == user_id)
|
||||
.map(|profile| profile.display_name);
|
||||
let _ = response.send(display_name);
|
||||
}
|
||||
}
|
||||
ServerMessage::SkinRequested {
|
||||
request_id,
|
||||
requester_id,
|
||||
skin_hash,
|
||||
} => {
|
||||
let data = profiles
|
||||
.borrow()
|
||||
.skin_hash
|
||||
.as_deref()
|
||||
.filter(|current_hash| *current_hash == skin_hash)
|
||||
.and_then(|_| crate::skins::read_local_base64(handle, &skin_hash));
|
||||
send(&mut writer, &ClientMessage::ProvideSkin {
|
||||
request_id,
|
||||
requester_id,
|
||||
skin_hash,
|
||||
data,
|
||||
}).await?;
|
||||
}
|
||||
ServerMessage::SkinResolved {
|
||||
request_id,
|
||||
user_id,
|
||||
skin_hash,
|
||||
data,
|
||||
} => {
|
||||
if let Some((expected_user_id, expected_hash, response)) =
|
||||
pending_skin_lookups.remove(&request_id)
|
||||
{
|
||||
let data = (user_id == expected_user_id && skin_hash == expected_hash)
|
||||
.then_some(data)
|
||||
.flatten();
|
||||
let _ = response.send(data);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Message::Ping(data) => writer.send(Message::Pong(data)).await?,
|
||||
Message::Close(_) => return Ok(()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn send<S>(
|
||||
writer: &mut S,
|
||||
message: &ClientMessage,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>>
|
||||
where
|
||||
S: futures_util::Sink<Message> + Unpin,
|
||||
S::Error: std::error::Error + Send + Sync + 'static,
|
||||
{
|
||||
writer
|
||||
.send(Message::Text(serde_json::to_string(message)?.into()))
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn recv<S>(reader: &mut S) -> Result<ServerMessage, Box<dyn std::error::Error + Send + Sync>>
|
||||
where
|
||||
S: futures_util::Stream<Item = Result<Message, tokio_tungstenite::tungstenite::Error>> + Unpin,
|
||||
{
|
||||
while let Some(message) = reader.next().await {
|
||||
if let Message::Text(text) = message? {
|
||||
return Ok(serde_json::from_str(&text)?);
|
||||
}
|
||||
}
|
||||
Err("server closed the socket".into())
|
||||
}
|
||||
|
||||
fn url(remote: &Remote) -> String {
|
||||
let address = remote.address.trim_end_matches('/');
|
||||
let address = address
|
||||
.strip_prefix("http://")
|
||||
.or_else(|| address.strip_prefix("https://"))
|
||||
.or_else(|| address.strip_prefix("ws://"))
|
||||
.or_else(|| address.strip_prefix("wss://"))
|
||||
.unwrap_or(address);
|
||||
let scheme = if remote.address.starts_with("https://") || remote.address.starts_with("wss://") {
|
||||
"wss"
|
||||
} else {
|
||||
"ws"
|
||||
};
|
||||
let port = remote
|
||||
.port
|
||||
.map(|port| format!(":{port}"))
|
||||
.unwrap_or_default();
|
||||
format!("{scheme}://{address}{port}/v1/ws")
|
||||
}
|
||||
+63
-314
@@ -3,28 +3,25 @@ use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use futures_util::StreamExt;
|
||||
use futures_util::stream::FuturesUnordered;
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use tauri::{AppHandle, Manager, State};
|
||||
use tauri_specta::Event;
|
||||
use tokio::sync::{mpsc, oneshot, watch};
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
use wyd_common::{
|
||||
ClientMessage, InteractionContent, InteractionDeliveryStatus, Profile, ServerMessage,
|
||||
friends_bytes, interaction_bytes, message_bytes, profile_bytes, register_bytes,
|
||||
};
|
||||
use wyd_common::{InteractionContent, InteractionDeliveryStatus};
|
||||
|
||||
use crate::db::AppDatabase;
|
||||
use crate::friends::{self, FriendsChanged};
|
||||
use crate::interactions;
|
||||
use crate::keypair::AppKeypair;
|
||||
use crate::live_data::LiveData;
|
||||
use crate::remotes::{self, Remote, RemotesChanged};
|
||||
|
||||
mod connection;
|
||||
mod presence;
|
||||
|
||||
use connection::{ConnectionInputs, InteractionRequest, ProfileLookupRequest, SkinLookupRequest};
|
||||
use presence::{Change as FriendPresenceChange, FriendPresence};
|
||||
|
||||
type Statuses = Arc<Mutex<HashMap<String, (u64, ConnectionStatus)>>>;
|
||||
@@ -63,32 +60,11 @@ struct Connection {
|
||||
sender: mpsc::Sender<String>,
|
||||
interaction_sender: mpsc::Sender<InteractionRequest>,
|
||||
profile_lookup_sender: mpsc::Sender<ProfileLookupRequest>,
|
||||
skin_lookup_sender: mpsc::Sender<SkinLookupRequest>,
|
||||
task: tauri::async_runtime::JoinHandle<()>,
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
struct InteractionRequest {
|
||||
interaction_id: String,
|
||||
recipient_id: String,
|
||||
payload: String,
|
||||
response: oneshot::Sender<InteractionDeliveryStatus>,
|
||||
}
|
||||
|
||||
struct ProfileLookupRequest {
|
||||
request_id: String,
|
||||
user_id: String,
|
||||
response: oneshot::Sender<Option<String>>,
|
||||
}
|
||||
|
||||
struct ConnectionInputs {
|
||||
profiles: watch::Receiver<crate::user::User>,
|
||||
friends: watch::Receiver<Vec<String>>,
|
||||
keypair: AppKeypair,
|
||||
live_data: mpsc::Receiver<String>,
|
||||
interactions: mpsc::Receiver<InteractionRequest>,
|
||||
profile_lookups: mpsc::Receiver<ProfileLookupRequest>,
|
||||
}
|
||||
|
||||
pub struct Network {
|
||||
connections: Mutex<HashMap<String, Connection>>,
|
||||
statuses: Statuses,
|
||||
@@ -100,6 +76,10 @@ pub struct Network {
|
||||
}
|
||||
|
||||
impl Network {
|
||||
pub(crate) fn public_key(&self) -> &str {
|
||||
self.keypair.public_key()
|
||||
}
|
||||
|
||||
pub fn send_live_data(&self, data: LiveData) {
|
||||
let Ok(payload) = serde_json::to_string(&data) else {
|
||||
eprintln!("failed to serialize live data");
|
||||
@@ -222,6 +202,53 @@ impl Network {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub(crate) async fn request_skin(
|
||||
&self,
|
||||
user_id: String,
|
||||
skin_hash: String,
|
||||
) -> Result<Option<Vec<u8>>, String> {
|
||||
if user_id == self.keypair.public_key() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let senders: Vec<_> = self
|
||||
.connections
|
||||
.lock()
|
||||
.map_err(|error| error.to_string())?
|
||||
.values()
|
||||
.map(|connection| connection.skin_lookup_sender.clone())
|
||||
.collect();
|
||||
let request_id = uuid::Uuid::new_v4().to_string();
|
||||
let mut responses = Vec::new();
|
||||
for sender in senders {
|
||||
let (response, receiver) = oneshot::channel();
|
||||
if sender
|
||||
.try_send(SkinLookupRequest {
|
||||
request_id: request_id.clone(),
|
||||
user_id: user_id.clone(),
|
||||
skin_hash: skin_hash.clone(),
|
||||
response,
|
||||
})
|
||||
.is_ok()
|
||||
{
|
||||
responses.push(receiver);
|
||||
}
|
||||
}
|
||||
|
||||
let mut pending: FuturesUnordered<_> = responses
|
||||
.into_iter()
|
||||
.map(|response| tokio::time::timeout(Duration::from_secs(3), response))
|
||||
.collect();
|
||||
while let Some(result) = pending.next().await {
|
||||
if let Ok(Ok(Some(data))) = result
|
||||
&& let Some(bytes) = crate::skins::decode_response(&data, &skin_hash)
|
||||
{
|
||||
return Ok(Some(bytes));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn sync_remotes(&self, handle: &AppHandle, remotes: Vec<Remote>) -> Result<(), String> {
|
||||
let desired: HashMap<_, _> = remotes
|
||||
.into_iter()
|
||||
@@ -252,13 +279,14 @@ impl Network {
|
||||
let (sender, receiver) = mpsc::channel(32);
|
||||
let (interaction_sender, interaction_receiver) = mpsc::channel(16);
|
||||
let (profile_lookup_sender, profile_lookup_receiver) = mpsc::channel(16);
|
||||
let (skin_lookup_sender, skin_lookup_receiver) = mpsc::channel(16);
|
||||
set_initial(
|
||||
&self.statuses,
|
||||
&remote,
|
||||
generation,
|
||||
ConnectionState::Connecting,
|
||||
);
|
||||
let task = tauri::async_runtime::spawn(run(
|
||||
let task = tauri::async_runtime::spawn(connection::run(
|
||||
handle.clone(),
|
||||
self.statuses.clone(),
|
||||
self.friend_presence.clone(),
|
||||
@@ -271,6 +299,7 @@ impl Network {
|
||||
live_data: receiver,
|
||||
interactions: interaction_receiver,
|
||||
profile_lookups: profile_lookup_receiver,
|
||||
skin_lookups: skin_lookup_receiver,
|
||||
},
|
||||
));
|
||||
connections.insert(
|
||||
@@ -280,6 +309,7 @@ impl Network {
|
||||
sender,
|
||||
interaction_sender,
|
||||
profile_lookup_sender,
|
||||
skin_lookup_sender,
|
||||
task,
|
||||
generation,
|
||||
},
|
||||
@@ -334,244 +364,6 @@ pub async fn init(handle: &AppHandle) -> Result<(), Box<dyn std::error::Error>>
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run(
|
||||
handle: AppHandle,
|
||||
statuses: Statuses,
|
||||
friend_presence: Arc<FriendPresence>,
|
||||
remote: Remote,
|
||||
generation: u64,
|
||||
mut inputs: ConnectionInputs,
|
||||
) {
|
||||
loop {
|
||||
changed(
|
||||
&handle,
|
||||
&statuses,
|
||||
&remote,
|
||||
generation,
|
||||
ConnectionState::Connecting,
|
||||
);
|
||||
if let Err(error) = connect(
|
||||
&handle,
|
||||
&statuses,
|
||||
&friend_presence,
|
||||
&remote,
|
||||
generation,
|
||||
&mut inputs,
|
||||
)
|
||||
.await
|
||||
{
|
||||
eprintln!("remote {} disconnected: {error}", remote.id);
|
||||
}
|
||||
apply_friend_presence_change(&handle, friend_presence.remove(&remote.id));
|
||||
changed(
|
||||
&handle,
|
||||
&statuses,
|
||||
&remote,
|
||||
generation,
|
||||
ConnectionState::Disconnected,
|
||||
);
|
||||
tokio::time::sleep(Duration::from_secs(5)).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn connect(
|
||||
handle: &AppHandle,
|
||||
statuses: &Statuses,
|
||||
friend_presence: &FriendPresence,
|
||||
remote: &Remote,
|
||||
generation: u64,
|
||||
inputs: &mut ConnectionInputs,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
let ConnectionInputs {
|
||||
profiles,
|
||||
friends,
|
||||
keypair,
|
||||
live_data,
|
||||
interactions: active_outgoing,
|
||||
profile_lookups,
|
||||
} = inputs;
|
||||
let (socket, _) = tokio_tungstenite::connect_async(url(remote)).await?;
|
||||
let (mut writer, mut reader) = socket.split();
|
||||
|
||||
let challenge = match recv(&mut reader).await? {
|
||||
ServerMessage::Challenge { version, challenge } if version == wyd_common::VERSION => {
|
||||
challenge
|
||||
}
|
||||
_ => return Err("server did not send a compatible challenge".into()),
|
||||
};
|
||||
let current = profiles.borrow_and_update().clone();
|
||||
let registration_profile = Profile {
|
||||
id: current.id,
|
||||
display_name: current.display_name,
|
||||
};
|
||||
let registration_friends = friends.borrow_and_update().clone();
|
||||
send(
|
||||
&mut writer,
|
||||
&ClientMessage::Register {
|
||||
signature: keypair.sign(®ister_bytes(
|
||||
&challenge,
|
||||
®istration_profile,
|
||||
®istration_friends,
|
||||
)),
|
||||
profile: registration_profile,
|
||||
friends: registration_friends,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
if !matches!(recv(&mut reader).await?, ServerMessage::Registered) {
|
||||
return Err("server rejected registration".into());
|
||||
}
|
||||
while live_data.try_recv().is_ok() {}
|
||||
while let Ok(request) = active_outgoing.try_recv() {
|
||||
let _ = request
|
||||
.response
|
||||
.send(InteractionDeliveryStatus::Unavailable);
|
||||
}
|
||||
send(&mut writer, &ClientMessage::SyncFriendProfiles).await?;
|
||||
send(&mut writer, &ClientMessage::SyncFriendStatuses).await?;
|
||||
changed(
|
||||
handle,
|
||||
statuses,
|
||||
remote,
|
||||
generation,
|
||||
ConnectionState::Connected,
|
||||
);
|
||||
|
||||
let mut pending_interactions = HashMap::new();
|
||||
let mut pending_profile_lookups: HashMap<String, (String, oneshot::Sender<Option<String>>)> =
|
||||
HashMap::new();
|
||||
loop {
|
||||
tokio::select! {
|
||||
payload = live_data.recv() => {
|
||||
let payload = payload.ok_or("network sender closed")?;
|
||||
send(&mut writer, &ClientMessage::Signed {
|
||||
signature: keypair.sign(&message_bytes(&payload)),
|
||||
payload,
|
||||
}).await?;
|
||||
}
|
||||
request = active_outgoing.recv() => {
|
||||
let request = request.ok_or("interaction sender closed")?;
|
||||
let signature = keypair.sign(&interaction_bytes(
|
||||
&request.interaction_id,
|
||||
&request.recipient_id,
|
||||
&request.payload,
|
||||
));
|
||||
send(&mut writer, &ClientMessage::Interaction {
|
||||
interaction_id: request.interaction_id.clone(),
|
||||
recipient_id: request.recipient_id,
|
||||
payload: request.payload,
|
||||
signature,
|
||||
}).await?;
|
||||
pending_interactions.insert(request.interaction_id, request.response);
|
||||
}
|
||||
request = profile_lookups.recv() => {
|
||||
let request = request.ok_or("profile lookup sender closed")?;
|
||||
if request.response.is_closed() {
|
||||
continue;
|
||||
}
|
||||
pending_profile_lookups.retain(|_, (_, response)| !response.is_closed());
|
||||
send(&mut writer, &ClientMessage::ResolveProfile {
|
||||
request_id: request.request_id.clone(),
|
||||
user_id: request.user_id.clone(),
|
||||
}).await?;
|
||||
pending_profile_lookups.insert(
|
||||
request.request_id,
|
||||
(request.user_id, request.response),
|
||||
);
|
||||
}
|
||||
changed = profiles.changed() => {
|
||||
changed.map_err(|_| "profile sender closed")?;
|
||||
let current = profiles.borrow_and_update().clone();
|
||||
let profile = Profile {
|
||||
id: current.id,
|
||||
display_name: current.display_name,
|
||||
};
|
||||
send(&mut writer, &ClientMessage::ProfileUpdated {
|
||||
signature: keypair.sign(&profile_bytes(&profile)),
|
||||
profile,
|
||||
}).await?;
|
||||
}
|
||||
changed = friends.changed() => {
|
||||
changed.map_err(|_| "friends sender closed")?;
|
||||
let friends = friends.borrow_and_update().clone();
|
||||
send(&mut writer, &ClientMessage::FriendsUpdated {
|
||||
signature: keypair.sign(&friends_bytes(&friends)),
|
||||
friends,
|
||||
}).await?;
|
||||
}
|
||||
message = reader.next() => match message.ok_or("server closed the socket")?? {
|
||||
Message::Text(text) => match serde_json::from_str(&text)? {
|
||||
ServerMessage::FriendProfileUpdated { profile } => {
|
||||
let database = handle.state::<AppDatabase>();
|
||||
if let Err(error) = friends::apply_profile_update(handle, &database, profile).await {
|
||||
eprintln!("failed to update friend profile: {error}");
|
||||
}
|
||||
}
|
||||
ServerMessage::FriendProfiles { profiles } => {
|
||||
let database = handle.state::<AppDatabase>();
|
||||
if let Err(error) = friends::apply_profile_sync(handle, &database, profiles).await {
|
||||
eprintln!("failed to synchronize friend profiles: {error}");
|
||||
}
|
||||
}
|
||||
ServerMessage::FriendStatusChanged { friend_id, online } => {
|
||||
update_friend_presence(
|
||||
handle,
|
||||
friend_presence,
|
||||
&remote.id,
|
||||
friend_id,
|
||||
online,
|
||||
);
|
||||
}
|
||||
ServerMessage::FriendStatuses { friend_ids } => {
|
||||
apply_friend_presence_change(
|
||||
handle,
|
||||
friend_presence.replace(&remote.id, friend_ids),
|
||||
);
|
||||
}
|
||||
ServerMessage::FriendLiveData { friend_id, payload } => {
|
||||
match serde_json::from_str(&payload) {
|
||||
Ok(LiveData::Cursor { positions }) => {
|
||||
crate::cursor::emit_position(handle, friend_id, positions);
|
||||
}
|
||||
Ok(LiveData::ForegroundApp { meta }) => {
|
||||
crate::ufa::emit_friend_app(handle, friend_id, meta);
|
||||
}
|
||||
Err(error) => {
|
||||
eprintln!("failed to decode friend live data: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
ServerMessage::FriendInteraction {
|
||||
interaction_id,
|
||||
friend_id,
|
||||
payload,
|
||||
} => {
|
||||
interactions::receive(handle, interaction_id, friend_id, &payload);
|
||||
}
|
||||
ServerMessage::InteractionDelivery { interaction_id, status } => {
|
||||
if let Some(response) = pending_interactions.remove(&interaction_id) {
|
||||
let _ = response.send(status);
|
||||
}
|
||||
}
|
||||
ServerMessage::ProfileResolved { request_id, profile } => {
|
||||
if let Some((user_id, response)) = pending_profile_lookups.remove(&request_id) {
|
||||
let display_name = profile
|
||||
.filter(|profile| profile.id == user_id)
|
||||
.map(|profile| profile.display_name);
|
||||
let _ = response.send(display_name);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Message::Ping(data) => writer.send(Message::Pong(data)).await?,
|
||||
Message::Close(_) => return Ok(()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn list_statuses(
|
||||
@@ -702,52 +494,6 @@ fn snapshot(statuses: &Statuses) -> Result<Vec<ConnectionStatus>, String> {
|
||||
Ok(statuses)
|
||||
}
|
||||
|
||||
async fn send<S>(
|
||||
writer: &mut S,
|
||||
message: &ClientMessage,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>>
|
||||
where
|
||||
S: futures_util::Sink<Message> + Unpin,
|
||||
S::Error: std::error::Error + Send + Sync + 'static,
|
||||
{
|
||||
writer
|
||||
.send(Message::Text(serde_json::to_string(message)?.into()))
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn recv<S>(reader: &mut S) -> Result<ServerMessage, Box<dyn std::error::Error + Send + Sync>>
|
||||
where
|
||||
S: futures_util::Stream<Item = Result<Message, tokio_tungstenite::tungstenite::Error>> + Unpin,
|
||||
{
|
||||
while let Some(message) = reader.next().await {
|
||||
if let Message::Text(text) = message? {
|
||||
return Ok(serde_json::from_str(&text)?);
|
||||
}
|
||||
}
|
||||
Err("server closed the socket".into())
|
||||
}
|
||||
|
||||
fn url(remote: &Remote) -> String {
|
||||
let address = remote.address.trim_end_matches('/');
|
||||
let address = address
|
||||
.strip_prefix("http://")
|
||||
.or_else(|| address.strip_prefix("https://"))
|
||||
.or_else(|| address.strip_prefix("ws://"))
|
||||
.or_else(|| address.strip_prefix("wss://"))
|
||||
.unwrap_or(address);
|
||||
let scheme = if remote.address.starts_with("https://") || remote.address.starts_with("wss://") {
|
||||
"wss"
|
||||
} else {
|
||||
"ws"
|
||||
};
|
||||
let port = remote
|
||||
.port
|
||||
.map(|port| format!(":{port}"))
|
||||
.unwrap_or_default();
|
||||
format!("{scheme}://{address}{port}/v1/ws")
|
||||
}
|
||||
|
||||
fn friend_ids(friends: Vec<crate::friends::Friend>, own_id: &str) -> Vec<String> {
|
||||
let mut ids: Vec<_> = friends
|
||||
.into_iter()
|
||||
@@ -770,14 +516,17 @@ mod tests {
|
||||
Friend {
|
||||
id: "friend-b".to_owned(),
|
||||
display_name: Some("Old name".to_owned()),
|
||||
skin_hash: None,
|
||||
},
|
||||
Friend {
|
||||
id: "self".to_owned(),
|
||||
display_name: None,
|
||||
skin_hash: None,
|
||||
},
|
||||
Friend {
|
||||
id: "friend-a".to_owned(),
|
||||
display_name: Some("Any name".to_owned()),
|
||||
skin_hash: None,
|
||||
},
|
||||
];
|
||||
|
||||
|
||||
@@ -16,19 +16,21 @@ pub struct ProfileChanged {
|
||||
}
|
||||
|
||||
pub async fn get(database: &AppDatabase, public_key: &str) -> Result<User, sqlx::Error> {
|
||||
let display_name =
|
||||
sqlx::query_scalar::<_, String>("SELECT display_name FROM profile WHERE id = ?1")
|
||||
.bind(PROFILE_ID)
|
||||
.fetch_one(database.pool())
|
||||
.await?;
|
||||
let (display_name, skin_hash) = sqlx::query_as::<_, (String, Option<String>)>(
|
||||
"SELECT display_name, skin_hash FROM profile WHERE id = ?1",
|
||||
)
|
||||
.bind(PROFILE_ID)
|
||||
.fetch_one(database.pool())
|
||||
.await?;
|
||||
|
||||
Ok(User {
|
||||
id: public_key.to_owned(),
|
||||
display_name: if display_name.len() <= 0 {
|
||||
display_name: if display_name.is_empty() {
|
||||
"Anonymous".to_string()
|
||||
} else {
|
||||
display_name
|
||||
},
|
||||
skin_hash,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -36,12 +38,16 @@ async fn update(
|
||||
database: &AppDatabase,
|
||||
public_key: &str,
|
||||
display_name: String,
|
||||
skin_hash: Option<String>,
|
||||
) -> Result<User, sqlx::Error> {
|
||||
sqlx::query("UPDATE profile SET display_name = ?1 WHERE id = ?2")
|
||||
.bind(display_name)
|
||||
.bind(PROFILE_ID)
|
||||
.execute(database.pool())
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"UPDATE profile SET display_name = ?1, skin_hash = COALESCE(?2, skin_hash) WHERE id = ?3",
|
||||
)
|
||||
.bind(display_name)
|
||||
.bind(skin_hash)
|
||||
.bind(PROFILE_ID)
|
||||
.execute(database.pool())
|
||||
.await?;
|
||||
|
||||
get(database, public_key).await
|
||||
}
|
||||
@@ -74,8 +80,13 @@ pub async fn update_profile(
|
||||
keypair: State<'_, AppKeypair>,
|
||||
network: State<'_, Network>,
|
||||
display_name: String,
|
||||
skin_data: Option<Vec<u8>>,
|
||||
) -> Result<User, String> {
|
||||
let profile = update(&database, keypair.public_key(), display_name)
|
||||
let skin_hash = skin_data
|
||||
.as_deref()
|
||||
.map(|data| crate::skins::store_local(&handle, data))
|
||||
.transpose()?;
|
||||
let profile = update(&database, keypair.public_key(), display_name, skin_hash)
|
||||
.await
|
||||
.map_err(db::command_error)?;
|
||||
network.update_profile(profile.clone());
|
||||
@@ -106,7 +117,7 @@ mod tests {
|
||||
async fn profile_uses_the_supplied_keypair_identity() {
|
||||
let database = database().await;
|
||||
|
||||
let profile = update(&database, "public-key", "Wind".to_owned())
|
||||
let profile = update(&database, "public-key", "Wind".to_owned(), None)
|
||||
.await
|
||||
.expect("update profile");
|
||||
|
||||
@@ -115,6 +126,7 @@ mod tests {
|
||||
User {
|
||||
id: "public-key".to_owned(),
|
||||
display_name: "Wind".to_owned(),
|
||||
skin_hash: None,
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -122,8 +134,20 @@ mod tests {
|
||||
User {
|
||||
id: "rotated-public-key".to_owned(),
|
||||
display_name: "Wind".to_owned(),
|
||||
skin_hash: None,
|
||||
}
|
||||
);
|
||||
|
||||
let profile = update(
|
||||
&database,
|
||||
"public-key",
|
||||
"Wind Two".to_owned(),
|
||||
Some("a".repeat(64)),
|
||||
)
|
||||
.await
|
||||
.expect("update profile and skin together");
|
||||
assert_eq!(profile.display_name, "Wind Two");
|
||||
assert_eq!(profile.skin_hash, Some("a".repeat(64)));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -136,6 +160,6 @@ mod tests {
|
||||
.await
|
||||
.expect("read profile columns");
|
||||
|
||||
assert_eq!(columns, vec!["id", "display_name"]);
|
||||
assert_eq!(columns, vec!["id", "display_name", "skin_hash"]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
use std::io::Cursor;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
use sha2::{Digest, Sha256};
|
||||
use tauri::{AppHandle, Manager, State};
|
||||
|
||||
use crate::network::Network;
|
||||
|
||||
const MAX_SKIN_BYTES: usize = 64 * 1024;
|
||||
const SKIN_WIDTH: u32 = 64;
|
||||
const SKIN_HEIGHT: u32 = 64;
|
||||
|
||||
fn validate_hash(hash: &str) -> Result<(), String> {
|
||||
if wyd_common::is_skin_hash(hash) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("Skin hash must be a 64-character SHA-256 value".to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
fn hash(bytes: &[u8]) -> String {
|
||||
format!("{:x}", Sha256::digest(bytes))
|
||||
}
|
||||
|
||||
fn validate(bytes: &[u8]) -> Result<String, String> {
|
||||
if bytes.is_empty() || bytes.len() > MAX_SKIN_BYTES {
|
||||
return Err(format!(
|
||||
"Skin PNG must be at most {} KiB",
|
||||
MAX_SKIN_BYTES / 1024
|
||||
));
|
||||
}
|
||||
let dimensions = image::ImageReader::with_format(Cursor::new(bytes), image::ImageFormat::Png)
|
||||
.into_dimensions()
|
||||
.map_err(|_| "Skin must be a valid PNG image".to_owned())?;
|
||||
if dimensions != (SKIN_WIDTH, SKIN_HEIGHT) {
|
||||
return Err(format!("Skin must be {SKIN_WIDTH}×{SKIN_HEIGHT} pixels"));
|
||||
}
|
||||
image::load_from_memory_with_format(bytes, image::ImageFormat::Png)
|
||||
.map_err(|_| "Skin must be a valid PNG image".to_owned())?;
|
||||
Ok(hash(bytes))
|
||||
}
|
||||
|
||||
fn local_path(handle: &AppHandle, hash: &str) -> Result<PathBuf, String> {
|
||||
Ok(handle
|
||||
.path()
|
||||
.app_data_dir()
|
||||
.map_err(|error| error.to_string())?
|
||||
.join("skins")
|
||||
.join(format!("{hash}.png")))
|
||||
}
|
||||
|
||||
fn cache_path(handle: &AppHandle, hash: &str) -> Result<PathBuf, String> {
|
||||
Ok(handle
|
||||
.path()
|
||||
.app_cache_dir()
|
||||
.map_err(|error| error.to_string())?
|
||||
.join("skins")
|
||||
.join(format!("{hash}.png")))
|
||||
}
|
||||
|
||||
fn read_verified(path: PathBuf, expected_hash: &str) -> Result<Option<Vec<u8>>, String> {
|
||||
let bytes = match std::fs::read(path) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(error) => return Err(error.to_string()),
|
||||
};
|
||||
Ok(validate(&bytes)
|
||||
.is_ok_and(|actual_hash| actual_hash == expected_hash)
|
||||
.then_some(bytes))
|
||||
}
|
||||
|
||||
pub(crate) fn decode_response(data: &str, expected_hash: &str) -> Option<Vec<u8>> {
|
||||
if data.len() > wyd_common::MAX_SKIN_B64_SIZE {
|
||||
return None;
|
||||
}
|
||||
let bytes = STANDARD.decode(data).ok()?;
|
||||
(validate(&bytes).ok()?.as_str() == expected_hash).then_some(bytes)
|
||||
}
|
||||
|
||||
fn write(path: PathBuf, bytes: &[u8]) -> Result<(), String> {
|
||||
let parent = path
|
||||
.parent()
|
||||
.ok_or_else(|| "Skin path has no parent directory".to_owned())?;
|
||||
std::fs::create_dir_all(parent).map_err(|error| error.to_string())?;
|
||||
std::fs::write(path, bytes).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
pub(crate) fn read_local_base64(handle: &AppHandle, skin_hash: &str) -> Option<String> {
|
||||
validate_hash(skin_hash).ok()?;
|
||||
read_verified(local_path(handle, skin_hash).ok()?, skin_hash)
|
||||
.ok()
|
||||
.flatten()
|
||||
.map(|bytes| STANDARD.encode(bytes))
|
||||
}
|
||||
|
||||
pub(crate) fn store_local(handle: &AppHandle, data: &[u8]) -> Result<String, String> {
|
||||
let skin_hash = validate(data)?;
|
||||
write(local_path(handle, &skin_hash)?, data)?;
|
||||
Ok(skin_hash)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn resolve_skin(
|
||||
handle: AppHandle,
|
||||
network: State<'_, Network>,
|
||||
user_id: String,
|
||||
skin_hash: String,
|
||||
) -> Result<Option<String>, String> {
|
||||
validate_hash(&skin_hash)?;
|
||||
crate::user::validate_id(&user_id)?;
|
||||
|
||||
let bytes = if user_id == network.public_key() {
|
||||
read_verified(local_path(&handle, &skin_hash)?, &skin_hash)?
|
||||
} else if let Some(bytes) = read_verified(cache_path(&handle, &skin_hash)?, &skin_hash)? {
|
||||
Some(bytes)
|
||||
} else {
|
||||
let Some(bytes) = network.request_skin(user_id, skin_hash.clone()).await? else {
|
||||
return Ok(None);
|
||||
};
|
||||
write(cache_path(&handle, &skin_hash)?, &bytes)?;
|
||||
Some(bytes)
|
||||
};
|
||||
|
||||
Ok(bytes.map(|bytes| STANDARD.encode(bytes)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rejects_non_png_and_invalid_hashes() {
|
||||
assert!(validate(b"not a png").is_err());
|
||||
assert!(validate_hash("../skin").is_err());
|
||||
assert!(validate_hash(&"a".repeat(64)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_png_dimensions_before_full_validation() {
|
||||
let mut bytes = Cursor::new(Vec::new());
|
||||
image::DynamicImage::new_rgba8(SKIN_WIDTH + 1, SKIN_HEIGHT)
|
||||
.write_to(&mut bytes, image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
validate(&bytes.into_inner()).unwrap_err(),
|
||||
"Skin must be 64×64 pixels"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_a_64_by_64_png_and_returns_its_sha256_hash() {
|
||||
let mut bytes = Cursor::new(Vec::new());
|
||||
image::DynamicImage::new_rgba8(SKIN_WIDTH, SKIN_HEIGHT)
|
||||
.write_to(&mut bytes, image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
let bytes = bytes.into_inner();
|
||||
|
||||
assert_eq!(validate(&bytes).unwrap(), hash(&bytes));
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ use specta::Type;
|
||||
pub struct User {
|
||||
pub id: String,
|
||||
pub display_name: String,
|
||||
pub skin_hash: Option<String>,
|
||||
}
|
||||
|
||||
pub(crate) fn validate_id(id: &str) -> Result<(), String> {
|
||||
|
||||
+7
-4
@@ -35,8 +35,8 @@ async deleteRemote(id: string) : Promise<boolean> {
|
||||
async getProfile() : Promise<User> {
|
||||
return await TAURI_INVOKE("get_profile");
|
||||
},
|
||||
async updateProfile(displayName: string) : Promise<User> {
|
||||
return await TAURI_INVOKE("update_profile", { displayName });
|
||||
async updateProfile(displayName: string, skinData: number[] | null) : Promise<User> {
|
||||
return await TAURI_INVOKE("update_profile", { displayName, skinData });
|
||||
},
|
||||
async getPublicKey() : Promise<string> {
|
||||
return await TAURI_INVOKE("get_public_key");
|
||||
@@ -50,6 +50,9 @@ async listFriendStatuses() : Promise<string[]> {
|
||||
async resolveFriendDisplayName(userId: string) : Promise<string | null> {
|
||||
return await TAURI_INVOKE("resolve_friend_display_name", { userId });
|
||||
},
|
||||
async resolveSkin(userId: string, skinHash: string) : Promise<string | null> {
|
||||
return await TAURI_INVOKE("resolve_skin", { userId, skinHash });
|
||||
},
|
||||
async pickAndSendImage(recipientId: string) : Promise<boolean> {
|
||||
return await TAURI_INVOKE("pick_and_send_image", { recipientId });
|
||||
},
|
||||
@@ -125,7 +128,7 @@ export type ForegroundAppChanged = { meta: AppMeta }
|
||||
* A configured public-key relationship with optional cached remote metadata.
|
||||
* The display name remains absent until learned from a signed remote profile.
|
||||
*/
|
||||
export type Friend = { id: string; displayName: string | null }
|
||||
export type Friend = { id: string; displayName: string | null; skinHash: string | null }
|
||||
export type FriendForegroundAppChanged = { friendId: string; meta: AppMeta }
|
||||
export type FriendInteractionReceived = { interactionId: string; friendId: string; content: InteractionContent }
|
||||
export type FriendStatusesChanged = { friendIds: string[] }
|
||||
@@ -143,7 +146,7 @@ export type SceneHitbox = { x: number; y: number; width: number; height: number
|
||||
* Public user identity exchanged with peers and remote servers. `id` is the
|
||||
* user's Ed25519 public key and is not persisted as local profile metadata.
|
||||
*/
|
||||
export type User = { id: string; displayName: string }
|
||||
export type User = { id: string; displayName: string; skinHash: string | null }
|
||||
|
||||
/** tauri-specta globals **/
|
||||
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
let dirty = $state(false);
|
||||
let busy = $state(false);
|
||||
let error = $state("");
|
||||
let skinFile = $state<File | null>(null);
|
||||
let skinInput = $state<HTMLInputElement | null>(null);
|
||||
|
||||
$effect(() => {
|
||||
if (!dirty) displayName = $profile?.displayName ?? "";
|
||||
@@ -21,12 +23,15 @@
|
||||
onMount(() => register("general", { apply, reset }, { dirty, busy }));
|
||||
|
||||
function updateDirty() {
|
||||
dirty = displayName.trim() !== ($profile?.displayName ?? "");
|
||||
dirty =
|
||||
displayName.trim() !== ($profile?.displayName ?? "") || skinFile !== null;
|
||||
error = "";
|
||||
}
|
||||
|
||||
function reset() {
|
||||
displayName = $profile?.displayName ?? "";
|
||||
skinFile = null;
|
||||
if (skinInput) skinInput.value = "";
|
||||
dirty = false;
|
||||
error = "";
|
||||
}
|
||||
@@ -42,8 +47,13 @@
|
||||
busy = true;
|
||||
error = "";
|
||||
try {
|
||||
await commands.updateProfile(nextName);
|
||||
const skinData = skinFile
|
||||
? Array.from(new Uint8Array(await skinFile.arrayBuffer()))
|
||||
: null;
|
||||
await commands.updateProfile(nextName, skinData);
|
||||
displayName = nextName;
|
||||
skinFile = null;
|
||||
if (skinInput) skinInput.value = "";
|
||||
dirty = false;
|
||||
return true;
|
||||
} catch (cause) {
|
||||
@@ -78,6 +88,34 @@
|
||||
This name can be changed at any time.
|
||||
</p>
|
||||
|
||||
<label class="fieldset-label mt-2" for="skin-file">Character skin</label>
|
||||
<div class="join w-full">
|
||||
<input
|
||||
class="input join-item min-w-0 flex-1"
|
||||
value={skinFile?.name ?? ($profile?.skinHash ? "Custom skin" : "Default skin")}
|
||||
readonly
|
||||
aria-label="Selected character skin"
|
||||
/>
|
||||
<button
|
||||
class="btn join-item"
|
||||
type="button"
|
||||
disabled={!$profile || busy}
|
||||
onclick={() => skinInput?.click()}>Choose PNG</button
|
||||
>
|
||||
</div>
|
||||
<input
|
||||
id="skin-file"
|
||||
class="hidden"
|
||||
type="file"
|
||||
accept="image/png"
|
||||
bind:this={skinInput}
|
||||
onchange={(event) => {
|
||||
skinFile = event.currentTarget.files?.[0] ?? null;
|
||||
updateDirty();
|
||||
}}
|
||||
/>
|
||||
<p class="fieldset-label">64×64 Minecraft-format PNG, base layer only.</p>
|
||||
|
||||
<label class="fieldset-label mt-2" for="public-key"
|
||||
>Identification Key
|
||||
<div
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
error = "";
|
||||
|
||||
try {
|
||||
await commands.updateProfile(displayName);
|
||||
await commands.updateProfile(displayName, null);
|
||||
} catch (err) {
|
||||
error = String(err);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { commands } from "$lib/bindings";
|
||||
|
||||
export const DEFAULT_SKIN_URL = "/default-skin.png";
|
||||
|
||||
export async function resolveSkinSource(
|
||||
userId: string,
|
||||
skinHash: string | null,
|
||||
) {
|
||||
if (!skinHash) return DEFAULT_SKIN_URL;
|
||||
|
||||
try {
|
||||
const data = await commands.resolveSkin(userId, skinHash);
|
||||
return data ? `data:image/png;base64,${data}` : DEFAULT_SKIN_URL;
|
||||
} catch (error) {
|
||||
console.error(`Failed to resolve custom skin for ${userId}`, error);
|
||||
return DEFAULT_SKIN_URL;
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,16 @@
|
||||
id === $liveMetadata.localId || $onlineFriendIds.has(id),
|
||||
),
|
||||
);
|
||||
let skinHashes = $derived(
|
||||
new Map(
|
||||
visiblePuppets.map(({ id }) => [
|
||||
id,
|
||||
id === $profile?.id
|
||||
? $profile.skinHash
|
||||
: ($friends.find((friend) => friend.id === id)?.skinHash ?? null),
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
onMount(startHitboxSync);
|
||||
|
||||
@@ -94,6 +104,7 @@
|
||||
puppets={visiblePuppets}
|
||||
frozenPuppetId={selectedUserId}
|
||||
onBoundsChange={(bounds) => (puppetBounds = bounds)}
|
||||
{skinHashes}
|
||||
/>
|
||||
|
||||
<div role="banner" class="pointer-events-none fixed inset-0 z-10">
|
||||
|
||||
@@ -10,10 +10,12 @@
|
||||
puppets,
|
||||
frozenPuppetId,
|
||||
onBoundsChange,
|
||||
skinHashes,
|
||||
}: {
|
||||
puppets: readonly PuppetState[];
|
||||
frozenPuppetId: string | null;
|
||||
onBoundsChange: (bounds: PuppetScreenBounds[]) => void;
|
||||
skinHashes: ReadonlyMap<string, string | null>;
|
||||
} = $props();
|
||||
|
||||
let renderDiv = $state<HTMLDivElement | null>(null);
|
||||
@@ -37,6 +39,7 @@
|
||||
frozenPuppetId,
|
||||
clock.getDelta(),
|
||||
clock.getElapsed(),
|
||||
skinHashes,
|
||||
);
|
||||
world.render();
|
||||
|
||||
|
||||
@@ -2,13 +2,26 @@ import type { PuppetState } from "$lib/bindings";
|
||||
import * as THREE from "three";
|
||||
import type { World } from "../world";
|
||||
import { PuppetAnimation } from "./animation";
|
||||
import { PuppetSkin } from "./skin";
|
||||
|
||||
export type PuppetRig = {
|
||||
root: THREE.Group;
|
||||
body: THREE.Mesh<THREE.BoxGeometry, THREE.Material | THREE.Material[]>;
|
||||
head: THREE.Mesh<THREE.BoxGeometry, THREE.Material | THREE.Material[]>;
|
||||
leftArm: THREE.Group;
|
||||
leftArmMesh: THREE.Mesh<THREE.BoxGeometry, THREE.Material | THREE.Material[]>;
|
||||
rightArm: THREE.Group;
|
||||
rightArmMesh: THREE.Mesh<
|
||||
THREE.BoxGeometry,
|
||||
THREE.Material | THREE.Material[]
|
||||
>;
|
||||
leftLeg: THREE.Group;
|
||||
leftLegMesh: THREE.Mesh<THREE.BoxGeometry, THREE.Material | THREE.Material[]>;
|
||||
rightLeg: THREE.Group;
|
||||
rightLegMesh: THREE.Mesh<
|
||||
THREE.BoxGeometry,
|
||||
THREE.Material | THREE.Material[]
|
||||
>;
|
||||
};
|
||||
|
||||
export class Puppet {
|
||||
@@ -16,12 +29,16 @@ export class Puppet {
|
||||
|
||||
private readonly rig: PuppetRig;
|
||||
private readonly animation: PuppetAnimation;
|
||||
private readonly skin: PuppetSkin;
|
||||
private readonly targetGroundPosition = new THREE.Vector3();
|
||||
|
||||
constructor(readonly id: string) {
|
||||
this.rig = this.createRig();
|
||||
this.root = this.rig.root;
|
||||
this.animation = new PuppetAnimation(this.rig);
|
||||
const placeholderMaterial = this.rig.body.material;
|
||||
this.skin = new PuppetSkin(id, this.rig);
|
||||
if (!Array.isArray(placeholderMaterial)) placeholderMaterial.dispose();
|
||||
}
|
||||
|
||||
update(
|
||||
@@ -30,7 +47,9 @@ export class Puppet {
|
||||
frozen: boolean,
|
||||
deltaSeconds: number,
|
||||
elapsedSeconds: number,
|
||||
skinHash: string | null,
|
||||
) {
|
||||
this.skin.update(skinHash);
|
||||
if (frozen) {
|
||||
this.animation.pause();
|
||||
return;
|
||||
@@ -50,28 +69,18 @@ export class Puppet {
|
||||
}
|
||||
|
||||
dispose() {
|
||||
const disposedMaterials = new Set<THREE.Material>();
|
||||
this.skin.dispose();
|
||||
|
||||
this.root.traverse((object) => {
|
||||
if (!(object instanceof THREE.Mesh)) return;
|
||||
|
||||
object.geometry.dispose();
|
||||
const materials = Array.isArray(object.material)
|
||||
? object.material
|
||||
: [object.material];
|
||||
for (const material of materials) {
|
||||
if (disposedMaterials.has(material)) continue;
|
||||
material.dispose();
|
||||
disposedMaterials.add(material);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private createRig(): PuppetRig {
|
||||
const root = new THREE.Group();
|
||||
const material = new THREE.MeshStandardMaterial({
|
||||
color: this.colorFromId(),
|
||||
});
|
||||
const material = new THREE.MeshStandardMaterial();
|
||||
|
||||
const body = new THREE.Mesh(new THREE.BoxGeometry(16, 24, 8), material);
|
||||
body.position.y = 36;
|
||||
@@ -79,14 +88,54 @@ export class Puppet {
|
||||
const head = new THREE.Mesh(new THREE.BoxGeometry(16, 16, 16), material);
|
||||
head.position.y = 56;
|
||||
|
||||
const leftArm = this.createLimbPivot(-12, 48, 8, 24, 8, material);
|
||||
const rightArm = this.createLimbPivot(12, 48, 8, 24, 8, material);
|
||||
const leftLeg = this.createLimbPivot(-4, 24, 8, 24, 8, material);
|
||||
const rightLeg = this.createLimbPivot(4, 24, 8, 24, 8, material);
|
||||
const { pivot: leftArm, mesh: leftArmMesh } = this.createLimbPivot(
|
||||
-12,
|
||||
48,
|
||||
8,
|
||||
24,
|
||||
8,
|
||||
material,
|
||||
);
|
||||
const { pivot: rightArm, mesh: rightArmMesh } = this.createLimbPivot(
|
||||
12,
|
||||
48,
|
||||
8,
|
||||
24,
|
||||
8,
|
||||
material,
|
||||
);
|
||||
const { pivot: leftLeg, mesh: leftLegMesh } = this.createLimbPivot(
|
||||
-4,
|
||||
24,
|
||||
8,
|
||||
24,
|
||||
8,
|
||||
material,
|
||||
);
|
||||
const { pivot: rightLeg, mesh: rightLegMesh } = this.createLimbPivot(
|
||||
4,
|
||||
24,
|
||||
8,
|
||||
24,
|
||||
8,
|
||||
material,
|
||||
);
|
||||
|
||||
root.add(body, head, leftArm, rightArm, leftLeg, rightLeg);
|
||||
|
||||
return { root, leftArm, rightArm, leftLeg, rightLeg };
|
||||
return {
|
||||
root,
|
||||
body,
|
||||
head,
|
||||
leftArm,
|
||||
leftArmMesh,
|
||||
rightArm,
|
||||
rightArmMesh,
|
||||
leftLeg,
|
||||
leftLegMesh,
|
||||
rightLeg,
|
||||
rightLegMesh,
|
||||
};
|
||||
}
|
||||
|
||||
private createLimbPivot(
|
||||
@@ -107,15 +156,6 @@ export class Puppet {
|
||||
limb.position.y = -height / 2;
|
||||
pivot.add(limb);
|
||||
|
||||
return pivot;
|
||||
}
|
||||
|
||||
private colorFromId() {
|
||||
let hash = 0;
|
||||
for (const character of this.id) {
|
||||
hash = (hash * 31 + character.charCodeAt(0)) >>> 0;
|
||||
}
|
||||
|
||||
return new THREE.Color().setHSL((hash % 360) / 360, 0.55, 0.62);
|
||||
return { pivot, mesh: limb };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ export class PuppetManager {
|
||||
frozenPuppetId: string | null,
|
||||
deltaSeconds: number,
|
||||
elapsedSeconds: number,
|
||||
skinHashes: ReadonlyMap<string, string | null>,
|
||||
) {
|
||||
this.syncPuppets(states);
|
||||
|
||||
@@ -25,6 +26,7 @@ export class PuppetManager {
|
||||
state.id === frozenPuppetId,
|
||||
deltaSeconds,
|
||||
elapsedSeconds,
|
||||
skinHashes.get(state.id) ?? null,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
import { resolveSkinSource } from "$lib/skins";
|
||||
import * as THREE from "three";
|
||||
import type { PuppetRig } from ".";
|
||||
|
||||
type Region = {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
flipX?: boolean;
|
||||
};
|
||||
type Faces = [Region, Region, Region, Region, Region, Region];
|
||||
type SkinPart = {
|
||||
mesh: THREE.Mesh<THREE.BoxGeometry, THREE.Material | THREE.Material[]>;
|
||||
faces: Faces;
|
||||
};
|
||||
|
||||
const ATLAS_SIZE = 64;
|
||||
const region = (
|
||||
x: number,
|
||||
y: number,
|
||||
width: number,
|
||||
height: number,
|
||||
flipX = false,
|
||||
): Region => ({ x, y, width, height, flipX });
|
||||
const faces = (
|
||||
right: Region,
|
||||
left: Region,
|
||||
top: Region,
|
||||
bottom: Region,
|
||||
front: Region,
|
||||
back: Region,
|
||||
): Faces => [right, left, top, bottom, front, back];
|
||||
|
||||
const HEAD = faces(
|
||||
region(0, 8, 8, 8, true),
|
||||
region(16, 8, 8, 8, true),
|
||||
region(8, 0, 8, 8),
|
||||
region(16, 0, 8, 8),
|
||||
region(8, 8, 8, 8),
|
||||
region(24, 8, 8, 8),
|
||||
);
|
||||
const BODY = faces(
|
||||
region(16, 20, 4, 12, true),
|
||||
region(28, 20, 4, 12, true),
|
||||
region(20, 16, 8, 4),
|
||||
region(28, 16, 8, 4),
|
||||
region(20, 20, 8, 12),
|
||||
region(32, 20, 8, 12),
|
||||
);
|
||||
const RIGHT_ARM = faces(
|
||||
region(40, 20, 4, 12, true),
|
||||
region(48, 20, 4, 12, true),
|
||||
region(44, 16, 4, 4),
|
||||
region(48, 16, 4, 4),
|
||||
region(44, 20, 4, 12),
|
||||
region(52, 20, 4, 12),
|
||||
);
|
||||
const LEFT_ARM = faces(
|
||||
region(32, 52, 4, 12, true),
|
||||
region(40, 52, 4, 12, true),
|
||||
region(36, 48, 4, 4),
|
||||
region(40, 48, 4, 4),
|
||||
region(36, 52, 4, 12),
|
||||
region(44, 52, 4, 12),
|
||||
);
|
||||
const RIGHT_LEG = faces(
|
||||
region(0, 20, 4, 12, true),
|
||||
region(8, 20, 4, 12, true),
|
||||
region(4, 16, 4, 4),
|
||||
region(8, 16, 4, 4),
|
||||
region(4, 20, 4, 12),
|
||||
region(12, 20, 4, 12),
|
||||
);
|
||||
const LEFT_LEG = faces(
|
||||
region(16, 52, 4, 12, true),
|
||||
region(24, 52, 4, 12, true),
|
||||
region(20, 48, 4, 4),
|
||||
region(24, 48, 4, 4),
|
||||
region(20, 52, 4, 12),
|
||||
region(28, 52, 4, 12),
|
||||
);
|
||||
|
||||
function applyUvs(geometry: THREE.BoxGeometry, regions: Faces) {
|
||||
const uv = geometry.attributes.uv;
|
||||
regions.forEach((item, faceIndex) => {
|
||||
const offset = faceIndex * 4;
|
||||
const regionLeft = item.x / ATLAS_SIZE;
|
||||
const regionRight = (item.x + item.width) / ATLAS_SIZE;
|
||||
const left = item.flipX ? regionRight : regionLeft;
|
||||
const right = item.flipX ? regionLeft : regionRight;
|
||||
const top = 1 - item.y / ATLAS_SIZE;
|
||||
const bottom = 1 - (item.y + item.height) / ATLAS_SIZE;
|
||||
uv.setXY(offset, left, top);
|
||||
uv.setXY(offset + 1, right, top);
|
||||
uv.setXY(offset + 2, left, bottom);
|
||||
uv.setXY(offset + 3, right, bottom);
|
||||
});
|
||||
uv.needsUpdate = true;
|
||||
}
|
||||
|
||||
function loadTexture(url: string) {
|
||||
return new Promise<THREE.Texture>((resolve, reject) => {
|
||||
new THREE.TextureLoader().load(
|
||||
url,
|
||||
(texture) => {
|
||||
texture.colorSpace = THREE.SRGBColorSpace;
|
||||
texture.magFilter = THREE.NearestFilter;
|
||||
texture.minFilter = THREE.NearestFilter;
|
||||
texture.generateMipmaps = false;
|
||||
resolve(texture);
|
||||
},
|
||||
undefined,
|
||||
reject,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export class PuppetSkin {
|
||||
private readonly material: THREE.MeshStandardMaterial;
|
||||
private texture: THREE.Texture | null = null;
|
||||
private requestedHash: string | null | undefined;
|
||||
private requestId = 0;
|
||||
|
||||
constructor(
|
||||
private readonly userId: string,
|
||||
rig: PuppetRig,
|
||||
) {
|
||||
this.material = new THREE.MeshStandardMaterial({
|
||||
color: "white",
|
||||
transparent: true,
|
||||
alphaTest: 0.5,
|
||||
});
|
||||
const parts: SkinPart[] = [
|
||||
{ mesh: rig.head, faces: HEAD },
|
||||
{ mesh: rig.body, faces: BODY },
|
||||
{ mesh: rig.leftArmMesh, faces: LEFT_ARM },
|
||||
{ mesh: rig.rightArmMesh, faces: RIGHT_ARM },
|
||||
{ mesh: rig.leftLegMesh, faces: LEFT_LEG },
|
||||
{ mesh: rig.rightLegMesh, faces: RIGHT_LEG },
|
||||
];
|
||||
for (const part of parts) {
|
||||
part.mesh.material = this.material;
|
||||
applyUvs(part.mesh.geometry, part.faces);
|
||||
}
|
||||
}
|
||||
|
||||
update(skinHash: string | null) {
|
||||
if (skinHash === this.requestedHash) return;
|
||||
this.requestedHash = skinHash;
|
||||
const requestId = ++this.requestId;
|
||||
|
||||
resolveSkinSource(this.userId, skinHash)
|
||||
.then(async (source) => {
|
||||
if (requestId !== this.requestId) return;
|
||||
const texture = await loadTexture(source);
|
||||
if (requestId !== this.requestId) {
|
||||
texture.dispose();
|
||||
return;
|
||||
}
|
||||
this.texture?.dispose();
|
||||
this.texture = texture;
|
||||
this.material.map = texture;
|
||||
this.material.needsUpdate = true;
|
||||
})
|
||||
.catch((error) =>
|
||||
console.error(`Failed to load skin for ${this.userId}`, error),
|
||||
);
|
||||
}
|
||||
|
||||
dispose() {
|
||||
this.requestId++;
|
||||
this.texture?.dispose();
|
||||
this.material.dispose();
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.2 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 191 KiB |
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="26.6" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 308"><path fill="#FF3E00" d="M239.682 40.707C211.113-.182 154.69-12.301 113.895 13.69L42.247 59.356a82.198 82.198 0 0 0-37.135 55.056a86.566 86.566 0 0 0 8.536 55.576a82.425 82.425 0 0 0-12.296 30.719a87.596 87.596 0 0 0 14.964 66.244c28.574 40.893 84.997 53.007 125.787 27.016l71.648-45.664a82.182 82.182 0 0 0 37.135-55.057a86.601 86.601 0 0 0-8.53-55.577a82.409 82.409 0 0 0 12.29-30.718a87.573 87.573 0 0 0-14.963-66.244"></path><path fill="#FFF" d="M106.889 270.841c-23.102 6.007-47.497-3.036-61.103-22.648a52.685 52.685 0 0 1-9.003-39.85a49.978 49.978 0 0 1 1.713-6.693l1.35-4.115l3.671 2.697a92.447 92.447 0 0 0 28.036 14.007l2.663.808l-.245 2.659a16.067 16.067 0 0 0 2.89 10.656a17.143 17.143 0 0 0 18.397 6.828a15.786 15.786 0 0 0 4.403-1.935l71.67-45.672a14.922 14.922 0 0 0 6.734-9.977a15.923 15.923 0 0 0-2.713-12.011a17.156 17.156 0 0 0-18.404-6.832a15.78 15.78 0 0 0-4.396 1.933l-27.35 17.434a52.298 52.298 0 0 1-14.553 6.391c-23.101 6.007-47.497-3.036-61.101-22.649a52.681 52.681 0 0 1-9.004-39.849a49.428 49.428 0 0 1 22.34-33.114l71.664-45.677a52.218 52.218 0 0 1 14.563-6.398c23.101-6.007 47.497 3.036 61.101 22.648a52.685 52.685 0 0 1 9.004 39.85a50.559 50.559 0 0 1-1.713 6.692l-1.35 4.116l-3.67-2.693a92.373 92.373 0 0 0-28.037-14.013l-2.664-.809l.246-2.658a16.099 16.099 0 0 0-2.89-10.656a17.143 17.143 0 0 0-18.398-6.828a15.786 15.786 0 0 0-4.402 1.935l-71.67 45.674a14.898 14.898 0 0 0-6.73 9.975a15.9 15.9 0 0 0 2.709 12.012a17.156 17.156 0 0 0 18.404 6.832a15.841 15.841 0 0 0 4.402-1.935l27.345-17.427a52.147 52.147 0 0 1 14.552-6.397c23.101-6.006 47.497 3.037 61.102 22.65a52.681 52.681 0 0 1 9.003 39.848a49.453 49.453 0 0 1-22.34 33.12l-71.664 45.673a52.218 52.218 0 0 1-14.563 6.398"></path></svg>
|
||||
|
Before Width: | Height: | Size: 1.9 KiB |
@@ -1,6 +0,0 @@
|
||||
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
|
||||
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 2.5 KiB |
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||
|
Before Width: | Height: | Size: 1.5 KiB |
Reference in New Issue
Block a user