private async Task <int[]> GetNumberOfWinsAndLosses(Player player)
        {
            string  jsonString;
            dynamic responseInJson;
            bool    isError = false;

            do
            {
                try
                {
                    isError    = false;
                    jsonString = await NetComm.GetResponseOfURL($"players/{player.SteamId}/wl", _httpClient);

                    responseInJson = JsonToFrom.Deserialize <dynamic>(jsonString);
                    int[] winAndLose = new int[2] {
                        responseInJson.win, responseInJson.lose
                    };
                    return(winAndLose);
                }
                catch (Exception)
                {
                    isError = true;
                    Thread.Sleep(10 * 1000);
                }
            } while (isError);
            return(new int[] { 0, 0 });
        }
Exemple #2
0
        private void RefreshLocalDevices()
        {
            panel_FlowLayoutDevices.Controls.Clear();


            NetComm.ScoutNetworkDevices();
        }
Exemple #3
0
        public Panel CreateLocalDevicesElement(Point location, int width, int height, Form _form)
        {
            mainForm            = _form;
            FileDisplayList     = new List <DarkFileDisplay>();
            MainPanel           = new Panel();
            MainPanel.Location  = location;
            MainPanel.Size      = new Size(width, height);
            MainPanel.BackColor = Color.Transparent;

            Panel DeviceScoutPanel = CreateDeviceScoutPanel();

            MainPanel.Controls.Add(DeviceScoutPanel);

            FileDisplayMinX = DeviceScoutPanel.Location.X + DeviceScoutPanel.Width;

            CreateFileAreaPanel(FileDisplayMinX);
            CreateFileUploadVisualPanel();
            panel_FlowLayoutFiles.Visible = false;

            panel_DragDropFiles = CreateFileDropSendPanel(FileDisplayMinX);
            FileAreaPanel.Controls.Add(panel_DragDropFiles);


            // Create the various state panels



            FileAreaPanel.Visible = false;

            panel_ButtonsMain = new Panel();

            panel_ButtonsMain.Location = new Point(FileAreaPanel.Location.X, FileAreaPanel.Location.Y + FileAreaPanel.Height + 10);
            panel_ButtonsMain.Size     = new Size(FileAreaPanel.Width, 200);
            MainPanel.Controls.Add(panel_ButtonsMain);

            panel_SendFiles         = CreateSendButtons();
            panel_SendFiles.Visible = false;;
            panel_ButtonsMain.Controls.Add(panel_SendFiles);
            panel_ButtonsMain.Controls.Add(btn_TerminateTransfers);


            ChangeGuiState(GUIState.NoDeviceSelected);


            DataProcessor.NetworkDiscoveryEvent += NetworkDiscoveryEvent;

            NetComm.ScoutNetworkDevices();

            // Subscribe to events
            DataProcessor.OutboundTransferFinished += Transferfinished;
            DataProcessor.OutboundTransferStarted  += TransferStarted;
            DataProcessor.OutboundTransferProgress += TransferProgress;


            return(MainPanel);
        }
Exemple #4
0
        private async Task <string> GetStatsAsync(Player player, double timeInHours)
        {
            string url            = $"players/{player.SteamId}/wl?date={timeInHours / 24}";
            var    responseInJson = await NetComm.GetResponseOfURL(url);

            dynamic response = responseInJson.Deserialize <dynamic>();
            int     wins     = response.win;
            int     losses   = response.lose;
            string  content  = $"<@{player.DiscordId}>'s score: {wins}/{losses} in last {timeInHours} hours.";

            return(content);
        }
