Skip to content

Commit 3072e0c

Browse files
Eliminate a bunch of redundant string downloading/parsing code (ipnp and geoip now share majority of code)
1 parent 090f54a commit 3072e0c

File tree

5 files changed

+69
-129
lines changed

5 files changed

+69
-129
lines changed

fCraft/Commands/InfoCommands.cs

Lines changed: 24 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1786,12 +1786,19 @@ static void IPInfoHandler( Player player, CommandReader cmd ) {
17861786
} else {
17871787
info = FindPlayerInfo(player, cmd);
17881788
}
1789+
17891790
if (info == null) return;
1790-
if (info.GeoIP != info.LastIP.ToString()) {
1791-
GetGeoip(info);
1791+
GetGeoipInfo(info);
1792+
PrintGeoIpInfo(player, info);
1793+
}
1794+
1795+
static void PrintGeoIpInfo(Player player, PlayerInfo info) {
1796+
if (info.Name != null) {
1797+
player.Message( "Geo Info about: {0}&S ({1})", info.ClassyName, info.GeoIP ?? "N/A" );
1798+
} else {
1799+
player.Message( "Geo Info about: &f{0}", info.GeoIP ?? "N/A" );
17921800
}
1793-
1794-
player.Message( "Geo Info about: {0}&S ({1})", info.ClassyName, info.GeoIP ?? "N/A" );
1801+
17951802
player.Message(" Country: &f{1}&S ({0})", info.CountryCode ?? "N/A", info.CountryName ?? "N/A");
17961803
player.Message(" Continent: &f{0}", info.Continent ?? "N/A");
17971804
player.Message(" Subdivisions: &f{0}", info.Subdivision);
@@ -1823,45 +1830,25 @@ private static void IPNPInfoHandler(Player player, CommandReader cmd) {
18231830
player.Message("Info: Invalid IP range format. Use CIDR notation.");
18241831
return;
18251832
}
1826-
JsonObject result = null;
1827-
try {
1828-
result = JsonObject.Parse(Server.downloadDatastring("http://geoip.pw/api/" + ip));
1829-
if (result.Get("message") != null) {
1830-
player.Message("No information found!");
1831-
return;
1832-
}
1833-
player.Message("Geo Info about: &f{0}", result.Get("ip") ?? "N/A");
1834-
player.Message(" Country: &f{0}&S ({1})", result.Get("country") ?? "N/A", result.Get("country_abbr") ?? "N/A");
1835-
player.Message(" Continent: &f{0}", result.Get("continent") ?? "N/A");
1836-
player.Message(" Subdivisions: &f{0}", nan.Replace(result.Get("subdivision"), "").Split(',').JoinToString(", "));
1837-
player.Message(" Latitude: &f{0}", result.Get("latitude") ?? "N/A");
1838-
player.Message(" Longitude: &f{0}", result.Get("longitude") ?? "N/A");
1839-
player.Message(" Timezone: &f{0}", result.Get("timezone") ?? "N/A");
1840-
byte acc;
1841-
byte.TryParse(result.Get("accuracy"), out acc);
1842-
player.Message(" Hostname: &f{0}", result.Get("host") ?? "N/A");
1843-
player.Message(" Accuracy: &f{0}", acc);
1844-
player.Message("Geoip information by: &9http://geoip.pw/");
1845-
1846-
} catch (Exception ex) {
1847-
Logger.Log(LogType.Warning, "Could not access GeoIP website (Ex: " + ex + ")");
1848-
}
1833+
1834+
PlayerInfo tmp = new PlayerInfo(0); tmp.LastIP = ip;
1835+
GetGeoipInfo(tmp);
1836+
PrintGeoIpInfo(player, tmp);
18491837
}
18501838

