Skip to content

Commit

Permalink
optimization, add new api
Browse files Browse the repository at this point in the history
  • Loading branch information
samyycX committed Jul 4, 2024
1 parent ba6076f commit e8c40a3
Show file tree
Hide file tree
Showing 28 changed files with 237 additions and 834 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
obj
Main/obj
Shared/obj
output
24 changes: 0 additions & 24 deletions BuffInspector.csproj

This file was deleted.

111 changes: 46 additions & 65 deletions BuffInspector.cs → Main/BuffInspector.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,9 @@
using System.Collections;
using System.Reflection;
using System.Security.Cryptography;
using System.Timers;
using CounterStrikeSharp.API;
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Attributes.Registration;
using CounterStrikeSharp.API.Core.Commands;
using CounterStrikeSharp.API.Core.Plugin.Host;
using CounterStrikeSharp.API.Core.Capabilities;
using CounterStrikeSharp.API.Modules.Commands;
using CounterStrikeSharp.API.Modules.Entities.Constants;
using CounterStrikeSharp.API.Modules.Memory;
using CounterStrikeSharp.API.Modules.Memory.DynamicFunctions;
using Microsoft.Extensions.Localization;
using Newtonsoft.Json;

namespace BuffInspector;
Expand All @@ -20,17 +13,21 @@ public class Config : BasePluginConfig {
public bool EnableImagePreview {get; set;} = true;
public float ImagePreviewTime {get; set;} = 5f;
public bool EnableSticker {get; set;} = true;

public bool PureApiMode {get; set;} = false;
}
public partial class BuffInspector : BasePlugin, IPluginConfig<Config>
{


public override string ModuleName => "Buff Inspector";
public override string ModuleVersion => "3";
public override string ModuleVersion => "4";
public override string ModuleAuthor => "samyyc";
private DatabaseConnection Database;
public Config Config {get; set;}

public PluginCapability<IBuffApiService> BuffApiServiceCapability = new("buffinspector:service");

public static Dictionary<int,string> KnifeDefIndexToName { get; } = new Dictionary<int, string>
{
{ 500, "weapon_bayonet" },
Expand All @@ -55,17 +52,29 @@ public partial class BuffInspector : BasePlugin, IPluginConfig<Config>
{ 526, "weapon_knife_kukri" }
};


public Dictionary<ulong, string> CenterImages = new Dictionary<ulong, string>();
private List<PlayerSticker> TempStickers = new List<PlayerSticker>();
private MemoryFunctionVoid<nint, string, float> CAttributeList_SetOrAddAttributeValueByName = new(GameData.GetSignature("CAttributeList_SetOrAddAttributeValueByName"));
private MemoryFunctionVoid<nint, string, float>? CAttributeList_SetOrAddAttributeValueByName = null;

public static BuffInspector INSTANCE;

public static SkinInfoDisplayer SkinInfoDisplayer;

public void OnConfigParsed(Config config) {
Config = config;
}

public override void Load(bool hotReload)
{
INSTANCE = this;
SkinInfoDisplayer = new(Localizer);
Capabilities.RegisterPluginCapability(BuffApiServiceCapability, () => new BuffApiServiceImpl());
RegisterListener<Listeners.OnTick>(SkinInfoDisplayer.OnTick);
Localizer = base.Localizer;
if (Config.PureApiMode) {
Console.WriteLine("Buff Inspector is now loaded as pure api library.");
return;
}
CAttributeList_SetOrAddAttributeValueByName = new(GameData.GetSignature("CAttributeList_SetOrAddAttributeValueByName"));
var CS2WeaponPaintsConfigPath = Path.Join(ModuleDirectory, "../../configs/plugins/WeaponPaints/WeaponPaints.json");
if (!File.Exists(CS2WeaponPaintsConfigPath)) {
throw new FileNotFoundException($"Weapon Paints Config {CS2WeaponPaintsConfigPath} Not Found.");
Expand All @@ -77,28 +86,21 @@ public override void Load(bool hotReload)

Database = new DatabaseConnection(info);

RegisterListener<Listeners.OnTick>(OnTick);
RegisterListener<Listeners.OnEntityCreated>(OnEntityCreated);

this.AddCommand("css_buff", "css_buff [buff分享链接]", OnBuffCommand);

Console.WriteLine("Buff Inspector Loaded.");
}

public override void Unload(bool hotReload)
{
RemoveListener<Listeners.OnEntityCreated>(OnEntityCreated);
RemoveListener<Listeners.OnTick>(OnTick);
}

private void OnTick() {
if (!Config.EnableImagePreview) {
if (Config.PureApiMode) {
return;
}
foreach (var (steamid, imgurl) in CenterImages) {
var player = Utilities.GetPlayerFromSteamId(steamid);
if (player != null && imgurl != null && player.IsValid && player.Pawn.IsValid && player.PlayerPawn.IsValid) {
player.PrintToCenterHtml($"<img src=\"{imgurl}\" width=100 height=100></img>", 10);
}
}
RemoveListener<Listeners.OnEntityCreated>(OnEntityCreated);
RemoveListener<Listeners.OnTick>(SkinInfoDisplayer.OnTick);
RemoveCommand("css_buff", OnBuffCommand);
}

private float ViewAsFloat(uint value)
Expand All @@ -108,6 +110,9 @@ private float ViewAsFloat(uint value)
}

private void OnEntityCreated(CEntityInstance entity) {
if (Config.PureApiMode) {
return;
}
if (!entity.IsValid) {
return;
}
Expand Down Expand Up @@ -141,9 +146,10 @@ private void OnEntityCreated(CEntityInstance entity) {
});
}

[ConsoleCommand("css_buff")]
[CommandHelper(minArgs: 1, usage: "[buff分享链接]", whoCanExecute: CommandUsage.CLIENT_ONLY)]
public async void OnBuffCommand(CCSPlayerController player, CommandInfo commandInfo) {
public async void OnBuffCommand(CCSPlayerController? player, CommandInfo commandInfo) {
if (player == null) {
return;
}
var splited = commandInfo.GetCommandString.Split(" ");
splited = splited.Where(x => !string.IsNullOrEmpty(x)).ToArray();
if (splited.Length < 2) {
Expand All @@ -157,7 +163,7 @@ public async void OnBuffCommand(CCSPlayerController player, CommandInfo commandI

if (!Config.UseSync) {
var task = new Task(async() => {
SkinInfo? skinInfo = await scrapeUrl(url);
SkinInfo? skinInfo = await Scraper.scrapeUrl(url, Config.EnableSticker);

if (skinInfo == null) {
Server.NextFrame(() => player.PrintToChat(Localizer["failed"]));
Expand All @@ -178,30 +184,17 @@ public async void OnBuffCommand(CCSPlayerController player, CommandInfo commandI
if (skinInfo.Stickers.Count() > 0) {
TempStickers.Add(new( steamid, skinInfo.DefIndex, skinInfo.Stickers ));
}

await Server.NextFrameAsync(() => {
player.PrintToChat(Localizer["success"]);
player.PrintToChat(Localizer["hint.name", skinInfo.title]);
player.PrintToChat(Localizer["hint.seed", skinInfo.PaintSeed]);
player.PrintToChat(Localizer["hint.index", skinInfo.PaintIndex]);
player.PrintToChat(Localizer["hint.wear", skinInfo.PaintWear]);
foreach (var sticker in skinInfo.Stickers) {
player.PrintToChat(Localizer["hint.sticker", sticker.Slot, sticker.Name]);
}
player.PrintToChat(Localizer["hint.update"]);
if (CenterImages.ContainsKey(steamid)) {
CenterImages.Remove(steamid);
}
CenterImages.Add(steamid, skinInfo.img);
AddTimer(Config.ImagePreviewTime, () => {
CenterImages.Remove(steamid);
});

Server.NextFrame(() => {
SkinInfoDisplayer.ShowSkinInfoToPlayer(player, skinInfo, Config.EnableImagePreview, Config.ImagePreviewTime, false);
});



});
task.Start();
} else {
SkinInfo? skinInfo = scrapeUrl(url).Result;
SkinInfo? skinInfo = Scraper.scrapeUrl(url, Config.EnableSticker).Result;

if (skinInfo == null) {
player.PrintToChat(Localizer["failed"]);
Expand All @@ -223,24 +216,12 @@ await Server.NextFrameAsync(() => {
TempStickers.Add(new( steamid, skinInfo.DefIndex, skinInfo.Stickers ));
}

player.PrintToChat(Localizer["success"]);
player.PrintToChat(Localizer["hint.name", skinInfo.title]);
player.PrintToChat(Localizer["hint.seed", skinInfo.PaintSeed]);
player.PrintToChat(Localizer["hint.index", skinInfo.PaintIndex]);
player.PrintToChat(Localizer["hint.wear", skinInfo.PaintWear]);
foreach (var sticker in skinInfo.Stickers) {
player.PrintToChat(Localizer["hint.sticker", sticker.Slot, sticker.Name]);
}
if (CenterImages.ContainsKey(steamid)) {
CenterImages.Remove(steamid);
}
CenterImages.Add(steamid, skinInfo.img);
AddTimer(Config.ImagePreviewTime, () => {
CenterImages.Remove(steamid);
});
SkinInfoDisplayer.ShowSkinInfoToPlayer(player, skinInfo, Config.EnableImagePreview, Config.ImagePreviewTime, true);

player.ExecuteClientCommandFromServer("css_wp");
}

return;
}
}

Expand Down
37 changes: 37 additions & 0 deletions Main/BuffInspector.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<BaseOutputPath>..\output\</BaseOutputPath>
<OutputPath>$(BaseOutputPath)Release\plugins\BuffInspector</OutputPath>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="CounterStrikeSharp.API" Version="1.0.213">
<IncludeAssets>compile</IncludeAssets>
</PackageReference>
<PackageReference Include="Dapper" Version="2.1.44"/>
<PackageReference Include="HtmlAgilityPack" Version="1.11.60" />
<PackageReference Include="MySQLConnector" Version="2.3.6" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
<ItemGroup>
<LangFiles Include="lang/*.*" />
<Reference Include="BuffInspectorShared">
<HintPath>..\output\Release\shared\BuffInspectorShared\BuffInspectorShared.dll</HintPath>
</Reference>
</ItemGroup>

<Target Name="PostBuild" AfterTargets="Build">
<Copy SourceFiles="@(LangFiles)" DestinationFolder="$(OutputPath)\lang" />
<Copy SourceFiles="$(NuGetPackageRoot)\dapper\2.1.44\lib\net7.0\Dapper.dll" DestinationFolder="$(OutputPath)" />
<Copy SourceFiles="$(NuGetPackageRoot)\htmlagilitypack\1.11.60\lib\Net45\HtmlAgilityPack.dll" DestinationFolder="$(OutputPath)" />
<Copy SourceFiles="$(NuGetPackageRoot)\mysqlconnector\2.3.6\lib\net8.0\MySQLConnector.dll" DestinationFolder="$(OutputPath)" />
<Copy SourceFiles="$(NuGetPackageRoot)\newtonsoft.json\13.0.3\lib\net6.0\Newtonsoft.Json.dll" DestinationFolder="$(OutputPath)" />
<Delete Files="$(OutputPath)\BuffInspectorShared.dll" />
<Delete Files="$(OutputPath)\BuffInspectorShared.pdb" />
</Target>
</Project>
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
17 changes: 11 additions & 6 deletions Scraper.cs → Main/Scraper.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
using System.Text.RegularExpressions;
using HtmlAgilityPack;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace BuffInspector;

partial class BuffInspector {
public class Scraper {

private Dictionary<string, int> ItemNameToDefIndex = new Dictionary<string, int>() {
private static Dictionary<string, int> ItemNameToDefIndex = new Dictionary<string, int>() {
{ "沙漠之鹰", 1 },
{ "双持贝瑞塔", 2 },
{ "FN57", 3 },
Expand Down Expand Up @@ -76,7 +75,7 @@ partial class BuffInspector {
var result = Regex.Matches(input, "(\\d+)");
return result.First()?.Value;
}
private async Task<SkinInfo?> scrapeUrl(string url) {
public async static Task<SkinInfo?> scrapeUrl(string url, bool enableSticker) {
url = url.Replace("https://", "").Replace("http://", "");

if (!url.StartsWith("buff.163.com")) {
Expand Down Expand Up @@ -112,6 +111,10 @@ partial class BuffInspector {
if (title == null) {
return null;
}
string? nametag = htmlDoc.DocumentNode.SelectSingleNode("//p[@class='name_tag']")?.InnerText;
if (nametag != null) {
nametag = Regex.Matches(nametag, @"(?<=“)(.*)(?=”)").FirstOrDefault()?.Value;
}
var img = htmlDoc.DocumentNode.SelectSingleNode("//img")?.GetAttributeValue("src", "");
var informations = htmlDoc.DocumentNode.SelectNodes("//div[@class='info-card'][1]/p");
// informations为Null则该链接不为枪械、刀具或手套皮肤
Expand Down Expand Up @@ -141,13 +144,13 @@ partial class BuffInspector {
int IntPaintIndex = int.Parse(paintIndex);
float FloatPaintWear = float.Parse(paintWear);

skinInfo = new SkinInfo(title, img, DefIndex, IntPaintIndex, IntPaintSeed, FloatPaintWear);
skinInfo = new SkinInfo(title, img, nametag, DefIndex, IntPaintIndex, IntPaintSeed, FloatPaintWear);
} catch (Exception _) {
Console.WriteLine("Error when parsing: "+url);
return null;
}

if (!Config.EnableSticker) {
if (!enableSticker) {
return skinInfo;
}

Expand All @@ -169,6 +172,8 @@ partial class BuffInspector {
}
}

skinInfo.Stickers = skinInfo.Stickers.OrderBy((sticker) => sticker.Slot).ToList();

return skinInfo;

}
Expand Down
Loading

0 comments on commit e8c40a3

Please sign in to comment.