<commit_before>﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;

namespace DatabaseAPI
{
    /// <summary>
    /// If activated on a server then it will update the
    /// unitystation rest api with the status of this server
    /// To gain access to the unitystation hub for your server
    /// speak to unitystation staff on discord
    /// </summary>
    public partial class ServerData
    {
        private ServerConfig config;
        /// <summary>
        /// The server config that holds the values 
        /// for your RCON and Unitystation HUB API connections
        /// </summary>
        public static ServerConfig ServerConfig
        {
            get
            {
                return Instance.config;
            }
        }
        private BuildInfo buildInfo;

        private bool connectedToHub = false;
        private string hubCookie;
        private const string hubRoot = "https://api.unitystation.org";
        private const string hubLogin = hubRoot + "/login?data=";
        private const string hubUpdate = hubRoot + "/statusupdate?data=";
        private float updateWait = 0f;

        void AttemptConfigLoad()
        {
            var path = Path.Combine(Application.streamingAssetsPath, "/config/config.json");
            buildInfo = JsonUtility.FromJson<BuildInfo>(File.ReadAllText(Path.Combine(Application.streamingAssetsPath, "buildinfo.json")));

            if (File.Exists(path))
            {
                config = JsonUtility.FromJson<ServerConfig>(File.ReadAllText(path));
                AttemptHubConnection();
            }
            else
            {
                Logger.Log("No config found for Rcon and Server Hub connections", Category.DatabaseAPI);
            }
        }

        //Attempts to auth with api.unitystation.org for server status updates
        void AttemptHubConnection()
        {
            if (string.IsNullOrEmpty(config.HubUser) || string.IsNullOrEmpty(config.HubPass))
            {
                Logger.Log("Invalid Hub creds found, aborting HUB connection", Category.DatabaseAPI);
                return;
            }

            var loginReq = new HubLoginReq
            {
                username = config.HubUser,
                password = config.HubPass
            };

            Instance.StartCoroutine(Instance.TryHubLogin(loginReq));
        }

        IEnumerator TryHubLogin(HubLoginReq loginRequest)
        {
            var requestData = JsonUtility.ToJson(loginRequest);
            UnityWebRequest r = UnityWebRequest.Get(hubLogin + UnityWebRequest.EscapeURL(requestData));
            yield return r.SendWebRequest();
            if (r.error != null)
            {
                Logger.Log("Hub Login request failed: " + r.error, Category.DatabaseAPI);
                yield break;
            }
            else
            {
                var response = JsonUtility.FromJson<ApiResponse>(r.downloadHandler.text);
                if (response.errorCode == 0)
                {
                    string s = r.GetResponseHeader("set-cookie");
                    hubCookie = s.Split(';') [0];
                    Logger.Log("Hub connected successfully", Category.DatabaseAPI);
                    connectedToHub = true;
                }
                else
                {
                    Logger.Log("Hub Login request failed: " + response.errorMsg, Category.DatabaseAPI);
                }
            }
        }

        void MonitorServerStatus()
        {
            updateWait += Time.deltaTime;
            //Update the hub every 5 seconds
            if (updateWait >= 5f)
            {
                updateWait = 0f;
                Instance.StartCoroutine(Instance.SendServerStatus());
            }
        }

        IEnumerator SendServerStatus()
        {
            var status = new ServerStatus();
            status.ServerName = config.ServerName;
            status.ForkName = buildInfo.ForkName;
            status.BuildVersion = buildInfo.BuildNumber;
            status.CurrentMap = SceneManager.GetActiveScene().name;
            status.GameMode = GameManager.Instance.gameMode.ToString();
            status.IngameTime = GameManager.Instance.stationTime.ToShortTimeString();
            status.PlayerCount = PlayerList.Instance.ConnectionCount;
            status.ServerIP = CustomNetworkManager.Instance.networkAddress;
            status.ServerPort = CustomNetworkManager.Instance.networkPort;
            status.WinDownload = config.WinDownload;
            status.OSXDownload = config.OSXDownload;
            status.LinuxDownload = config.LinuxDownload;

            UnityWebRequest r = UnityWebRequest.Get(hubUpdate + UnityWebRequest.EscapeURL(JsonUtility.ToJson(status)));
            r.SetRequestHeader("Cookie", hubCookie);
            yield return r.SendWebRequest();
            if (r.error != null)
            {
                Logger.Log("Failed to update hub with server status" + r.error, Category.DatabaseAPI);
            }
        }
    }

    [Serializable]
    public class HubLoginReq
    {
        public string username;
        public string password;
    }

    [Serializable]
    public class ApiResponse
    {
        public int errorCode = 0; //0 = all good, read the message variable now, otherwise read errorMsg
        public string errorMsg;
        public string message;
    }

