Skip to content

Commit 1bb858e

Browse files
committed
Switch to HttpClient and run the web request on the thread pool
1 parent cc6b417 commit 1bb858e

File tree

6 files changed

+76
-69
lines changed

6 files changed

+76
-69
lines changed

Feli.OpenMod.JoinLeaveMessages/Events/EventListener.cs

Lines changed: 35 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
1-
using Feli.OpenMod.JoinLeaveMessages.Helpers;
1+
using Cysharp.Threading.Tasks;
2+
using Feli.OpenMod.JoinLeaveMessages.Helpers;
23
using Microsoft.Extensions.Configuration;
34
using Microsoft.Extensions.Localization;
5+
using Microsoft.Extensions.Logging;
46
using OpenMod.API.Eventing;
57
using OpenMod.Unturned.Users.Events;
68
using SDG.Unturned;
9+
using System;
710
using System.Threading.Tasks;
811
using UnityEngine;
912

@@ -14,42 +17,59 @@ public class EventListener : IEventListener<UnturnedUserConnectedEvent>, IEventL
1417
private readonly IConfiguration _configuration;
1518
private readonly IStringLocalizer _stringLocalizer;
1619
private readonly IpGeolocationHelper _geolocator;
20+
private readonly ILogger<EventListener> _logger;
1721

1822
public EventListener(
1923
IConfiguration configuration,
2024
IStringLocalizer stringLocalizer,
21-
IpGeolocationHelper geolocator)
25+
IpGeolocationHelper geolocator,
26+
ILogger<EventListener> logger)
2227
{
2328
_configuration = configuration;
2429
_stringLocalizer = stringLocalizer;
2530
_geolocator = geolocator;
31+
_logger = logger;
2632
}
2733

28-
public async Task HandleEventAsync(object sender, UnturnedUserConnectedEvent @event)
34+
public Task HandleEventAsync(object sender, UnturnedUserConnectedEvent @event)
2935
{
30-
if (!_configuration.GetSection("joinMessage:enabled").Get<bool>())
31-
return;
36+
if (!_configuration.GetSection("joinMessage:enabled").Get<bool>())
37+
return Task.CompletedTask;
3238

33-
var country = string.Empty;
39+
UniTask.RunOnThreadPool(async () =>
40+
{
41+
try
42+
{
43+
var country = string.Empty;
3444

35-
if (_configuration.GetSection("joinMessage:showCountry").Get<bool>())
36-
country = await _geolocator.GetCountryFromIpAsync(@event.User.Player.Address.MapToIPv4().ToString());
45+
if (_configuration.GetSection("joinMessage:showCountry").Get<bool>())
46+
country = await _geolocator.GetCountryFromIpAsync(@event.User.Player.Address.MapToIPv4().ToString());
3747

38-
var message = _stringLocalizer["join", new
39-
{
40-
User = @event.User,
41-
Country = country
42-
}];
48+
var message = _stringLocalizer["join", new
49+
{
50+
User = @event.User,
51+
Country = country
52+
}];
4353

44-
ChatManager.serverSendMessage(message, Color.green, mode: EChatMode.GLOBAL, iconURL: _configuration["joinMessage:customIconUrl"], useRichTextFormatting: true);
54+
await UniTask.SwitchToMainThread();
55+
56+
ChatManager.serverSendMessage(message, Color.green, mode: EChatMode.GLOBAL, iconURL: _configuration["joinMessage:customIconUrl"], useRichTextFormatting: true);
57+
}
58+
catch (Exception ex)
59+
{
60+
_logger.LogError(ex, "There was an error during the player join");
61+
}
62+
});
63+
64+
return Task.CompletedTask;
4565
}
4666

