Skip to content

Commit

Permalink
Switch to HttpClient and run the web request on the thread pool
Browse files Browse the repository at this point in the history
  • Loading branch information
negrifelipe committed Aug 6, 2022
1 parent cc6b417 commit 1bb858e
Show file tree
Hide file tree
Showing 6 changed files with 76 additions and 69 deletions.
50 changes: 35 additions & 15 deletions Feli.OpenMod.JoinLeaveMessages/Events/EventListener.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
using Feli.OpenMod.JoinLeaveMessages.Helpers;
using Cysharp.Threading.Tasks;
using Feli.OpenMod.JoinLeaveMessages.Helpers;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using OpenMod.API.Eventing;
using OpenMod.Unturned.Users.Events;
using SDG.Unturned;
using System;
using System.Threading.Tasks;
using UnityEngine;

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

public EventListener(
IConfiguration configuration,
IStringLocalizer stringLocalizer,
IpGeolocationHelper geolocator)
IpGeolocationHelper geolocator,
ILogger<EventListener> logger)
{
_configuration = configuration;
_stringLocalizer = stringLocalizer;
_geolocator = geolocator;
_logger = logger;
}

public async Task HandleEventAsync(object sender, UnturnedUserConnectedEvent @event)
public Task HandleEventAsync(object sender, UnturnedUserConnectedEvent @event)
{
if (!_configuration.GetSection("joinMessage:enabled").Get<bool>())
return;
if (!_configuration.GetSection("joinMessage:enabled").Get<bool>())
return Task.CompletedTask;

var country = string.Empty;
UniTask.RunOnThreadPool(async () =>
{
try
{
var country = string.Empty;
if (_configuration.GetSection("joinMessage:showCountry").Get<bool>())
country = await _geolocator.GetCountryFromIpAsync(@event.User.Player.Address.MapToIPv4().ToString());
if (_configuration.GetSection("joinMessage:showCountry").Get<bool>())
country = await _geolocator.GetCountryFromIpAsync(@event.User.Player.Address.MapToIPv4().ToString());
var message = _stringLocalizer["join", new
{
User = @event.User,
Country = country
}];
var message = _stringLocalizer["join", new
{
User = @event.User,
Country = country
}];
ChatManager.serverSendMessage(message, Color.green, mode: EChatMode.GLOBAL, iconURL: _configuration["joinMessage:customIconUrl"], useRichTextFormatting: true);
await UniTask.SwitchToMainThread();
ChatManager.serverSendMessage(message, Color.green, mode: EChatMode.GLOBAL, iconURL: _configuration["joinMessage:customIconUrl"], useRichTextFormatting: true);
}
catch (Exception ex)
{
_logger.LogError(ex, "There was an error during the player join");
}
});

return Task.CompletedTask;
}

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