    [Serializable]
    public class ServerStatus
    {
        public string ServerName;
        public string ForkName;
        public int BuildVersion;
        public string CurrentMap;<commit_msg>auth required on hub for server status updating<commit_after>﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;

namespace DatabaseAPI
{
    /// <summary>
    /// If activated on a server then it will update the
    /// unitystation rest api with the status of this server
    /// To gain access to the unitystation hub for your server
    /// speak to unitystation staff on discord
    /// </summary>
    public partial class ServerData
    {
        private ServerConfig config;
        /// <summary>
        /// The server config that holds the values 
        /// for your RCON and Unitystation HUB API connections
        /// </summary>
        public static ServerConfig ServerConfig
        {
            get
            {
                return Instance.config;
            }
        }
        private BuildInfo buildInfo;

        private bool connectedToHub = false;
        private string hubCookie;
        private const string hubRoot = "https://api.unitystation.org";
        private const string hubLogin = hubRoot + "/login?data=";
        private const string hubUpdate = hubRoot + "/statusupdate?data=";
        private float updateWait = 0f;

        void AttemptConfigLoad()
        {
            var path = Path.Combine(Application.streamingAssetsPath, "/config/config.json");
            buildInfo = JsonUtility.FromJson<BuildInfo>(File.ReadAllText(Path.Combine(Application.streamingAssetsPath, "buildinfo.json")));

            if (File.Exists(path))
            {
                config = JsonUtility.FromJson<ServerConfig>(File.ReadAllText(path));
                AttemptHubConnection();
            }
            else
            {
                Logger.Log("No config found for Rcon and Server Hub connections", Category.DatabaseAPI);
            }
        }

        //Attempts to auth with api.unitystation.org for server status updates
        void AttemptHubConnection()
        {
            if (string.IsNullOrEmpty(config.HubUser) || string.IsNullOrEmpty(config.HubPass))
            {
                Logger.Log("Invalid Hub creds found, aborting HUB connection", Category.DatabaseAPI);
                return;
            }

            var loginReq = new HubLoginReq
            {
                username = config.HubUser,
                password = <PASSWORD>
            };

            Instance.StartCoroutine(Instance.TryHubLogin(loginReq));
        }

        IEnumerator TryHubLogin(HubLoginReq loginRequest)
        {
            var requestData = JsonUtility.ToJson(loginRequest);
            UnityWebRequest r = UnityWebRequest.Get(hubLogin + UnityWebRequest.EscapeURL(requestData));
            yield return r.SendWebRequest();
            if (r.error != null)
            {
                Logger.Log("Hub Login request failed: " + r.error, Category.DatabaseAPI);
                yield break;
            }
            else
            {
                var response = JsonUtility.FromJson<ApiResponse>(r.downloadHandler.text);
                if (response.errorCode == 0)
                {
                    string s = r.GetResponseHeader("set-cookie");
                    hubCookie = s.Split(';') [0];
                    Logger.Log("Hub connected successfully", Category.DatabaseAPI);
                    connectedToHub = true;
                }
                else
                {
                    Logger.Log("Hub Login request failed: " + response.errorMsg, Category.DatabaseAPI);
                }
            }
        }

        void MonitorServerStatus()
        {
            updateWait += Time.deltaTime;
            //Update the hub every 5 seconds
            if (updateWait >= 5f)
            {
                updateWait = 0f;
                Instance.StartCoroutine(Instance.SendServerStatus());
            }
        }

        IEnumerator SendServerStatus()
        {
            var status = new ServerStatus();
            status.ServerName = config.ServerName;
            status.ForkName = buildInfo.ForkName;
            status.BuildVersion = buildInfo.BuildNumber;
            status.CurrentMap = SceneManager.GetActiveScene().name;
            status.GameMode = GameManager.Instance.gameMode.ToString();
            status.IngameTime = GameManager.Instance.stationTime.ToShortTimeString();
            status.PlayerCount = PlayerList.Instance.ConnectionCount;
            status.ServerIP = CustomNetworkManager.Instance.networkAddress;
            status.ServerPort = CustomNetworkManager.Instance.networkPort;
            status.WinDownload = config.WinDownload;
            status.OSXDownload = config.OSXDownload;
            status.LinuxDownload = config.LinuxDownload;

            UnityWebRequest r = UnityWebRequest.Get(hubUpdate + UnityWebRequest.EscapeURL(JsonUtility.ToJson(status)) + "&user=" + config.HubUser);
            r.SetRequestHeader("Cookie", hubCookie);
            yield return r.SendWebRequest();
            if (r.error != null)
            {
                Logger.Log("Failed to update hub with server status" + r.error, Category.DatabaseAPI);
            }
        }
    }

    [Serializable]
    public class HubLoginReq
    {
        public string username;
        public string password;
    }

    [Serializable]
    public class ApiResponse
    {
        public int errorCode = 0; //0 = all good, read the message variable now, otherwise read errorMsg
        public string errorMsg;
        public string message;
    }

    [Serializable]
    public class ServerStatus
    {
        public string ServerName;
        public string ForkName;
        public int BuildVersion;
        public string CurrentMap;
{'fraction_non_alphanumeric': 0.08299842739821772, 'fraction_numerical': 0.001397868250917351, 'mean_word_length': 1.8125307125307126, 'pattern_counts': {'":': 0, '<': 18, '<?xml version=': 0, '>': 20, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 14, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '827615', 'n_tokens_mistral': 2801, 'n_tokens_neox': 2713, 'n_words': 688}