Skip to content
Permalink
Browse files

Eliminate a bunch of redundant string downloading/parsing code (ipnp …

…and geoip now share majority of code)
  • Loading branch information...
UnknownShadow200 committed Jul 3, 2018
1 parent 090f54a commit 3072e0c365d93d27e1d209104a9aa1ece4d73994
Showing with 69 additions and 129 deletions.
  1. +24 −39 fCraft/Commands/InfoCommands.cs
  2. +26 −1 fCraft/Network/HttpUtil.cs
  3. +9 −27 fCraft/Player/Player.cs
  4. +3 −5 fCraft/Player/PlayerInfo.cs
  5. +7 −57 fCraft/System/Server.cs
@@ -1786,12 +1786,19 @@ static void EmotesHandler(Player player, CommandReader cmd)
} else {
info = FindPlayerInfo(player, cmd);
}

if (info == null) return;
if (info.GeoIP != info.LastIP.ToString()) {
GetGeoip(info);
GetGeoipInfo(info);
PrintGeoIpInfo(player, info);
}

static void PrintGeoIpInfo(Player player, PlayerInfo info) {
if (info.Name != null) {
player.Message( "Geo Info about: {0}&S ({1})", info.ClassyName, info.GeoIP ?? "N/A" );
} else {
player.Message( "Geo Info about: &f{0}", info.GeoIP ?? "N/A" );
}

player.Message( "Geo Info about: {0}&S ({1})", info.ClassyName, info.GeoIP ?? "N/A" );

player.Message(" Country: &f{1}&S ({0})", info.CountryCode ?? "N/A", info.CountryName ?? "N/A");
player.Message(" Continent: &f{0}", info.Continent ?? "N/A");
player.Message(" Subdivisions: &f{0}", info.Subdivision);
@@ -1823,45 +1830,25 @@ static void EmotesHandler(Player player, CommandReader cmd)
player.Message("Info: Invalid IP range format. Use CIDR notation.");
return;
}
JsonObject result = null;
try {
result = JsonObject.Parse(Server.downloadDatastring("http://geoip.pw/api/" + ip));
if (result.Get("message") != null) {
player.Message("No information found!");
return;
}
player.Message("Geo Info about: &f{0}", result.Get("ip") ?? "N/A");
player.Message(" Country: &f{0}&S ({1})", result.Get("country") ?? "N/A", result.Get("country_abbr") ?? "N/A");
player.Message(" Continent: &f{0}", result.Get("continent") ?? "N/A");
player.Message(" Subdivisions: &f{0}", nan.Replace(result.Get("subdivision"), "").Split(',').JoinToString(", "));
player.Message(" Latitude: &f{0}", result.Get("latitude") ?? "N/A");
player.Message(" Longitude: &f{0}", result.Get("longitude") ?? "N/A");
player.Message(" Timezone: &f{0}", result.Get("timezone") ?? "N/A");
byte acc;
byte.TryParse(result.Get("accuracy"), out acc);
player.Message(" Hostname: &f{0}", result.Get("host") ?? "N/A");
player.Message(" Accuracy: &f{0}", acc);
player.Message("Geoip information by: &9http://geoip.pw/");

} catch (Exception ex) {
Logger.Log(LogType.Warning, "Could not access GeoIP website (Ex: " + ex + ")");
}

PlayerInfo tmp = new PlayerInfo(0); tmp.LastIP = ip;
GetGeoipInfo(tmp);
PrintGeoIpInfo(player, tmp);
}

