internal void GetPage(int currentPage)
        {
            if (!_loading)
            {
                Console.WriteLine($"Getting page {currentPage}");
                try
                {
                    _loading = true;
                    _multiplayerServerList._pageUpButton.interactable   = false;
                    _multiplayerServerList._pageDownButton.interactable = false;
                    _serverHubConnection = new TcpClient(Config.Instance.ServerHubIP, Config.Instance.ServerHubPort);
                    ClientDataPacket packet = new ClientDataPacket()
                    {
                        ConnectionType = ConnectionType.Client, Offset = _multiplayerServerList._currentPage
                    };

                    _serverHubConnection.GetStream().Write(packet.ToBytes(), 0, packet.ToBytes().Length);
                    StartCoroutine(WaitForResponse());
                    Console.WriteLine("Waiting for response...");
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Exception: {e}");
                    _loading = false;
                    TextMeshProUGUI _errorText = ui.CreateText(rectTransform, "Can't connect to ServerHub!", new Vector2(0f, -48f));
                    _errorText.alignment = TextAlignmentOptions.Center;
                    Destroy(_errorText.gameObject, 4f);
                }
            }
        }
Esempio n. 2
0
        internal void GetServers()
        {
            if (!_loading)
            {
                Console.WriteLine($"Get servers from ServerHubs");
                try
                {
                    _loading = true;

                    _multiplayerServerList.SetServers(new List <Data.Data>());
                    _serverHubs.ForEach(x => x.RequestServers());

                    Console.WriteLine("Waiting for response...");
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Exception: {e}");
                    _loading = false;
                    TextMeshProUGUI _errorText = ui.CreateText(rectTransform, "Can't connect to ServerHub!", new Vector2(0f, -48f));
                    _errorText.alignment = TextAlignmentOptions.Center;
                    Destroy(_errorText.gameObject, 4f);
                }
            }
        }
