vrc 0.5.0

Unofficial rust types of VRChat's API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
//! Wrappers for VRC IDs.
//!
//! Wrapping them IDs in newtypes makes sure you aren't trying to accidentally
//! compare different types of VRC IDs with each other like so:
//!
//! ```compile_fail,E0308
//! let user_id = vrc::id::User::from("usr_c1644b5b-3ca4-45b4-97c6-a2a0de70d469");
//! let instance_id = vrc::id::Instance::from("whatever-instance-ids-look-like");
//! assert!(user_id != record_id, "can't compare different types of IDs")
//! ```

use std::fmt;

use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Visitor};

// TODO: serialization & deserilization customizations

macro_rules! add_id {
	(
		$(#[$meta:meta])*
		$name:ident,
		$id_matches:expr
	) => {
		#[doc = concat!("An ID of a VRC ", stringify!($name))]
		///
		$(#[$meta])*
		///
		/// # Example usage
		///
		/// Note that parse checks that the ID follows the correct format:
		///
		/// ```no_run
		#[doc = concat!("use vrc::id::", stringify!($name), ";")]
		#[doc = concat!("let parse_res = \"an-id-that-is-of-an-invalid-format\".parse::<", stringify!($name), ">();")]
		/// assert!(parse_res.is_err());
		/// ```
		///
		/// But parsing checks can also be ignored by using infallible `From<String>` implementations:
		///
		/// ```
		#[doc = concat!("use vrc::id::", stringify!($name), ";")]
		/// // Note that parsing will fail with the wrong format
		#[doc = concat!("let id1 = ", stringify!($name), "::from(\"totally-legit-id\");")]
		#[doc = concat!("let id2 = ", stringify!($name), "::from(\"other-totally-legit-id\");")]
		/// assert!(id1 != id2);
		/// ```
		///
		/// The deserialization also checks the that the IDs format is valid, whilst serialization does not check the validity.
		#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
		#[repr(transparent)]
		pub struct $name(String);

		impl $name {
			/// Checks if the ID matches the expected format
			#[must_use]
			pub fn is_valid(&self) -> bool {
				$id_matches(&self.0)
			}
		}

		impl AsRef<str> for $name {
			/// Extracts a string slice containing the entire inner String.
			#[must_use]
			fn as_ref(&self) -> &str {
				&self.0
			}
		}

		impl std::fmt::Display for $name {
			fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
				write!(f, "{}", self.0)
			}
		}

		/// Fallible: "...".`parse::`<id::Type>()
		impl std::str::FromStr for $name {
			type Err = &'static str;

			fn from_str(id: &str) -> Result<Self, Self::Err> {
				if !$id_matches(&id) {
					return Err(concat!("ID doesn't match expected format"))
				}
				Ok(Self(id.to_owned()))
			}
		}

		/// Infallible: `id::Type::from`("...") or "...".`into()`
		impl From<&str> for $name {
			fn from(id: &str) -> Self {
				Self(id.to_owned())
			}
		}

		/// Infallible: `id::Type::from`(String) or String.`into()`
		impl From<String> for $name {
			fn from(id: String) -> Self {
				Self(id)
			}
		}

		impl From<$name> for String {
			fn from(id: $name) -> String {
				id.0
			}
		}

		impl From<$name> for Any {
			fn from(id: $name) -> Any {
				Any::$name(id)
			}
		}

		/// The deserializer will give an error if the inner String doesn't start with
		/// the proper prefix.
		impl<'de> serde::de::Deserialize<'de> for $name {
			fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
			where
				D: Deserializer<'de>,
			{
				struct IdVisitor;

				impl<'de> Visitor<'de> for IdVisitor {
					type Value = $name;

					fn expecting(
						&self, formatter: &mut std::fmt::Formatter,
					) -> std::fmt::Result {
						formatter
							.write_str(concat!("a string ID of ", stringify!($name), ", that is of the correct format"))
					}

					fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
					where
						E: serde::de::Error,
					{
						if !$id_matches(&v) {
							return Err(serde::de::Error::invalid_value(
								serde::de::Unexpected::Str(v),
								&concat!("matching the ID format of ", stringify!($name)),
							));
						}

						Ok($name(v.to_string()))
					}
				}

				deserializer.deserialize_str(IdVisitor)
			}
		}
	};
}

// VRC still has some legacy IDs, thus allowing 10 char strings without prefix
add_id!(Avatar, |v: &str| v.starts_with("avtr_") || v.len() == 10);
add_id!(Group, |v: &str| v.starts_with("grp_"));
// TODO: Manual implementation that breaks down instance name, type, region, and
// so on, assuming a valid instance ID.
add_id!(
	/// Instance ID validation is near impossible, so pretty much anything is accepted for it
	Instance,
	|_v: &str| true
);
add_id!(UnityPackage, |v: &str| v.starts_with("unp_") || v.len() == 10);
add_id!(User, |v: &str| v.starts_with("usr_") || v.len() == 10);
add_id!(GroupMember, |v: &str| v.starts_with("gmem_"));
add_id!(World, |v: &str| v.starts_with("wrld_") || v.len() == 10);

/// Offline or the id of the world or whatever type T is
#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub enum OfflineOr<T> {
	/// The ID was replaced by offline
	#[serde(rename = "offline")]
	Offline,
	/// There exists an ID
	#[serde(untagged)]
	Id(T),
}