Exemple #5
0
        private async Task <string> GetMedal(ulong id)
        {
            string steamId    = PlayerConfiguration.Players.Where(x => x.DiscordId.Equals(id.ToString())).FirstOrDefault().SteamId;
            var    url        = $"players/{steamId}";
            var    jsonString = await NetComm.GetResponseOfURL(url, _httpClient);

            var    playerInfo  = JsonToFrom.Deserialize <dynamic>(jsonString);
            string playerMedal = (string)playerInfo.rank_tier;

            if (string.IsNullOrEmpty(playerMedal))
            {
                return($"<@{id}> is uncalibrated.");
            }
            var actualMedal = (Medal)((int)char.GetNumericValue(playerMedal[0]) - 1);
            var star        = (int)char.GetNumericValue(playerMedal[1]);

            return($"<@{id}> is {actualMedal}[{star}].");
        }
        private async Task FindAndDisplayTotalMatchesPlayed()
        {
            var channel = await Program.Discord.GetChannelAsync(BotDetails.BotFeedChannel);

            foreach (var player in PlayerConfiguration.Players)
            {
                var jsonString = await NetComm.GetResponseOfURL($"players/{player.SteamId}/wl?date=1", _httpClient);

                var responseInJson = JsonToFrom.Deserialize <dynamic>(jsonString);
                int wins           = responseInJson.win;
                int losses         = responseInJson.lose;
                if (wins + losses > 0)
                {
                    string content = $"<@{player.DiscordId}> won {wins} game{GetPlural(wins)} out of {wins + losses} game{GetPlural(wins + losses)} today.";
                    channel.SendMessageAsync(content);
                }
            }
        }
Exemple #7
0
        private void InitializeNetwork()
        {
            // Get the correct registry key for startup
            rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);


            // Settings
#if DEBUG
            ChangeDestinationFolder("C:/FileJumpFolder");
            ChangeDeviceName("CARLO_BB");
            UserSettings.DeviceType = 1; // HARDCODED. Desktop application
#else
            UserSettings.DeviceType = 1; // HARDCODED. Desktop application

            if (UserSettings.MachineName == "NULL")
            {
                ChangeDeviceName(Environment.MachineName);
            }

            // If the destination folder has not been specified, use the default one (main folder / Incoming Files)

            if (!Directory.Exists(UserSettings.DestinationFolder))
            {
                ChangeDestinationFolder(Path.Combine(Directory.GetCurrentDirectory(), "Incoming Files"));
            }

            // // Check the startup setting
            //if (UserSettings.RunOnStartUp == true)
            //{
            //    startup_Checkbox.CheckState = CheckState.Checked; // This also automatically runs AddToStartup which checks if it is running on startup,
            //}                                                     // else it adds it.
            //else
            //{
            //    startup_Checkbox.CheckState = CheckState.Unchecked; // This runs the remove check
            //}