Esempio n. 3
0
        protected override void DidActivate()
        {
            ui              = BSMultiplayerUI._instance;
            _songLoader     = FindObjectOfType <SongLoader>();
            localPlayerInfo = new PlayerInfo(GetUserInfo.GetUserName(), GetUserInfo.GetUserID());

            if (_songPreviewPlayer == null)
            {
                ObjectProvider[] providers = Resources.FindObjectsOfTypeAll <ObjectProvider>().Where(x => x.name == "SongPreviewPlayerProvider").ToArray();

                if (providers.Length > 0)
                {
                    _songPreviewPlayer = providers[0].GetProvidedObject <SongPreviewPlayer>();
                }
            }

            if (_backButton == null)
            {
                _backButton = ui.CreateBackButton(rectTransform);

                _backButton.onClick.AddListener(delegate()
                {
                    BSMultiplayerClient._instance.DataReceived -= DataReceived;
                    BSMultiplayerClient._instance.DisconnectFromServer();
                    _songPreviewPlayer.CrossfadeToDefault();
                    try
                    {
                        transform.parent.GetComponent <MultiplayerServerHubViewController>().UpdatePage();
                    } catch (Exception e)
                    {
                        Console.WriteLine($"ServerHub exception: {e}");
                    }
                    foreach (AvatarController avatar in _avatars)
                    {
                        Destroy(avatar.gameObject);
                    }
                    DismissModalViewController(null, false);
                });
            }

            if (_timerText == null)
            {
                _timerText           = ui.CreateText(rectTransform, "", new Vector2(0f, -5f));
                _timerText.fontSize  = 8f;
                _timerText.alignment = TextAlignmentOptions.Center;
                _timerText.rectTransform.sizeDelta = new Vector2(20f, 6f);
            }

            if (_selectText == null)
            {
                _selectText           = ui.CreateText(rectTransform, "", new Vector2(0f, -36f));
                _selectText.fontSize  = 7f;
                _selectText.alignment = TextAlignmentOptions.Center;
                _selectText.rectTransform.sizeDelta = new Vector2(120f, 6f);
            }

            if (_loadingIndicator == null)
            {
                try
                {
                    _loadingIndicator = ui.CreateLoadingIndicator(rectTransform);
                    (_loadingIndicator.transform as RectTransform).anchorMin        = new Vector2(0.5f, 0.5f);
                    (_loadingIndicator.transform as RectTransform).anchorMax        = new Vector2(0.5f, 0.5f);
                    (_loadingIndicator.transform as RectTransform).anchoredPosition = new Vector2(0f, 0f);
                    _loadingIndicator.SetActive(true);
                }
                catch (Exception e)
                {
                    Console.WriteLine("EXCEPTION: " + e);
                }
            }

            if (_selectedSongCell == null)
            {
                _selectedSongCell = Instantiate(Resources.FindObjectsOfTypeAll <SongListTableCell>().First(x => x.name == "SongListTableCell"), rectTransform, false);

                (_selectedSongCell.transform as RectTransform).anchorMin        = new Vector2(0.5f, 0.5f);
                (_selectedSongCell.transform as RectTransform).anchorMax        = new Vector2(0.5f, 0.5f);
                (_selectedSongCell.transform as RectTransform).anchoredPosition = new Vector2(-25f, 0);

                _selectedSongCell.gameObject.SetActive(false);
            }
            else
            {
                _selectedSongCell.gameObject.SetActive(false);
            }

            if (_multiplayerLeaderboard == null)
            {
                _multiplayerLeaderboard = ui.CreateViewController <MultiplayerLeaderboardViewController>();
                _multiplayerLeaderboard.rectTransform.anchorMin = new Vector2(0.3f, 0f);
                _multiplayerLeaderboard.rectTransform.anchorMax = new Vector2(0.7f, 1f);

                PushViewController(_multiplayerLeaderboard, true);
            }
            else
            {
                if (_viewControllers.IndexOf(_multiplayerLeaderboard) < 0)
                {
                    PushViewController(_multiplayerLeaderboard, true);
                }
            }

            Console.WriteLine($"Connecting to {selectedServerIP}:{selectedServerPort}");
            if (BSMultiplayerClient._instance.ConnectToServer(selectedServerIP, selectedServerPort))
            {
                BSMultiplayerClient._instance.SendString(JsonUtility.ToJson(new ClientCommand(ClientCommandType.GetServerState)));
                BSMultiplayerClient._instance.SendString(JsonUtility.ToJson(new ClientCommand(ClientCommandType.GetAvailableSongs)));
                StartCoroutine(BSMultiplayerClient._instance.ReceiveFromServerCoroutine());
                BSMultiplayerClient._instance.DataReceived += DataReceived;
            }
            else
            {
                _loading = false;
                TextMeshProUGUI _errorText = ui.CreateText(rectTransform, String.Format("Can't connect to server!"), new Vector2(0f, -48f));
                _errorText.alignment = TextAlignmentOptions.Center;
                Destroy(_errorText.gameObject, 5f);
            }
        }
Esempio n. 4
0
        IEnumerator DownloadSongByLevelId(string levelId)
        {
            Console.WriteLine("Donwloading " + levelId.Substring(0, levelId.IndexOf('∎')));

            _selectText.text = "Connecting to BeatSaver.com...";

            UnityWebRequest wwwId = UnityWebRequest.Get("https://beatsaver.com/api.php?mode=hashinfo&hash=" + levelId.Substring(0, levelId.IndexOf('∎')));

            wwwId.timeout = 10;

            yield return(wwwId.SendWebRequest());


            if (wwwId.isNetworkError || wwwId.isHttpError)
            {
                Console.WriteLine(wwwId.error);

                _selectText.text = "";

                TextMeshProUGUI _errorText = ui.CreateText(rectTransform, String.Format(wwwId.error), new Vector2(0f, -48f));
                _errorText.alignment = TextAlignmentOptions.Center;
                Destroy(_errorText.gameObject, 2f);
            }
            else
            {
                string parse = wwwId.downloadHandler.text;

                JSONNode node = JSON.Parse(parse);

                Song _tempSong = new Song(node[0]);

                UnityWebRequest wwwDl = UnityWebRequest.Get("https://beatsaver.com/dl.php?id=" + (_tempSong.id));
                wwwDl.timeout    = 10;
                _selectText.text = "Downloading " + HTML5Decode.HtmlDecode(_tempSong.beatname) + "...";
                yield return(wwwDl.SendWebRequest());

                if (wwwId.isNetworkError || wwwId.isHttpError)
                {
                    Console.WriteLine(wwwId.error);
                    TextMeshProUGUI _errorText = ui.CreateText(rectTransform, String.Format(wwwId.error), new Vector2(0f, -48f));
                    _errorText.alignment = TextAlignmentOptions.Center;
                    Destroy(_errorText.gameObject, 2f);
                }
                else
                {
                    string zipPath         = "";
                    string docPath         = "";
                    string customSongsPath = "";
                    try
                    {
                        byte[] data = wwwDl.downloadHandler.data;

                        docPath         = Application.dataPath;
                        docPath         = docPath.Substring(0, docPath.Length - 5);
                        docPath         = docPath.Substring(0, docPath.LastIndexOf("/"));
                        customSongsPath = docPath + "/CustomSongs/";
                        zipPath         = customSongsPath + _tempSong.beatname + ".zip";
                        File.WriteAllBytes(zipPath, data);
                        Console.WriteLine("Downloaded zip file!");

                        FastZip zip = new FastZip();

                        Console.WriteLine("Extracting...");
                        zip.ExtractZip(zipPath, customSongsPath, null);

                        File.Delete(zipPath);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("EXCEPTION: " + e);
                        yield break;
                    }
                }
            }
        }