#[cfg(test)]
#[test]
fn offline_or_id() {
	assert_eq!(
		&serde_json::to_string(&OfflineOr::<String>::Offline).unwrap(),
		"\"offline\""
	);
	let user = crate::id::User::from(
		"usr_c1644b5b-3ca4-45b4-97c6-a2a0de70d469".to_owned(),
	);
	assert_eq!(
		&serde_json::to_string(&OfflineOr::<crate::id::User>::Id(user)).unwrap(),
		"\"usr_c1644b5b-3ca4-45b4-97c6-a2a0de70d469\""
	);

	let id = "\"private\"";
	assert!(serde_json::from_str::<OfflineOr<crate::id::User>>(id).is_err());
	let id = "\"offline\"";
	serde_json::from_str::<OfflineOr<crate::id::User>>(id).unwrap();
	let id = "\"invalid\"";
	assert!(serde_json::from_str::<OfflineOr<crate::id::User>>(id).is_err());
	let id = "\"usr_c1644b5b-3ca4-45b4-97c6-a2a0de70d469\"";
	serde_json::from_str::<OfflineOr<crate::id::User>>(id).unwrap();
	let id = "\"invalid\"";
	serde_json::from_str::<OfflineOr<String>>(id).unwrap();
}

impl<T> OfflineOr<T> {
	/// Gives the ID as an option instead
	pub const fn as_option(&self) -> Option<&T> {
		match &self {
			Self::Offline => None,
			Self::Id(id) => Some(id),
		}
	}
}

/// Offline or private or the id of the instance or whatever type T is
#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub enum OfflineOrPrivateOr<T> {
	/// Offline currently
	#[serde(rename = "private")]
	Private,
	/// The ID was replaced by offline
	#[serde(rename = "offline")]
	Offline,
	/// There exists an ID
	#[serde(untagged)]
	Id(T),
}

impl<T> OfflineOrPrivateOr<T> {
	/// Gives the ID as an option instead
	pub const fn as_option(&self) -> Option<&T> {
		match &self {
			Self::Offline | Self::Private => None,
			Self::Id(id) => Some(id),
		}
	}
}