#endif

            NetComm.InitializeNetwork(UserSettings.MachineName, UserSettings.DeviceType, UserSettings.DestinationFolder, new FileHandler());
        }
        public async Task <string> ProcessAsync(DiscordMessage message)
        {
            string url        = $"players/{message.Author.SteamId()}/heroes?limit={_matchesLimit}&having={_havingAtleastMatches}";
            var    jsonString = await NetComm.GetResponseOfURL(url);

            var        heroDetails    = JsonToFrom.Deserialize <dynamic>(jsonString);
            List <int> randomedHeroId = GetRandomedHeroIds(heroDetails);

            string toReturn = string.Empty;

            toReturn += $"<@{message.Author.Id}> Here are some recent heroes which you have played:\n";
            for (int i = 0; i < randomedHeroId.Count; i += _delimiter)
            {
                toReturn += '`';
                for (int j = i; j < i + _delimiter && j < randomedHeroId.Count; j++)
                {
                    string currentHeroName = HeroDetails.GetHeroById(randomedHeroId[j]).localized_name;
                    toReturn += $"{currentHeroName}" + GetSpacesForHeroName(currentHeroName);
                }
                toReturn += "`\n";
            }

            return(toReturn);
        }
        public override async void Run(DiscordClient discord)
        {
            _botTestingChannel = await discord.GetChannelAsync(BotDetails.BotFeedChannel);

            var listOfPlayers = PlayerConfiguration.Players;

            _httpClient.BaseAddress = new Uri(OpenDotaConfiguration.OpenDotaAPIAddress);
            foreach (var player in listOfPlayers)
            {
                player.TotalMatches = await GetTotalMatches(player);
            }
            while (true)
            {
                try
                {
                    Program.DumpLogger.Log("Fetching Wins and Losses for players.");
                    Dictionary <string, List <Player> > matchIdToPlayersMapping = new Dictionary <string, List <Player> >();
                    foreach (var player in listOfPlayers)
                    {
                        var currentMatches = await GetTotalMatches(player);

                        if (currentMatches != player.TotalMatches)
                        {
                            int extraGames = currentMatches - player.TotalMatches;
                            player.TotalMatches = currentMatches;

                            var jsonString = await NetComm.GetResponseOfURL($"players/{player.SteamId}/matches?limit=1", _httpClient);

                            dynamic lastMatch = JsonToFrom.Deserialize <dynamic>(jsonString)[0];
                            string  matchId   = lastMatch.match_id;
                            if (!matchIdToPlayersMapping.ContainsKey(matchId))
                            {
                                matchIdToPlayersMapping[matchId] = new List <Player>();
                            }

                            matchIdToPlayersMapping[matchId].Add(player);
                        }
                    }
                    foreach (var matchId in matchIdToPlayersMapping.Keys)
                    {
                        string matchDetailsString = await NetComm.GetResponseOfURL($"matches/{matchId}", _httpClient);

                        dynamic matchDetails   = JsonToFrom.Deserialize <dynamic>(matchDetailsString);
                        string  normalOrRanked = GetNormalOrRankedMatch(matchDetails);
                        string  reply          = string.Empty;
                        foreach (var player in matchIdToPlayersMapping[matchId])
                        {
                            reply += GenerateMatchString(matchDetails, normalOrRanked, player);
                        }
                        reply += GenerateDotaBuffLink(matchId);
                        await _botTestingChannel.SendMessageAsync(reply);

                        Program.Logger.Log($"Match Details logged for match id: {matchId}");
                    }
                }
                catch (Exception e)
                {
                    Program.DumpLogger.Log($"Exception in {GetType().Name}\nMessage: {e.Message}\nStack Trace: {e.StackTrace}");
                    Thread.Sleep(30 * 1000);
                    continue;
                }
                Thread.Sleep(5 * 60 * 1000);
            }
        }
        public override async void Run(DiscordClient discord)
        {
            var channel = await discord.GetChannelAsync(BotDetails.BotFeedChannel);

            var lastMessage = (await channel.GetMessagesAsync(1)).FirstOrDefault();
            var matchId     = Regex.Match(lastMessage.Content, $"[0-9]+$").Value;

            if (matchId == null || matchId == string.Empty)
            {
                do
                {
                    var lastNMessage = (await channel.GetMessagesAsync(1, before: lastMessage.Id)).FirstOrDefault();
                    matchId     = Regex.Match(lastNMessage.Content, $"[0-9]+$").Value;
                    lastMessage = lastNMessage;
                } while (matchId == null || matchId == string.Empty);
            }

            var matchDetailsString = KeyValueCache.Get(matchId);

            if (matchDetailsString == null)
            {
                matchDetailsString = await NetComm.GetResponseOfURL($"matches/{matchId}", _httpClient);

                KeyValueCache.Put(matchId, matchDetailsString);
            }
            dynamic matchDetails = JsonToFrom.Deserialize <dynamic>(matchDetailsString);
            long    matchEndTime = (long)matchDetails.start_time + (long)matchDetails.duration;
            double  diffInTime   = GetDiffInDays(matchEndTime);

            foreach (var player in PlayerConfiguration.Players)
            {
                var recentMatches = JsonToFrom.Deserialize <dynamic>(await NetComm.GetResponseOfURL($"players/{player.SteamId}/matches?date={diffInTime}", _httpClient));
                foreach (var recentMatch in recentMatches)
                {
                    string recentMatchId = recentMatch.match_id;
                    if (!_matchMap.ContainsKey(recentMatchId))
                    {
                        _matchMap[recentMatchId] = new List <Player>();
                    }
                    _matchMap[recentMatchId].Add(player);
                }
            }
            var _matchMapOrdered = _matchMap.OrderBy(x => x.Key);

            foreach (var matchMap in _matchMapOrdered)
            {
                if (KeyValueCache.Get(matchMap.Key) == null)
                {
                    KeyValueCache.Put(matchMap.Key, await NetComm.GetResponseOfURL($"matches/{matchMap.Key}", _httpClient));
                }
                dynamic parsedMatch = JsonToFrom.Deserialize <dynamic>(KeyValueCache.Get(matchMap.Key));
                string  matchString = string.Empty;
                foreach (var player in matchMap.Value)
                {
                    matchString += GenerateMatchString(parsedMatch, GetNormalOrRankedMatch(parsedMatch), player);
                }
                matchString += GenerateDotaBuffLink(matchMap.Key);
                channel.SendMessageAsync(matchString);
                Program.Logger.Log($"Offline Tracker logged match {matchMap.Key}.");
            }
        }