public static void GetGeoip(PlayerInfo info) {
public static void GetGeoipInfo(PlayerInfo info) {
string ip = info.LastIP.ToString();
if (IPAddress.Parse(ip).IsLocal() && Server.ExternalIP != null) {
ip = Server.ExternalIP.ToString();
}
if (ip == info.GeoIP) {
return;
}
if (ip == info.GeoIP) return;

JsonObject result = null;
try {
result = JsonObject.Parse(Server.downloadDatastring("http://geoip.pw/api/" + ip));
if (result.Get("message") != null) {
return;
}
string url = "http://geoip.pw/api/" + ip;
result = JsonObject.Parse(HttpUtil.DownloadString(url, "get GeoIP info", 10000));
if (result.Get("message") != null) return;

info.CountryName = result.Get("country") ?? "N/A";
info.CountryCode = result.Get("country_abbr") ?? "N/A";
info.Continent = result.Get("continent") ?? "N/A";
@@ -1871,12 +1858,9 @@ static void EmotesHandler(Player player, CommandReader cmd)
info.TimeZone = result.Get("timezone") ?? "N/A";
info.Hostname = result.Get("host") ?? "N/A";
info.GeoIP = result.Get("ip") ?? "N/A";
return;

} catch (Exception ex) {
Logger.Log(LogType.Warning, "Could not access GeoIP website (Ex: " + ex + ")");
Logger.Log(LogType.Debug, ex.ToString());
return;
}
}

@@ -1927,7 +1911,8 @@ static void EmotesHandler(Player player, CommandReader cmd)
break;
}

string data = Server.downloadDatastring("http://www.classicube.net/api/" + value);
string url = "http://www.classicube.net/api/" + value;
string data = HttpUtil.DownloadString(url, "get user info", 10000);
if (string.IsNullOrEmpty(data) || !data.Contains("username")) {
player.Message("Player not found!");
return;
@@ -1,8 +1,10 @@
// Part of fCraft | Copyright 2009-2015 Matvei Stefarov <me@matvei.org> | BSD-3 | See LICENSE.txt //Copyright (c) 2011-2013 Jon Baker, Glenn Marien and Lao Tszy <Jonty800@gmail.com> //Copyright (c) <2012-2014> <LeChosenOne, DingusBungus> | ProCraft Copyright 2014-2018 Joseph Beauvais <123DMWM@gmail.com>
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Cache;
using System.Net.Sockets;
using JetBrains.Annotations;

@@ -68,7 +70,7 @@ public static class HttpUtil {
}
}
return req;
}
}

public static WebClient CreateWebClient(TimeSpan timeout) {
return new CustomWebClient(timeout);
@@ -82,5 +84,28 @@ class CustomWebClient : WebClient {
return CreateRequest(address, timeout);
}
}


[CanBeNull]
public static string DownloadString(string url, string action, int timeoutMS) {
HttpWebRequest request = CreateRequest(new Uri(url), TimeSpan.FromMilliseconds(timeoutMS));
request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);

try {
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
if (response.StatusCode != HttpStatusCode.OK) {
Logger.Log(LogType.Warning, "Could not {1}: {0}", response.StatusDescription, action);
return null;
}

using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
return reader.ReadToEnd();
}
}
} catch (WebException ex) {
Logger.Log(LogType.Warning, "Could not {1}: {0}", ex, action);
return null;
}
}
}
}
@@ -2007,7 +2007,7 @@ public bool StopPossessing([NotNull]Player target)

#region Static Utilities

static readonly Uri PaidCheckUri = new Uri( "http://www.minecraft.net/haspaid.jsp?user=" );
const string paidCheckUri = "http://www.minecraft.net/haspaid.jsp?user=";
const int PaidCheckTimeout = 5000;


@@ -2016,32 +2016,14 @@ public bool StopPossessing([NotNull]Player target)
public static AccountType CheckPaidStatus( [NotNull] string name ) {
if( name == null ) throw new ArgumentNullException( "name" );

Uri uri = new Uri( PaidCheckUri + Uri.EscapeDataString( name ) );
HttpWebRequest request = HttpUtil.CreateRequest( uri, TimeSpan.FromMilliseconds( PaidCheckTimeout ) );
request.CachePolicy = new RequestCachePolicy( RequestCacheLevel.NoCacheNoStore );

try {
using( WebResponse response = request.GetResponse() ) {
using( StreamReader responseReader = new StreamReader( response.GetResponseStream() ) ) {
string paidStatusString = responseReader.ReadToEnd();
bool isPaid;
if( Boolean.TryParse( paidStatusString, out isPaid ) ) {
if( isPaid ) {
return AccountType.Paid;
} else {
return AccountType.Free;
}
} else {
return AccountType.Unknown;
}
}
}
} catch( WebException ex ) {
Logger.Log( LogType.Warning,
"Could not check paid status of player {0}: {1}",
name, ex.Message );
return AccountType.Unknown;
}
string uri = paidCheckUri + Uri.EscapeDataString( name );
string data = HttpUtil.DownloadString( uri, "check paid status", PaidCheckTimeout );

bool isPaid;
if( data != null && Boolean.TryParse( data, out isPaid ) ) {
return isPaid ? AccountType.Paid : AccountType.Free;
}
return AccountType.Unknown;
}