#[cfg(test)]
#[test]
fn offline_or_private_or_id() {
	assert_eq!(
		&serde_json::to_string(&OfflineOrPrivateOr::<String>::Offline).unwrap(),
		"\"offline\""
	);
	assert_eq!(
		&serde_json::to_string(&OfflineOrPrivateOr::<String>::Private).unwrap(),
		"\"private\""
	);
	let user = crate::id::User::from(
		"usr_c1644b5b-3ca4-45b4-97c6-a2a0de70d469".to_owned(),
	);
	assert_eq!(
		&serde_json::to_string(&OfflineOrPrivateOr::<crate::id::User>::Id(user))
			.unwrap(),
		"\"usr_c1644b5b-3ca4-45b4-97c6-a2a0de70d469\""
	);

	let id = "\"private\"";
	serde_json::from_str::<OfflineOrPrivateOr<crate::id::User>>(id).unwrap();
	let id = "\"offline\"";
	serde_json::from_str::<OfflineOrPrivateOr<crate::id::User>>(id).unwrap();
	let id = "\"invalid\"";
	assert!(
		serde_json::from_str::<OfflineOrPrivateOr<crate::id::User>>(id).is_err()
	);
	let id = "\"usr_c1644b5b-3ca4-45b4-97c6-a2a0de70d469\"";
	serde_json::from_str::<OfflineOrPrivateOr<crate::id::User>>(id).unwrap();
	let id = "\"invalid\"";
	serde_json::from_str::<OfflineOrPrivateOr<String>>(id).unwrap();
}

/// Any of the VRC IDs
///
/// # Example usage
///
/// ```
/// let id1 = "usr_totally-legit-uuid".parse::<vrc::id::User>().unwrap();
/// let id1: vrc::id::Any = id1.into();
/// let id2 =
/// 	"12345~group(grp_totally-legit-uuid)~groupAccessType(public)~region(us)"
/// 		.parse::<vrc::id::Instance>()
/// 		.unwrap();
/// let id2: vrc::id::Any = id2.into();
/// assert!(id1 != id2);
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[serde(untagged)]
pub enum Any {
	/// An avatar ID
	Avatar(Avatar),
	/// An group ID
	Group(Group),
	/// An instance ID
	Instance(Instance),
	/// An ID for an Unity package
	UnityPackage(UnityPackage),
	/// An user ID
	User(User),
	/// A world ID
	World(World),
	/// A group member ID
	GroupMember(GroupMember),
}

impl AsRef<str> for Any {
	/// Extracts a string slice containing the entire inner String.
	#[must_use]
	fn as_ref(&self) -> &str {
		match self {
			Self::Avatar(v) => v.as_ref(),
			Self::Group(v) => v.as_ref(),
			Self::Instance(v) => v.as_ref(),
			Self::UnityPackage(v) => v.as_ref(),
			Self::User(v) => v.as_ref(),
			Self::World(v) => v.as_ref(),
			Self::GroupMember(v) => v.as_ref(),
		}
	}
}

impl std::fmt::Display for Any {
	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
		write!(f, "{}", self.as_ref())
	}
}

/// A world instance's ID
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct WorldInstance {
	/// The instance ID
	pub instance: Instance,
	/// The world ID
	pub world: World,
}

impl fmt::Display for WorldInstance {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(f, "{}:{}", self.world.as_ref(), self.instance.as_ref())
	}
}

impl Serialize for WorldInstance {
	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
	where
		S: Serializer,
	{
		serializer.serialize_str(&self.to_string())
	}
}

/// The deserializer will give an error if the inner String doesn't start with
/// the proper prefix.
impl<'de> serde::de::Deserialize<'de> for WorldInstance {
	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
	where
		D: Deserializer<'de>,
	{
		struct IdVisitor;

		impl<'de> Visitor<'de> for IdVisitor {
			type Value = WorldInstance;

			fn expecting(
				&self, formatter: &mut std::fmt::Formatter,
			) -> std::fmt::Result {
				formatter
					.write_str(concat!("a string, WorldInstance, that is of format `{vrc::id:World}:{vrc::id:Instance}`"))
			}

			fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
			where
				E: serde::de::Error,
			{
				let (world, instance) = v.split_once(':').ok_or_else(|| {
					serde::de::Error::invalid_value(
						serde::de::Unexpected::Str(v),
						&"should be able to be split at a `:` character",
					)
				})?;

				let world: World = world.parse().map_err(|e| {
					serde::de::Error::invalid_value(serde::de::Unexpected::Str(v), &e)
				})?;
				let instance: Instance = instance.parse().map_err(|e| {
					serde::de::Error::invalid_value(serde::de::Unexpected::Str(v), &e)
				})?;

				Ok(WorldInstance { instance, world })
			}
		}

		deserializer.deserialize_str(IdVisitor)
	}
}