1851-
public static void GetGeoip(PlayerInfo info) {
1839+
public static void GetGeoipInfo(PlayerInfo info) {
18521840
string ip = info.LastIP.ToString();
18531841
if (IPAddress.Parse(ip).IsLocal() && Server.ExternalIP != null) {
18541842
ip = Server.ExternalIP.ToString();
18551843
}
1856-
if (ip == info.GeoIP) {
1857-
return;
1858-
}
1844+
if (ip == info.GeoIP) return;
1845+
18591846
JsonObject result = null;
18601847
try {
1861-
result = JsonObject.Parse(Server.downloadDatastring("http://geoip.pw/api/" + ip));
1862-
if (result.Get("message") != null) {
1863-
return;
1864-
}
1848+
string url = "http://geoip.pw/api/" + ip;
1849+
result = JsonObject.Parse(HttpUtil.DownloadString(url, "get GeoIP info", 10000));
1850+
if (result.Get("message") != null) return;
1851+
18651852
info.CountryName = result.Get("country") ?? "N/A";
18661853
info.CountryCode = result.Get("country_abbr") ?? "N/A";
18671854
info.Continent = result.Get("continent") ?? "N/A";
@@ -1871,12 +1858,9 @@ public static void GetGeoip(PlayerInfo info) {
18711858
info.TimeZone = result.Get("timezone") ?? "N/A";
18721859
info.Hostname = result.Get("host") ?? "N/A";
18731860
info.GeoIP = result.Get("ip") ?? "N/A";
1874-
return;
1875-
18761861
} catch (Exception ex) {
18771862
Logger.Log(LogType.Warning, "Could not access GeoIP website (Ex: " + ex + ")");
18781863
Logger.Log(LogType.Debug, ex.ToString());
1879-
return;
18801864
}
18811865
}
18821866

@@ -1927,7 +1911,8 @@ private static void APIPInfoHandler(Player player, CommandReader cmd) {
19271911
break;
19281912
}
19291913

1930-
string data = Server.downloadDatastring("http://www.classicube.net/api/" + value);
1914+
string url = "http://www.classicube.net/api/" + value;
1915+
string data = HttpUtil.DownloadString(url, "get user info", 10000);
19311916
if (string.IsNullOrEmpty(data) || !data.Contains("username")) {
19321917
player.Message("Player not found!");
19331918
return;

fCraft/Network/HttpUtil.cs

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
// 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>
22
using System;
33
using System.Collections.Generic;
4+
using System.IO;
45
using System.Linq;
56
using System.Net;
7+
using System.Net.Cache;
68
using System.Net.Sockets;
79
using JetBrains.Annotations;
810

@@ -68,7 +70,7 @@ public static HttpWebRequest CreateRequest([NotNull] Uri uri, TimeSpan timeout)
6870
}
6971
}
7072
return req;
71-
}
73+
}
7274

7375
public static WebClient CreateWebClient(TimeSpan timeout) {
7476
return new CustomWebClient(timeout);
@@ -82,5 +84,28 @@ protected override WebRequest GetWebRequest(Uri address) {
8284
return CreateRequest(address, timeout);
8385
}
8486
}
87+
88+
89+
[CanBeNull]
90+
public static string DownloadString(string url, string action, int timeoutMS) {
91+
HttpWebRequest request = CreateRequest(new Uri(url), TimeSpan.FromMilliseconds(timeoutMS));
92+
request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
93+
94+
try {
95+
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
96+
if (response.StatusCode != HttpStatusCode.OK) {
97+
Logger.Log(LogType.Warning, "Could not {1}: {0}", response.StatusDescription, action);
98+
return null;
99+
}
100+
101+
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
102+
return reader.ReadToEnd();
103+
}
104+
}
105+
} catch (WebException ex) {
106+
Logger.Log(LogType.Warning, "Could not {1}: {0}", ex, action);
107+
return null;
108+
}
109+
}
85110
}
86111
}

fCraft/Player/Player.cs

Lines changed: 9 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -2007,7 +2007,7 @@ public bool StopPossessing([NotNull]Player target)
20072007

20082008
#region Static Utilities
20092009

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

20132013

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

2019-
Uri uri = new Uri( PaidCheckUri + Uri.EscapeDataString( name ) );
2020-
HttpWebRequest request = HttpUtil.CreateRequest( uri, TimeSpan.FromMilliseconds( PaidCheckTimeout ) );
2021-
request.CachePolicy = new RequestCachePolicy( RequestCacheLevel.NoCacheNoStore );
2022-
2023-
try {
2024-
using( WebResponse response = request.GetResponse() ) {
2025-
using( StreamReader responseReader = new StreamReader( response.GetResponseStream() ) ) {
2026-
string paidStatusString = responseReader.ReadToEnd();
2027-
bool isPaid;
2028-
if( Boolean.TryParse( paidStatusString, out isPaid ) ) {
2029-
if( isPaid ) {
2030-
return AccountType.Paid;
2031-
} else {
2032-
return AccountType.Free;
2033-
}
2034-
} else {
2035-
return AccountType.Unknown;
2036-
}
2037-
}
2038-
}
2039-
} catch( WebException ex ) {
2040-
Logger.Log( LogType.Warning,
2041-
"Could not check paid status of player {0}: {1}",
2042-
name, ex.Message );
2043-
return AccountType.Unknown;
2044-
}
2019+
string uri = paidCheckUri + Uri.EscapeDataString( name );
2020+
string data = HttpUtil.DownloadString( uri, "check paid status", PaidCheckTimeout );
2021+
2022+
bool isPaid;
2023+
if( data != null && Boolean.TryParse( data, out isPaid ) ) {
2024+
return isPaid ? AccountType.Paid : AccountType.Free;
2025+
}
2026+
return AccountType.Unknown;
20452027
}
20462028