var message = _stringLocalizer["leave", new
var message = _stringLocalizer["leave", new
{
User = @event.User
}];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
<PackageDescription>Broadcast users connections and disconnections to the global chat</PackageDescription>
<PackageLicenseExpression>Apache-2.0</PackageLicenseExpression>
<PackageAuthors>FPlugins;Felixer001</PackageAuthors>
<PackageOwners>FPlugins</PackageOwners>
<PackageOwners>FPlugins;Felixer001</PackageOwners>
<PackageTags>openmod openmod-plugin unturned</PackageTags>
<Version>0.0.0</Version>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
Expand Down
25 changes: 5 additions & 20 deletions Feli.OpenMod.JoinLeaveMessages/Helpers/IpGeolocationHelper.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

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

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

var response = (HttpWebResponse)await request.GetResponseAsync();

if (response.StatusCode != HttpStatusCode.OK)
if (!response.IsSuccessStatusCode)
{
_logger.LogError("HTTP Error: {StatusCode}, {StatusCodeString}", (int)response.StatusCode, response.StatusCode.ToString());
return string.Empty;
}

var content = await ReadContentAsync(response.GetResponseStream());
var content = await response.Content.ReadAsStringAsync();

var @object = JObject.Parse(content);

if (@object["status"].ToString() == "fail")
{
_logger.LogError("Failed to get the ip location. Error: {message}", @object["message"].ToString());
Expand All @@ -39,17 +36,5 @@ public async Task<string> GetCountryFromIpAsync(string address)

return @object["country"].ToString();
}

internal WebRequest CreateRequest(string address)
{
return WebRequest.Create($"http://ip-api.com/json/{address}?fields=status,message,country");
}

internal async Task<string> ReadContentAsync(Stream stream)
{
using var reader = new StreamReader(stream);

return await reader.ReadToEndAsync();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
<PropertyGroup>
<TargetFramework>net461</TargetFramework>
<LangVersion>latest</LangVersion>
<Version>1.0.1</Version>
<AssemblyVersion>1.0.1</AssemblyVersion>
<Version>1.0.3</Version>
<AssemblyVersion>1.0.3</AssemblyVersion>
</PropertyGroup>

<ItemGroup>
Expand Down
30 changes: 8 additions & 22 deletions Feli.RocketMod.JoinLeaveMessages/Helpers/IpGeolocationHelper.cs
Original file line number Diff line number Diff line change
@@ -1,47 +1,33 @@
using Newtonsoft.Json.Linq;
using Rocket.Core.Logging;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

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

var response = (HttpWebResponse)request.GetResponse();

if (response.StatusCode != HttpStatusCode.OK)
if (!response.IsSuccessStatusCode)
{
Logger.LogError($"HTTP Error: {(int)response.StatusCode}, {response.StatusCode}");
return string.Empty;
}

var content = ReadContent(response.GetResponseStream());
var content = await response.Content.ReadAsStringAsync();

var @object = JObject.Parse(content);

if(@object["status"].ToString() == "fail")
if (@object["status"].ToString() == "fail")
{
Logger.LogError($"Failed to get the ip location. Error: {@object["message"]}");
return string.Empty;
}

return @object["country"].ToString();
}

internal static WebRequest CreateRequest(string address)
{
return WebRequest.Create($"http://ip-api.com/json/{address}?fields=status,message,country");
}

internal static string ReadContent(Stream stream)
{
using var reader = new StreamReader(stream);

return reader.ReadToEnd();
}
}
}
34 changes: 25 additions & 9 deletions Feli.RocketMod.JoinLeaveMessages/Plugin.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
using Feli.RocketMod.JoinLeaveMessages.Helpers;
using Rocket.API.Collections;
using Rocket.Core.Plugins;
using Rocket.Core.Utils;
using Rocket.Unturned;
using Rocket.Unturned.Player;
using SDG.Unturned;
using System;
using System.Threading.Tasks;
using UnityEngine;
using Logger = Rocket.Core.Logging.Logger;

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

protected override void Load()
{
if(Configuration.Instance.JoinMessages)
if (Configuration.Instance.JoinMessages)
U.Events.OnPlayerConnected += OnPlayerConnected;

if(Configuration.Instance.LeaveMessages)
if (Configuration.Instance.LeaveMessages)
U.Events.OnPlayerDisconnected += OnPlayerDisconnected;

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

private void OnPlayerConnected(UnturnedPlayer player)
{
var country = string.Empty;
Task.Run(async () =>
{
try
{
var country = string.Empty;
if (Configuration.Instance.ShowCountry)
country = IpGeolocationHelper.GetCountryFromIp(player.IP);

var message = Translate("Join", player.DisplayName, country);
if (Configuration.Instance.ShowCountry)
country = await IpGeolocationHelper.GetCountryFromIp(player.IP);
Logger.Log(message);
ChatManager.serverSendMessage(message, Color.green, mode: EChatMode.GLOBAL, iconURL: Configuration.Instance.CustomImageUrl, useRichTextFormatting: true);
var message = Translate("Join", player.DisplayName, country);
TaskDispatcher.QueueOnMainThread(() =>
{
Logger.Log(message);
ChatManager.serverSendMessage(message, Color.green, mode: EChatMode.GLOBAL, iconURL: Configuration.Instance.CustomImageUrl, useRichTextFormatting: true);
});
}
catch (Exception ex)
{
Logger.LogException(ex, "There was an error during the player join");
}
});
}

private void OnPlayerDisconnected(UnturnedPlayer player)
Expand Down

0 comments on commit 1bb858e

Please sign in to comment.