static readonly Regex
@@ -117,7 +117,7 @@ public sealed partial class PlayerInfo : IClassy {

public void GeoipLoginCallback( SchedulerTask task ) {
PlayerInfo info = (PlayerInfo)task.UserState;
InfoCommands.GetGeoip(info);
InfoCommands.GetGeoipInfo(info);
DisplayGeoIp(true);
}

@@ -460,8 +460,6 @@ public string BlocksDrawnString
public string Longitude;
/// <summary> List of subdivisions (City, State, etc) sorting by accuracy from left to right. </summary>
public string Subdivision = "NA";
/// <summary> Players geoip accuracy</summary>
public byte Accuracy = 0;
/// <summary> Players hostname</summary>
public string Hostname;
/// <summary> Players continent</summary>
@@ -757,7 +755,7 @@ public PlayerInfo( [NotNull] string name, [NotNull] IPAddress lastIP, [NotNull]
if (count > 81) info.skinName = PlayerDB.Unescape(fields[81]);

if (count > 82) info.Subdivision = PlayerDB.Unescape(fields[82]);
if (count > 83) byte.TryParse(fields[83], out info.Accuracy);
//if (count > 83) byte.TryParse(fields[83], out info.Accuracy);
if (count > 84) info.Hostname = fields[84];
if (count > 85) info.Continent = fields[85];

@@ -1276,7 +1274,7 @@ public PlayerInfo( [NotNull] string name, [NotNull] IPAddress lastIP, [NotNull]
sb.Append(',');
sb.AppendEscaped(Subdivision); // 82
sb.Append(',');
sb.Append(Accuracy); // 83
//sb.Append(Accuracy); // 83 unused
sb.Append(',');
sb.Append(Hostname); // 84
sb.Append(',');
@@ -1113,68 +1113,18 @@ static void CheckIdles(SchedulerTask task)
}


static readonly Uri IPCheckUri = new Uri("http://www.classicube.net/api/myip/");
const string ipCheckUri = "http://www.classicube.net/api/myip/";
const int IPCheckTimeout = 20000;


/// <summary> Checks server's external IP, as reported by fCraft.net. </summary>
[CanBeNull]
static IPAddress CheckExternalIP()
{
HttpWebRequest request = HttpUtil.CreateRequest(IPCheckUri,
TimeSpan.FromMilliseconds(IPCheckTimeout));
request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);

try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
Logger.Log(LogType.Warning, "Could not check external IP: {0}",
response.StatusDescription);
return null;
}

// ReSharper disable AssignNullToNotNullAttribute
using (StreamReader responseReader = new StreamReader(response.GetResponseStream()))
{
// ReSharper restore AssignNullToNotNullAttribute
string responseString = responseReader.ReadToEnd();
IPAddress result;

if (IPAddress.TryParse(responseString, out result)) return result;
return null;
}
}
}
catch (WebException ex)
{
Logger.Log(LogType.Warning, "Could not check external IP: {0}", ex);
return null;
}
}

/// <summary> Safely downloads data. </summary>
[CanBeNull]
public static string downloadDatastring(string url) {
HttpWebRequest request = HttpUtil.CreateRequest(new Uri(url), TimeSpan.FromSeconds(10));
request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);

try {
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
if (response.StatusCode != HttpStatusCode.OK) {
Logger.Log(LogType.Warning, "Could not download data: {0}", response.StatusDescription);
return null;
}
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
return reader.ReadToEnd();
}
}
} catch (WebException ex) {
Logger.Log(LogType.Warning, "Could not download data: {0}", ex);
return null;
}
static IPAddress CheckExternalIP() {
string data = HttpUtil.DownloadString(ipCheckUri, "check external IP", IPCheckTimeout);
IPAddress ip = null;

if (data == null || !IPAddress.TryParse(data, out ip)) return null;
return ip;
}

// Callback for setting the local IP binding. Implements System.Net.BindIPEndPoint delegate.

0 comments on commit 3072e0c

Please sign in to comment.
You can’t perform that action at this time.