Esempio n. 5
0
        protected override void DidActivate()
        {
            ui          = BSMultiplayerUI._instance;
            _songLoader = FindObjectOfType <SongLoader>();

            if (_songPreviewPlayer == null)
            {
                ObjectProvider[] providers = Resources.FindObjectsOfTypeAll <ObjectProvider>().Where(x => x.name == "SongPreviewPlayerProvider").ToArray();

                if (providers.Length > 0)
                {
                    _songPreviewPlayer = providers[0].GetProvidedObject <SongPreviewPlayer>();
                }
            }

            if (_backButton == null)
            {
                _backButton = ui.CreateBackButton(rectTransform);

                _backButton.onClick.AddListener(delegate()
                {
                    BSMultiplayerMain._instance.DataReceived -= DataReceived;
                    BSMultiplayerMain._instance.DisconnectFromServer();
                    DismissModalViewController(null, false);
                });
            }

            if (_timerText == null)
            {
                _timerText           = ui.CreateText(rectTransform, "", new Vector2(0f, -5f));
                _timerText.fontSize  = 8f;
                _timerText.alignment = TextAlignmentOptions.Center;
                _timerText.rectTransform.sizeDelta = new Vector2(20f, 6f);
            }

            if (_selectText == null)
            {
                _selectText           = ui.CreateText(rectTransform, "", new Vector2(0f, -36f));
                _selectText.fontSize  = 7f;
                _selectText.alignment = TextAlignmentOptions.Center;
                _selectText.rectTransform.sizeDelta = new Vector2(40f, 6f);
            }

            if (_loadingIndicator == null)
            {
                try
                {
                    _loadingIndicator = ui.CreateLoadingIndicator(rectTransform);
                    (_loadingIndicator.transform as RectTransform).anchorMin        = new Vector2(0.5f, 0.5f);
                    (_loadingIndicator.transform as RectTransform).anchorMax        = new Vector2(0.5f, 0.5f);
                    (_loadingIndicator.transform as RectTransform).anchoredPosition = new Vector2(0f, 0f);
                    _loadingIndicator.SetActive(true);
                }
                catch (Exception e)
                {
                    Console.WriteLine("EXCEPTION: " + e);
                }
            }

            if (_selectedSongCell == null)
            {
                _selectedSongCell = Instantiate(Resources.FindObjectsOfTypeAll <SongListTableCell>().First(x => x.name == "SongListTableCell"), rectTransform, false);

                (_selectedSongCell.transform as RectTransform).anchorMin        = new Vector2(0.5f, 0.5f);
                (_selectedSongCell.transform as RectTransform).anchorMax        = new Vector2(0.5f, 0.5f);
                (_selectedSongCell.transform as RectTransform).anchoredPosition = new Vector2(-25f, 0);

                _selectedSongCell.gameObject.SetActive(false);
            }
            else
            {
                _selectedSongCell.gameObject.SetActive(false);
            }



            if (BSMultiplayerMain._instance.ConnectToServer())
            {
                BSMultiplayerMain._instance.SendString(JsonUtility.ToJson(new ClientCommand(ClientCommandType.GetServerState)));
                BSMultiplayerMain._instance.SendString(JsonUtility.ToJson(new ClientCommand(ClientCommandType.GetAvailableSongs)));
                StartCoroutine(BSMultiplayerMain._instance.ReceiveFromServerCoroutine());
                BSMultiplayerMain._instance.DataReceived += DataReceived;
            }
            else
            {
                _loading = false;
                TextMeshProUGUI _errorText = ui.CreateText(rectTransform, String.Format("Can't connect to server!"), new Vector2(0f, -48f));
                _errorText.alignment = TextAlignmentOptions.Center;
                Destroy(_errorText.gameObject, 5f);
            }
        }
