diff --git a/Assets/PlayroomKit/PlayroomKit.cs b/Assets/PlayroomKit/PlayroomKit.cs index b4cffa2..ec7046b 100644 --- a/Assets/PlayroomKit/PlayroomKit.cs +++ b/Assets/PlayroomKit/PlayroomKit.cs @@ -348,7 +348,24 @@ public void ClearTurns(Action callback = null) #endregion - #region Discord + #region Discord Helpers + public static bool IsDicordContext() + { + return Application.absoluteURL.Contains("discord"); + } + + private static bool ValidateDiscord(string warningMessage) + { + if (!IsDicordContext()) + { + UnityEngine.Debug.LogWarning($"[PlayroomDiscord] {warningMessage}"); + return false; + } + return true; + } + #endregion + + #region Discord public void OpenDiscordInviteDialog(Action callback = null) { CheckPlayRoomInitialized(); @@ -391,6 +408,14 @@ public void SubscribeDiscordEvent(SDKEvent eventName, Action callback) _playroomService.SubscribeDiscordEvent(eventName, callback); } + public void PatchDiscordUrlMappings(List mappings, PatchUrlMappingsConfig config = null) + { + if (!ValidateDiscord("PatchUrlMappings only works inside discord.")) + return; + + _playroomService.PatchDiscordUrlMappings(mappings, config); + } + #endregion } } \ No newline at end of file diff --git a/Assets/PlayroomKit/modules/Discord/Utils.cs b/Assets/PlayroomKit/modules/Discord/Utils.cs new file mode 100644 index 0000000..466d52a --- /dev/null +++ b/Assets/PlayroomKit/modules/Discord/Utils.cs @@ -0,0 +1,23 @@ +using System.Collections.Generic; + +namespace Discord +{ + public class Mapping + { + public string Prefix { get; set; } + public string Target { get; set; } + } + + public class RemapInput { + public string URL { get; set; } + public List Mappings { get; set; } + } + + public class PatchUrlMappingsConfig + { + public bool PatchFetch { get; set; } = true; + public bool PatchWebSocket { get; set; } = true; + public bool PatchXhr { get; set; } = true; + public bool PatchSrcAttributes { get; set; } = false; + } +} \ No newline at end of file diff --git a/Assets/PlayroomKit/modules/Discord/Utils.cs.meta b/Assets/PlayroomKit/modules/Discord/Utils.cs.meta new file mode 100644 index 0000000..d56ed58 --- /dev/null +++ b/Assets/PlayroomKit/modules/Discord/Utils.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 346011cae8250034d892b142573453c0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/PlayroomKit/modules/Headers.cs b/Assets/PlayroomKit/modules/Headers.cs index b1b9aee..4f1e2bc 100644 --- a/Assets/PlayroomKit/modules/Headers.cs +++ b/Assets/PlayroomKit/modules/Headers.cs @@ -187,6 +187,9 @@ private static extern string GetPersistentDataInternal(string key, [DllImport("__Internal")] private static extern void SubscribeDiscordInternal(string eventName, Action callback); + + [DllImport("__Internal")] + private static extern void PatchDiscordUrlMappingsInternal(string prefix, string target); #endregion } } \ No newline at end of file diff --git a/Assets/PlayroomKit/modules/Interfaces/IPlayroomBase.cs b/Assets/PlayroomKit/modules/Interfaces/IPlayroomBase.cs index 7a5176a..ffca027 100644 --- a/Assets/PlayroomKit/modules/Interfaces/IPlayroomBase.cs +++ b/Assets/PlayroomKit/modules/Interfaces/IPlayroomBase.cs @@ -79,6 +79,7 @@ public void InsertCoin(InitOptions options = null, Action onLaunchCallBack = nul public void GetDiscordEntitlements(Action> callback); public void DiscordPriceFormat(float price, string currency, string locale, Action callback); public void SubscribeDiscordEvent(SDKEvent eventName, Action callback); + public void PatchDiscordUrlMappings(List mappings, PatchUrlMappingsConfig config = null); #endregion diff --git a/Assets/PlayroomKit/modules/Interfaces/IPlayroomBuildExtensions.cs b/Assets/PlayroomKit/modules/Interfaces/IPlayroomBuildExtensions.cs index 382c377..98c4dff 100644 --- a/Assets/PlayroomKit/modules/Interfaces/IPlayroomBuildExtensions.cs +++ b/Assets/PlayroomKit/modules/Interfaces/IPlayroomBuildExtensions.cs @@ -1,3 +1,6 @@ +using Discord; +using System.Collections.Generic; + namespace Playroom { public interface IPlayroomBuildExtensions @@ -7,5 +10,7 @@ public interface IPlayroomBuildExtensions void SetState(string key, bool value, bool reliable = false); void SetState(string key, float value, bool reliable = false); void SetState(string key, object value, bool reliable = false); + + void PatchDiscordUrlMappings(List mappings, PatchUrlMappingsConfig config = null); } } \ No newline at end of file diff --git a/Assets/PlayroomKit/modules/MockMode/BrowserMode/BrowserMockService.cs b/Assets/PlayroomKit/modules/MockMode/BrowserMode/BrowserMockService.cs index 5a0b12d..3b66496 100644 --- a/Assets/PlayroomKit/modules/MockMode/BrowserMode/BrowserMockService.cs +++ b/Assets/PlayroomKit/modules/MockMode/BrowserMode/BrowserMockService.cs @@ -354,6 +354,11 @@ public void OpenDiscordExternalLink(string url, Action callback = null) DebugLogger.LogWarning("[MockMode] Discord external link is currently not supported in browser mock mode!"); callback?.Invoke("true"); } + + public void PatchDiscordUrlMappings(List mappings, PatchUrlMappingsConfig config = null) + { + DebugLogger.LogWarning("[MockMode] Patch Discord URL Mappings is currently not supported in browser mock mode!"); + } #endregion } #endif diff --git a/Assets/PlayroomKit/modules/MockMode/LocalPlayroomService.cs b/Assets/PlayroomKit/modules/MockMode/LocalPlayroomService.cs index dccd18a..4b0eeb8 100644 --- a/Assets/PlayroomKit/modules/MockMode/LocalPlayroomService.cs +++ b/Assets/PlayroomKit/modules/MockMode/LocalPlayroomService.cs @@ -254,6 +254,11 @@ public void OpenDiscordExternalLink(string url, Action callback = null) DebugLogger.LogWarning("[MockMode] Discord external link is currently not supported in local mode!"); callback?.Invoke("true"); } + + public void PatchDiscordUrlMappings(List mappings, PatchUrlMappingsConfig config = null) + { + DebugLogger.LogWarning("[MockMode] Patch Discord URL Mappings is currently not supported in local mode!"); + } #endregion } } \ No newline at end of file diff --git a/Assets/PlayroomKit/modules/PlayroomBuildService.cs b/Assets/PlayroomKit/modules/PlayroomBuildService.cs index ac884f0..66429e0 100644 --- a/Assets/PlayroomKit/modules/PlayroomBuildService.cs +++ b/Assets/PlayroomKit/modules/PlayroomBuildService.cs @@ -433,6 +433,14 @@ private static void ClearTurnsCallback() #endregion #region Discord API + public void PatchDiscordUrlMappings(List mappings, PatchUrlMappingsConfig config = null) + { + for (int i = 0; i < mappings.Count; i++) + { + PatchDiscordUrlMappingsInternal(mappings[i].Prefix, mappings[i].Target); + } + } + public void OpenDiscordInviteDialog(Action callback = null) { CheckPlayRoomInitialized(); @@ -598,7 +606,6 @@ private static void InvokeOnErrorInsertCoin(string error) _onError?.Invoke(error); Debug.LogException(new Exception(error)); } - #endregion } } diff --git a/Assets/PlayroomKit/src/index.js b/Assets/PlayroomKit/src/index.js index 881d8d7..3ed197f 100644 --- a/Assets/PlayroomKit/src/index.js +++ b/Assets/PlayroomKit/src/index.js @@ -1208,8 +1208,7 @@ mergeInto(LibraryManager.library, { }, - // callback variant - DiscordPriceFormatInternal: function(amount, currencyOrPtr, localeOrPtr, callbackPtr) { + DiscordPriceFormatInternal: function(amount, currencyOrPtr, localeOrPtr, callbackPtr) { var currency = (typeof currencyOrPtr === 'string') ? currencyOrPtr : UTF8ToString(currencyOrPtr); @@ -1229,9 +1228,24 @@ mergeInto(LibraryManager.library, { {{{ makeDynCall("vi", "callbackPtr") }}}(0); }); }, - - //#endregion + + PatchDiscordUrlMappingsInternal: function (prefix, target) { + prefix = UTF8ToString(prefix); + target = UTF8ToString(target); + console.log(`[JSLIB]: PatchingURL: ${prefix} and ${target}`); + + try { + Playroom.getDiscordSDK().then(discordSDK => { + discordSDK.patchUrlMappings([{ prefix: prefix, target: target }]); + }).catch(err => { + console.error("Discord SDK load failed:", err); + }); + } catch (error) { + console.error(`[JSLIB] error PatchUrlMappingsInternal: ${error}`); + } + }, + //#endregion //#region Utils GetPlayroomTokenInternal: function () { diff --git a/Assets/Scenes/TestScene.unity b/Assets/Scenes/TestScene.unity index 32c6ca9..fccab54 100644 --- a/Assets/Scenes/TestScene.unity +++ b/Assets/Scenes/TestScene.unity @@ -266,7 +266,7 @@ GameObject: serializedVersion: 6 m_Component: - component: {fileID: 1054460207} - - component: {fileID: 1054460206} + - component: {fileID: 1054460208} m_Layer: 0 m_Name: GameManager m_TagString: Untagged @@ -274,23 +274,6 @@ GameObject: m_NavMeshLayer: 0 m_StaticEditorFlags: 0 m_IsActive: 1 ---- !u!114 &1054460206 -MonoBehaviour: - m_ObjectHideFlags: 0 - m_CorrespondingSourceObject: {fileID: 0} - m_PrefabInstance: {fileID: 0} - m_PrefabAsset: {fileID: 0} - m_GameObject: {fileID: 1054460205} - m_Enabled: 1 - m_EditorHideFlags: 0 - m_Script: {fileID: 11500000, guid: dc3a2b9cdc24aab40906ce4bcdee9943, type: 3} - m_Name: - m_EditorClassIdentifier: - baseUrl: https://ws.joinplayroom.com/api/store - gameApiKey: - text: {fileID: 1547749} - skus: [] - entitlements: [] --- !u!4 &1054460207 Transform: m_ObjectHideFlags: 0 @@ -306,6 +289,19 @@ Transform: m_Children: [] m_Father: {fileID: 0} m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!114 &1054460208 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1054460205} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: 75cfd53c3bec10f4cbfc44d61b3f260c, type: 3} + m_Name: + m_EditorClassIdentifier: + responseText: {fileID: 1547749} --- !u!1001 &1407290422 PrefabInstance: m_ObjectHideFlags: 0 diff --git a/Assets/Scripts/GameManager.cs b/Assets/Scripts/GameManager.cs index 293f4ae..e98011f 100644 --- a/Assets/Scripts/GameManager.cs +++ b/Assets/Scripts/GameManager.cs @@ -46,7 +46,6 @@ public class GameManager : MonoBehaviour #endregion - #region Debug UI [Header("Debug UI")] private bool showDebugWindow = false; @@ -58,6 +57,13 @@ public class GameManager : MonoBehaviour private string discordSkusText = ""; private string hqEntitlementsText = ""; private string hqSkusText = ""; + + + List mappings = new() + { + new Mapping() { Prefix = "json", Target = "jsonplaceholder.typicode.com", } + }; + #endregion #region Custom Classes @@ -70,19 +76,27 @@ public class CustomMetadataClass #region Unity Lifecycle - - - void Awake() + IEnumerator GetRequest(string url, Action onComplete) { - if (Application.absoluteURL.Contains("discord")) + using (UnityWebRequest webRequest = UnityWebRequest.Get(url)) { - baseUrl = ".proxy/_ws/api/store"; - } - else - { - baseUrl = "https://ws.joinplayroom.com/api/store"; + yield return webRequest.SendWebRequest(); + if (webRequest.result == UnityWebRequest.Result.Success) + { + Debug.Log("Response: " + webRequest.downloadHandler.text); + onComplete?.Invoke(webRequest.downloadHandler.text); + } + else + { + Debug.LogError("Error: " + webRequest.error); + onComplete?.Invoke(webRequest.downloadHandler.text); + } } + } + + void Awake() + { // Initialize fake Discord SKUs discordSkus = new List { @@ -157,14 +171,15 @@ private void Update() if (Input.GetKeyDown(KeyCode.P)) { - playroomKit.StartDiscordPurchase(skuId, (response) => - { - discordEntitlements = DiscordEntitlement.FromJSON(response); - debugText = "Purchase completed!\n" + response; - }, (onErrorResponse) => + + Debug.LogWarning("Patching Discord URL Mappings"); + + playroomKit.PatchDiscordUrlMappings(new() { - text.text = onErrorResponse; + new Mapping() { Prefix = ".proxy/json", Target = "jsonplaceholder.typicode.com", }, }); + + } if (Input.GetKeyDown(KeyCode.T)) @@ -221,6 +236,15 @@ private void Update() }); } + if (Input.GetKeyDown(KeyCode.J)) + { + StartCoroutine(GetRequest("https://jsonplaceholder.typicode.com/todos/1", (response) => + { + text.text = "Response from JSON Placeholder: " + response; + Debug.Log("Response: " + response); + })); + } + } #endregion @@ -461,6 +485,4 @@ GUIStyle EditorLabelBold() return style; } #endregion - - } \ No newline at end of file diff --git a/Assets/Scripts/Test.cs b/Assets/Scripts/Test.cs new file mode 100644 index 0000000..95412fd --- /dev/null +++ b/Assets/Scripts/Test.cs @@ -0,0 +1,110 @@ +using UnityEngine; +using Playroom; +using System.Collections.Generic; +using System.Collections; +using UnityEngine.Networking; +using TMPro; +using UnityEngine.UI; +using Discord; +using System; + + +public class Test : MonoBehaviour +{ + PlayroomKit prk; + + [Header("UI Elements")] + [SerializeField] TextMeshProUGUI responseText; + + // Using Playroomkit for setting up discord auth and hosting the activity. PlayroomKit prk; + bool discordReady; + + // Creating the mappings for the external resources, we will need to add this in discord developer portal as well check : https://discord.com/developers/docs/activities/development-guides#using-external-resources + List mappings = new() + { + new Mapping() { Prefix = "/.proxy/json", Target = "jsonplaceholder.typicode.com", }, + new Mapping() { Prefix = "/.proxy/_ws", Target = "https://ws.joinplayroom.com", } + }; + + void Awake() + { + prk = new(); + prk.PatchDiscordUrlMappings(mappings); + } + + void Start() + { + prk.InsertCoin(new() + { + // gameId = "cW0r8UJ1aXnZ8v5TPYmv", + gameId = "FmOBeUfQO2AOLNIrJNSJ", + discord = true, + }, () => + { + Debug.LogWarning("Coin Inserted"); + }); + } + + void Update() + { + if (Input.GetKeyDown(KeyCode.Space)) + { + APICall(); + } + + if (Input.GetKeyDown(KeyCode.S)) + { + StartCoroutine(GetSKUS((response) => + { + Debug.LogWarning("SKUs: " + response); + responseText.text = response; + })); + } + } + + #region API Call + private void APICall() + { + StartCoroutine(GetRequest("https://jsonplaceholder.typicode.com/todos/1")); + } + + IEnumerator GetRequest(string url) + { + using (UnityWebRequest webRequest = UnityWebRequest.Get(url)) + { + yield return webRequest.SendWebRequest(); + if (webRequest.result == UnityWebRequest.Result.Success) + { + Debug.Log("Response: " + webRequest.downloadHandler.text); + responseText.text = webRequest.downloadHandler.text; + } + else + { + Debug.LogError("Error: " + webRequest.error); + responseText.text = webRequest.error; + } + } + } + + private IEnumerator GetSKUS(Action onRequestComplete = null) + { + // var url = $"https://ws.joinplayroom.com/api/store/sku?gameId={UnityWebRequest.EscapeURL("FmOBeUfQO2AOLNIrJNSJ")}&platform={UnityWebRequest.EscapeURL("discord")}"; + var url = $"/.proxy/_ws/api/store/sku?gameId={UnityWebRequest.EscapeURL("FmOBeUfQO2AOLNIrJNSJ")}&platform={UnityWebRequest.EscapeURL("discord")}"; + + using (var req = UnityWebRequest.Get(url)) + { + req.SetRequestHeader("x-game-api", "510a71af-3a69-4f5d-9b9b-296a1871e624"); + yield return req.SendWebRequest(); + + if (req.result == UnityWebRequest.Result.ConnectionError || req.result == UnityWebRequest.Result.ProtocolError) + { + Debug.LogError($"Error fetching SKUs: {req.error}"); + } + else + { + onRequestComplete?.Invoke(req.downloadHandler.text); + } + } + } + #endregion +} \ No newline at end of file diff --git a/Assets/Scripts/Test.cs.meta b/Assets/Scripts/Test.cs.meta new file mode 100644 index 0000000..9f5baf8 --- /dev/null +++ b/Assets/Scripts/Test.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 75cfd53c3bec10f4cbfc44d61b3f260c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: