Skip to content

Commit

Permalink
1.0.9
Browse files Browse the repository at this point in the history
  • Loading branch information
oqyh authored Apr 9, 2024
1 parent 7ef952f commit f5cb3b0
Show file tree
Hide file tree
Showing 8 changed files with 1,178 additions and 553 deletions.
799 changes: 250 additions & 549 deletions CnD_Sound.cs

Large diffs are not rendered by default.

160 changes: 160 additions & 0 deletions Config/Configs.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
using System.Text.Json;
using System.Text.Json.Serialization;

namespace CnD_Sound.Config
{
public static class Configs
{
public static class Shared {
public static string? CookiesFolderPath { get; set; }
}

private static readonly string ConfigDirectoryName = "config";
private static readonly string ConfigFileName = "config.json";
private static string? _configFilePath;
private static ConfigData? _configData;

private static readonly JsonSerializerOptions SerializationOptions = new()
{
Converters =
{
new JsonStringEnumConverter()
},
WriteIndented = true,
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip,
};

public static bool IsLoaded()
{
return _configData is not null;
}

public static ConfigData GetConfigData()
{
if (_configData is null)
{
throw new Exception("Config not yet loaded.");
}

return _configData;
}

public static ConfigData Load(string modulePath)
{
var configFileDirectory = Path.Combine(modulePath, ConfigDirectoryName);
if(!Directory.Exists(configFileDirectory))
{
Directory.CreateDirectory(configFileDirectory);
}

_configFilePath = Path.Combine(configFileDirectory, ConfigFileName);
if (File.Exists(_configFilePath))
{
_configData = JsonSerializer.Deserialize<ConfigData>(File.ReadAllText(_configFilePath), SerializationOptions);
}
else
{
_configData = new ConfigData();
}

if (_configData is null)
{
throw new Exception("Failed to load configs.");
}

SaveConfigData(_configData);

return _configData;
}

private static void SaveConfigData(ConfigData configData)
{
if (_configFilePath is null)
{
throw new Exception("Config not yet loaded.");
}

File.WriteAllText(_configFilePath, JsonSerializer.Serialize(configData, SerializationOptions));
}

public class ConfigData
{
public bool DisableLoopConnections { get; set; }
public bool RemoveDefaultDisconnect { get; set; }
public string InGameSoundConnect { get; set; }
public string InGameSoundDisconnect { get; set; }
public string InGameAllowDisableCommandsOnlyForGroups { get; set; }
public string InGameSoundDisableCommands { get; set; }
public int RemovePlayerCookieOlderThanXDays { get; set; }
public string empty { get; set; }
public bool SendLogToText { get; set; }
public string Log_TextConnectMessageFormat { get; set; }
public string Log_TextDisconnectMessageFormat { get; set; }
public int Log_AutoDeleteLogsMoreThanXdaysOld { get; set; }
private int _Log_SendLogToDiscordOnMode;
public int Log_SendLogToDiscordOnMode
{
get => _Log_SendLogToDiscordOnMode;
set
{
_Log_SendLogToDiscordOnMode = value;
if (_Log_SendLogToDiscordOnMode < 0 || _Log_SendLogToDiscordOnMode > 3)
{
Log_SendLogToDiscordOnMode = 0;
Console.WriteLine("|||||||||||||||||||||||||||||||||||||||||||||||| I N V A L I D ||||||||||||||||||||||||||||||||||||||||||||||||");
Console.WriteLine("[Vote-GoldKingZ] Log_SendLogToDiscordOnMode: is invalid, setting to default value (0) Please Choose 0 or 1 or 2 or 3.");
Console.WriteLine("[Vote-GoldKingZ] Log_SendLogToDiscordOnMode (0) = Disable");
Console.WriteLine("[Vote-GoldKingZ] Log_SendLogToDiscordOnMode (1) = Text Only");
Console.WriteLine("[Vote-GoldKingZ] Log_SendLogToDiscordOnMode (2) = Text With + Name + Hyperlink To Steam Profile");
Console.WriteLine("[Vote-GoldKingZ] Log_SendLogToDiscordOnMode (3) = Text With + Name + Hyperlink To Steam Profile + Profile Picture");
Console.WriteLine("|||||||||||||||||||||||||||||||||||||||||||||||| I N V A L I D ||||||||||||||||||||||||||||||||||||||||||||||||");
}
}
}
private string? _Log_DiscordSideColor;
public string Log_DiscordSideColor
{
get => _Log_DiscordSideColor!;
set
{
_Log_DiscordSideColor = value;
if (_Log_DiscordSideColor.StartsWith("#"))
{
Log_DiscordSideColor = _Log_DiscordSideColor.Substring(1);
}
}
}
public string Log_DiscordWebHookURL { get; set; }
public string Log_DiscordConnectMessageFormat { get; set; }
public string Log_DiscordDisconnectMessageFormat { get; set; }
public string Log_DiscordUsersWithNoAvatarImage { get; set; }
public string empty2 { get; set; }
public string Information_For_You_Dont_Delete_it { get; set; }

public ConfigData()
{
DisableLoopConnections = true;
RemoveDefaultDisconnect = true;
InGameSoundConnect = "sounds/buttons/blip1.vsnd_c";
InGameSoundDisconnect = "sounds/player/taunt_clap_01.vsnd_c";
InGameAllowDisableCommandsOnlyForGroups = "";
InGameSoundDisableCommands = "!stopsound,!stopsounds";
RemovePlayerCookieOlderThanXDays = 7;
empty = "-----------------------------------------------------------------------------------";
SendLogToText = false;
Log_TextConnectMessageFormat = "[{DATE} - {TIME}] {PLAYERNAME} Connected [{SHORTCOUNTRY} - {CITY}] [{STEAMID} - {IP}]";
Log_TextDisconnectMessageFormat = "[{DATE} - {TIME}] {PLAYERNAME} Disconnected [{SHORTCOUNTRY} - {CITY}] [{STEAMID64}] [{STEAMID} - {IP}] [{REASON}]";
Log_AutoDeleteLogsMoreThanXdaysOld = 7;
Log_SendLogToDiscordOnMode = 0;
Log_DiscordSideColor = "00FFFF";
Log_DiscordWebHookURL = "https://discord.com/api/webhooks/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
Log_DiscordConnectMessageFormat = "{PLAYERNAME} Connected [{LONGCOUNTRY} - {CITY}]";
Log_DiscordDisconnectMessageFormat = "{PLAYERNAME} Disconnected [{LONGCOUNTRY} - {CITY}] [{REASON}]";
Log_DiscordUsersWithNoAvatarImage = "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/b5/b5bd56c1aa4644a474a2e4972be27ef9e82e517e_full.jpg";
empty2 = "-----------------------------------------------------------------------------------";
Information_For_You_Dont_Delete_it = " Vist [https://github.com/oqyh/cs2-Connect-Disconnect-Sound/tree/main?tab=readme-ov-file#-configuration-] To Understand All Above";
}
}
}
}
Binary file modified CounterStrikeSharp.API.dll
Binary file not shown.
231 changes: 231 additions & 0 deletions Helper/CnDJson.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,231 @@
using Newtonsoft.Json;
using CnD_Sound.Config;
using System.Text;
using System.Drawing;