Esempio n. 6
0
        private void DataReceived(string[] _data)
        {
            if (_data != null && _data.Length > 0)
            {
                foreach (string data in _data)
                {
                    ServerCommand command = null;

                    try
                    {
                        command = JsonUtility.FromJson <ServerCommand>(data);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Can't parse received JSON! Exception: " + e);
                    }

                    try
                    {
                        if (command != null)
                        {
                            switch (command.commandType)
                            {
                            case ServerCommandType.SetServerState:
                            {
                                if (command.serverState == ServerState.Playing)
                                {
                                    BSMultiplayerMain._instance.DataReceived -= DataReceived;
                                    BSMultiplayerMain._instance.DisconnectFromServer();
                                    TimeSpan timeRemaining = TimeSpan.FromSeconds(command.selectedSongDuration - command.selectedSongPlayTime);

                                    TextMeshProUGUI _errorText = ui.CreateText(rectTransform, "Game in progress, " + timeRemaining.Minutes.ToString("00") + ":" + timeRemaining.Seconds.ToString("00") + " remaining", new Vector2(0f, -48f));
                                    _errorText.alignment = TextAlignmentOptions.Center;
                                    Destroy(_errorText.gameObject, 3f);
                                }
                            }; break;

                            case ServerCommandType.SetLobbyTimer:
                            {
                                Console.WriteLine("Set timer text to " + command.lobbyTimer);
                                _timerText.text = command.lobbyTimer.ToString();
                            }; break;

                            case ServerCommandType.SetSelectedSong:
                            {
                                Console.WriteLine("Set selected song " + command.selectedLevelID);

                                _loading = false;

                                if (_selectedSong == null)
                                {
                                    try
                                    {
                                        _selectedSongDifficulty = command.selectedSongDifficlty;
                                        _selectedSong           = SongLoader.CustomSongInfos.First(x => x.levelId == command.selectedLevelID);

                                        _selectText.text = "Next song:";

                                        _selectedSongCell.gameObject.SetActive(true);
                                        _selectedSongCell.songName = _selectedSong.songName + "\n<size=80%>" + _selectedSong.songSubName + "</size>";
                                        _selectedSongCell.author   = _selectedSong.authorName;


                                        CustomLevelStaticData _songData = SongLoader.CustomLevelStaticDatas.First(x => x.levelId == _selectedSong.levelId);

                                        _selectedSongCell.coverImage = _songData.coverImage;

                                        PlayPreview(_songData);
                                    }
                                    catch (Exception e)
                                    {
                                        Console.WriteLine("EXCEPTION: " + e);
                                    }
                                }

                                Console.WriteLine("Done");
                            }; break;

                            case ServerCommandType.StartSelectedSongLevel:
                            {
                                Console.WriteLine("Starting selected song! Song: " + _selectedSong.songName + ", Diff: " + ((LevelStaticData.Difficulty)_selectedSongDifficulty).ToString());

                                BSMultiplayerMain._instance.DataReceived -= DataReceived;
                                GameplayOptions gameplayOptions = new GameplayOptions();
                                gameplayOptions.noEnergy = true;
                                gameplayOptions.mirror   = false;

                                if (BSMultiplayerMain._instance._mainGameSceneSetupData != null)
                                {
                                    BSMultiplayerMain._instance._mainGameSceneSetupData.SetData(_selectedSong.levelId, (LevelStaticData.Difficulty)_selectedSongDifficulty, null, null, 0f, gameplayOptions, GameplayMode.SoloStandard, null);
                                    BSMultiplayerMain._instance._mainGameSceneSetupData.TransitionToScene(0.7f);
                                    _selectedSong = null;
                                    return;
                                }
                                else
                                {
                                    Console.WriteLine("SceneSetupData is null!");
                                }
                            }; break;

                            case ServerCommandType.DownloadSongs: {
                                StartCoroutine(DownloadSongs(command.songsToDownload));
                                BSMultiplayerMain._instance.DisconnectFromServer();
                            }; break;
                            }
                        }
                        else
                        {
                            Console.WriteLine("Server Command is null!");
                        }
                    }catch (Exception e)
                    {
                        Console.WriteLine("Exception (parse switch): " + e);
                    }
                }
            }


            StartCoroutine(BSMultiplayerMain._instance.ReceiveFromServerCoroutine());
        }
        IEnumerator DownloadSongByLevelId(string levelId)
        {
            Console.WriteLine("Downloading " + levelId.Substring(0, levelId.IndexOf('∎')));

            _selectText.text = "Connecting to BeatSaver...";

            UnityWebRequest wwwId = UnityWebRequest.Get($"{beatSaverURL}/api/songs/search/hash/" + levelId.Substring(0, levelId.IndexOf('∎')));

            wwwId.timeout = 10;

            yield return(wwwId.SendWebRequest());


            if (wwwId.isNetworkError || wwwId.isHttpError)
            {
                Console.WriteLine(wwwId.error);

                _selectText.text = "";

                TextMeshProUGUI _errorText = ui.CreateText(rectTransform, String.Format(wwwId.error), new Vector2(0f, -48f));
                _errorText.alignment = TextAlignmentOptions.Center;
                Destroy(_errorText.gameObject, 2f);
            }
            else
            {
                Console.WriteLine("Received response from BeatSaver");

                JSONNode node = JSON.Parse(wwwId.downloadHandler.text);

                if (node["songs"].Count == 0)
                {
                    _selectText.text = $"Song {levelId.Split('∎')[1]} doesn't exist!";
                    yield break;
                }

                Song _tempSong = Song.FromSearchNode(node["songs"][0]);

                UnityWebRequest wwwDl = UnityWebRequest.Get(_tempSong.downloadUrl);

                bool  timeout = false;
                float time    = 0f;

                UnityWebRequestAsyncOperation asyncRequest = wwwDl.SendWebRequest();

                while (!asyncRequest.isDone || asyncRequest.progress < 1f)
                {
                    yield return(null);

                    time += Time.deltaTime;

                    if (time >= 15f && asyncRequest.progress == 0f)
                    {
                        wwwDl.Abort();
                        timeout = true;
                    }

                    _selectText.text = "Downloading " + _tempSong.beatname + " - " + Math.Round(asyncRequest.progress * 100) + "%";
                }

                if (wwwId.isNetworkError || wwwId.isHttpError || timeout)
                {
                    if (timeout)
                    {
                        Console.WriteLine("Request timeout");
                        TextMeshProUGUI _errorText = ui.CreateText(rectTransform, String.Format("Request timeout"), new Vector2(0f, -48f));
                        _errorText.alignment = TextAlignmentOptions.Center;
                        Destroy(_errorText.gameObject, 2f);
                    }
                    else
                    {
                        Console.WriteLine(wwwId.error);
                        TextMeshProUGUI _errorText = ui.CreateText(rectTransform, String.Format(wwwId.error), new Vector2(0f, -48f));
                        _errorText.alignment = TextAlignmentOptions.Center;
                        Destroy(_errorText.gameObject, 2f);
                    }
                }
                else
                {
                    string docPath         = "";
                    string customSongsPath = "";
                    string zipPath         = "";
                    try
                    {
                        byte[] data = wwwDl.downloadHandler.data;

                        docPath         = Application.dataPath;
                        docPath         = docPath.Substring(0, docPath.Length - 5);
                        docPath         = docPath.Substring(0, docPath.LastIndexOf("/"));
                        customSongsPath = docPath + "/CustomSongs/" + _tempSong.id + "/";
                        zipPath         = customSongsPath + _tempSong.id + ".zip";
                        if (!Directory.Exists(customSongsPath))
                        {
                            Directory.CreateDirectory(customSongsPath);
                        }
                        File.WriteAllBytes(zipPath, data);
                        Console.WriteLine("Downloaded zip file!");

                        Console.WriteLine("Extracting...");

                        try
                        {
                            ZipFile.ExtractToDirectory(zipPath, customSongsPath);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine($"Can't extract ZIP! Exception: {e}");
                        }


                        File.Delete(zipPath);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("EXCEPTION: " + e);
                        yield break;
                    }
                }
            }
        }