Exemple #11
0
        public MainPage()
        {
            InitializeComponent();

            label_LoggedInText.Visible  = false;
            panel_RegisterLogin.Visible = true;

            // Get the correct registry key for startup
            rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);


            // Settings
#if DEBUG
            ChangeDestinationFolder("C:/FileJumpFolder");
            ChangeDeviceName("CARLO_BB");
            UserSettings.DeviceType     = 1; // HARDCODED. Desktop application
            startup_Checkbox.CheckState = CheckState.Unchecked;
#else
            UserSettings.DeviceType = 1; // HARDCODED. Desktop application

            if (UserSettings.MachineName == "NULL")
            {
                ChangeDeviceName(Environment.MachineName);
            }

            // If the destination folder has not been specified, use the default one (main folder / Incoming Files)

            if (!Directory.Exists(UserSettings.DestinationFolder))
            {
                ChangeDestinationFolder(Path.Combine(Directory.GetCurrentDirectory(), "Incoming Files"));
            }

            // Check the startup setting
            if (UserSettings.RunOnStartUp == true)
            {
                startup_Checkbox.CheckState = CheckState.Checked; // This also automatically runs AddToStartup which checks if it is running on startup,
            }                                                     // else it adds it.
            else
            {
                startup_Checkbox.CheckState = CheckState.Unchecked; // This runs the remove check
            }
#endif

            NetComm.InitializeNetwork(UserSettings.MachineName, UserSettings.DeviceType, UserSettings.DestinationFolder, new FileHandler());

            // Notifications settings
            tray_icon.BalloonTipShown   += Tray_icon_BalloonTipShown;
            tray_icon.BalloonTipClosed  += Tray_icon_BalloonTipClosed;
            tray_icon.BalloonTipClicked += Tray_icon_BalloonTipClicked;

            // Subscribe to events
            DataProcessor.NetworkDiscoveryEvent       += NetworkDiscoveryReceived;
            DataProcessor.IncomingTransferFinished    += IncomingTransferFinished;
            DataProcessor.InboundTextTransferFinished += InboundTextTransferFinished;

            ApiCommunication.LoginActionResult  += LoginResultEvent;
            ApiCommunication.LogoutActionResult += LogoutResultEvent;

            // Form events
            btn_OnlineFiles.Click += btn_OnlineStorage;

            btn_Topbar_Close.MouseEnter += OnTopBarButtonEnter;
            btn_Topbar_Close.MouseLeave += OnTopBarButtonLeave;

            btn_Topbar_Minimize.MouseEnter += OnTopBarButtonEnter;
            btn_Topbar_Minimize.MouseLeave += OnTopBarButtonLeave;

            // Some buttons settings
            btn_Register.MouseEnter += (s, e) => btn_Register.Cursor = Cursors.Hand;
            btn_Register.MouseLeave += (s, e) => btn_Register.Cursor = Cursors.Arrow;

            btn_Login.MouseEnter += (s, e) => btn_Login.Cursor = Cursors.Hand;
            btn_Login.MouseLeave += (s, e) => btn_Login.Cursor = Cursors.Arrow;

            btn_Register.MouseClick += btn_Register_Click;
            btn_Login.MouseClick    += btn_Login_Click;



            // Reset the devices count and run a scan
            DevicesCount = 0;
            NetComm.ScoutNetworkDevices();

            CheckIfShouldPerformLogin();

            panel_TopBar.Location = new Point(1, 1);
            panel_TopBar.Size     = new Size(this.Size.Width - 2, 23);
        }
Exemple #12
0
 private void btn_RefreshNetwork_Click(object sender, EventArgs e)
 {
     DevicesCount = 0;
     ResetGUIDevices();
     NetComm.ScoutNetworkDevices();
 }