use std::sync::Arc;
use crate::achievements::{AchievementCache, Achievements};
use crate::desktop::{offline_only, refresh_ownership_via_desktop, RefreshOutcome, OFFLINE_ONLY_ENV};
use crate::device::{now_unix, primary_device_hash};
use crate::error::{OwnershipStatus, SdkError};
use crate::friends::Friends;
use crate::net::{Net, NetState};
use crate::p2p::{P2p, P2pState};
use crate::paths::{launch_user_id, load_cached_drm_flag, load_session, SessionState};
use crate::session::{Session, SessionSnapshot, TrackingState};
use crate::ticket::{check_ownership_offline, OwnershipCheck};
pub const MAX_GAME_ID_LEN: usize = 256;
pub(crate) fn validate_game_id(game_id: &str) -> Result<(), SdkError> {
if game_id.is_empty() {
return Err(SdkError::invalid_game_id("The game id is empty.")
.with_hint("Set ARCANE_GAME_ID to the game id shown for this title in the Arcane portal."));
}
if game_id.len() > MAX_GAME_ID_LEN {
return Err(SdkError::invalid_game_id("The game id is too long.")
.with_hint("Set ARCANE_GAME_ID to the game id from the Arcane portal, not a file path or a token.")
.with_context("length", game_id.len())
.with_context("max_length", MAX_GAME_ID_LEN));
}
if let Some((index, bad)) = game_id
.char_indices()
.find(|(_, c)| !(c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.')))
{
return Err(SdkError::invalid_game_id(
"The game id contains a character that is not allowed.",
)
.with_hint(
"Allowed characters are ASCII letters, digits, and `_`, `-`, `.`. \
Check for stray whitespace or quotes around the value.",
)
.with_context("index", index)
.with_context("character", format!("{bad:?}")));
}
Ok(())
}
#[derive(Debug, Clone)]
pub struct ArcaneClient {
game_id: String,
user_id: Option<String>,
device_hash: String,
ownership: OwnershipStatus,
ticket_expires_at: Option<i64>,
checked_at: i64,
session: Arc<Session>,
achievements: Arc<AchievementCache>,
p2p: Arc<P2pState>,
net: Arc<NetState>,
}
impl ArcaneClient {
pub fn init() -> Result<Self, SdkError> {
let game_id = crate::paths::launch_game_id()?;
let client = Self::resolve_ownership(&game_id)?;
client.session.begin(client.tracking_state());
Ok(client)
}
fn resolve_ownership(game_id: &str) -> Result<Self, SdkError> {
if offline_only() {
return Self::from_cached_ticket(game_id);
}
match refresh_ownership_via_desktop(game_id) {
Ok(outcome) => Self::after_refresh(game_id, outcome),
Err(err) if err.is_cloud_unreachable() => Self::from_cached_ticket(game_id)
.map_err(|cache_err| cache_err.with_context("desktop_refresh", err.message())),
Err(err) => Err(err),
}
}
fn after_refresh(game_id: &str, outcome: RefreshOutcome) -> Result<Self, SdkError> {
match check_ownership_offline(game_id) {
Ok(check) => {
let mut client = Self::from_check(game_id, check);
client.user_id = client.user_id.or(outcome.user_id);
Ok(client)
}
Err(err) if !outcome.drm_enabled && err.should_refresh_via_desktop() => {
let mut client = Self::drm_disabled(game_id)?;
client.user_id = client.user_id.or(outcome.user_id);
Ok(client)
}
Err(err) => Err(err),
}
}
fn from_cached_ticket(game_id: &str) -> Result<Self, SdkError> {
if let Some(false) = load_cached_drm_flag(game_id) {
return Self::drm_disabled(game_id);
}
check_ownership_offline(game_id).map(|check| Self::from_check(game_id, check))
}
fn tracking_state(&self) -> TrackingState {
if offline_only() {
return TrackingState::Disabled;
}
if self.ownership == OwnershipStatus::DrmDisabled && self.user_id.is_none() {
return TrackingState::Disabled;
}
TrackingState::Pending
}
pub fn refresh(&mut self) -> Result<OwnershipStatus, SdkError> {
if offline_only() {
return Err(SdkError::network_required(
"Ownership refresh is disabled because the SDK is running in offline-only mode.",
)
.with_hint(format!(
"Unset {OFFLINE_ONLY_ENV} to let the SDK contact the Arcane desktop app."
))
.with_context("env", OFFLINE_ONLY_ENV));
}
let outcome = refresh_ownership_via_desktop(&self.game_id)?;
let mut next = match check_ownership_offline(&self.game_id) {
Ok(check) => Self::from_check(&self.game_id, check),
Err(err) if !outcome.drm_enabled && err.should_refresh_via_desktop() => {
Self::drm_disabled(&self.game_id)?
}
Err(err) => return Err(err),
};
next.user_id = next.user_id.or(outcome.user_id).or(self.user_id.clone());
next.session = Arc::clone(&self.session);
next.achievements = Arc::clone(&self.achievements);
next.p2p = Arc::clone(&self.p2p);
next.net = Arc::clone(&self.net);
let status = next.ownership.clone();
*self = next;
Ok(status)
}
pub fn game_id(&self) -> &str {
&self.game_id
}
pub fn user_id(&self) -> Option<&str> {
self.user_id.as_deref()
}
pub fn device_hash(&self) -> &str {
&self.device_hash
}
pub fn ownership(&self) -> OwnershipStatus {
self.ownership.clone()
}
pub fn is_owned(&self) -> bool {
self.ownership == OwnershipStatus::Owned
}
pub fn ticket_expires_at(&self) -> Option<i64> {
self.ticket_expires_at
}
pub fn checked_at(&self) -> i64 {
self.checked_at
}
pub fn frame(&self) {
self.session.frame();
}
pub fn set_graphics(&self, resolution: &str, preset: &str) {
self.session.set_graphics(resolution, preset);
}
pub fn achievements(&self) -> Achievements<'_> {
Achievements::new(&self.game_id, &self.achievements)
}
pub fn friends(&self) -> Friends<'_> {
Friends::new(&self.game_id, self.user_id.as_deref())
}
pub fn p2p(&self) -> P2p<'_> {
P2p::new(&self.game_id, &self.p2p)
}
pub fn net(&self) -> Net<'_> {
Net::new(&self.game_id, &self.net)
}
pub fn session(&self) -> SessionSnapshot {
self.session.snapshot()
}
pub fn shutdown(self) {
self.net().close();
self.session.end();
}
fn from_check(game_id: &str, check: OwnershipCheck) -> Self {
let p2p = Arc::new(P2pState::new());
Self {
game_id: game_id.to_string(),
user_id: check.user_id,
device_hash: check.device_hash,
ownership: check.status,
ticket_expires_at: check.ticket_expires_at,
checked_at: now_unix(),
session: Arc::new(Session::dormant(game_id, Arc::clone(&p2p))),
achievements: Arc::new(AchievementCache::new()),
p2p,
net: Arc::new(NetState::new()),
}
}
fn drm_disabled(game_id: &str) -> Result<Self, SdkError> {
let p2p = Arc::new(P2pState::new());
let user_id = launch_user_id().or_else(|| match load_session() {
SessionState::SignedIn(user_id) => Some(user_id),
_ => None,
});
let device_hash = user_id
.as_deref()
.and_then(primary_device_hash)
.unwrap_or_default();
Ok(Self {
game_id: game_id.to_string(),
user_id,
device_hash,
ownership: OwnershipStatus::DrmDisabled,
ticket_expires_at: None,
checked_at: now_unix(),
session: Arc::new(Session::dormant(game_id, Arc::clone(&p2p))),
achievements: Arc::new(AchievementCache::new()),
p2p,
net: Arc::new(NetState::new()),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_portal_shaped_ids() {
for id in [
"9a1f8c3e-4b27-4d1a-9f6e-2c8b5d70a413",
"game.01_beta",
"ABC",
"0",
] {
assert!(validate_game_id(id).is_ok(), "rejected {id}");
}
}
#[test]
fn rejects_an_empty_id() {
let err = validate_game_id("").unwrap_err();
assert_eq!(err.code(), "invalid_game_id");
assert!(err.hint().is_some());
}
#[test]
fn rejects_an_oversized_id() {
let err = validate_game_id(&"a".repeat(MAX_GAME_ID_LEN + 1)).unwrap_err();
assert_eq!(err.code(), "invalid_game_id");
assert!(err
.context()
.iter()
.any(|(k, v)| k == "length" && v == &(MAX_GAME_ID_LEN + 1).to_string()));
}
#[test]
fn rejects_characters_that_would_escape_a_url_or_path() {
for id in [
"9a1f8c3e/../evil",
"9a1f8c3e 4b27",
"9a1f8c3e?x=1",
"9a1f8c3e#frag",
"9a1f8c3e\n",
" 9a1f8c3e",
"9a1f8c3e ",
"9a1f8c3é",
] {
let err = validate_game_id(id).unwrap_err();
assert_eq!(err.code(), "invalid_game_id", "accepted {id:?}");
}
}
#[test]
fn reports_where_the_bad_character_is() {
let err = validate_game_id("9a1f8/c3e").unwrap_err();
let context: Vec<_> = err
.context()
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
assert!(context.contains(&("index", "5")));
assert!(context.contains(&("character", "'/'")));
}
}