Skip to content

Commit

Permalink
CrazyGames: integrate basic User SDK [ci skip]
Browse files Browse the repository at this point in the history
  • Loading branch information
geneotech committed Jul 3, 2024
1 parent 7819208 commit a500ed8
Show file tree
Hide file tree
Showing 9 changed files with 150 additions and 52 deletions.
77 changes: 71 additions & 6 deletions cmake/web/assets/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@ const ipinfo_endpoint = 'https://hypersomnia.xyz/geolocation';
const clientIdDiscord = '1189671952479158403';
const revoke_origin = 'https://hypersomnia.xyz';

function passAuthDataToCpp(provider, profileId, profileName, avatarUrl, authToken, expiresIn) {
Module.ccall('on_auth_data_received', 'void', ['string', 'string', 'string', 'string', 'string', 'number'],
[provider, profileId, profileName, avatarUrl, authToken, expiresIn]);
}

function getUserGeolocation() {
fetch(ipinfo_endpoint)
.then(response => response.json())
Expand Down Expand Up @@ -175,16 +180,51 @@ async function pre_run_cg() {
console.log("pre_run_cg");

if (window.CrazyGames) {
await window.CrazyGames.SDK.init();
}
else {
try {
await window.CrazyGames.SDK.init();

const available = window.CrazyGames.SDK.user.isUserAccountAvailable;
console.log("User account system available", available);

if (available) {
try {
const token = await window.CrazyGames.SDK.user.getUserToken();
console.log("Get token result", token);

const payloadBase64 = token.split('.')[1];
const payloadDecoded = atob(payloadBase64);
const payload = JSON.parse(payloadDecoded);

console.log("Decoded token payload", payload);

Module.initial_user = {
userId: payload.userId,
username: payload.username,
profilePictureUrl: payload.profilePictureUrl,
token: token
};
} catch (e) {
console.log("getUserToken failed:", e);
}
}
} catch (e) {
console.log("CG SDK init error: ", e);
}
} else {
console.log("window.CrazyGames is undefined!");
}

console.log("pre_run_cg finished");
Module.removeRunDependency('cginit');
}

function try_fetch_initial_user() {
if (Module.initial_user) {
const u = Module.initial_user;
passAuthDataToCpp('crazygames', u.userId, u.username, u.profilePictureUrl, u.token, 3600);
}
}

function pre_run() {
// Add a run dependency to ensure syncing is done before the application starts
Module.addRunDependency('idbfs');
Expand Down Expand Up @@ -275,9 +315,30 @@ function loginDiscord() {
window.open(authUrl, '_blank');
}

function passAuthDataToCpp(provider, profileId, profileName, avatarUrl, authToken, expiresIn) {
Module.ccall('on_auth_data_received', 'void', ['string', 'string', 'string', 'string', 'string', 'number'],
[provider, profileId, profileName, avatarUrl, authToken, expiresIn]);
function loginCrazyGames() {
if (window.CrazyGames) {
window.CrazyGames.SDK.user.showAuthPrompt()
.then(user => {
if (user) {
return window.CrazyGames.SDK.user.getUserToken();
} else {
throw new Error('User cancelled login or already signed in');
}
})
.then(token => {
const payloadBase64 = token.split('.')[1];
const payloadDecoded = atob(payloadBase64);
const payload = JSON.parse(payloadDecoded);
console.log("Decoded token payload", payload);

passAuthDataToCpp('crazygames', payload.userId, payload.username, payload.profilePictureUrl, token, 3600);
})
.catch(e => {
console.log("Auth prompt or token retrieval failed:", e);
});
} else {
console.log("window.CrazyGames is undefined!");
}
}

function fetchUserProfile(accessToken, expiresIn) {
Expand Down Expand Up @@ -346,9 +407,13 @@ function create_module(for_cg) {

Module.getUserGeolocation = getUserGeolocation;

Module.try_fetch_initial_user = try_fetch_initial_user;

if (for_cg) {
Module.sync_idbfs = sync_idbfs_cg;
Module['preRun'].push(pre_run_cg);

Module.loginCrazyGames = loginCrazyGames;
}

if (for_io) {
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
29 changes: 17 additions & 12 deletions src/application/gui/leaderboards_gui.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -403,22 +403,27 @@ void leaderboards_gui_state::perform(const leaderboards_input in) {

#if PLATFORM_WEB
if (logged_in) {
ImGui::SameLine();
const auto avail = ImGui::GetContentRegionAvail();
if (in.is_crazygames) {
/* No Log Out button. */
}
else {
ImGui::SameLine();
const auto avail = ImGui::GetContentRegionAvail();

float offset_x = avail.x - ImGui::CalcTextSize("Sign in 9").x;
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + offset_x);
float offset_x = avail.x - ImGui::CalcTextSize("Sign in 9").x;
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + offset_x);

auto darkened_selectables = scoped_selectable_colors({
rgba(255, 255, 255, 20),
rgba(255, 255, 255, 30),
rgba(255, 255, 255, 60)
});
auto darkened_selectables = scoped_selectable_colors({
rgba(255, 255, 255, 20),
rgba(255, 255, 255, 30),
rgba(255, 255, 255, 60)
});

//auto sc = scoped_text_color(rgba(255, 255, 255, 200));
//auto sc = scoped_text_color(rgba(255, 255, 255, 200));

if (ImGui::Selectable("Log out", false, 0, ImVec2(100, 0))) {
wants_log_out = true;
if (ImGui::Selectable("Log out", false, 0, ImVec2(100, 0))) {
wants_log_out = true;
}
}
}
#endif
Expand Down
1 change: 1 addition & 0 deletions src/application/gui/leaderboards_gui.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ struct leaderboards_input {
const ltrb menu_ltrb;
#if PLATFORM_WEB
const bool is_logged_in;
const bool is_crazygames;
#endif
};

Expand Down
42 changes: 27 additions & 15 deletions src/application/gui/social_sign_in_gui.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
#include "application/setups/debugger/detail/maybe_different_colors.h"
#include "augs/misc/imgui/imgui_controls.h"

void sign_in_with_google();
void sign_in_with_discord();
void sign_in_with_crazygames();

social_sign_in_state::social_sign_in_state(const std::string& title)
: standard_window_mixin<social_sign_in_state>(title)
Expand All @@ -21,7 +21,13 @@ bool social_sign_in_state::perform(social_sign_in_input in) {

center_next_window(ImGuiCond_Always);

ImGui::SetNextWindowSize(ImVec2(450, in.prompted_once ? 260+60 : 335+60), ImGuiCond_Always);
auto h = in.prompted_once ? 260+60 : 335+60;

if (in.is_crazygames) {
h -= 60;
}

ImGui::SetNextWindowSize(ImVec2(450, h), ImGuiCond_Always);

const auto flags =
ImGuiWindowFlags_NoSavedSettings |
Expand Down Expand Up @@ -110,28 +116,34 @@ bool social_sign_in_state::perform(social_sign_in_input in) {

using N = assets::necessary_image_id;

#if 0
if (login_option(N::SOCIAL_GOOGLE, "Sign in with Google")) {
::sign_in_with_google();
}
#endif

{
auto sc = scoped_text_color(rgba(255, 255, 255, 230));
if (in.is_crazygames) {
ImGui::PushFont(ImGui::GetIO().Fonts->Fonts[1]);

if (login_option(N::SOCIAL_STEAM, "(opt.) Connect Discord to Steam", 1.0f, vec2(0.5, 0.2), 0.6f, "(Optional)\nUseful if you sometimes play Steam version\nand don't want a duplicate Web account.\n\nMatches played with Discord account\nwill count towards your Steam account.")) {
augs::open_url("https://hypersomnia.xyz/profile");
if (login_option(N::SOCIAL_CRAZYGAMES, "Sign in with CrazyGames")) {
#if PLATFORM_WEB
::sign_in_with_crazygames();
#endif
}
}
else {
{
auto sc = scoped_text_color(rgba(255, 255, 255, 230));

ImGui::PushFont(ImGui::GetIO().Fonts->Fonts[1]);
if (login_option(N::SOCIAL_STEAM, "(opt.) Connect Discord to Steam", 1.0f, vec2(0.5, 0.2), 0.6f, "(Optional)\nUseful if you sometimes play Steam version\nand don't want a duplicate Web account.\n\nMatches played with Discord account\nwill count towards your Steam account.")) {
augs::open_url("https://hypersomnia.xyz/profile");
}
}

if (login_option(N::SOCIAL_DISCORD, "Sign in with Discord")) {
ImGui::PushFont(ImGui::GetIO().Fonts->Fonts[1]);

if (login_option(N::SOCIAL_DISCORD, "Sign in with Discord")) {
#if PLATFORM_WEB
::sign_in_with_discord();
::sign_in_with_discord();
#endif
}
}


ImGui::PopFont();

text(" ");
Expand Down
1 change: 1 addition & 0 deletions src/application/gui/social_sign_in_gui.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
struct social_sign_in_input {
const necessary_images_in_atlas_map& necessary_images;
const bool prompted_once;
const bool is_crazygames;
};

struct social_sign_in_state : public standard_window_mixin<social_sign_in_state> {
Expand Down
9 changes: 7 additions & 2 deletions src/application/main/auth_providers.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
std::mutex pending_auth_datas_lk;
std::optional<web_auth_data> new_auth_data;

void sign_in_with_google() {
void sign_in_with_crazygames() {
main_thread_queue::execute([&]() {
EM_ASM({
Module.loginGoogle();
Module.loginCrazyGames();
});
});
}
Expand Down Expand Up @@ -46,6 +46,11 @@ inline void web_auth_data::log_out() {
*this = {};
}

auto has_new_auth_data() {
std::scoped_lock lk(pending_auth_datas_lk);
return new_auth_data.has_value();
}

auto get_new_auth_data() {
std::optional<web_auth_data> new_auth;

Expand Down
2 changes: 1 addition & 1 deletion src/view/necessary_image_id.h
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ namespace assets {
RANK_11,
RANK_12,

SOCIAL_GOOGLE,
SOCIAL_CRAZYGAMES,
SOCIAL_DISCORD,
SOCIAL_STEAM,
ASSOCIATE,
Expand Down
41 changes: 25 additions & 16 deletions src/work.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,11 @@ constexpr bool no_edge_zoomout_v = false;
#include <emscripten/html5.h>

EM_JS(void, call_hideProgress, (), {
hideProgress();
hideProgress();
});

EM_JS(void, call_try_fetch_initial_user, (), {
try_fetch_initial_user();
});

EM_JS(void, call_setLocation, (const char* newPath), {
Expand Down Expand Up @@ -1564,7 +1568,8 @@ work_result work(
WEBSTATIC auto perform_social_sign_in_popup = [&](const bool prompted_once) {
const bool confirmed = social_sign_in.perform({
streaming.necessary_images_in_atlas,
prompted_once
prompted_once,
params.is_crazygames
});

if (confirmed) {
Expand All @@ -1582,13 +1587,22 @@ work_result work(
}
};

try {
social_sign_in.cached_auth = augs::from_json_file<web_auth_data>(CACHED_AUTH_PATH);
LOG("Loaded some cached auth from %x", CACHED_AUTH_PATH);
if (params.is_crazygames) {
call_try_fetch_initial_user();

if (::has_new_auth_data()) {
config.prompted_for_sign_in_once = true;
}
}
catch (...) {
social_sign_in.cached_auth = {};
LOG("No cached auth found in %x", CACHED_AUTH_PATH);
else {
try {
social_sign_in.cached_auth = augs::from_json_file<web_auth_data>(CACHED_AUTH_PATH);
LOG("Loaded some cached auth from %x", CACHED_AUTH_PATH);
}
catch (...) {
social_sign_in.cached_auth = {};
LOG("No cached auth found in %x", CACHED_AUTH_PATH);
}
}

if (social_sign_in.cached_auth.is_set()) {
Expand Down Expand Up @@ -2504,7 +2518,8 @@ work_result work(

menu_ltrb
#if PLATFORM_WEB
, is_signed_in()
, is_signed_in(),
params.is_crazygames
#endif
});
};
Expand Down Expand Up @@ -3181,10 +3196,6 @@ work_result work(
return false;
}

if (params.is_crazygames) {
return false;
}

return true;
}();

Expand All @@ -3194,9 +3205,7 @@ work_result work(
}
}

if (!params.is_crazygames) {
perform_social_sign_in_popup(config.prompted_for_sign_in_once);
}
perform_social_sign_in_popup(config.prompted_for_sign_in_once);

if (const auto new_auth = get_new_auth_data()) {
const auto before_sign_in =
Expand Down

0 comments on commit a500ed8

Please sign in to comment.