< Summary

Class:WebSocketCommunication
Assembly:WebSocketCommunication
File(s):/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/WorldRuntime/KernelCommunication/WebSocketCommunication/WebSocketCommunication.cs
Covered lines:0
Uncovered lines:150
Coverable lines:150
Total lines:256
Line coverage:0% (0 of 150)
Covered branches:0
Total branches:0

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity NPath complexity Sequence coverage
WebSocketCommunication(...)0%2100%
WebSocketCommunication()0%2100%
StartServer(...)0%56700%
InitMessageTypeToBridgeName()0%2100%
ProcessMessages()0%3421800%
Dispose()0%2100%

File(s)

/tmp/workspace/unity-renderer/unity-renderer/Assets/Scripts/MainScripts/DCL/WorldRuntime/KernelCommunication/WebSocketCommunication/WebSocketCommunication.cs

#LineLine coverage
 1using System;
 2using System.Collections;
 3using System.Collections.Generic;
 4using System.Net.Sockets;
 5using DCL;
 6using UnityEngine;
 7using WebSocketSharp.Server;
 8
 9public class WebSocketCommunication : IKernelCommunication
 10{
 11    WebSocketServer ws;
 12    private Coroutine updateCoroutine;
 13    private bool requestStop = false;
 14
 015    private Dictionary<string, GameObject> bridgeGameObjects = new Dictionary<string, GameObject>();
 16
 017    public Dictionary<string, string> messageTypeToBridgeName = new Dictionary<string, string>(); // Public to be able t
 18
 19    [System.NonSerialized]
 020    public static Queue<DCLWebSocketService.Message> queuedMessages = new Queue<DCLWebSocketService.Message>();
 21
 22    [System.NonSerialized]
 23    public static volatile bool queuedMessagesDirty;
 24
 025    public bool isServerReady => ws.IsListening;
 26
 27    private string StartServer(int port, int maxPort, bool withSSL)
 28    {
 029        if (port > maxPort)
 30        {
 031            throw new SocketException((int)SocketError.AddressAlreadyInUse);
 32        }
 33        string wssServerUrl;
 034        string wssServiceId = "dcl";
 35        try
 36        {
 037            if (withSSL)
 38            {
 039                wssServerUrl = $"wss://localhost:{port}/";
 040                ws = new WebSocketServer(wssServerUrl)
 41                {
 42                    SslConfiguration =
 43                    {
 44                        ServerCertificate = CertificateUtils.CreateSelfSignedCert(),
 45                        ClientCertificateRequired = false,
 46                        CheckCertificateRevocation = false,
 047                        ClientCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true
 48                    },
 49                    KeepClean = false
 50                };
 051            }
 52            else
 53            {
 054                wssServerUrl = $"ws://localhost:{port}/";
 055                ws = new WebSocketServer(wssServerUrl);
 56            }
 57
 058            ws.AddWebSocketService<DCLWebSocketService>("/" + wssServiceId);
 059            ws.Start();
 060        }
 061        catch (InvalidOperationException e)
 62        {
 063            ws.Stop();
 064            if (withSSL) // Search for available ports only if we're using SSL
 65            {
 066                SocketException se = (SocketException)e.InnerException;
 067                if (se is { SocketErrorCode: SocketError.AddressAlreadyInUse })
 68                {
 069                    return StartServer(port + 1, maxPort, withSSL);
 70                }
 71            }
 072            throw new InvalidOperationException(e.Message, e.InnerException);
 73        }
 74
 075        string wssUrl = wssServerUrl + wssServiceId;
 076        return wssUrl;
 077    }
 78
 079    public WebSocketCommunication(bool withSSL = false, int startPort = 5000, int endPort = 5100)
 80    {
 081        InitMessageTypeToBridgeName();
 82
 083        DCL.DataStore.i.debugConfig.isWssDebugMode = true;
 84
 085        string url = StartServer(startPort, endPort, withSSL);
 86
 087        Debug.Log("WebSocket Server URL: " + url);
 88
 089        DataStore.i.wsCommunication.url = url;
 90
 091        DataStore.i.wsCommunication.communicationReady.Set(true);
 92
 093        updateCoroutine = CoroutineStarter.Start(ProcessMessages());
 094    }
 95
 96    private void InitMessageTypeToBridgeName()
 97    {
 98        // Please, use `Bridges` as a bridge name, avoid adding messages here. The system will use `Bridges` as the defa
 099        messageTypeToBridgeName["SetDebug"] = "Main";
 0100        messageTypeToBridgeName["SetSceneDebugPanel"] = "Main";
 0101        messageTypeToBridgeName["ShowFPSPanel"] = "Main";
 0102        messageTypeToBridgeName["HideFPSPanel"] = "Main";
 0103        messageTypeToBridgeName["SetEngineDebugPanel"] = "Main";
 0104        messageTypeToBridgeName["SendSceneMessage"] = "Main";
 0105        messageTypeToBridgeName["LoadParcelScenes"] = "Main";
 0106        messageTypeToBridgeName["UnloadScene"] = "Main";
 0107        messageTypeToBridgeName["Reset"] = "Main";
 0108        messageTypeToBridgeName["CreateGlobalScene"] = "Main";
 0109        messageTypeToBridgeName["BuilderReady"] = "Main";
 0110        messageTypeToBridgeName["UpdateParcelScenes"] = "Main";
 0111        messageTypeToBridgeName["LoadProfile"] = "Main";
 0112        messageTypeToBridgeName["AddUserProfileToCatalog"] = "Main";
 0113        messageTypeToBridgeName["AddUserProfilesToCatalog"] = "Main";
 0114        messageTypeToBridgeName["RemoveUserProfilesFromCatalog"] = "Main";
 0115        messageTypeToBridgeName["ActivateRendering"] = "Main";
 0116        messageTypeToBridgeName["DeactivateRendering"] = "Main";
 0117        messageTypeToBridgeName["ForceActivateRendering"] = "Main";
 0118        messageTypeToBridgeName["AddWearablesToCatalog"] = "Main";
 0119        messageTypeToBridgeName["WearablesRequestFailed"] = "Main";
 0120        messageTypeToBridgeName["RemoveWearablesFromCatalog"] = "Main";
 0121        messageTypeToBridgeName["ClearWearableCatalog"] = "Main";
 0122        messageTypeToBridgeName["InitializeFriends"] = "Main";
 0123        messageTypeToBridgeName["UpdateFriendshipStatus"] = "Main";
 0124        messageTypeToBridgeName["UpdateUserPresence"] = "Main";
 0125        messageTypeToBridgeName["FriendNotFound"] = "Main";
 0126        messageTypeToBridgeName["AddMessageToChatWindow"] = "Main";
 0127        messageTypeToBridgeName["UpdateMinimapSceneInformation"] = "Main";
 0128        messageTypeToBridgeName["UpdateHotScenesList"] = "Main";
 0129        messageTypeToBridgeName["SetRenderProfile"] = "Main";
 0130        messageTypeToBridgeName["CrashPayloadRequest"] = "Main";
 0131        messageTypeToBridgeName["SetDisableAssetBundles"] = "Main";
 0132        messageTypeToBridgeName["DumpRendererLockersInfo"] = "Main";
 0133        messageTypeToBridgeName["PublishSceneResult"] = "Main";
 0134        messageTypeToBridgeName["BuilderProjectInfo"] = "Main";
 0135        messageTypeToBridgeName["BuilderInWorldCatalogHeaders"] = "Main";
 0136        messageTypeToBridgeName["RequestedHeaders"] = "Main";
 0137        messageTypeToBridgeName["AddAssets"] = "Main";
 0138        messageTypeToBridgeName["RunPerformanceMeterTool"] = "Main";
 0139        messageTypeToBridgeName["InstantiateBotsAtWorldPos"] = "Main";
 0140        messageTypeToBridgeName["InstantiateBotsAtCoords"] = "Main";
 0141        messageTypeToBridgeName["StartBotsRandomizedMovement"] = "Main";
 0142        messageTypeToBridgeName["StopBotsMovement"] = "Main";
 0143        messageTypeToBridgeName["RemoveBot"] = "Main";
 0144        messageTypeToBridgeName["ClearBots"] = "Main";
 0145        messageTypeToBridgeName["ToggleSceneBoundingBoxes"] = "Main";
 0146        messageTypeToBridgeName["TogglePreviewMenu"] = "Main";
 147
 0148        messageTypeToBridgeName["Teleport"] = "CharacterController";
 149
 0150        messageTypeToBridgeName["SetRotation"] = "CameraController";
 151
 0152        messageTypeToBridgeName["ShowNotificationFromJson"] = "HUDController";
 0153        messageTypeToBridgeName["ConfigureHUDElement"] = "HUDController";
 0154        messageTypeToBridgeName["ShowTermsOfServices"] = "HUDController";
 0155        messageTypeToBridgeName["RequestTeleport"] = "HUDController";
 0156        messageTypeToBridgeName["ShowAvatarEditorInSignUp"] = "HUDController";
 0157        messageTypeToBridgeName["SetUserTalking"] = "HUDController";
 0158        messageTypeToBridgeName["SetUsersMuted"] = "HUDController";
 0159        messageTypeToBridgeName["ShowWelcomeNotification"] = "HUDController";
 0160        messageTypeToBridgeName["UpdateBalanceOfMANA"] = "HUDController";
 0161        messageTypeToBridgeName["SetPlayerTalking"] = "HUDController";
 0162        messageTypeToBridgeName["SetVoiceChatEnabledByScene"] = "HUDController";
 0163        messageTypeToBridgeName["TriggerSelfUserExpression"] = "HUDController";
 0164        messageTypeToBridgeName["AirdroppingRequest"] = "HUDController";
 165
 0166        messageTypeToBridgeName["GetMousePosition"] = "BuilderController";
 0167        messageTypeToBridgeName["SelectGizmo"] = "BuilderController";
 0168        messageTypeToBridgeName["ResetObject"] = "BuilderController";
 0169        messageTypeToBridgeName["ZoomDelta"] = "BuilderController";
 0170        messageTypeToBridgeName["SetPlayMode"] = "BuilderController";
 0171        messageTypeToBridgeName["TakeScreenshot"] = "BuilderController";
 0172        messageTypeToBridgeName["ResetBuilderScene"] = "BuilderController";
 0173        messageTypeToBridgeName["SetBuilderCameraPosition"] = "BuilderController";
 0174        messageTypeToBridgeName["SetBuilderCameraRotation"] = "BuilderController";
 0175        messageTypeToBridgeName["ResetBuilderCameraZoom"] = "BuilderController";
 0176        messageTypeToBridgeName["SetGridResolution"] = "BuilderController";
 0177        messageTypeToBridgeName["OnBuilderKeyDown"] = "BuilderController";
 0178        messageTypeToBridgeName["UnloadBuilderScene"] = "BuilderController";
 0179        messageTypeToBridgeName["SetSelectedEntities"] = "BuilderController";
 0180        messageTypeToBridgeName["GetCameraTargetBuilder"] = "BuilderController";
 0181        messageTypeToBridgeName["PreloadFile"] = "BuilderController";
 0182        messageTypeToBridgeName["SetBuilderConfiguration"] = "BuilderController";
 183
 0184        messageTypeToBridgeName["SetTutorialEnabled"] = "TutorialController";
 0185        messageTypeToBridgeName["SetTutorialEnabledForUsersThatAlreadyDidTheTutorial"] = "TutorialController";
 0186    }
 187
 188    IEnumerator ProcessMessages()
 189    {
 0190        var hudControllerGO = GameObject.Find("HUDController");
 0191        var mainGO = GameObject.Find("Main");
 192
 0193        while (!requestStop)
 194        {
 0195            lock (queuedMessages)
 196            {
 0197                if (queuedMessagesDirty)
 198                {
 0199                    while (queuedMessages.Count > 0)
 200                    {
 0201                        DCLWebSocketService.Message msg = queuedMessages.Dequeue();
 202
 0203                        switch (msg.type)
 204                        {
 205                            // Add to this list the messages that are used a lot and you want better performance
 206                            case "SendSceneMessage":
 0207                                DCL.Environment.i.world.sceneController.SendSceneMessage(msg.payload);
 0208                                break;
 209                            case "Reset":
 0210                                DCL.Environment.i.world.sceneController.UnloadAllScenesQueued();
 0211                                break;
 212                            case "SetVoiceChatEnabledByScene":
 0213                                if (int.TryParse(msg.payload, out int value)) // The payload should be `string`, this wi
 214                                {
 0215                                    hudControllerGO.SendMessage(msg.type, value);
 216                                }
 0217                                break;
 218                            case "RunPerformanceMeterTool":
 0219                                if (float.TryParse(msg.payload, out float durationInSeconds)) // The payload should be `
 220                                {
 0221                                    mainGO.SendMessage(msg.type, durationInSeconds);
 222                                }
 0223                                break;
 224                            default:
 0225                                if (!messageTypeToBridgeName.TryGetValue(msg.type, out string bridgeName))
 226                                {
 0227                                    bridgeName = "Bridges"; // Default bridge
 228                                }
 229
 0230                                if (bridgeGameObjects.TryGetValue(bridgeName, out GameObject bridgeObject) == false)
 231                                {
 0232                                    bridgeObject = GameObject.Find(bridgeName);
 0233                                    bridgeGameObjects.Add(bridgeName, bridgeObject);
 234                                }
 235
 0236                                if (bridgeObject != null)
 237                                {
 0238                                    bridgeObject.SendMessage(msg.type, msg.payload);
 239                                }
 240                                break;
 241                        }
 242
 0243                        if (DCLWebSocketService.VERBOSE)
 244                        {
 0245                            Debug.Log(
 246                                "<b><color=#0000FF>WebSocketCommunication</color></b> >>> Got it! passing message of typ
 247                                msg.type);
 248                        }
 249                    }
 250                }
 0251            }
 0252            yield return null;
 253        }
 0254    }
 0255    public void Dispose() { ws.Stop(); }
 256}