20472029
static readonly Regex

fCraft/Player/PlayerInfo.cs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ public void GeoipLogin() {
117117

118118
public void GeoipLoginCallback( SchedulerTask task ) {
119119
PlayerInfo info = (PlayerInfo)task.UserState;
120-
InfoCommands.GetGeoip(info);
120+
InfoCommands.GetGeoipInfo(info);
121121
DisplayGeoIp(true);
122122
}
123123

@@ -460,8 +460,6 @@ public bool AllowThirdPerson {
460460
public string Longitude;
461461
/// <summary> List of subdivisions (City, State, etc) sorting by accuracy from left to right. </summary>
462462
public string Subdivision = "NA";
463-
/// <summary> Players geoip accuracy</summary>
464-
public byte Accuracy = 0;
465463
/// <summary> Players hostname</summary>
466464
public string Hostname;
467465
/// <summary> Players continent</summary>
@@ -757,7 +755,7 @@ internal static PlayerInfo LoadFormat2( string[] fields, int count ) {
757755
if (count > 81) info.skinName = PlayerDB.Unescape(fields[81]);
758756

759757
if (count > 82) info.Subdivision = PlayerDB.Unescape(fields[82]);
760-
if (count > 83) byte.TryParse(fields[83], out info.Accuracy);
758+
//if (count > 83) byte.TryParse(fields[83], out info.Accuracy);
761759
if (count > 84) info.Hostname = fields[84];
762760
if (count > 85) info.Continent = fields[85];
763761

@@ -1276,7 +1274,7 @@ internal void Serialize( StringBuffer sb ) {
12761274
sb.Append(',');
12771275
sb.AppendEscaped(Subdivision); // 82
12781276
sb.Append(',');
1279-
sb.Append(Accuracy); // 83
1277+
//sb.Append(Accuracy); // 83 unused
12801278
sb.Append(',');
12811279
sb.Append(Hostname); // 84
12821280
sb.Append(',');

fCraft/System/Server.cs

Lines changed: 7 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1113,68 +1113,18 @@ public static string GetRandomString( int chars ) {
11131113
}
11141114

11151115

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

11191119

11201120
/// <summary> Checks server's external IP, as reported by fCraft.net. </summary>
11211121
[CanBeNull]
1122-
static IPAddress CheckExternalIP()
1123-
{
1124-
HttpWebRequest request = HttpUtil.CreateRequest(IPCheckUri,
1125-
TimeSpan.FromMilliseconds(IPCheckTimeout));
1126-
request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
1127-
1128-
try
1129-
{
1130-
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
1131-
{
1132-
if (response.StatusCode != HttpStatusCode.OK)
1133-
{
1134-
Logger.Log(LogType.Warning, "Could not check external IP: {0}",
1135-
response.StatusDescription);
1136-
return null;
1137-
}
1138-
1139-
// ReSharper disable AssignNullToNotNullAttribute
1140-
using (StreamReader responseReader = new StreamReader(response.GetResponseStream()))
1141-
{
1142-
// ReSharper restore AssignNullToNotNullAttribute
1143-
string responseString = responseReader.ReadToEnd();
1144-
IPAddress result;
1145-
1146-
if (IPAddress.TryParse(responseString, out result)) return result;
1147-
return null;
1148-
}
1149-
}
1150-
}
1151-
catch (WebException ex)
1152-
{
1153-
Logger.Log(LogType.Warning, "Could not check external IP: {0}", ex);
1154-
return null;
1155-
}
1156-
}
1157-
1158-
/// <summary> Safely downloads data. </summary>
1159-
[CanBeNull]
1160-
public static string downloadDatastring(string url) {
1161-
HttpWebRequest request = HttpUtil.CreateRequest(new Uri(url), TimeSpan.FromSeconds(10));
1162-
request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
1163-
1164-
try {
1165-
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
1166-
if (response.StatusCode != HttpStatusCode.OK) {
1167-
Logger.Log(LogType.Warning, "Could not download data: {0}", response.StatusDescription);
1168-
return null;
1169-
}
1170-
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
1171-
return reader.ReadToEnd();
1172-
}
1173-
}
1174-
} catch (WebException ex) {
1175-
Logger.Log(LogType.Warning, "Could not download data: {0}", ex);
1176-
return null;
1177-
}
1122+
static IPAddress CheckExternalIP() {
1123+
string data = HttpUtil.DownloadString(ipCheckUri, "check external IP", IPCheckTimeout);
1124+
IPAddress ip = null;
1125+
1126+
if (data == null || !IPAddress.TryParse(data, out ip)) return null;
1127+
return ip;
11781128
}
11791129

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

0 commit comments

Comments
 (0)