namespace CnD_Sound;

public class CnD_SoundJson
{
private static readonly HttpClient _httpClient = new HttpClient();
private static readonly HttpClient httpClient = new HttpClient();
private class PersonData
{
public int Id { get; set; }
public bool BoolValue { get; set; }
public DateTime Date { get; set; }
}
public static async Task SendToDiscordWebhookNormal(string webhookUrl, string message)
{
try
{
var payload = new { content = message };
var jsonPayload = Newtonsoft.Json.JsonConvert.SerializeObject(payload);
var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");

var response = await _httpClient.PostAsync(webhookUrl, content).ConfigureAwait(false);


}
catch
{
}
}

public static async Task SendToDiscordWebhookNameLink(string webhookUrl, string message, string steamUserId, string STEAMNAME)
{
try
{
string profileLink = GetSteamProfileLink(steamUserId);
int colorss = int.Parse(Configs.GetConfigData().Log_DiscordSideColor, System.Globalization.NumberStyles.HexNumber);
Color color = Color.FromArgb(colorss >> 16, (colorss >> 8) & 0xFF, colorss & 0xFF);
using (var httpClient = new HttpClient())
{
var embed = new
{
type = "rich",
title = STEAMNAME,
url = profileLink,
description = message,
color = color.ToArgb() & 0xFFFFFF
};

var payload = new
{
embeds = new[] { embed }
};

var jsonPayload = Newtonsoft.Json.JsonConvert.SerializeObject(payload);
var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(webhookUrl, content).ConfigureAwait(false);

}
}
catch
{
}
}
public static async Task SendToDiscordWebhookNameLinkWithPicture(string webhookUrl, string message, string steamUserId, string STEAMNAME)
{
try
{
string profileLink = GetSteamProfileLink(steamUserId);
string profilePictureUrl = await GetProfilePictureAsync(steamUserId, Configs.GetConfigData().Log_DiscordUsersWithNoAvatarImage);
int colorss = int.Parse(Configs.GetConfigData().Log_DiscordSideColor, System.Globalization.NumberStyles.HexNumber);
Color color = Color.FromArgb(colorss >> 16, (colorss >> 8) & 0xFF, colorss & 0xFF);
using (var httpClient = new HttpClient())
{
var embed = new
{
type = "rich",
description = message,
color = color.ToArgb() & 0xFFFFFF,
author = new
{
name = STEAMNAME,
url = profileLink,
icon_url = profilePictureUrl
}
};

var payload = new
{
embeds = new[] { embed }
};

var jsonPayload = Newtonsoft.Json.JsonConvert.SerializeObject(payload);
var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(webhookUrl, content).ConfigureAwait(false);
}
}
catch
{

}
}
public static async Task<string> GetProfilePictureAsync(string steamId64, string defaultImage)
{
try
{
string apiUrl = $"https://steamcommunity.com/profiles/{steamId64}/?xml=1";

HttpResponseMessage response = await httpClient.GetAsync(apiUrl);

if (response.IsSuccessStatusCode)
{
string xmlResponse = await response.Content.ReadAsStringAsync();
int startIndex = xmlResponse.IndexOf("<avatarFull><![CDATA[") + "<avatarFull><![CDATA[".Length;
int endIndex = xmlResponse.IndexOf("]]></avatarFull>", startIndex);

if (endIndex >= 0)
{
string profilePictureUrl = xmlResponse.Substring(startIndex, endIndex - startIndex);
return profilePictureUrl;
}
else
{
return defaultImage;
}
}
else
{
return null!;
}
}
catch
{
return null!;
}
}
public static string GetSteamProfileLink(string userId)
{
return $"https://steamcommunity.com/profiles/{userId}";
}

public static void SaveToJsonFile(int id, bool boolValue, DateTime date)
{
string cookiesFilePath = Configs.Shared.CookiesFolderPath!;
string Fpath = Path.Combine(cookiesFilePath,"../../plugins/CnD_Sound/Cookies/");
string Fpathc = Path.Combine(cookiesFilePath,"../../plugins/CnD_Sound/Cookies/CnD_Sound_Cookies.json");
try
{
if(!Directory.Exists(Fpath))
{
Directory.CreateDirectory(Fpath);
}

if (!File.Exists(Fpathc))
{
File.WriteAllText(Fpathc, "[]");
}

List<PersonData> allPersonsData;
string jsonData = File.ReadAllText(Fpathc);
allPersonsData = JsonConvert.DeserializeObject<List<PersonData>>(jsonData) ?? new List<PersonData>();

PersonData existingPerson = allPersonsData.Find(p => p.Id == id)!;

if (existingPerson != null)
{
existingPerson.BoolValue = boolValue;
existingPerson.Date = date;
}
else
{
PersonData newPerson = new PersonData { Id = id, BoolValue = boolValue, Date = date };
allPersonsData.Add(newPerson);
}
allPersonsData.RemoveAll(p => (DateTime.Now - p.Date).TotalDays > Configs.GetConfigData().RemovePlayerCookieOlderThanXDays);

string updatedJsonData = JsonConvert.SerializeObject(allPersonsData, Formatting.Indented);
try
{
File.WriteAllText(Fpathc, updatedJsonData);
}catch
{
}
}catch
{
}
}

public static bool RetrieveBoolValueById(int targetId)
{
string cookiesFilePath = Configs.Shared.CookiesFolderPath!;
string Fpath = Path.Combine(cookiesFilePath,"../../plugins/CnD_Sound/Cookies/");
string Fpathc = Path.Combine(cookiesFilePath,"../../plugins/CnD_Sound/Cookies/CnD_Sound_Cookies.json");
try
{
if (File.Exists(Fpathc))
{
string jsonData = File.ReadAllText(Fpathc);
List<PersonData> allPersonsData = JsonConvert.DeserializeObject<List<PersonData>>(jsonData) ?? new List<PersonData>();

PersonData targetPerson = allPersonsData.Find(p => p.Id == targetId)!;

if (targetPerson != null)
{
if (DateTime.Now - targetPerson.Date <= TimeSpan.FromDays(Configs.GetConfigData().RemovePlayerCookieOlderThanXDays))
{
return targetPerson.BoolValue;
}
else
{
allPersonsData.Remove(targetPerson);
string updatedJsonData = JsonConvert.SerializeObject(allPersonsData, Formatting.Indented);
try
{
File.WriteAllText(Fpathc, updatedJsonData);
}catch
{
}
}
}
}
return false;
}catch
{
return false;
}
}
}
Loading

0 comments on commit f5cb3b0

Please sign in to comment.