#[cfg(test)]
#[test]
fn user_id_parsing() {
	// Tupper
	let id = "\"usr_c1644b5b-3ca4-45b4-97c6-a2a0de70d469\"";
	serde_json::from_str::<crate::id::User>(id).unwrap();

	let id = "\"grp_c1644b5b-3ca4-45b4-97c6-a2a0de70d469\"";
	assert!(serde_json::from_str::<crate::id::User>(id).is_err());

	// Valid length old user ID
	let id = "\"qYZJsbJRqA\"";
	serde_json::from_str::<crate::id::User>(id).unwrap();

	// Invalid length
	let id = "\"qYZJsbJRqA1\"";
	assert!(serde_json::from_str::<crate::id::User>(id).is_err());
}

#[cfg(test)]
#[test]
fn world_and_instance() {
	let original_id = "\"wrld_ba913a96-fac4-4048-a062-9aa5db092812:12345~hidden(usr_c1644b5b-3ca4-45b4-97c6-a2a0de70d469)~region(eu)~nonce(27e8414a-59a0-4f3d-af1f-f27557eb49a2)\"";
	let id: crate::id::WorldInstance = serde_json::from_str(original_id)
		.expect("to be able to deserialize WorldInstance");
	let id: String =
		serde_json::to_string(&id).expect("to be able to serialize WorldInstance");
	assert_eq!(original_id, id);
}

#[cfg(test)]
#[test]
fn strict_from_string() {
	use std::str::FromStr;

	let original_id = "\"grp_93451756-8327-4ecc-b978-3e60aa9f64a9\"";
	let id: crate::id::Group =
		serde_json::from_str(original_id).expect("to be able to deserialize Group");
	let id: String =
		serde_json::to_string(&id).expect("to be able to serialize a valid Group");
	assert_eq!(original_id, id);

	let original_id = "\"93451756-8327-4ecc-b978-3e60aa9f64a9\"";

	// For now, deserialization is still allowed with invalid IDs
	//assert!(serde_json::from_str::<crate::id::Group>(original_id).is_err(),
	// "deserializing an invalid Group ID errors");
	assert!(
		crate::id::Group::from_str(original_id).is_err(),
		"from_str for an invalid Group ID errors"
	);
	// From<String> implementations are infallible, which should always should
	// work...
	let id = crate::id::Group::from(original_id);
	assert!(
		!id.is_valid(),
		"Force converted group ID can be detected as invalid"
	);
	let _id: String = serde_json::to_string(&id)
		.expect("to be able to serialize an invalid Group");
}

#[cfg(test)]
#[test]
fn instance_id() {
	let original_id = "\"12345\"";
	let id: crate::id::Instance = serde_json::from_str(original_id)
		.expect("to be able to deserialize instance ID");
	let id: String = serde_json::to_string(&id)
		.expect("to be able to serialize a valid instance");
	assert_eq!(original_id, id);

	serde_json::from_str::<crate::id::Instance>("\"59422~region(eu)\"").unwrap();
	// Heard that instance IDs can be pretty much anything
	//assert!(serde_json::from_str::<crate::id::Instance>("\"region(eu)\"").
	// is_err()); assert!(serde_json::from_str::<crate::id::Instance>("\"1234\""
	// ).is_err());
}