Skip to content

Commit abbb4e4

Browse files
committed
Updated /GenHeightMap and /DrawImage
Combine URL Parsing and Image Downloading. Tried to foolproof Imgur URL parsing somewhat.
1 parent 01cb104 commit abbb4e4

3 files changed

Lines changed: 80 additions & 80 deletions

File tree

‎fCraft/Commands/BuildingCommands.cs‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2672,7 +2672,6 @@ static void DrawImageHandler(Player player, CommandReader cmd)
26722672
private static void DrawImageCallback(Player player, Vector3I[] marks, object tag)
26732673
{
26742674
ImageDrawOperation op = (ImageDrawOperation)tag;
2675-
player.Message("&HDrawImage: Downloading {0}", op.ImageUrl);
26762675
try
26772676
{
26782677
op.Prepare(marks);

‎fCraft/Commands/WorldCommands.cs‎

Lines changed: 72 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
using System.Diagnostics;
1313
using System.Net;
1414
using System.Drawing;
15+
using System.Text.RegularExpressions;
1516

1617
namespace fCraft {
1718
/// <summary> Contains commands related to world management. </summary>
@@ -962,13 +963,21 @@ private static void GenHMHandler(Player player, CommandReader cmd) {
962963

963964
// generate the map
964965
int mapWidth = 0, mapLength = 0;
965-
player.SendNow(Packet.Message(0, "Downloading file from: &9" + url, player));
966-
heightmap = DownloadImage(url, player);
966+
try {
967+
heightmap = DownloadImage(url, player);
968+
}
969+
catch (ArgumentException ex) {
970+
player.Message("&WGenHeightMap: Error setting up: " + ex.Message);
971+
}
972+
catch (Exception ex) {
973+
Logger.Log(LogType.Warning, "GenHeightMap: Error downloading image from {0}: {1}", url, ex);
974+
player.Message("&WGenHeightMap: Error downloading: " + ex.Message);
975+
}
967976
if (heightmap == null) return;
968977
mapWidth = heightmap.Width;
969978
mapLength = heightmap.Height;
970979
if (!Map.IsValidDimension(mapWidth) || !Map.IsValidDimension(mapLength)) {
971-
player.Message("Invalid image size along {0} &S(Must be inbetween 16 and 1024)", Map.IsValidDimension(mapWidth) ? "height: &F" + mapLength : "width: &F" + mapWidth);
980+
player.Message("&WInvalid image size along {0} &S(Must be inbetween 16 and 1024)", Map.IsValidDimension(mapWidth) ? "height: &F" + mapLength : "width: &F" + mapWidth);
972981
return;
973982
}
974983
player.SendNow(Packet.Message(0, "Generating HeightMap...", player));
@@ -1106,48 +1115,82 @@ public static Bitmap DownloadImage(string url, Player player) {
11061115
using (WebResponse resp = reqLen.GetResponse()) {
11071116
int.TryParse(resp.Headers.Get("Content-Length"), out ContentLength);
11081117
}
1109-
if (ContentLength > 5000000) {
1110-
player.Message("&WImage size is too large {0}MB > 5MB", ContentLength / 1000000);
1118+
if (ContentLength > 10000000) {
1119+
player.Message("&WImage size is too large {0}MB > 10MB", ContentLength / 1000000);
11111120
return null;
11121121
}
11131122

1114-
HttpWebRequest request = HttpUtil.CreateRequest(new Uri(url), TimeSpan.FromSeconds(6));
1123+
player.Message("Downloading file from: &9" + url);
1124+
if (ContentLength > 1000000) {
1125+
player.Message("Depending on the image size, this could take some time.");
1126+
}
1127+
HttpWebRequest request = HttpUtil.CreateRequest(new Uri(url), TimeSpan.FromSeconds(15));
11151128
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
1116-
if ((response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Moved ||
1117-
response.StatusCode == HttpStatusCode.Redirect) &&
1118-
response.ContentType.CaselessStarts("image")) {
1119-
// if the remote file was found, download it
1120-
using (Stream inputStream = response.GetResponseStream()) {
1121-
// TODO: check file size limit?
1122-
return new Bitmap(inputStream);
1129+
if (response.ContentType.CaselessStarts("image")) {
1130+
if ((response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Moved ||
1131+
response.StatusCode == HttpStatusCode.Redirect)) {
1132+
// if the remote file was found, download it
1133+
using (Stream inputStream = response.GetResponseStream()) {
1134+
// TODO: check file size limit?
1135+
player.Message("&SImage successfully downloaded!");
1136+
return new Bitmap(inputStream);
1137+
}
1138+
} else {
1139+
player.Message("&WFailed to download the image from the given url.");
1140+
throw new Exception("Error downloading image: " + response.StatusCode);
11231141
}
11241142
} else {
1125-
player.Message("&WFailed to download the image from the given url.");
1126-
throw new Exception("Error downloading image: " + response.StatusCode);
1143+
player.Message("&WThe given URL is not an image.");
1144+
throw new Exception("URL is not Content Type of Image");
11271145
}
11281146
}
11291147

11301148
}
11311149

11321150
public static bool parseUrl(ref string urlString, Player player) {
11331151
if (urlString.NullOrWhiteSpace()) {
1134-
player.Message("You must provide a url to a heightmap image.");
1152+
player.Message("You must provide a URL to an image.");
11351153
return false;
11361154
}
1137-
1138-
if (urlString.StartsWith("http://imgur.com/")) urlString = "http://i.imgur.com/" + urlString.Substring("http://imgur.com/".Length) + ".png";
1139-
if (urlString.StartsWith("++")) urlString = "http://i.imgur.com/" + urlString.Substring(2) + ".png";
1140-
if (!urlString.CaselessStarts("http://") && !urlString.CaselessStarts("https://")) urlString = "http://" + urlString;
1141-
1142-
if (!urlString.CaselessStarts("http://i.imgur.com/") && !urlString.CaselessStarts("https://123DMWM.com/")) {
1143-
player.Message("For safety reasons we only accept images uploaded to &9http://imgur.com/ &SSorry for this inconvenience.");
1144-
player.Message(" You cannot use: &9" + urlString);
1145-
return false;
1155+
string queryStr = "";
1156+
if (urlString.Contains('?')) {
1157+
queryStr = urlString.Substring(urlString.IndexOf('?'));
1158+
urlString = urlString.Substring(0, urlString.IndexOf('?'));
11461159
}
1147-
1148-
if (!urlString.CaselessEnds(".png") && !urlString.CaselessEnds(".jpg") && !urlString.CaselessEnds(".bmp")) {
1149-
player.Message("URL must be a link to an image (.png/.jpg/.bmp");
1150-
return false;
1160+
if (urlString.StartsWith("++")) {
1161+
urlString = "https://i.imgur.com/" + urlString.Substring(2) + ".png";
1162+
}
1163+
if (!urlString.CaselessStarts("http://") && !urlString.CaselessStarts("https://")) {
1164+
urlString = "http://" + urlString;
1165+
}
1166+
if (urlString.CaselessContains("imgur.com")) {
1167+
if (urlString.CaselessContains("//www.imgur.com/") || urlString.CaselessStarts("www.imgur.com/")) {
1168+
urlString = urlString.ReplaceString("www.imgur.com", "i.imgur.com", StringComparison.OrdinalIgnoreCase);
1169+
}
1170+
if (urlString.CaselessContains("//imgur.com/") || urlString.CaselessStarts("imgur.com/")) {
1171+
urlString = urlString.ReplaceString("imgur.com", "i.imgur.com", StringComparison.OrdinalIgnoreCase);
1172+
}
1173+
if (urlString.CaselessContains("//i.imgur.com/") && !Regex.Match(urlString, @"\.[a-z0-9]{2,5}$", RegexOptions.IgnoreCase).Success) {
1174+
urlString += ".png";
1175+
}
1176+
if (urlString.CaselessContains("/gallery/") || urlString.CaselessContains("/a/")) {
1177+
player.Message("You cannot use an Imgur Gallery or Album URL.");
1178+
return false;
1179+
}
1180+
}
1181+
if (player.Info.Rank != RankManager.HighestRank) {//let highest rank use any URL
1182+
if (!urlString.CaselessEnds(".png") && !urlString.CaselessEnds(".jpg") && !urlString.CaselessEnds(".jpeg") && !urlString.CaselessEnds(".bmp") && !urlString.CaselessEnds(".gif")) {
1183+
player.Message("URL must be a link to an image (.png/.jpg/.bmp");
1184+
return false;
1185+
}
1186+
if (!urlString.CaselessContains("i.imgur.com") && !urlString.CaselessContains("123dmwm.com/I/")) {
1187+
player.Message("For safety reasons we only accept images uploaded to &9https://imgur.com/ &SSorry for this inconvenience.");
1188+
player.Message(" You cannot use: &9" + urlString);
1189+
return false;
1190+
}
1191+
}
1192+
if (queryStr != "") {
1193+
urlString += queryStr;
11511194
}
11521195

11531196
return true;

‎fCraft/Drawing/DrawOps/DrawImageOperation.cs‎

Lines changed: 8 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -72,43 +72,20 @@ public ImageDrawOperation([NotNull] Player player, [NotNull] BlockPalette palett
7272

7373
public override bool ReadParams(CommandReader cmd) {
7474
// get image URL
75-
string str = cmd.Next();
76-
if (str.NullOrWhiteSpace()) return false;
77-
78-
// if string starts with "++", load image from imgur
79-
if (str.StartsWith("++")) {
80-
str = "http://i.imgur.com/" + str.Substring(2) + ".png";
81-
}
82-
// prepend the protocol, if needed (assume http)
83-
if (!str.CaselessStarts("http://") && !str.CaselessStarts("https://")) {
84-
str = "http://" + str;
85-
}
86-
87-
// Convert imgur web page url to direct image url
88-
if (str.StartsWith("http://imgur.com/")) {
89-
str = "http://i.imgur.com/" + str.Substring("http://imgur.com/".Length) + ".png";
90-
}
91-
if (str.StartsWith("https://imgur.com/")) {
92-
str = "https://i.imgur.com/" + str.Substring("https://imgur.com/".Length) + ".png";
93-
}
94-
95-
if (!str.CaselessEnds(".png") && !str.CaselessEnds(".jpg") && !str.CaselessEnds(".gif")) {
96-
Player.Message("URL must be a link to an image");
97-
return false;
98-
}
75+
string urlstr = cmd.Next();
76+
77+
if (!WorldCommands.parseUrl(ref urlstr, Player)) return false;
9978

10079
// validate the image URL
10180
Uri url;
102-
if (!Uri.TryCreate(str, UriKind.Absolute, out url)) {
81+
if (!Uri.TryCreate(urlstr, UriKind.Absolute, out url)) {
10382
Player.Message("DrawImage: Invalid URL given.");
10483
return false;
10584
} else if (!url.Scheme.Equals(Uri.UriSchemeHttp) && !url.Scheme.Equals(Uri.UriSchemeHttps)) {
10685
Player.Message("DrawImage: Invalid URL given. Only HTTP and HTTPS links are allowed.");
10786
return false;
108-
} else if (!url.Host.CaselessEquals("i.imgur.com")) {
109-
Player.Message("For safety reasons we only accept images uploaded to &9http://imgur.com/ &SSorry for this inconvenience.");
110-
return false;
11187
}
88+
11289
ImageUrl = url;
11390

11491
// Check if player gave optional second argument (palette name)
@@ -150,28 +127,9 @@ public override bool Prepare(Vector3I[] marks) {
150127

151128
// Download the image
152129
if (ImageBitmap == null) {
153-
if (ImageUrl == null) {
154-
throw new InvalidOperationException(
155-
"Either ImageBitmap or ImageUrl must be set before calling Prepare()");
156-
}
157-
158-
HttpWebRequest request = HttpUtil.CreateRequest(ImageUrl, DownloadTimeout);
159-
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
160-
// Check that the remote file was found. The ContentType
161-
// check is performed since a request for a non-existent
162-
// image file might be redirected to a 404-page, which would
163-
// yield the StatusCode "OK", even though the image was not found.
164-
if ((response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Moved ||
165-
response.StatusCode == HttpStatusCode.Redirect) &&
166-
response.ContentType.CaselessStarts("image")) {
167-
// if the remote file was found, download it
168-
using (Stream inputStream = response.GetResponseStream()) {
169-
// TODO: check file size limit?
170-
ImageBitmap = new Bitmap(inputStream);
171-
}
172-
} else {
173-
throw new Exception("Error downloading image: " + response.StatusCode);
174-
}
130+
ImageBitmap = WorldCommands.DownloadImage(ImageUrl.ToString(), Player);
131+
if (ImageBitmap == null) {
132+
throw new Exception("Error downloading image");
175133
}
176134
}
177135

0 commit comments

Comments
 (0)