4767
public Task HandleEventAsync(object sender, UnturnedUserDisconnectedEvent @event)
4868
{
4969
if (!_configuration.GetSection("leaveMessage:enabled").Get<bool>())
5070
return Task.CompletedTask;
5171

52-
var message = _stringLocalizer["leave", new
72+
var message = _stringLocalizer["leave", new
5373
{
5474
User = @event.User
5575
}];

Feli.OpenMod.JoinLeaveMessages/Feli.OpenMod.JoinLeaveMessages.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
<PackageDescription>Broadcast users connections and disconnections to the global chat</PackageDescription>
1212
<PackageLicenseExpression>Apache-2.0</PackageLicenseExpression>
1313
<PackageAuthors>FPlugins;Felixer001</PackageAuthors>
14-
<PackageOwners>FPlugins</PackageOwners>
14+
<PackageOwners>FPlugins;Felixer001</PackageOwners>
1515
<PackageTags>openmod openmod-plugin unturned</PackageTags>
1616
<Version>0.0.0</Version>
1717
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
Lines changed: 5 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
using Microsoft.Extensions.Logging;
22
using Newtonsoft.Json.Linq;
3-
using System.IO;
4-
using System.Net;
3+
using System.Net.Http;
54
using System.Threading.Tasks;
65

76
namespace Feli.OpenMod.JoinLeaveMessages.Helpers
@@ -17,20 +16,18 @@ public IpGeolocationHelper(ILogger<IpGeolocationHelper> logger)
1716

1817
public async Task<string> GetCountryFromIpAsync(string address)
1918
{
20-
var request = CreateRequest(address);
19+
using var client = new HttpClient();
20+
var response = await client.GetAsync($"http://ip-api.com/json/{address}?fields=status,message,country");
2121

22-
var response = (HttpWebResponse)await request.GetResponseAsync();
23-
24-
if (response.StatusCode != HttpStatusCode.OK)
22+
if (!response.IsSuccessStatusCode)
2523
{
2624
_logger.LogError("HTTP Error: {StatusCode}, {StatusCodeString}", (int)response.StatusCode, response.StatusCode.ToString());
2725
return string.Empty;
2826
}
2927

30-
var content = await ReadContentAsync(response.GetResponseStream());
28+
var content = await response.Content.ReadAsStringAsync();
3129

3230
var @object = JObject.Parse(content);
33-
3431
if (@object["status"].ToString() == "fail")
3532
{
3633
_logger.LogError("Failed to get the ip location. Error: {message}", @object["message"].ToString());
@@ -39,17 +36,5 @@ public async Task<string> GetCountryFromIpAsync(string address)
3936

4037
return @object["country"].ToString();
4138
}
42-
43-
internal WebRequest CreateRequest(string address)
44-
{
45-
return WebRequest.Create($"http://ip-api.com/json/{address}?fields=status,message,country");
46-
}
47-
48-
internal async Task<string> ReadContentAsync(Stream stream)
49-
{
50-
using var reader = new StreamReader(stream);
51-
52-
return await reader.ReadToEndAsync();
53-
}
5439
}
5540
}

Feli.RocketMod.JoinLeaveMessages/Feli.RocketMod.JoinLeaveMessages.csproj

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
<PropertyGroup>
44
<TargetFramework>net461</TargetFramework>
55
<LangVersion>latest</LangVersion>
6-
<Version>1.0.1</Version>
7-
<AssemblyVersion>1.0.1</AssemblyVersion>
6+
<Version>1.0.3</Version>
7+
<AssemblyVersion>1.0.3</AssemblyVersion>
88
</PropertyGroup>
99

1010
<ItemGroup>
Lines changed: 8 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,33 @@
11
using Newtonsoft.Json.Linq;
22
using Rocket.Core.Logging;
3-
using System.IO;
4-
using System.Net;
3+
using System.Net.Http;
4+
using System.Threading.Tasks;
55

66
namespace Feli.RocketMod.JoinLeaveMessages.Helpers
77
{
88
public class IpGeolocationHelper
99
{
10-
public static string GetCountryFromIp(string address)
10+
public static async Task<string> GetCountryFromIp(string address)
1111
{
12-
var request = CreateRequest(address);
12+
using var client = new HttpClient();
13+
var response = await client.GetAsync($"http://ip-api.com/json/{address}?fields=status,message,country");
1314

14-
var response = (HttpWebResponse)request.GetResponse();
15-
16-
if (response.StatusCode != HttpStatusCode.OK)
15+
if (!response.IsSuccessStatusCode)
1716
{
1817
Logger.LogError($"HTTP Error: {(int)response.StatusCode}, {response.StatusCode}");
1918
return string.Empty;
2019
}
2120

22-
var content = ReadContent(response.GetResponseStream());
21+
var content = await response.Content.ReadAsStringAsync();
2322

2423
var @object = JObject.Parse(content);
25-
26-
if(@object["status"].ToString() == "fail")
24+
if (@object["status"].ToString() == "fail")
2725
{
2826
Logger.LogError($"Failed to get the ip location. Error: {@object["message"]}");
2927
return string.Empty;
3028
}
3129

3230
return @object["country"].ToString();
3331
}
34-
35-
internal static WebRequest CreateRequest(string address)
36-
{
37-
return WebRequest.Create($"http://ip-api.com/json/{address}?fields=status,message,country");
38-
}
39-
40-
internal static string ReadContent(Stream stream)
41-
{
42-
using var reader = new StreamReader(stream);
43-
44-
return reader.ReadToEnd();
45-
}
4632
}
4733
}

Feli.RocketMod.JoinLeaveMessages/Plugin.cs

Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
using Feli.RocketMod.JoinLeaveMessages.Helpers;
22
using Rocket.API.Collections;
33
using Rocket.Core.Plugins;
4+
using Rocket.Core.Utils;
45
using Rocket.Unturned;
56
using Rocket.Unturned.Player;
67
using SDG.Unturned;
8+
using System;
9+
using System.Threading.Tasks;
710
using UnityEngine;
811
using Logger = Rocket.Core.Logging.Logger;
912

@@ -19,10 +22,10 @@ public class Plugin : RocketPlugin<Configuration>
1922

2023
protected override void Load()
2124
{
22-
if(Configuration.Instance.JoinMessages)
25+
if (Configuration.Instance.JoinMessages)
2326
U.Events.OnPlayerConnected += OnPlayerConnected;
2427

25-
if(Configuration.Instance.LeaveMessages)
28+
if (Configuration.Instance.LeaveMessages)
2629
U.Events.OnPlayerDisconnected += OnPlayerDisconnected;
2730

2831
Logger.Log($"JoinLeaveMessages plugin v1.0.2 loaded !");
@@ -31,15 +34,28 @@ protected override void Load()
3134

3235
private void OnPlayerConnected(UnturnedPlayer player)
3336
{
34-
var country = string.Empty;
37+
Task.Run(async () =>
38+
{
39+
try
40+
{
41+
var country = string.Empty;
3542

36-
if (Configuration.Instance.ShowCountry)
37-
country = IpGeolocationHelper.GetCountryFromIp(player.IP);
38-
39-
var message = Translate("Join", player.DisplayName, country);
43+
if (Configuration.Instance.ShowCountry)
44+
country = await IpGeolocationHelper.GetCountryFromIp(player.IP);
4045

41-
Logger.Log(message);
42-
ChatManager.serverSendMessage(message, Color.green, mode: EChatMode.GLOBAL, iconURL: Configuration.Instance.CustomImageUrl, useRichTextFormatting: true);
46+
var message = Translate("Join", player.DisplayName, country);
47+
48+
TaskDispatcher.QueueOnMainThread(() =>
49+
{
50+
Logger.Log(message);
51+
ChatManager.serverSendMessage(message, Color.green, mode: EChatMode.GLOBAL, iconURL: Configuration.Instance.CustomImageUrl, useRichTextFormatting: true);
52+
});
53+
}
54+
catch (Exception ex)
55+
{
56+
Logger.LogException(ex, "There was an error during the player join");
57+
}
58+
});
4359
}
4460

4561
private void OnPlayerDisconnected(UnturnedPlayer player)

0 commit comments

Comments
 (0)