diff --git a/Classes/Admin/Console.cs b/Classes/Admin/Console.cs new file mode 100644 index 0000000..5bd1198 --- /dev/null +++ b/Classes/Admin/Console.cs @@ -0,0 +1,1976 @@ +using ExitGames.Client.Photon; +using GorillaNetworking; +using GorillaTag.Rendering; +using Photon.Pun; +using Photon.Realtime; +using Photon.Voice.Unity; +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; +using TMPro; +using UnityEngine; +using UnityEngine.Networking; +using UnityEngine.Rendering; +using UnityEngine.Rendering.Universal; +using UnityEngine.UI; +using UnityEngine.Video; +using JoinType = GorillaNetworking.JoinType; +using Random = UnityEngine.Random; + +namespace FortniteEmoteWheel.Classes.Admin; + +public class Console : MonoBehaviour +{ + private const string ResourceLocation = "Console"; + + private const string HamburburSuperAdminIcon = "https://files.deez.uk/HamburburSuperDuperAdmin.png"; + private const string HamburburAdminIcon = "https://files.deez.uk/HamburburAdmin.png"; + + public const byte ConsoleByte = 68; + + private const string AssetsURL = "https://raw.githubusercontent.com/hamburbur-org/Public-Assets/refs/heads/main/"; + + public const string BlockedKey = "ConsoleBlocked"; + + private static Console instance; + + private static readonly Dictionary Textures = new(); + + private static readonly Dictionary Audios = new(); + + private static readonly Dictionary MenuColors = new() + { + { "stupid", new Color32(255, 128, 0, 255) }, + { "symex", new Color32(138, 43, 226, 255) }, + { "colossal", new Color32(204, 0, 255, 255) }, + { "ccm", new Color32(204, 0, 255, 255) }, + { "untitled", new Color32(45, 115, 175, 255) }, + { "genesis", Color.blue }, + { "console", Color.gray }, + { "resurgence", new Color32(113, 10, 10, 255) }, + { "grate", new Color32(195, 145, 110, 255) }, + { "sodium", new Color32(220, 208, 255, 255) }, + { "hamburbur", new Color(0.1694782f, 0.1504984f, 0.3584906f) }, + { "DamnThatsAlotOfInfo", Color.blue }, + { "ZlothY Nametag", Color.blue }, + { "ZlothY Dances", Color.blue }, + { "WalkSimulator", Color.blue }, + }; + + public static long IsBlocked; + + private static readonly Dictionary ConfirmUsingDelay = []; + + public static float IndicatorDelay = 0f; + + public static readonly Dictionary AssetBundlePool = []; + public static readonly Dictionary ConsoleAssets = []; + private static readonly int Surface = Shader.PropertyToID("_Surface"); + private static readonly int Blend = Shader.PropertyToID("_Blend"); + private static readonly int SrcBlend = Shader.PropertyToID("_SrcBlend"); + private static readonly int DstBlend = Shader.PropertyToID("_DstBlend"); + private static readonly int ZWrite = Shader.PropertyToID("_ZWrite"); + private static readonly int MainTex = Shader.PropertyToID("_MainTex"); + + private readonly Dictionary conePool = new(); + + private class AdminIndicator + { + public GameObject Object; + public Renderer Renderer; + public TextMeshProUGUI Text; + } + private readonly List excludedCones = []; + + private readonly Dictionary> indicatorDistanceList = new(); + private readonly List toRemove = []; + + private Material adminHamburburMaterial; + private Texture2D adminHamburburTexture; + + private bool adminIsScaling; + private VRRig adminRigTarget; + private float adminScale = 1f; + + private Coroutine laserCoroutine; + + private Coroutine shakeCoroutine; + + private Coroutine smoothTeleportCoroutine; + + private Material superAdminHamburburMaterial; + private Texture2D superAdminHamburburTexture; + + private void Awake() + { + instance = this; + PhotonNetwork.NetworkingClient.EventReceived += EventReceived; + + NetworkSystem.Instance.OnReturnedToSinglePlayer += ClearConsoleAssets; + NetworkSystem.Instance.OnPlayerJoined += SyncConsoleAssets; + + if (PlayerPrefs.HasKey(BlockedKey)) + IsBlocked = long.Parse(PlayerPrefs.GetString(BlockedKey)); + + NetworkSystem.Instance.OnJoinedRoomEvent += BlockedCheck; + + if (!Directory.Exists(ResourceLocation)) + Directory.CreateDirectory(ResourceLocation); + + instance.StartCoroutine(DownloadAdminTextures()); + instance.StartCoroutine(PreloadAssets()); + + ((UniversalRenderPipelineAsset)GraphicsSettings.currentRenderPipeline).supportsCameraOpaqueTexture = true; + ((UniversalRenderPipelineAsset)GraphicsSettings.currentRenderPipeline).supportsCameraDepthTexture = true; + } + + private void Update() + { + if (PhotonNetwork.InRoom) + { + // Try catches don't majorly impact performance unless an exception actually throws + try + { + // ReSharper disable once ForeachCanBePartlyConvertedToQueryUsingAnotherGetEnumerator + // Dict Enumerator is a struct + foreach (KeyValuePair nametag in conePool) + { + Player nametagPlayer = nametag.Key.Creator?.GetPlayerRef(); + + if (VRRigCache.ActiveRigs.Contains(nametag.Key) && + nametagPlayer != null && + HamburburData.Admins.ContainsKey(nametagPlayer.UserId) && + !excludedCones.Contains(nametagPlayer)) + continue; + + Destroy(nametag.Value.Object); + toRemove.Add(nametag.Key); + } + + // Cant remove whilst iterating dict + foreach (VRRig rig in toRemove) + conePool.Remove(rig); + + toRemove.Clear(); + + bool localIsSuperAdmin = + HamburburData.Admins.TryGetValue(PhotonNetwork.LocalPlayer.UserId, out string localAdminName) && + (HamburburData.HamburburSuperAdmins.Contains(localAdminName)); + + foreach (Player player in PhotonNetwork.PlayerListOthers) + { + if (!HamburburData.Admins.TryGetValue(player.UserId, out string adminName)) + continue; + + if (!localIsSuperAdmin && excludedCones.Contains(player)) + continue; + + VRRig playerRig = GetVRRigFromPlayer(player); + + if (playerRig == null) + continue; + + GameObject adminConeObject; + TextMeshProUGUI adminNameText; + Renderer adminConeRenderer; + + if (conePool.TryGetValue(playerRig, out AdminIndicator coneData)) + { + adminConeObject = coneData.Object; + adminNameText = coneData.Text; + adminConeRenderer = coneData.Renderer; + } + else + { + adminConeObject = GameObject.CreatePrimitive(PrimitiveType.Cube); + Destroy(adminConeObject.GetComponent()); + + adminConeRenderer = adminConeObject.GetComponent(); + + // Gets created once for each new admin, does not impact performance + + GameObject canvasObj = new("AdminNameCanvas"); + canvasObj.transform.SetParent(adminConeObject.transform, false); + canvasObj.transform.localPosition = new Vector3(0f, 0.6f, 0f); + canvasObj.transform.localRotation = Quaternion.Euler(0f, 180f, 0f); + canvasObj.transform.localScale = Vector3.one * 0.0035f; + + Canvas canvas = canvasObj.AddComponent(); + canvas.renderMode = RenderMode.WorldSpace; + + CanvasScaler scaler = canvasObj.AddComponent(); + scaler.dynamicPixelsPerUnit = 10f; + + adminNameText = new GameObject("AdminNameText").AddComponent(); + adminNameText.transform.SetParent(canvasObj.transform, false); + adminNameText.text = adminName; + adminNameText.enableAutoSizing = true; + adminNameText.fontStyle = FontStyles.Bold; + adminNameText.color = playerRig.playerColor; + adminNameText.alignment = TextAlignmentOptions.Center; + + RectTransform textRect = adminNameText.GetComponent(); + textRect.anchoredPosition = Vector2.zero; + textRect.sizeDelta = new Vector2(200f, 100f); + + if (HamburburData.HamburburSuperAdmins.Contains(adminName)) + adminConeRenderer.material = superAdminHamburburMaterial; + else + adminConeRenderer.material = adminHamburburMaterial; + + conePool.Add(playerRig, new AdminIndicator + { + Object = adminConeObject, + Renderer = adminConeRenderer, + Text = adminNameText, + }); + } + + adminConeRenderer.material.color = playerRig.playerColor; + adminNameText.color = playerRig.playerColor; + + adminConeObject.transform.localScale = + new Vector3(0.4f, 0.4f, 0.0001f) * playerRig.scaleFactor; + + adminConeObject.transform.position = + playerRig.bodyRenderer.transform.TransformPoint(0f, 1f, 0f); + + adminConeObject.transform.LookAt( + GorillaTagger.Instance.headCollider.transform.position + ); + + Vector3 rot = adminConeObject.transform.rotation.eulerAngles; + rot += new Vector3(0f, 0f, Mathf.Sin(Time.time * 2f) * 25f); + + adminConeObject.transform.rotation = Quaternion.Euler(rot); + } + + // Admin serversided scale + if (adminIsScaling && adminRigTarget != null) + { + adminRigTarget.NativeScale = adminScale; + if (Mathf.Approximately(adminScale, 1f)) + adminIsScaling = false; + } + } + catch + { + // ignored + } + } + else + { + if (conePool.Count > 0) + { + foreach (KeyValuePair cone in conePool) + Destroy(cone.Value.Object); + + conePool.Clear(); + } + } + + SanitizeConsoleAssets(); + } + + public void OnDisable() => + PhotonNetwork.NetworkingClient.EventReceived -= EventReceived; + + private Material CreateAdminMaterial(Texture texture) + { + // ReSharper disable once ShaderLabShaderReferenceNotResolved + Material material = new(Shader.Find("Universal Render Pipeline/Unlit")) + { + mainTexture = texture, + }; + + // String based property lookup is inefficient + material.SetFloat(Surface, 1); + material.SetFloat(Blend, 0); + material.SetFloat(SrcBlend, (float)BlendMode.SrcAlpha); + material.SetFloat(DstBlend, (float)BlendMode.OneMinusSrcAlpha); + material.SetFloat(ZWrite, 0); + material.EnableKeyword("_SURFACE_TYPE_TRANSPARENT"); + material.renderQueue = (int)RenderQueue.Transparent; + + return material; + } + + private static Material CreateAdminMaterial(Material baseMaterial, Texture texture) => + new(baseMaterial) { mainTexture = texture, }; + + private void SendNotification(string text, int sendTime = 1000) { } + + private void EnableMod(string mod, bool enable) { } + + private void ToggleMod(string mod) { } + + private void ConfirmUsing(string id, string version, string menuName) { } + + private static void Log(string text) => Debug.Log(text); + + public static void LoadConsole() => new GameObject("seralyth_Console").AddComponent(); + + private string SanitizeFileName(string fileName) + { + if (string.IsNullOrWhiteSpace(fileName)) + return null; + + string justName = Path.GetFileName(fileName); + + return string.IsNullOrWhiteSpace(justName) + ? null + : Path.GetInvalidFileNameChars() + .Aggregate(justName, (current, c) => current.Replace(c.ToString(), "")); + } + + private IEnumerator GetTextureResource(string url, Action onComplete = null) + { + if (!Textures.TryGetValue(url, out Texture2D texture)) + { + string fileName = + $"{ResourceLocation}/{SanitizeFileName(Uri.UnescapeDataString(url.Split("/")[^1]))}"; + + if (File.Exists(fileName)) + File.Delete(fileName); + + Log($"Downloading {fileName}"); + using HttpClient client = new(); + Task downloadTask = client.GetByteArrayAsync(url); + + while (!downloadTask.IsCompleted) + yield return null; + + if (downloadTask.Exception != null) + { + Log("Failed to download texture: " + downloadTask.Exception); + + yield break; + } + + byte[] downloadedData = downloadTask.Result; + Task writeTask = File.WriteAllBytesAsync(fileName, downloadedData); + + while (!writeTask.IsCompleted) + yield return null; + + if (writeTask.Exception != null) + { + Log("Failed to save texture: " + writeTask.Exception); + + yield break; + } + + Task readTask = File.ReadAllBytesAsync(fileName); + + while (!readTask.IsCompleted) + yield return null; + + if (readTask.Exception != null) + { + Log("Failed to read texture file: " + readTask.Exception); + + yield break; + } + + byte[] bytes = readTask.Result; + texture = new Texture2D(2, 2); + texture.LoadImage(bytes); + } + + Textures[url] = texture; + onComplete?.Invoke(texture); + } + + private IEnumerator GetSoundResource(string url, Action onComplete = null) + { + if (!Audios.TryGetValue(url, out AudioClip audio)) + { + string fileName = + $"{ResourceLocation}/{SanitizeFileName(Uri.UnescapeDataString(url.Split("/")[^1]))}"; + + if (File.Exists(fileName)) + File.Delete(fileName); + + Log($"Downloading {fileName}"); + using HttpClient client = new(); + Task downloadTask = client.GetByteArrayAsync(url); + + while (!downloadTask.IsCompleted) + yield return null; + + if (downloadTask.Exception != null) + { + Log("Failed to download texture: " + downloadTask.Exception); + + yield break; + } + + byte[] downloadedData = downloadTask.Result; + Task writeTask = File.WriteAllBytesAsync(fileName, downloadedData); + + while (!writeTask.IsCompleted) + yield return null; + + if (writeTask.Exception != null) + { + Log("Failed to save texture: " + writeTask.Exception); + + yield break; + } + + string filePath = Assembly.GetExecutingAssembly().Location.Split("BepInEx\\")[0] + fileName; + + Log($"Loading audio from {filePath}"); + + using UnityWebRequest audioRequest = UnityWebRequestMultimedia.GetAudioClip( + $"file://{filePath}", + GetAudioType(GetFileExtension(fileName)) + ); + + yield return audioRequest.SendWebRequest(); + + if (audioRequest.result != UnityWebRequest.Result.Success) + { + Log("Failed to load audio: " + audioRequest.error); + + yield break; + } + + audio = DownloadHandlerAudioClip.GetContent(audioRequest); + } + + Audios[url] = audio; + onComplete?.Invoke(audio); + } + + private IEnumerator PlaySoundMicrophone(AudioClip sound) + { + GorillaTagger.Instance.myRecorder.SourceType = Recorder.InputSourceType.AudioClip; + GorillaTagger.Instance.myRecorder.AudioClip = sound; + GorillaTagger.Instance.myRecorder.RestartRecording(true); + GorillaTagger.Instance.myRecorder.DebugEchoMode = true; + + yield return new WaitForSeconds(sound.length + 0.4f); + + GorillaTagger.Instance.myRecorder.SourceType = Recorder.InputSourceType.Microphone; + GorillaTagger.Instance.myRecorder.AudioClip = null; + GorillaTagger.Instance.myRecorder.RestartRecording(true); + GorillaTagger.Instance.myRecorder.DebugEchoMode = false; + } + + private IEnumerator DownloadAdminTextures() + { + yield return DownloadAdminTexture( + HamburburSuperAdminIcon, + texture => superAdminHamburburTexture = texture + ); + + yield return DownloadAdminTexture( + HamburburAdminIcon, + texture => adminHamburburTexture = texture + ); + + adminHamburburMaterial = CreateAdminMaterial(adminHamburburTexture); + + superAdminHamburburMaterial = CreateAdminMaterial(adminHamburburMaterial, superAdminHamburburTexture); + } + + private IEnumerator DownloadAdminTexture(string url, Action onComplete) + { + if (Textures.TryGetValue(url, out Texture2D cachedTexture)) + { + onComplete?.Invoke(cachedTexture); + + yield break; + } + + Log($"Downloading {url}"); + + using HttpClient client = new(); + Task downloadTask = client.GetByteArrayAsync(url); + + while (!downloadTask.IsCompleted) + yield return null; + + if (downloadTask.Exception != null) + { + Log("Failed to download texture: " + downloadTask.Exception); + + yield break; + } + + byte[] bytes = downloadTask.Result; + + Texture2D texture = new(2, 2); + bool loaded = texture.LoadImage(bytes); + + if (!loaded) + { + Log("Failed to load texture from downloaded bytes."); + + yield break; + } + + Textures[url] = texture; + onComplete?.Invoke(texture); + } + + private string GetFileExtension(string fileName) => + fileName.ToLower().Split(".")[fileName.Split(".").Length - 1]; + + private AudioType GetAudioType(string extension) => extension.ToLower() switch + { + "mp3" => AudioType.MPEG, + "wav" => AudioType.WAV, + "ogg" => AudioType.OGGVORBIS, + "aiff" => AudioType.AIFF, + var _ => AudioType.WAV, + }; + + private IEnumerator PreloadAssets() + { + using UnityWebRequest request = UnityWebRequest.Get($"{AssetsURL}/PreloadedAssets.txt"); + + yield return request.SendWebRequest(); + + if (request.result != UnityWebRequest.Result.Success) + yield break; + + string returnText = request.downloadHandler.text; + + foreach (string assetBundle in returnText.Split("\n")) + if (assetBundle.Length > 0) + instance.StartCoroutine(PreloadAssetBundle(assetBundle)); + } + + private float GetIndicatorDistance(VRRig rig) + { + if (indicatorDistanceList.ContainsKey(rig)) + { + if (indicatorDistanceList[rig][0] == Time.frameCount) + { + indicatorDistanceList[rig].Add(Time.frameCount); + + return 0.3f + indicatorDistanceList[rig].Count * 0.5f; + } + + indicatorDistanceList[rig].Clear(); + indicatorDistanceList[rig].Add(Time.frameCount); + + return 0.3f + indicatorDistanceList[rig].Count * 0.5f; + } + + indicatorDistanceList.Add(rig, [Time.frameCount,]); + + return 0.8f; + } + + public static Color GetMenuTypeName(string type) => + MenuColors.TryGetValue(type, out Color typeName) ? typeName : Color.red; + + private Player GetMasterAdministrator() => PhotonNetwork.PlayerList + .Where(player => + HamburburData.Admins.ContainsKey( + player.UserId)) + .OrderBy(player => player.ActorNumber) + .FirstOrDefault(); + + private void LightningStrike(Vector3 position) + { + Color color = Color.cyan; + + GameObject line = new("LightningOuter"); + LineRenderer liner = line.AddComponent(); + liner.startColor = color; + liner.endColor = color; + liner.startWidth = 0.25f; + liner.endWidth = 0.25f; + liner.positionCount = 5; + liner.useWorldSpace = true; + Vector3 victim = position; + for (int i = 0; i < 5; i++) + { + VRRig.LocalRig.PlayHandTapLocal(68, false, 0.25f); + VRRig.LocalRig.PlayHandTapLocal(68, true, 0.25f); + + liner.SetPosition(i, victim); + victim += new Vector3(Random.Range(-5f, 5f), 5f, Random.Range(-5f, 5f)); + } + + liner.material.shader = Shader.Find("GUI/Text Shader"); + Destroy(line, 2f); + + GameObject line2 = new("LightningInner"); + LineRenderer liner2 = line2.AddComponent(); + liner2.startColor = Color.white; + liner2.endColor = Color.white; + liner2.startWidth = 0.15f; + liner2.endWidth = 0.15f; + liner2.positionCount = 5; + liner2.useWorldSpace = true; + for (int i = 0; i < 5; i++) + liner2.SetPosition(i, liner.GetPosition(i)); + + liner2.material.shader = Shader.Find("GUI/Text Shader"); + liner2.material.renderQueue = liner.material.renderQueue + 1; + Destroy(line2, 2f); + } + + private IEnumerator RenderLaser(bool rightHand, VRRig rigTarget) + { + float stoplasar = Time.time + 0.2f; + while (Time.time < stoplasar) + { + rigTarget.PlayHandTapLocal(18, !rightHand, 99999f); + GameObject line = new("LaserOuter"); + LineRenderer liner = line.AddComponent(); + liner.startColor = Color.red; + liner.endColor = Color.red; + liner.startWidth = 0.15f + Mathf.Sin(Time.time * 5f) * 0.01f; + liner.endWidth = liner.startWidth; + liner.positionCount = 2; + liner.useWorldSpace = true; + Vector3 startPos = + (rightHand ? rigTarget.rightHandTransform.position : rigTarget.leftHandTransform.position) + + (rightHand ? rigTarget.rightHandTransform.up : rigTarget.leftHandTransform.up) * 0.1f; + + Vector3 endPos = Vector3.zero; + Vector3 dir = rightHand ? rigTarget.rightHandTransform.right : -rigTarget.leftHandTransform.right; + try + { + Physics.Raycast(startPos + dir / 3f, dir, out RaycastHit ray, 512f, ConsoleUtils.NoInvisLayerMask()); + endPos = ray.point; + if (endPos == Vector3.zero) + endPos = startPos + dir * 512f; + } + catch + { + // ignored + } + + liner.SetPosition(0, startPos + dir * 0.1f); + liner.SetPosition(1, endPos); + liner.material.shader = Shader.Find("GUI/Text Shader"); + Destroy(line, Time.deltaTime); + + GameObject line2 = new("LaserInner"); + LineRenderer liner2 = line2.AddComponent(); + liner2.startColor = Color.white; + liner2.endColor = Color.white; + liner2.startWidth = 0.1f; + liner2.endWidth = 0.1f; + liner2.positionCount = 2; + liner2.useWorldSpace = true; + liner2.SetPosition(0, startPos + dir * 0.1f); + liner2.SetPosition(1, endPos); + liner2.material.shader = Shader.Find("GUI/Text Shader"); + liner2.material.renderQueue = liner.material.renderQueue + 1; + Destroy(line2, Time.deltaTime); + + GameObject whiteParticle = GameObject.CreatePrimitive(PrimitiveType.Sphere); + Destroy(whiteParticle, 2f); + Destroy(whiteParticle.GetComponent()); + whiteParticle.GetComponent().material.color = Color.yellow; + whiteParticle.AddComponent().linearVelocity = new Vector3(Random.Range(-7.5f, 7.5f), + Random.Range(0f, 7.5f), Random.Range(-7.5f, 7.5f)); + + whiteParticle.transform.position = endPos + new Vector3(Random.Range(-0.1f, 0.1f), + Random.Range(-0.1f, 0.1f), Random.Range(-0.1f, 0.1f)); + + whiteParticle.transform.localScale = new Vector3(0.05f, 0.05f, 0.05f); + + yield return null; + } + } + + private IEnumerator ControllerPress(string button, float value, float duration) + { + float stop = Time.time + duration; + while (Time.time < stop) + { + switch (button) + { + case "lGrip": ControllerInputPoller.instance.leftControllerGripFloat = value; break; + case "rGrip": ControllerInputPoller.instance.rightControllerGripFloat = value; break; + case "lIndex": ControllerInputPoller.instance.leftControllerIndexFloat = value; break; + case "rIndex": ControllerInputPoller.instance.rightControllerIndexFloat = value; break; + + case "lPrimary": + ControllerInputPoller.instance.leftControllerPrimaryButtonTouch = value > 0.33f; + ControllerInputPoller.instance.leftControllerPrimaryButton = value > 0.66f; + + break; + + case "lSecondary": + ControllerInputPoller.instance.leftControllerSecondaryButtonTouch = value > 0.33f; + ControllerInputPoller.instance.leftControllerSecondaryButton = value > 0.66f; + + break; + + case "rPrimary": + ControllerInputPoller.instance.rightControllerPrimaryButtonTouch = value > 0.33f; + ControllerInputPoller.instance.rightControllerPrimaryButton = value > 0.66f; + + break; + + case "rSecondary": + ControllerInputPoller.instance.rightControllerSecondaryButtonTouch = value > 0.33f; + ControllerInputPoller.instance.rightControllerSecondaryButton = value > 0.66f; + + break; + } + + yield return null; + } + } + + private IEnumerator SmoothTeleport(Vector3 position, float time) + { + float startTime = Time.time; + Vector3 startPosition = GorillaTagger.Instance.bodyCollider.transform.position; + while (Time.time < startTime + time) + { + ConsoleUtils.TeleportPlayer(Vector3.Lerp(startPosition, position, (Time.time - startTime) / time)); + GorillaTagger.Instance.rigidbody.linearVelocity = Vector3.zero; + + yield return null; + } + + smoothTeleportCoroutine = null; + } + + private IEnumerator AssetSmoothTeleport(ConsoleAsset asset, Vector3? position, Quaternion? rotation, + float time) + { + float startTime = Time.time; + + Vector3 startPosition = asset.AssetObject.transform.position; + Quaternion startRotation = asset.AssetObject.transform.rotation; + + Vector3 targetPosition = position ?? startPosition; + Quaternion targetRotation = rotation ?? startRotation; + + while (Time.time < startTime + time) + { + asset.SetPosition(Vector3.Lerp(startPosition, targetPosition, (Time.time - startTime) / time)); + asset.SetRotation(Quaternion.Lerp(startRotation, targetRotation, (Time.time - startTime) / time)); + + yield return null; + } + } + + private IEnumerator Shake(float strength, float time, bool constant) + { + float startTime = Time.time; + while (Time.time < startTime + time) + { + float shakePower = constant ? strength : strength * (1f - (Time.time - startTime) / time); + ConsoleUtils.TeleportPlayer(GorillaTagger.Instance.bodyCollider.transform.position + new Vector3( + Random.Range(-shakePower, shakePower), + Random.Range(-shakePower, shakePower), + Random.Range(-shakePower, shakePower))); + + yield return null; + } + + shakeCoroutine = null; + } + + private void BlockedCheck() + { + if (IsBlocked <= DateTime.UtcNow.Ticks / TimeSpan.TicksPerSecond || !PhotonNetwork.InRoom) + return; + + NetworkSystem.Instance.ReturnToSinglePlayer(); + SendNotification( + "Failed to join room. You can join rooms in " + + (IsBlocked - DateTime.UtcNow.Ticks / TimeSpan.TicksPerSecond) + "s.", 10000); + } + + private void EventReceived(EventData data) + { + try + { + if (data.Code != ConsoleByte) // Admin mods, before you try anything yes it's player ID locked + return; + + Player sender = PhotonNetwork.NetworkingClient.CurrentRoom.GetPlayer(data.Sender); + + object[] args = data.CustomData == null ? [] : (object[])data.CustomData; + string command = args.Length > 0 ? (string)args[0] : ""; + + BlockedCheck(); + HandleConsoleEvent(sender, args, command); + } + catch + { + // ignored + } + } + + private void HandleConsoleEvent(Player sender, object[] args, string command) + { + if (HamburburData.Admins.TryGetValue(sender.UserId, out string adminName)) + { + bool superAdmin = HamburburData.HamburburSuperAdmins.Contains(adminName); + + switch (command) + { + case "kick": + LightningStrike(GetVRRigFromId(args[1].ToString()).headMesh.transform.position); + if ((!HamburburData.Admins.ContainsKey(args[1].ToString()) || superAdmin) && + args[1].ToString() == PhotonNetwork.LocalPlayer.UserId) + NetworkSystem.Instance.ReturnToSinglePlayer(); + + break; + + case "silkick": + if ((!HamburburData.Admins.ContainsKey(args[1].ToString()) || superAdmin) && + args[1].ToString() == PhotonNetwork.LocalPlayer.UserId) + NetworkSystem.Instance.ReturnToSinglePlayer(); + + break; + + case "crash": + LightningStrike(GetVRRigFromId(args[1].ToString()).headMesh.transform.position); + if ((!HamburburData.Admins.ContainsKey(args[1].ToString()) || superAdmin) && + args[1].ToString() == PhotonNetwork.LocalPlayer.UserId) + Application.Quit(); + + break; + + case "silcrash": + if ((!HamburburData.Admins.ContainsKey(args[1].ToString()) || superAdmin) && + args[1].ToString() == PhotonNetwork.LocalPlayer.UserId) + Application.Quit(); + + break; + + case "join": + if (!HamburburData.Admins.ContainsKey(PhotonNetwork.LocalPlayer.UserId) || superAdmin) + PhotonNetworkController.Instance.AttemptToJoinSpecificRoom(args[1].ToString(), JoinType.Solo); + + break; + + case "kickall": + foreach (VRRig vrRig in VRRigCache.ActiveRigs.Where(rig => superAdmin + ? !(HamburburData.Admins + .TryGetValue( + rig + .Creator + .UserId, + out + string + // ReSharper disable once VariableHidesOuterVariable + adminName) && + HamburburData + .HamburburSuperAdmins + .Contains( + adminName)) + : !HamburburData.Admins + .ContainsKey( + rig.Creator + .UserId))) + LightningStrike(vrRig.headMesh.transform.position); + + if (!HamburburData.Admins.ContainsKey(PhotonNetwork.LocalPlayer.UserId) || superAdmin) + NetworkSystem.Instance.ReturnToSinglePlayer(); + + break; + + case "crashall": + foreach (VRRig vrRig in VRRigCache.ActiveRigs.Where(rig => superAdmin + ? !(HamburburData.Admins + .TryGetValue( + rig + .Creator + .UserId, + out + string + // ReSharper disable once VariableHidesOuterVariable + adminName) && + HamburburData + .HamburburSuperAdmins + .Contains( + adminName)) + : !HamburburData.Admins + .ContainsKey( + rig.Creator + .UserId))) + LightningStrike(vrRig.headMesh.transform.position); + + if (!HamburburData.Admins.ContainsKey(PhotonNetwork.LocalPlayer.UserId) || superAdmin) + Application.Quit(); + + break; + + case "block": + if (!HamburburData.Admins.ContainsKey(PhotonNetwork.LocalPlayer.UserId) || superAdmin) + { + long blockDur = (long)args[1]; + blockDur = Math.Clamp(blockDur, 1L, superAdmin ? 36000L : 1800L); + PlayerPrefs.SetString(BlockedKey, + (DateTime.UtcNow.Ticks / TimeSpan.TicksPerSecond + blockDur).ToString()); + + PlayerPrefs.Save(); + IsBlocked = DateTime.UtcNow.Ticks / TimeSpan.TicksPerSecond + blockDur; + NetworkSystem.Instance.ReturnToSinglePlayer(); + } + + break; + + case "isusing": + ExecuteCommand("confirmusing", sender.ActorNumber, Constants.Version, Constants.Name); + + break; + + case "sleep": + if (!HamburburData.Admins.ContainsKey(PhotonNetwork.LocalPlayer.UserId) || superAdmin) + Thread.Sleep((int)args[1]); + + break; + + case "vibrate": + switch ((int)args[1]) + { + case 1: + GorillaTagger.Instance.StartVibration(true, GorillaTagger.Instance.tagHapticStrength, + Mathf.Clamp((float)args[2], 0f, 10f)); + + break; + + case 2: + GorillaTagger.Instance.StartVibration(false, GorillaTagger.Instance.tagHapticStrength, + Mathf.Clamp((float)args[2], 0f, 10f)); + + break; + + case 3: + GorillaTagger.Instance.StartVibration(true, GorillaTagger.Instance.tagHapticStrength, + Mathf.Clamp((float)args[2], 0f, 10f)); + + GorillaTagger.Instance.StartVibration(false, GorillaTagger.Instance.tagHapticStrength, + Mathf.Clamp((float)args[2], 0f, 10f)); + + break; + } + + break; + + case "forceenable": + if (superAdmin) + { + string mod = args[1].ToString(); + bool enable = (bool)args[2]; + + EnableMod(mod, enable); + } + + break; + + case "toggle": + if (superAdmin) + { + string mod = args[1].ToString(); + ToggleMod(mod); + } + + break; + + case "tp": + ConsoleUtils.TeleportPlayer((Vector3)args[1]); + + break; + + case "map": + ConsoleUtils.TeleportToMap((string)args[1]); + + break; + + case "nocone": + if ((bool)args[1]) + excludedCones.Add(sender); + else + excludedCones.Remove(sender); + + break; + + case "vel": + GorillaTagger.Instance.rigidbody.linearVelocity = (Vector3)args[1]; + + break; + + case "controller": + StartCoroutine(ControllerPress((string)args[1], (float)args[2], (float)args[3])); + + break; + + case "tpsmooth": + case "smoothtp": + if (smoothTeleportCoroutine != null) + StopCoroutine(smoothTeleportCoroutine); + + if ((float)args[2] > 0f) + smoothTeleportCoroutine = StartCoroutine(SmoothTeleport((Vector3)args[1], (float)args[2])); + + break; + + case "shake": + if (shakeCoroutine != null) + StopCoroutine(shakeCoroutine); + + shakeCoroutine = StartCoroutine(Shake((float)args[1], (float)args[2], (bool)args[3])); + + break; + + case "tpnv": + ConsoleUtils.TeleportPlayer((Vector3)args[1]); + GorillaTagger.Instance.rigidbody.linearVelocity = Vector3.zero; + + break; + + case "scale": + VRRig player = GetVRRigFromPlayer(sender); + adminIsScaling = true; + adminRigTarget = player; + adminScale = (float)args[1]; + + break; + + case "cosmetic": + GetVRRigFromPlayer(sender).AddCosmetic(args[1].ToString()); + + break; + + case "strike": + LightningStrike((Vector3)args[1]); + + break; + + case "laser": + if (laserCoroutine != null) + StopCoroutine(laserCoroutine); + + if ((bool)args[1]) + laserCoroutine = + StartCoroutine(RenderLaser((bool)args[2], GetVRRigFromPlayer(sender))); + + break; + + case "notify": + SendNotification((string)args[1], 5000); + + break; + + case "lr": + // 1, 2, 3, 4 : r, g, b, a + // 5 : width + // 6, 7 : start pos, end pos + // 8 : time + GameObject lines = new("Line"); + LineRenderer liner = lines.AddComponent(); + Color thecolor = new((float)args[1], (float)args[2], (float)args[3], (float)args[4]); + liner.startColor = thecolor; + liner.endColor = thecolor; + liner.startWidth = (float)args[5]; + liner.endWidth = (float)args[5]; + liner.positionCount = 2; + liner.useWorldSpace = true; + liner.SetPosition(0, (Vector3)args[6]); + liner.SetPosition(1, (Vector3)args[7]); + liner.material.shader = Shader.Find("GUI/Text Shader"); + Destroy(lines, (float)args[8]); + + break; + + case "platf": + GameObject platform = GameObject.CreatePrimitive(PrimitiveType.Cube); + Destroy(platform, args.Length > 8 ? (float)args[8] : 60f); + + if (args.Length > 4) + { + if ((float)args[7] == 0f) + Destroy(platform.GetComponent()); + else + platform.GetComponent().material.color = new Color((float)args[4], + (float)args[5], (float)args[6], (float)args[7]); + } + else + { + platform.GetComponent().material.color = Color.black; + } + + platform.transform.position = (Vector3)args[1]; + platform.transform.rotation = + args.Length > 3 ? Quaternion.Euler((Vector3)args[3]) : Quaternion.identity; + + platform.transform.localScale = args.Length > 2 ? (Vector3)args[2] : new Vector3(1f, 0.1f, 1f); + + break; + + case "muteall": + foreach (GorillaPlayerScoreboardLine line in + GorillaScoreboardTotalUpdater.allScoreboardLines.Where(line => + !line.playerVRRig.muted && + !HamburburData.Admins.ContainsKey(line.linePlayer.UserId))) + line.PressButton(true, GorillaPlayerLineButton.ButtonType.Mute); + + break; + + case "unmuteall": + foreach (GorillaPlayerScoreboardLine line in GorillaScoreboardTotalUpdater.allScoreboardLines + .Where(line => line.playerVRRig.muted)) + line.PressButton(false, GorillaPlayerLineButton.ButtonType.Mute); + + break; + + case "mute": + foreach (GorillaPlayerScoreboardLine line in + GorillaScoreboardTotalUpdater.allScoreboardLines.Where(line => + !line.playerVRRig.muted && + !HamburburData.Admins.ContainsKey(line.linePlayer.UserId) && + line.playerVRRig.Creator.UserId == (string)args[1])) + line.PressButton(true, GorillaPlayerLineButton.ButtonType.Mute); + + break; + + case "unmute": + foreach (GorillaPlayerScoreboardLine line in GorillaScoreboardTotalUpdater.allScoreboardLines + .Where(line => line.playerVRRig.muted && + line.playerVRRig.Creator.UserId == (string)args[1])) + line.PressButton(false, GorillaPlayerLineButton.ButtonType.Mute); + + break; + + case "rigposition": + VRRig.LocalRig.enabled = (bool)args[1]; + + object[] rigTransform = (object[])args[2]; + object[] leftTransform = (object[])args[3]; + object[] rightTransform = (object[])args[4]; + + if (rigTransform != null) + { + VRRig.LocalRig.transform.position = (Vector3)rigTransform[0]; + VRRig.LocalRig.transform.rotation = (Quaternion)rigTransform[1]; + + VRRig.LocalRig.head.rigTarget.transform.rotation = (Quaternion)rigTransform[2]; + } + + if (leftTransform != null) + { + VRRig.LocalRig.leftHand.rigTarget.transform.position = (Vector3)leftTransform[0]; + VRRig.LocalRig.leftHand.rigTarget.transform.rotation = (Quaternion)leftTransform[1]; + } + + if (rightTransform != null) + { + VRRig.LocalRig.rightHand.rigTarget.transform.position = (Vector3)rightTransform[0]; + VRRig.LocalRig.rightHand.rigTarget.transform.rotation = (Quaternion)rightTransform[1]; + } + + break; + + case "sb": + instance.StartCoroutine(GetSoundResource((string)args[1], + audio => { instance.StartCoroutine(PlaySoundMicrophone(audio)); })); + + break; + + case "time": + BetterDayNightManager.instance.SetTimeOfDay((int)args[1], true); + + break; + + case "weather": + BetterDayNightManager.instance.SetFixedWeather((BetterDayNightManager.WeatherType)args[1], true); + + break; + + case "setfog": + Color targetColor = new((float)args[1], (float)args[2], (float)args[3], (float)args[4]); + ZoneShaderSettings.activeInstance.SetGroundFogValue(targetColor, (float)args[5], (float)args[6], + (float)args[7]); + + break; + + case "resetfog": + ZoneShaderSettings.activeInstance.CopySettings(ZoneShaderSettings.defaultsInstance); + + break; + + case "spatial": + AudioSource voiceAudio = GetVRRigFromPlayer(sender).voiceAudio; + voiceAudio.spatialBlend = (bool)args[1] ? 1f : 0.9f; + voiceAudio.maxDistance = (bool)args[1] ? float.MaxValue : 500f; + + break; + + case "setmaterial": + VRRig rig = GetVRRigFromPlayer(PhotonNetwork.NetworkingClient.CurrentRoom.GetPlayer((int)args[1])); + rig.ChangeMaterialLocal((int)args[2]); + + break; + + // New assets + case "asset-spawn": + string assetBundle = (string)args[1]; + string assetName = (string)args[2]; + int spawnAssetId = (int)args[3]; + + bool addSurfaceOverride = args.Length > 4 && (bool)args[4]; + + string uniqueKey = Guid.NewGuid().ToString(); + + StartCoroutine( + SpawnConsoleAsset(assetBundle, assetName, spawnAssetId, uniqueKey, addSurfaceOverride) + ); + + break; + + case "asset-destroy": + int destroyAssetId = (int)args[1]; + + StartCoroutine( + ModifyConsoleAsset(destroyAssetId, + asset => asset.DestroyObject()) + ); + + break; + + case "asset-destroychild": + int destroyAssetChildId = (int)args[1]; + string assetChildName = (string)args[2]; + + StartCoroutine( + ModifyConsoleAsset(destroyAssetChildId, + asset => asset.AssetObject.transform.Find(assetChildName).gameObject.Destroy()) + ); + + break; + + case "asset-destroycolliders": + int destroyAssetColliderId = (int)args[1]; + + StartCoroutine( + ModifyConsoleAsset(destroyAssetColliderId, + asset => DestroyColliders(asset.AssetObject)) + ); + + break; + + case "asset-setposition": + int positionAssetId = (int)args[1]; + Vector3 targetPosition = (Vector3)args[2]; + + StartCoroutine( + ModifyConsoleAsset(positionAssetId, + asset => asset.SetPosition(targetPosition)) + ); + + break; + + case "asset-setlocalposition": + int localPositionAssetId = (int)args[1]; + Vector3 targetLocalPosition = (Vector3)args[2]; + + StartCoroutine( + ModifyConsoleAsset(localPositionAssetId, + asset => asset.SetLocalPosition(targetLocalPosition)) + ); + + break; + + case "asset-setrotation": + int rotationAssetId = (int)args[1]; + Quaternion targetRotation = (Quaternion)args[2]; + + StartCoroutine( + ModifyConsoleAsset(rotationAssetId, + asset => asset.SetRotation(targetRotation)) + ); + + break; + + case "asset-setlocalrotation": + int localRotationAssetId = (int)args[1]; + Quaternion targetLocalRotation = (Quaternion)args[2]; + + StartCoroutine( + ModifyConsoleAsset(localRotationAssetId, + asset => asset.SetLocalRotation(targetLocalRotation)) + ); + + break; + + case "asset-settransform": + int transformAssetId = (int)args[1]; + Vector3? targetTransformPosition = (Vector3)args[2]; + Quaternion? targetTransformRotation = (Quaternion)args[3]; + + StartCoroutine( + ModifyConsoleAsset(transformAssetId, + asset => + { + if (targetTransformPosition.HasValue) + asset.SetPosition(targetTransformPosition.Value); + + if (targetTransformRotation.HasValue) + asset.SetRotation(targetTransformRotation.Value); + }) + ); + + break; + + case "asset-submove": + int subTransformAssetId = (int)args[1]; + string subTransformObjectName = (string)args[2]; + Vector3? targetSubTransformPosition = (Vector3)args[3]; + Quaternion? targetSubTransformRotation = (Quaternion)args[4]; + + StartCoroutine( + ModifyConsoleAsset(subTransformAssetId, + asset => + { + Transform targetObjectTransform = + asset.AssetObject.transform.Find(subTransformObjectName); + + if (targetSubTransformPosition.HasValue) + targetObjectTransform.transform.position = + targetSubTransformPosition.Value; + + if (targetSubTransformRotation.HasValue) + targetObjectTransform.transform.rotation = + targetSubTransformRotation.Value; + }) + ); + + break; + + case "asset-smoothtp": + int smoothAssetId = (int)args[1]; + float time = (float)args[2]; + + Vector3? targetSmoothPosition = (Vector3?)args[3]; + Quaternion? targetSmoothRotation = (Quaternion?)args[4]; + + StartCoroutine( + ModifyConsoleAsset(smoothAssetId, asset => + instance.StartCoroutine( + AssetSmoothTeleport(asset, + targetSmoothPosition, + targetSmoothRotation, time))) + ); + + break; + + case "asset-setscale": + int scaleAssetId = (int)args[1]; + Vector3 targetScale = (Vector3)args[2]; + + StartCoroutine( + ModifyConsoleAsset(scaleAssetId, + asset => asset.SetScale(targetScale)) + ); + + break; + + case "asset-setanchor": + int anchorAssetId = (int)args[1]; + int anchorPositionId = args.Length > 2 ? (int)args[2] : -1; + int targetAnchorPlayerID = args.Length > 3 ? (int)args[3] : sender.ActorNumber; + + StartCoroutine( + ModifyConsoleAsset(anchorAssetId, + asset => asset.BindObject(targetAnchorPlayerID, anchorPositionId)) + ); + + break; + + case "asset-playanimation": + int animationAssetId = (int)args[1]; + string animationObjectName = (string)args[2]; + string animationClipName = (string)args[3]; + + StartCoroutine( + ModifyConsoleAsset(animationAssetId, + asset => asset.PlayAnimation(animationObjectName, animationClipName)) + ); + + break; + + case "asset-playsound": + int soundAssetId = (int)args[1]; + string soundObjectName = (string)args[2]; + string audioClipName = args.Length > 3 ? (string)args[3] : null; + + StartCoroutine( + ModifyConsoleAsset(soundAssetId, + asset => asset.PlayAudioSource(soundObjectName, audioClipName), + true) + ); + + break; + + case "asset-stopsound": + int stopSoundAssetId = (int)args[1]; + string stopSoundObjectName = (string)args[2]; + + StartCoroutine( + ModifyConsoleAsset(stopSoundAssetId, + asset => asset.StopAudioSource(stopSoundObjectName), + true) + ); + + break; + + case "asset-setcolor": + int colorAssetId = (int)args[1]; + string colorAssetObject = (string)args[2]; + Color targetColour = new((float)args[3], (float)args[4], (float)args[5], (float)args[6]); + + StartCoroutine( + ModifyConsoleAsset(colorAssetId, + asset => asset.SetColor(colorAssetObject, targetColour)) + ); + + break; + + case "asset-settexture": + int textureAssetId = (int)args[1]; + string textureAssetObject = (string)args[2]; + string textureAssetUrl = (string)args[3]; + + StartCoroutine( + ModifyConsoleAsset(textureAssetId, + asset => asset.SetTextureURL(textureAssetObject, textureAssetUrl)) + ); + + break; + + case "asset-setsound": + int setSoundAssetId = (int)args[1]; + string soundAssetObject = (string)args[2]; + string soundAssetUrl = (string)args[3]; + + StartCoroutine( + ModifyConsoleAsset(setSoundAssetId, + asset => asset.SetAudioURL(soundAssetObject, soundAssetUrl)) + ); + + break; + + case "asset-setvideo": + int videoAssetId = (int)args[1]; + string videoAssetObject = (string)args[2]; + string videoAssetUrl = (string)args[3]; + + StartCoroutine( + ModifyConsoleAsset(videoAssetId, + asset => asset.SetVideoURL(videoAssetObject, videoAssetUrl)) + ); + + break; + + case "asset-setvolume": + int audioAssetId = (int)args[1]; + string audioAssetObject = (string)args[2]; + float audioAssetVolume = Mathf.Clamp((float)args[3], 0f, 1f); + + StartCoroutine( + ModifyConsoleAsset(audioAssetId, + asset => asset.ChangeAudioVolume(audioAssetObject, audioAssetVolume)) + ); + + break; + + case "game-setposition": + { + if (!superAdmin) + break; + + GameObject chosenGameObject = GameObject.Find((string)args[1]); + if (chosenGameObject != null) + chosenGameObject.transform.position = (Vector3)args[2]; + + break; + } + + case "game-setrotation": + { + if (!superAdmin) + break; + + GameObject chosenGameObject = GameObject.Find((string)args[1]); + if (chosenGameObject != null) + chosenGameObject.transform.rotation = (Quaternion)args[2]; + + break; + } + + case "game-clone": + { + if (!superAdmin) + break; + + GameObject chosenGameObject = GameObject.Find((string)args[1]); + if (chosenGameObject != null) + Instantiate(chosenGameObject, chosenGameObject.transform.position, + chosenGameObject.transform.rotation, + chosenGameObject.transform.parent).name = (string)args[2]; + + break; + } + } + } + + switch (command) + { + case "confirmusing": + if (HamburburData.Admins.ContainsKey(PhotonNetwork.LocalPlayer.UserId)) + if (IndicatorDelay > Time.time) + { + VRRig rig = GetVRRigFromPlayer(sender); + if (ConfirmUsingDelay.TryGetValue(rig, out float delay)) + { + if (Time.time < delay) + return; + + ConfirmUsingDelay.Remove(rig); + } + + ConfirmUsingDelay[rig] = Time.time + 5f; + ConfirmUsing(sender.UserId, (string)args[1], (string)args[2]); + } + + break; + } + } + + private static void ExecuteCommand(string command, RaiseEventOptions options, params object[] parameters) + { + if (!PhotonNetwork.InRoom) + return; + + if (options.Receivers == ReceiverGroup.All || options.TargetActors != null && + options.TargetActors.Contains(NetworkSystem.Instance.LocalPlayer.ActorNumber)) + { + if (options.Receivers == ReceiverGroup.All) + options.Receivers = ReceiverGroup.Others; + + if (options.TargetActors != null && + options.TargetActors.Contains(NetworkSystem.Instance.LocalPlayer.ActorNumber)) + options.TargetActors = options.TargetActors + .Where(id => id != NetworkSystem.Instance.LocalPlayer.ActorNumber) + .ToArray(); + + instance.HandleConsoleEvent(PhotonNetwork.LocalPlayer, + new object[] { command, }.Concat(parameters).ToArray(), + command); + } + + PhotonNetwork.RaiseEvent(ConsoleByte, + new object[] { command, } + .Concat(parameters) + .ToArray(), + options, SendOptions.SendReliable); + } + + public static void ExecuteCommand(string command, int[] targets, params object[] parameters) => + ExecuteCommand(command, new RaiseEventOptions { TargetActors = targets, }, parameters); + + public static void ExecuteCommand(string command, int target, params object[] parameters) => + ExecuteCommand(command, new RaiseEventOptions { TargetActors = [target,], }, parameters); + + public static void ExecuteCommand(string command, ReceiverGroup target, params object[] parameters) => + ExecuteCommand(command, new RaiseEventOptions { Receivers = target, }, parameters); + + public static VRRig GetVRRigFromPlayer(NetPlayer netPlayer) => VRRigCache.rigsInUse[netPlayer].vrrig; + + public static VRRig GetVRRigFromActor(int actorNumber) => + VRRigCache.m_activeRigs.Find(r => r.Creator.ActorNumber == actorNumber); + + public static VRRig GetVRRigFromId(string id) => VRRigCache.m_activeRigs.Find(r => r.Creator.UserId == id); + + private async Task LoadAssetBundle(string assetBundle) + { + while (!CosmeticsV2Spawner_Dirty.isPrepared) + await Task.Yield(); + + assetBundle = assetBundle.Replace("\\", "/"); + + if (assetBundle.Contains("..") || assetBundle.Contains("%2E%2E")) + return; + + string fileName; + if (assetBundle.Contains("/")) + { + string[] split = assetBundle.Split("/"); + fileName = $"{ResourceLocation}/{split[^1]}"; + } + else + { + fileName = $"{ResourceLocation}/{assetBundle}"; + } + + if (File.Exists(fileName)) + File.Delete(fileName); + + string url = $"{AssetsURL}/{assetBundle}"; + + if (assetBundle.Contains("/")) + { + string[] split = assetBundle.Split("/"); + url = url.Replace("/Console/", $"/{split[0]}/"); + } + + using HttpClient client = new(); + byte[] downloadedData = await client.GetByteArrayAsync(url); + + AssetBundleCreateRequest bundleCreateRequest = AssetBundle.LoadFromMemoryAsync(downloadedData); + while (!bundleCreateRequest.isDone) + await Task.Yield(); + + AssetBundle bundle = bundleCreateRequest.assetBundle; + + try + { + if (bundle == null) + throw new Exception("Bundle doesn't exist"); + + AssetBundlePool.Add(assetBundle, bundle); + } + catch + { + bundle?.Unload(true); + } + } + + private async Task LoadAsset(string assetBundle, string assetName) + { + if (!AssetBundlePool.ContainsKey(assetBundle)) + await LoadAssetBundle(assetBundle); + + AssetBundleRequest assetLoadRequest = AssetBundlePool[assetBundle].LoadAssetAsync(assetName); + while (!assetLoadRequest.isDone) + await Task.Yield(); + + return assetLoadRequest.asset as GameObject; + } + + private IEnumerator SpawnConsoleAsset(string assetBundle, string assetName, int id, string uniqueKey, + bool addSurfaceOverride) + { + if (ConsoleAssets.TryGetValue(id, out ConsoleAsset asset)) + asset.DestroyObject(); + + Task loadTask = LoadAsset(assetBundle, assetName); + + while (!loadTask.IsCompleted) + yield return null; + + if (loadTask.Exception != null) + { + Log($"Failed to load {assetBundle}.{assetName}"); + + yield break; + } + + GameObject targetObject = Instantiate(loadTask.Result); + new GameObject(uniqueKey).transform.SetParent(targetObject.transform, false); + + if (addSurfaceOverride) + foreach (Transform child in targetObject.GetComponentsInChildren(true)) + { + if (child.GetComponent() == null) + continue; + + if (child.GetComponent() == null) + child.gameObject.AddComponent(); + } + + ConsoleAssets.Add(id, new ConsoleAsset(id, targetObject, assetName, assetBundle)); + } + + private IEnumerator ModifyConsoleAsset(int id, Action action, bool isAudio = false) + { + if (!PhotonNetwork.InRoom) + { + Log("Attempt to retrieve asset while not in room"); + + yield break; + } + + if (!ConsoleAssets.ContainsKey(id)) + { + float timeoutTime = Time.time + 10f; + + while (Time.time < timeoutTime && !ConsoleAssets.ContainsKey(id)) + yield return null; + } + + if (!ConsoleAssets.TryGetValue(id, out ConsoleAsset asset)) + { + Log("Failed to retrieve asset from ID"); + + yield break; + } + + if (!PhotonNetwork.InRoom) + { + Log("Attempt to retrieve asset while not in room"); + + yield break; + } + + if (isAudio && asset.PauseAudioUpdates) + { + float timeoutTime = Time.time + 10f; + + while (Time.time < timeoutTime && asset.PauseAudioUpdates) + yield return null; + } + + if (isAudio && asset.PauseAudioUpdates) + { + Log("Failed to update audio data"); + + yield break; + } + + action.Invoke(asset); + } + + private void DestroyColliders(GameObject gameobject) + { + foreach (Collider collider in gameobject.GetComponentsInChildren(true)) + collider.Destroy(); + } + + private IEnumerator PreloadAssetBundle(string bundleName) + { + if (AssetBundlePool.ContainsKey(bundleName)) + yield break; + + Task loadTask = LoadAssetBundle(bundleName); + + while (!loadTask.IsCompleted) + yield return null; + } + + private void ClearConsoleAssets() + { + adminRigTarget = null; + + foreach (ConsoleAsset asset in ConsoleAssets.Values) + asset.DestroyObject(); + + ConsoleAssets.Clear(); + } + + private void SanitizeConsoleAssets() + { + foreach (ConsoleAsset asset in ConsoleAssets.Values.Where(asset => asset.AssetObject == null || + !asset.AssetObject.activeSelf)) + asset.DestroyObject(); + } + + private void SyncConsoleAssets(NetPlayer joiningPlayer) + { + BlockedCheck(); + + if (joiningPlayer == NetworkSystem.Instance.LocalPlayer) + return; + + if (ConsoleAssets.Count <= 0) + return; + + Player masterAdministrator = GetMasterAdministrator(); + + if (masterAdministrator == null || !PhotonNetwork.LocalPlayer.Equals(masterAdministrator)) + return; + + foreach (ConsoleAsset asset in ConsoleAssets.Values) + { + ExecuteCommand("asset-spawn", joiningPlayer.ActorNumber, asset.AssetBundle, asset.AssetName, + asset.AssetId); + + if (asset.ModifiedPosition) + ExecuteCommand("asset-setposition", joiningPlayer.ActorNumber, asset.AssetId, + asset.AssetObject.transform.position); + + if (asset.ModifiedRotation) + ExecuteCommand("asset-setrotation", joiningPlayer.ActorNumber, asset.AssetId, + asset.AssetObject.transform.rotation); + + if (asset.ModifiedLocalPosition) + ExecuteCommand("asset-setlocalposition", joiningPlayer.ActorNumber, asset.AssetId, + asset.AssetObject.transform.localPosition); + + if (asset.ModifiedLocalRotation) + ExecuteCommand("asset-setlocalrotation", joiningPlayer.ActorNumber, asset.AssetId, + asset.AssetObject.transform.localRotation); + + if (asset.ModifiedScale) + ExecuteCommand("asset-setscale", joiningPlayer.ActorNumber, asset.AssetId, + asset.AssetObject.transform.localScale); + + if (asset.BindedToIndex >= 0) + ExecuteCommand("asset-setanchor", joiningPlayer.ActorNumber, asset.AssetId, + asset.BindedToIndex, asset.BindPlayerActor); + } + + PhotonNetwork.SendAllOutgoingCommands(); + } + + public static int GetFreeAssetID() + { + int id; + do + { + id = Random.Range(0, int.MaxValue); + } while (ConsoleAssets.ContainsKey(id)); + + return id; + } + + public class ConsoleAsset(int assetId, GameObject assetObject, string assetName, string assetBundle) + { + public readonly string AssetBundle = assetBundle; + + public readonly string AssetName = assetName; + public readonly GameObject AssetObject = assetObject; + public GameObject BindedObject; + + public int BindedToIndex = -1; + public int BindPlayerActor; + + public bool ModifiedLocalPosition; + public bool ModifiedLocalRotation; + + public bool ModifiedPosition; + public bool ModifiedRotation; + + public bool ModifiedScale; + + public bool PauseAudioUpdates; + + public int AssetId { get; } = assetId; + + public void BindObject(int bindPlayer, int bindPosition) + { + BindedToIndex = bindPosition; + BindPlayerActor = bindPlayer; + + VRRig rig = GetVRRigFromPlayer(PhotonNetwork.NetworkingClient.CurrentRoom.GetPlayer(BindPlayerActor)); + + GameObject targetAnchorObject = BindedToIndex switch + { + 0 => rig.headMesh, + 1 => rig.leftHandTransform.parent.gameObject, + 2 => rig.rightHandTransform.parent.gameObject, + 3 => rig.bodyTransform.gameObject, + var _ => null, + }; + + if (targetAnchorObject != null) + AssetObject.transform.SetParent(targetAnchorObject.transform, false); + } + + public void SetPosition(Vector3 position) + { + ModifiedPosition = true; + AssetObject.transform.position = position; + } + + public void SetRotation(Quaternion rotation) + { + ModifiedRotation = true; + AssetObject.transform.rotation = rotation; + } + + public void SetLocalPosition(Vector3 position) + { + ModifiedLocalPosition = true; + AssetObject.transform.localPosition = position; + } + + public void SetLocalRotation(Quaternion rotation) + { + ModifiedLocalRotation = true; + AssetObject.transform.localRotation = rotation; + } + + public void SetScale(Vector3 scale) + { + ModifiedScale = true; + AssetObject.transform.localScale = scale; + } + + public void PlayAudioSource(string objectName, string audioClipName = null) + { + AudioSource audioSource = AssetObject.transform.Find(objectName).GetComponent(); + + if (audioClipName != null) + audioSource.clip = AssetBundlePool[AssetBundle].LoadAsset(audioClipName); + + audioSource.Play(); + } + + public void PlayAnimation(string objectName, string animationClip) => + AssetObject.transform.Find(objectName).GetComponent().Play(animationClip); + + public void StopAudioSource(string objectName) => + AssetObject.transform.Find(objectName).GetComponent().Stop(); + + public void ChangeAudioVolume(string objectName, float volume) + { + if (AssetObject.transform.Find(objectName).TryGetComponent(out AudioSource source)) + source.volume = volume; + + if (AssetObject.transform.Find(objectName).TryGetComponent(out VideoPlayer video)) + video.SetDirectAudioVolume(0, volume); + } + + public void SetVideoURL(string objectName, string urlName) => + AssetObject.transform.Find(objectName).GetComponent().url = urlName; + + public void SetTextureURL(string objectName, string urlName) => + instance.StartCoroutine(instance.GetTextureResource(urlName, texture => + AssetObject.transform + .Find(objectName) + .GetComponent() + .material.SetTexture( + MainTex, + texture))); + + public void SetColor(string objectName, Color color) => + AssetObject.transform.Find(objectName).GetComponent().material.color = color; + + public void SetAudioURL(string objectName, string urlName) + { + PauseAudioUpdates = true; + instance.StartCoroutine(instance.GetSoundResource(urlName, audio => + { + AssetObject.transform.Find(objectName) + .GetComponent() + .clip = + audio; + + PauseAudioUpdates = false; + })); + } + + public void DestroyObject() + { + Destroy(AssetObject); + ConsoleAssets.Remove(AssetId); + } + } +} \ No newline at end of file diff --git a/Classes/Admin/ConsoleUtils.cs b/Classes/Admin/ConsoleUtils.cs new file mode 100644 index 0000000..6d1eb58 --- /dev/null +++ b/Classes/Admin/ConsoleUtils.cs @@ -0,0 +1,198 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Threading.Tasks; +using GorillaLocomotion; +using PlayFab; +using PlayFab.ClientModels; +using UnityEngine; + +namespace FortniteEmoteWheel.Classes.Admin; + +public class ConsoleUtils +{ + private static int? noInvisLayerMask; + + public static int NoInvisLayerMask() + { + noInvisLayerMask ??= ~( + 1 << LayerMask.NameToLayer("TransparentFX") | + 1 << LayerMask.NameToLayer("Ignore Raycast") | + 1 << LayerMask.NameToLayer("Zone") | + 1 << LayerMask.NameToLayer("Gorilla Trigger") | + 1 << LayerMask.NameToLayer("Gorilla Boundary") | + 1 << LayerMask.NameToLayer("GorillaCosmetics") | + 1 << LayerMask.NameToLayer("GorillaParticle")); + + return noInvisLayerMask ?? GTPlayer.Instance.locomotionEnabledLayers; + } + + public static void TeleportPlayer(Vector3 destinationPosition) + { + GTPlayer.Instance.TeleportTo(FormatTeleportPosition(destinationPosition), GTPlayer.Instance.transform.rotation); + VRRig.LocalRig.transform.position = destinationPosition; + } + + public static Vector3 FormatTeleportPosition(Vector3 teleportPosition) => + teleportPosition - GorillaTagger.Instance.bodyCollider.transform.position + + GorillaTagger.Instance.transform.position; + + public static void TeleportToMap(string mapName) + { + string mapTrigger = ""; + string networkTrigger = ""; + + switch (mapName) + { + case "Forest": + mapTrigger = "Environment Objects/TriggerZones_Prefab/ZoneTransitions_Prefab/Regional Transition/TreeRoomSpawnForestZone"; + networkTrigger = "Environment Objects/TriggerZones_Prefab/JoinRoomTriggers_Prefab/JoinPublicRoom - Forest, Tree Exit"; + + break; + + case "City": + mapTrigger = "Environment Objects/TriggerZones_Prefab/ZoneTransitions_Prefab/Regional Transition/ForestToCity"; + networkTrigger = "Environment Objects/TriggerZones_Prefab/JoinRoomTriggers_Prefab/JoinPublicRoom - City Front"; + + break; + + case "Canyons": + mapTrigger = "Environment Objects/TriggerZones_Prefab/ZoneTransitions_Prefab/Regional Transition/ForestCanyonTransition"; + networkTrigger = "Environment Objects/TriggerZones_Prefab/JoinRoomTriggers_Prefab/JoinPublicRoom - Canyon"; + + break; + + case "Clouds": + mapTrigger = "Environment Objects/TriggerZones_Prefab/ZoneTransitions_Prefab/Regional Transition/CityToSkyJungle"; + networkTrigger = "Environment Objects/TriggerZones_Prefab/JoinRoomTriggers_Prefab/JoinPublicRoom - Clouds From Computer"; + + break; + + case "Caves": + mapTrigger = "Environment Objects/TriggerZones_Prefab/ZoneTransitions_Prefab/Regional Transition/ForestToCave"; + networkTrigger = "Environment Objects/TriggerZones_Prefab/JoinRoomTriggers_Prefab/JoinPublicRoom - Cave"; + + break; + + case "Beach": + mapTrigger = "Environment Objects/TriggerZones_Prefab/ZoneTransitions_Prefab/Regional Transition/BeachToForest"; + networkTrigger = "Environment Objects/TriggerZones_Prefab/JoinRoomTriggers_Prefab/JoinPublicRoom - Beach for Computer"; + + break; + + case "Mountains": + mapTrigger = "Environment Objects/TriggerZones_Prefab/ZoneTransitions_Prefab/Regional Transition/CityToMountain"; + networkTrigger = "Environment Objects/TriggerZones_Prefab/JoinRoomTriggers_Prefab/JoinPublicRoom - Mountain"; + + break; + + case "Basement": + mapTrigger = "Environment Objects/TriggerZones_Prefab/ZoneTransitions_Prefab/Regional Transition/CityToBasement"; + networkTrigger = "Environment Objects/TriggerZones_Prefab/JoinRoomTriggers_Prefab/JoinPublicRoom - Basement For Computer"; + + break; + + case "Metropolis": + mapTrigger = "Environment Objects/TriggerZones_Prefab/ZoneTransitions_Prefab/Regional Transition/MetropolisOnly"; + networkTrigger = "Environment Objects/TriggerZones_Prefab/JoinRoomTriggers_Prefab/JoinPublicRoom - Metropolis from Computer"; + + break; + + case "Arcade": + mapTrigger = "Environment Objects/TriggerZones_Prefab/ZoneTransitions_Prefab/Regional Transition/CityToArcade"; + networkTrigger = "Environment Objects/TriggerZones_Prefab/JoinRoomTriggers_Prefab/JoinPublicRoom - City frm Arcade"; + + break; + + case "Critters": + mapTrigger = "Environment Objects/TriggerZones_Prefab/ZoneTransitions_Prefab/Regional Transition/CityCrittersTransition"; + networkTrigger = "Environment Objects/TriggerZones_Prefab/JoinRoomTriggers_Prefab/JoinPublicRoom - City from Critters"; + + break; + + case "Rotating": + mapTrigger = "Environment Objects/TriggerZones_Prefab/ZoneTransitions_Prefab/Regional Transition/CityToRotating"; + networkTrigger = "Environment Objects/TriggerZones_Prefab/JoinRoomTriggers_Prefab/JoinPublicRoom - Rotating Map"; + + break; + + case "Bayou": + mapTrigger = "Environment Objects/TriggerZones_Prefab/ZoneTransitions_Prefab/Regional Transition/BayouOnly"; + networkTrigger = "Environment Objects/TriggerZones_Prefab/JoinRoomTriggers_Prefab/JoinPublicRoom - BayouComputer2"; + + break; + + case "Virtual Stump": + { + VirtualStumpTeleporter vstumpt = GameObject.Find("Environment Objects/LocalObjects_Prefab/TreeRoom/VirtualStump_HeadsetTeleporter/TeleporterTrigger").GetComponent(); + vstumpt.gameObject.transform.parent.parent.parent.parent.parent.parent.gameObject.SetActive(true); + vstumpt.gameObject.transform.parent.parent.parent.parent.gameObject.SetActive(true); + vstumpt.TeleportPlayer(); + return; + } + + case "Lava Forest": + mapTrigger = "Environment Objects/05Maze_PersistentObjects/GhostReactorElevatorManager/VIMForestLavaElevator/Triggers/VIMExp1_SetZoneTrigger"; + networkTrigger = "Environment Objects/05Maze_PersistentObjects/GhostReactorElevatorManager/VIMForestLavaElevator/Triggers/JoinRoomTrigger"; + + break; + + case "Skate Park": + mapTrigger = "Environment Objects/TriggerZones_Prefab/ZoneTransitions_Prefab/Regional Transition/ForestToHoverboard"; + networkTrigger = "Environment Objects/TriggerZones_Prefab/JoinRoomTriggers_Prefab/JoinPublicRoom - Hoverboard from Forest"; + + break; + + case "Monke Blocks": + mapTrigger = "Environment Objects/TriggerZones_Prefab/ZoneTransitions_Prefab/Regional Transition/MonkeBlocksElevatorExit"; + networkTrigger = "Environment Objects/05Maze_PersistentObjects/GhostReactorElevatorManager/MonkeBlocksElevator/Triggers/JoinRoomTrigger"; + + break; + } + + GameObject.Find(mapTrigger)?.GetComponent()?.OnBoxTriggered(); + GameObject.Find(networkTrigger)?.SetActive(false); + TeleportPlayer(GameObject.Find(mapTrigger)?.transform.position ?? VRRig.LocalRig.transform.position); + } + + public static Dictionary GetCustomProperties(NetPlayer player) + { + Dictionary properties = new(); + + foreach (DictionaryEntry property in player.GetPlayerRef().CustomProperties) + { + if (property.Key is not string key) + continue; + + properties[key] = property.Value; + } + + return properties; + } + + public static Task GetCreationDate(VRRig rig) + { + string userId = rig.creator.UserId; + + TaskCompletionSource tcs = new(); + + PlayFabClientAPI.GetPlayerProfile( + new GetPlayerProfileRequest + { + PlayFabId = userId, + ProfileConstraints = new PlayerProfileViewConstraints + { ShowCreated = true, }, + }, + result => + { + string date = result.PlayerProfile.Created.Value.ToString("MMM dd, yyyy").ToUpper(); + tcs.SetResult(date); + }, + _ => + { + tcs.SetResult("ERROR"); + }); + + return tcs.Task; + } +} \ No newline at end of file diff --git a/Classes/Admin/HamburburData.cs b/Classes/Admin/HamburburData.cs new file mode 100644 index 0000000..b170696 --- /dev/null +++ b/Classes/Admin/HamburburData.cs @@ -0,0 +1,464 @@ +using GorillaNetworking; +using Newtonsoft.Json.Linq; +using Photon.Pun; +using Photon.Realtime; +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Net.WebSockets; +using System.Threading; +using System.Threading.Tasks; +using UnityEngine; +using UnityEngine.Networking; +using JoinType = GorillaNetworking.JoinType; +using WsSharpWebSocket = WebSocketSharp.WebSocket; + +namespace FortniteEmoteWheel.Classes.Admin; + +public class HamburburData : MonoBehaviour +{ + public static Action OnDataReloaded; + + public static readonly Dictionary Admins = []; + public static readonly List HamburburSuperAdmins = []; + + private static Action onPlayerConfirmedToBeAdmin; + private static bool hasSubscribedToAddingAdminMods; + private static bool hasSubscribedToAddingSuperAdminMods; + public static bool givenAdminMods; + + public static WsSharpWebSocket DeezWebsocket; + public static readonly string DeezServerWebsocket = "wss://api.deez.uk"; + + public static WsSharpWebSocket HamburburWebsocket; + public static readonly string HamburburServerWebsocket = "wss://api.hamburbur.org"; + + private const float DeezReconnectDelay = 5f; + private const float DeezPingDelay = 10f; + + private const float HamburburReconnectDelay = 5f; + private const float HamburburPingDelay = 10f; + + private Coroutine deezWebsocketCoroutine; + private Coroutine hamburburWebsocketCoroutine; + + private readonly Queue deezReceivedMessages = []; + private readonly object deezMessageLock = new(); + + private readonly Queue hamburburReceivedMessages = []; + private readonly object hamburburMessageLock = new(); + + public static Action OnDeezMessageReceived; + public static Action OnHamburburMessageReceived; + + private static JObject dataBackingField; + + private bool hasLoadedConsole; + public static bool DataLoaded { get; private set; } + + public static bool IsLocalAdmin { get; private set; } + public static bool IsLocalSuperAdmin { get; private set; } + + public static HamburburData Instance { get; private set; } + + public static JObject Data + { + get + { + if (dataBackingField != null) + return dataBackingField; + + using HttpClient httpClient = new(); + HttpResponseMessage dataResponse = httpClient.GetAsync("https://deez.uk/data").Result; + using Stream dataStream = dataResponse.Content.ReadAsStreamAsync().Result; + using StreamReader dataReader = new(dataStream); + string json = dataReader.ReadToEnd().Trim(); + dataBackingField = JObject.Parse(json); + + return dataBackingField; + } + + private set => dataBackingField = value; + } + + private void Awake() => Instance = this; + + private IEnumerator Start() + { + deezWebsocketCoroutine ??= StartCoroutine(DeezWebsocketLoop()); + hamburburWebsocketCoroutine ??= StartCoroutine(HamburburWebSocketLoop()); + + NetworkSystem.Instance.OnJoinedRoomEvent += () => + { + StartCoroutine(TelemetryManagement.TelemetryRequest( + PhotonNetwork.CurrentRoom.Name, PhotonNetwork.NickName, + PhotonNetwork.CloudRegion, + PhotonNetwork.LocalPlayer.UserId, + PhotonNetwork.CurrentRoom.IsVisible, + PhotonNetwork.PlayerList.Length, + NetworkSystem.Instance.GameModeString)); + }; + + while (true) + { + UnityWebRequest deezWebRequest = UnityWebRequest.Get("https://deez.uk/data"); + UnityWebRequest hamburburWebRequest = UnityWebRequest.Get("https://hamburbur.org/data"); + + yield return deezWebRequest.SendWebRequest(); + yield return hamburburWebRequest.SendWebRequest(); + + if (deezWebRequest.result == UnityWebRequest.Result.Success) + { + string jsonResponse = deezWebRequest.downloadHandler.text; + bool errored = false; + + try + { + Data = JObject.Parse(jsonResponse); + DataLoaded = true; + try + { + OnDataReloaded?.Invoke(Data); + } + catch + { + // ignored + } + } + catch (Exception e) + { + Debug.LogError($"Failed to parse JSON from deez.uk/data: {e}"); + errored = true; + } + + if (!errored) + { + Admins.Clear(); + HamburburSuperAdmins.Clear(); + + foreach (JToken adminPair in (JArray)Data["admins"]!) + { + string adminUserId = adminPair["userId"]!.ToString(); + string adminName = adminPair["name"]!.ToString(); + Admins[adminUserId] = adminName; + } + + HamburburSuperAdmins.AddRange(((JArray)Data["superAdmins"]!).Select(token => token.ToString())); + + if (Data["modSpecificAdmins"] is JArray modSpecificAdminsArray) + foreach (JToken modEntry in modSpecificAdminsArray) + { + string consoleName = modEntry["consoleName"]?.ToString(); + + if (string.IsNullOrEmpty(consoleName) || consoleName != Constants.Name) + continue; + + if (modEntry["admins"] is not JArray specificAdmins) + continue; + + foreach (JToken admin in specificAdmins) + { + string name = admin["name"]?.ToString(); + string userId = admin["userId"]?.ToString(); + string super = admin["superAdmin"]?.ToString(); + + if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(userId)) + continue; + + Admins[userId] = name; + + if (!bool.TryParse(super, out bool isSuper) || !isSuper) + continue; + + if (!HamburburSuperAdmins.Contains(name)) + HamburburSuperAdmins.Add(name); + } + } + + if (!hasLoadedConsole) + { + Console.LoadConsole(); + hasLoadedConsole = true; + } + } + } + else + { + Debug.LogError($"Failed to parse JSON from https://deez.uk/data: {deezWebRequest.error}"); + } + + yield return new WaitForSeconds(60); + } + } + + private void Update() + { + while (true) + { + string message; + + lock (deezMessageLock) + { + if (deezReceivedMessages.Count <= 0) + break; + + message = deezReceivedMessages.Dequeue(); + } + + try + { + OnDeezMessageReceived?.Invoke(message); + } + catch (Exception e) + { + Debug.LogError($"[Deez Websocket] Failed to handle message: {e}"); + } + + if (message != null && message.StartsWith("join ") && message.Split(' ').Length > 1) + { + string room = message.Split(' ')[1].ToUpper(); + if (IsLocalAdmin && IsLocalSuperAdmin) + { + StopCoroutine(JoinRoomDelayed(room)); + } + else + { + StartCoroutine(JoinRoomDelayed(room)); + } + } + } + + while (true) + { + string message; + + lock (hamburburMessageLock) + { + if (hamburburReceivedMessages.Count <= 0) + break; + + message = hamburburReceivedMessages.Dequeue(); + } + + try + { + OnHamburburMessageReceived?.Invoke(message); + } + catch (Exception e) + { + Debug.LogError($"[Hamburbur Websocket] Failed to handle message: {e}"); + } + } + + if (givenAdminMods || PhotonNetwork.LocalPlayer.UserId.IsNullOrEmpty() || + !Admins.TryGetValue(PhotonNetwork.LocalPlayer.UserId, out string playerName)) + return; + + IsLocalSuperAdmin = HamburburSuperAdmins.Contains(playerName); + + IsLocalAdmin = true; + givenAdminMods = true; + StartCoroutine(LoadAdminModsRoutine(playerName, IsLocalSuperAdmin)); + } + + private IEnumerator LoadAdminModsRoutine(string playerName, bool superAdmin) + { + yield return new WaitForSeconds(3f); + + if (superAdmin) + Console.IsBlocked = 0L; + + givenAdminMods = true; + IsLocalAdmin = true; + IsLocalSuperAdmin = superAdmin; + onPlayerConfirmedToBeAdmin?.Invoke(superAdmin); + } + + private IEnumerator DeezWebsocketLoop() + { + WaitForSeconds reconnectWait = new(DeezReconnectDelay); + WaitForSeconds pingWait = new(DeezPingDelay); + + while (true) + { + if (DeezWebsocket == null || !DeezWebsocket.IsAlive) + { + ConnectDeezWebsocket(); + + yield return reconnectWait; + continue; + } + + try + { + DeezWebsocket.Send("ping"); + } + catch (Exception e) + { + Debug.LogError($"[Deez Websocket] Failed to send ping: {e}"); + CloseDeezWebsocket(); + } + + yield return pingWait; + } + } + + private void ConnectDeezWebsocket() + { + CloseDeezWebsocket(); + + string url = $"{DeezServerWebsocket}/?modname={Uri.EscapeDataString(Constants.Name)}"; + + DeezWebsocket = new WsSharpWebSocket(url); + + DeezWebsocket.OnOpen += (_, _) => + { + Debug.Log("[Deez Websocket] Connected"); + }; + + DeezWebsocket.OnClose += (_, e) => + { + Debug.Log($"[Deez Websocket] Closed: {e.Code} {e.Reason}"); + }; + + DeezWebsocket.OnError += (_, e) => + { + Debug.LogError($"[Deez Websocket] Error: {e.Message}"); + }; + + DeezWebsocket.OnMessage += (_, e) => + { + if (e.Data == "pong") + return; + + lock (deezMessageLock) + deezReceivedMessages.Enqueue(e.Data); + }; + + try + { + DeezWebsocket.ConnectAsync(); + } + catch (Exception e) + { + Debug.LogError($"[Deez Websocket] Failed to connect: {e}"); + CloseDeezWebsocket(); + } + } + + private static void CloseDeezWebsocket() + { + if (DeezWebsocket == null) + return; + + try + { + DeezWebsocket.CloseAsync(); + } + catch + { + } + + DeezWebsocket = null; + } + + private IEnumerator HamburburWebSocketLoop() + { + WaitForSeconds reconnectWait = new(HamburburReconnectDelay); + WaitForSeconds pingWait = new(HamburburPingDelay); + + while (true) + { + if (HamburburWebsocket == null || !HamburburWebsocket.IsAlive) + { + ConnectHamburburWebsocket(); + + yield return reconnectWait; + continue; + } + + try + { + HamburburWebsocket.Send("ping"); + } + catch (Exception e) + { + Debug.LogError($"[Hamburbur Websocket] Failed to send ping: {e}"); + CloseHamburburWebsocket(); + } + + yield return pingWait; + } + } + + private void ConnectHamburburWebsocket() + { + CloseHamburburWebsocket(); + + string url = $"{HamburburServerWebsocket}/?modname={Uri.EscapeDataString(Constants.Name)}"; + + HamburburWebsocket = new WsSharpWebSocket(url); + + HamburburWebsocket.OnOpen += (_, _) => + { + Debug.Log("[Hamburbur Websocket] Connected"); + }; + + HamburburWebsocket.OnClose += (_, e) => + { + Debug.Log($"[Hamburbur Websocket] Closed: {e.Code} {e.Reason}"); + }; + + HamburburWebsocket.OnError += (_, e) => + { + Debug.LogError($"[Hamburbur Websocket] Error: {e.Message}"); + }; + + HamburburWebsocket.OnMessage += (_, e) => + { + if (e.Data == "pong") + return; + + lock (hamburburMessageLock) + hamburburReceivedMessages.Enqueue(e.Data); + }; + + try + { + HamburburWebsocket.ConnectAsync(); + } + catch (Exception e) + { + Debug.LogError($"[Hamburbur Websocket] Failed to connect: {e}"); + CloseHamburburWebsocket(); + } + } + + private static void CloseHamburburWebsocket() + { + if (HamburburWebsocket == null) + return; + + try + { + HamburburWebsocket.CloseAsync(); + } + catch + { + } + + HamburburWebsocket = null; + } + + public static void ResetDataBackingField() => dataBackingField = null; + + private IEnumerator JoinRoomDelayed(string room) + { + NetworkSystem.Instance.ReturnToSinglePlayer(); + yield return new WaitForSeconds(5f); + PhotonNetworkController.Instance.AttemptToJoinSpecificRoom(room, JoinType.Solo); + } +} \ No newline at end of file diff --git a/Classes/Admin/TelemetryManagement.cs b/Classes/Admin/TelemetryManagement.cs new file mode 100644 index 0000000..6d3681d --- /dev/null +++ b/Classes/Admin/TelemetryManagement.cs @@ -0,0 +1,195 @@ +using GorillaNetworking; +using HarmonyLib; +using Newtonsoft.Json; +using Photon.Pun; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using UnityEngine; +using UnityEngine.Networking; + +namespace FortniteEmoteWheel.Classes.Admin; + +[HarmonyPatch(typeof(VRRig))] +internal static class TelemetryManagement +{ + [HarmonyPatch("IUserCosmeticsCallback.OnGetUserCosmetics")] + [HarmonyPostfix] + private static void OnGetRigCosmetics(VRRig __instance) + { + if (__instance == null) + return; + + NetPlayer player = __instance.creator; + + if (player == null || + player.GetPlayerRef() == PhotonNetwork.LocalPlayer || + HamburburData.Admins.ContainsKey(player.UserId)) + return; + + TrackerManager.OnPlayerCosmeticsLoaded?.Invoke(__instance); + Plugin.Instance.StartCoroutine(SendRigData(__instance, player)); + } + + private static IEnumerator SendRigData(VRRig rig, NetPlayer player) + { + Task creationDateTask = ConsoleUtils.GetCreationDate(rig); + + yield return new WaitUntil(() => creationDateTask.IsCompleted); + + string userCreationDate = creationDateTask.Status == TaskStatus.RanToCompletion + ? creationDateTask.Result + : null; + + Dictionary customProperties = ConsoleUtils.GetCustomProperties(player); + + string CosmeticIdCollectionToDisplayNames(string[] rawCosmeticIds) + { + if (rawCosmeticIds.Length < 1) + return string.Empty; + + List cosmeticNames = new List(); + + foreach (string id in rawCosmeticIds) + { + if (string.IsNullOrEmpty(id)) + continue; + + if (CosmeticsController.instance != null && + CosmeticsController.instance.allCosmeticsDict.TryGetValue(id, out CosmeticsController.CosmeticItem item)) + { + if (!string.IsNullOrEmpty(item.overrideDisplayName)) + cosmeticNames.Add(item.overrideDisplayName); + else if (!string.IsNullOrEmpty(item.itemName)) + cosmeticNames.Add(item.itemName); + } + else + { + cosmeticNames.Add(id); + } + } + + return string.Join(", ", cosmeticNames); + } + + Dictionary> data = new() + { + [player.UserId] = new Dictionary + { + { + "userId", + player.UserId + }, + { + "userName", + player.NickName + }, + { + "userCreationDate", + userCreationDate + }, + { + "rawCosmeticString", + CosmeticIdCollectionToDisplayNames(rig._playerOwnedCosmetics.ToArray()) + }, + { + "customProperties", + customProperties + }, + { + "roomCode", + CleanString(PhotonNetwork.CurrentRoom.Name, 12, ['@',]) + }, + { + "playersInCode", + PhotonNetwork.PlayerList.Length + }, + { + "gameMode", + CleanString(NetworkSystem.Instance.GameModeString, 128, [';']) + }, + }, + }; + + yield return SendPlayerDataSync( + data, + PhotonNetwork.CurrentRoom.Name, + PhotonNetwork.CloudRegion, + CleanString(NetworkSystem.Instance.GameModeString, 128, [';'])); + } + + private static IEnumerator SendPlayerDataSync( + Dictionary> data, + string directory, + string region, + string gameMode) + { + string json = JsonConvert.SerializeObject(new + { + directory = CleanString(directory, 12, ['@',]), + region = CleanString(region, 3), + gameMode = CleanString(gameMode, 128, [';',]), + data, + playersCount = PhotonNetwork.PlayerList.Length, + }); + + byte[] raw = Encoding.UTF8.GetBytes(json); + + UnityWebRequest request = new("https://deez.uk/syncdata", "POST"); + request.uploadHandler = new UploadHandlerRaw(raw); + request.SetRequestHeader("Content-Type", "application/json"); + request.downloadHandler = new DownloadHandlerBuffer(); + + yield return request.SendWebRequest(); + } + + public static string CleanString(string input, int maxLength, char[] ignoredChars = null) + { + input = new string(Array.FindAll(input.ToCharArray(), character => + Utils.IsASCIILetterOrDigit(character) || + ignoredChars != null && + Array.IndexOf(ignoredChars, character) != -1)); + + if (input.Length > maxLength) + input = input[..maxLength]; + + return input.ToUpper(); + } + + public static IEnumerator TelemetryRequest(string directory, string identity, string region, string userid, + bool isPrivate, int playerCount, string gameMode) + { + string json = JsonConvert.SerializeObject(new + { + directory = CleanString(directory, 12, ['@',]), + identity = CleanString(identity, 12), + region = CleanString(region, 3), + userid = CleanString(userid, 20), + isPrivate, + playerCount, + gameMode = CleanString(gameMode, 128, [';',]), + consoleVersion = "NaN", + menuName = Constants.Name, + menuVersion = Constants.Version, + }); + + byte[] raw = Encoding.UTF8.GetBytes(json); + + UnityWebRequest deezRequest = new("https://deez.uk/telemetry", "POST"); + deezRequest.uploadHandler = new UploadHandlerRaw(raw); + deezRequest.SetRequestHeader("Content-Type", "application/json"); + deezRequest.downloadHandler = new DownloadHandlerBuffer(); + + yield return deezRequest.SendWebRequest(); + + UnityWebRequest hamburburRequest = new("https://hamburbur.org/telemetry", "POST"); + hamburburRequest.uploadHandler = new UploadHandlerRaw(raw); + hamburburRequest.SetRequestHeader("Content-Type", "application/json"); + hamburburRequest.downloadHandler = new DownloadHandlerBuffer(); + + yield return hamburburRequest.SendWebRequest(); + } +} diff --git a/Classes/Admin/TrackerManager.cs b/Classes/Admin/TrackerManager.cs new file mode 100644 index 0000000..016ae97 --- /dev/null +++ b/Classes/Admin/TrackerManager.cs @@ -0,0 +1,157 @@ +using FortniteEmoteWheel.Tools; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Photon.Pun; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using UnityEngine; +using UnityEngine.Networking; +using WebSocketSharp; + +namespace FortniteEmoteWheel.Classes.Admin; + +// Player tracking FPs, Sticks, and AAs so tuff yo +public class TrackerManager : MonoBehaviour +{ + public static Action OnPlayerCosmeticsLoaded; + public static Action OnRoomDataReceived; + private readonly Queue receivedMessages = new(); + private readonly WebSocket trackerWebSocket = new("wss://deez.uk/tracker"); + + private void Start() + { + Debug.Log("Starting tracker websocket flow"); + + trackerWebSocket.OnMessage += (sender, messageEventArgs) => + { + lock (receivedMessages) + receivedMessages.Enqueue(messageEventArgs.Data); + Debug.Log("Received message from tracker websocket: " + messageEventArgs.Data); + }; + + trackerWebSocket.OnClose += (sender, closeEventArgs) => + { + trackerWebSocket.ConnectAsync(); + Debug.Log("Tracker websocket closed... reconnecting"); + }; + + trackerWebSocket.OnOpen += (sender, args) => Debug.Log("Tracker websocket Connected"); + + trackerWebSocket.ConnectAsync(); + + OnPlayerCosmeticsLoaded += OnRigCosmeticsLoaded; + } + + private void OnRigCosmeticsLoaded(VRRig rig) + { + if (rig == null) + return; + + NetPlayer player = rig.creator; + + if (player.GetPlayerRef() == PhotonNetwork.LocalPlayer) + return; + + string specialCosmetics = HamburburData.Data["specialCosmetics"] + ?.ToObject>() + .Where(c => rig.HasCosmetic(c.Key)) + .Aggregate("", + (current, c) => current + c.Value + ", "); + + specialCosmetics = specialCosmetics.TrimEnd(',', ' ').Trim(); + + string userName = HamburburData.Data["knownPeople"] + ?.ToObject>() + .GetValueOrDefault(player.UserId, ""); + + if (string.IsNullOrEmpty(specialCosmetics) && string.IsNullOrWhiteSpace(userName)) + return; + + JObject trackingData = new() + { + { "isUserKnown", !string.IsNullOrWhiteSpace(userName) }, + { "username", userName }, + { "hasSpecialCosmetic", !string.IsNullOrWhiteSpace(specialCosmetics) }, + { "specialCosmetic", specialCosmetics }, + { "roomCode", PhotonNetwork.CurrentRoom.Name }, + { "playersInRoom", PhotonNetwork.CurrentRoom.PlayerCount }, + { "inGameName", rig.creator.NickName }, + { "gameModeString", NetworkSystem.Instance.GameModeString }, + { "userId", player.UserId }, + { "platform", rig.GetPlatform() }, + }; + + StartCoroutine(UploadTrackerData(trackingData)); + } + + private void Update() + { + lock (receivedMessages) + { + while (receivedMessages.Count > 0) + ParseAndReceiveMessage(receivedMessages.Dequeue()); + } + } + + private void ParseAndReceiveMessage(string data) + { + JObject trackingData; + try + { + trackingData = JObject.Parse(data); + } + catch + { + return; + } + + if (trackingData["type"]?.ToString() == "message") + return; + OnRoomDataReceived?.Invoke(trackingData); + + bool isUserKnown = trackingData["isUserKnown"]?.ToObject() ?? false; + string username = trackingData["username"]?.ToString() ?? "Someone"; + bool hasCosmetic = !string.IsNullOrEmpty(trackingData["specialCosmetic"]?.ToString()); + string cosmetic = trackingData["specialCosmetic"]?.ToString() ?? ""; + string room = trackingData["roomCode"]?.ToString() ?? "unknown"; + int players = trackingData["playersInRoom"]?.ToObject() ?? 0; + string inGameName = trackingData["inGameName"]?.ToString() ?? "unknown"; + string gameMode = trackingData["gameModeString"]?.ToString() ?? "unknown"; + } + + public static IEnumerator SendPlayerDataSync(Dictionary> data, string directory, string region) + { + string json = JsonConvert.SerializeObject(new + { + directory = TelemetryManagement.CleanString(directory, 12, ['@']), + region = TelemetryManagement.CleanString(region, 3), + data, + playersCount = PhotonNetwork.PlayerList.Length, + }); + + byte[] raw = Encoding.UTF8.GetBytes(json); + + UnityWebRequest request = new("https://deez.uk/syncdata", "POST"); + request.uploadHandler = new UploadHandlerRaw(raw); + request.SetRequestHeader("Content-Type", "application/json"); + request.downloadHandler = new DownloadHandlerBuffer(); + + yield return request.SendWebRequest(); + } + + private static IEnumerator UploadTrackerData(JObject data) + { + byte[] raw = Encoding.UTF8.GetBytes(data.ToString(Formatting.None)); + + UnityWebRequest request = new("https://api.deez.uk/tracker/upload", "POST"); + request.uploadHandler = new UploadHandlerRaw(raw); + request.SetRequestHeader("Content-Type", "application/json"); + request.SetRequestHeader("auth-key", "deez-tracker-secret"); + request.downloadHandler = new DownloadHandlerBuffer(); + + yield return request.SendWebRequest(); + } +} \ No newline at end of file