Kanda Foundation 0.8.0
Loading...
Searching...
No Matches
Kanda Cloud Client

The Kanda CloudClient provides a convenient way to interact with Kanda Cloud services. It handles authentication, manages API requests, and provides access to various endpoints for different cloud functionalities.

Getting Started

Obtaining the CloudClient

The CloudClient can be obtained using the AppServiceLocator. This ensures that you're using a properly configured instance of the client throughout your application.

An application-level service container which spans the lifetime of multiple scenes....
Definition AppServiceLocator.cs:27
Provides a way to connect and interact with Kanda Cloud services.
Definition CloudClient.cs:11
Definition CloudAuthentication.cs:20
Definition AppServiceLocator.cs:5

Authentication

The CloudClient supports two main authentication flows:

Saved Credentials Login

This method attempts to log in using previously saved credentials that were encrypted and stored locally.

bool loginSuccess = await cloudClient.Auth.TryLoginWithSavedCredentials(CancellationToken.None);
if (loginSuccess)
{
KandaLog.Write("Successfully logged in with saved credentials");
}
else
{
KandaLog.Write("No valid saved credentials found");
}
ICloudAuthentication Auth
Used for login and credentials management.
Definition CloudClient.cs:15

Device Code Login

This method initiates a device code login flow, which is useful for devices without easy input methods. It provides a code and URL that the user needs to visit to complete authentication.

var deviceCodeData = await cloudClient.Auth.StartLoginWithDeviceCode(CancellationToken.None);
if (deviceCodeData.Succeeded)
{
KandaLog.Write($"Please enter this code: {deviceCodeData.UserCode}");
KandaLog.Write($"At this URL: {deviceCodeData.ActivationUrl}");
}
else
{
KandaLog.Write($"Failed to start device code flow: {deviceCodeData.Message}");
}
// The CloudClient will continue to poll in the background.
// You can listen for login events:
cloudClient.Auth.OnLogin += (LoginType loginType) => {
KandaLog.Write($"Successfully logged in via {loginType}");
};
cloudClient.Auth.OnLoginError += (string errorMessage) => {
KandaLog.Write($"Login failed: {errorMessage}");
};

Authentication Events

The authentication system provides several events you can subscribe to:

  • OnLogin: Called when login completes successfully
  • OnLogout: Called when user logs out successfully
  • OnLoginError: Called when login fails with an error message
  • OnSessionExpired: Called when the session expires and needs re-authentication

Core Endpoints

Note
Please note that any data models, and thus endpoints are named in convention with the Kanda Cloud, not the naming convention of the feature in Kanda SDK.

Check-Ins

Check-ins are used to test connectivity and track active users:

var checkInRequest = new CheckInPostRequest { Origin = "unity3d" };
var response = await cloudClient.CheckIns.CheckIn(checkInRequest, CancellationToken.None);
if (response.Succeeded)
{
KandaLog.Write($"Check-in successful. ID: {response.Data.Id}");
}
ICheckInEndpoint CheckIns
CheckIns are a way of testing connectivity and saying "hello" to Kanda Cloud services....
Definition CloudClient.cs:21

User Profiles

Manage user profile information:

// Get current user's profile
var profileResponse = await cloudClient.UserProfile.GetUserProfile(CancellationToken.None);
if (profileResponse.Succeeded)
{
KandaLog.Write($"Logged in as: {profileResponse.Data.Name}");
KandaLog.Write($"User ID: {profileResponse.Data.Id}");
}
// Update user's name
var updateRequest = new UpdateUserProfileRequest {
Id = profileResponse.Data.Id,
Name = "John Doe"
};
var updateResponse = await cloudClient.UserProfile.UpdateName(updateRequest, CancellationToken.None);
IUserProfileEndpoint UserProfile
UserProfile contains data related to a player.
Definition CloudClient.cs:50

Tenants

Manage organizational tenants that users belong to:

// Get a specific tenant
var tenantResponse = await cloudClient.Tenant.GetById("tenant-id", CancellationToken.None);
if (tenantResponse.Succeeded)
{
KandaLog.Write($"Tenant name: {tenantResponse.Data.Name}");
}
// Get all tenants (paginated)
var tenantsResponse = await cloudClient.Tenant.GetAll(pageSize: 100, CancellationToken.None);
if (tenantsResponse.Succeeded)
{
foreach (var tenant in tenantsResponse.Data.Items)
{
KandaLog.Write($"Found tenant: {tenant.Name}");
}
}
ITenantEndpoint Tenant
Tenants is used to organize users into different buckets (tenants) which is often equivalent to an or...
Definition CloudClient.cs:56

Session Management

Room Containers

Room Containers represent sessions that can contain multiple room instances. They specify which scenarios are available within the session:

// Create a new session with available scenarios
var createRequest = new CreateRoomContainerRequest {
Name = "Training Session",
CreatedByName = "Instructor Name",
ScenarioIds = new List<string> { "scenario-1", "scenario-2" },
AppVersion = Application.version,
Tags = new Dictionary<string, string> {
["hostType"] = HostType.ServerHosted.ToString()
}
};
var createResponse = await cloudClient.RoomContainers.Create(createRequest, CancellationToken.None);
// Get all available sessions
var sessionsResponse = await cloudClient.RoomContainers.GetAll(pageSize: 100, CancellationToken.None);
IRoomContainerEndpoint RoomContainers
RoomContainers can contain one or more RoomInstances. It also contains which Scenarios that can be jo...
Definition CloudClient.cs:33

Room Instances

Room Instances represent specific scenario instances within a session:

// Create a default room instance in a container
var roomRequest = new CreateRoomInstanceRequest {
RoomContainerId = "container-id",
ScenarioId = "scenario-id",
Name = "Main Room",
IsDefault = true,
SceneGuid = "unity-scene-guid"
};
var roomResponse = await cloudClient.RoomInstances.Create(roomRequest, CancellationToken.None);
// Get instances for a container
var instancesResponse = await cloudClient.RoomInstances.GetByRoomContainerId(
"container-id",
CancellationToken.None
);
IRoomInstanceEndpoint RoomInstances
RoomInstances is the lowest level in a session, and contains information about an instance within a s...
Definition CloudClient.cs:40

Room Servers

Manage dedicated server instances for rooms:

// Join a server
var joinRequest = new JoinRoomServerRequest {
RoomInstanceId = "instance-id",
UnityGameServerConfiguration = new UnityGameServerConfiguration {
UnityProjectId = "project-id",
UnityEnvironmentId = "env-id",
BuildConfigurationId = 1234,
FleetId = "fleet-id",
RegionId = "region-id"
}
};
var joinResponse = await cloudClient.RoomServers.Join(joinRequest, CancellationToken.None);
// Leave a server
var leaveRequest = new LeaveRoomServerRequest {
RoomInstanceId = "instance-id"
};
await cloudClient.RoomServers.Leave(leaveRequest, CancellationToken.None);
IRoomServerEndpoint RoomServers
Room servers provide a way to allocate multiplayer servers dedicated to room instances.
Definition CloudClient.cs:26

Error Handling

All endpoint methods return a CloudApiResponse<T> object that includes:

  • Success status
  • HTTP status code
  • Response data (if successful)
  • Error message (if failed)
// Generic error handling pattern
var response = await cloudClient.SomeEndpoint.SomeMethod(request, CancellationToken.None);
if (response.Succeeded)
{
// Work with response.Data
}
else
{
KandaLog.Write($"Request failed ({response.StatusCode}): {response.ErrorMessage}");
}
// You can also use the utility method to throw on failure
CloudApiResponseUtils.ThrowIfFailed(response);

Best Practices

  1. Handle cancellation tokens appropriately to allow for clean request cancellation
  2. Subscribe to authentication events to handle login state changes
  3. Check response.Succeeded before accessing response.Data
  4. Use the utilities provided in CloudUtils for common operations
  5. Consider implementing retry logic for important operations
  6. Remember to handle the OnSessionExpired event to re-authenticate when needed