Skip to content

Commit e05aa3d

Browse files
committed
Fixes + GetSafeStrinb
1 parent 93d2853 commit e05aa3d

31 files changed

+307
-93
lines changed

.vs/ScriptBloxAPI/v17/.suo

19 KB
Binary file not shown.

Backend Functions/MiscFunctions.cs

Lines changed: 78 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,17 @@
1-
using System;
1+
using Newtonsoft.Json.Linq;
2+
using Newtonsoft.Json;
3+
using System;
4+
using System.Diagnostics.CodeAnalysis;
25
using System.Globalization;
6+
using System.IO;
7+
using System.Net;
38
using System.Net.Http;
49
using System.Reflection;
10+
using System.Threading.Tasks;
511

612
namespace ScriptBloxAPI.Backend_Functions
713
{
8-
internal class MiscFunctions
14+
internal static class MiscFunctions
915
{
1016

1117
internal static HttpClient InternalClient;
@@ -16,11 +22,80 @@ internal static HttpClient HttpClient
1622
if (InternalClient != null) return InternalClient;
1723

1824
InternalClient = new HttpClient();
19-
InternalClient.DefaultRequestHeaders.UserAgent.ParseAdd(@$"iScriptBloxAPI/{Assembly.GetEntryAssembly()?.GetName().Version} (Windows 10/11; .NET Framework 4.8; C# <Latest>)");
25+
InternalClient.DefaultRequestHeaders.UserAgent.ParseAdd(@$"iScriptBloxAPI/{Assembly.GetEntryAssembly()?.GetName().Version} (Windows 10/11; .NET Framework {Environment.Version}; C# <Latest>)");
2026

2127
return InternalClient;
2228
}
2329
}
30+
31+
32+
[SuppressMessage("ReSharper", "SwitchStatementMissingSomeEnumCasesNoDefault")]
33+
public static async Task<string> GetSafeStringAsync(this HttpClient httpClient, string url)
34+
{
35+
HttpResponseMessage response = await httpClient.GetAsync(url);
36+
37+
switch (response.StatusCode)
38+
{
39+
case HttpStatusCode.NotFound:
40+
throw new ScriptBloxException(@$"The resource '{Path.GetFileNameWithoutExtension(url)}' could not be found.");
41+
case HttpStatusCode.BadRequest:
42+
throw new ScriptBloxException(@"An error occurred while trying to perform the request. Please ensure your request is correctly formatted.");
43+
case HttpStatusCode.Forbidden:
44+
throw new ScriptBloxException(@"The request was forbidden. You might have been rate-limited or lack proper permissions.");
45+
case HttpStatusCode.GatewayTimeout:
46+
throw new ScriptBloxException(@"The gateway timed out while processing the request. Please check if ScriptBlox is currently online.");
47+
case HttpStatusCode.InternalServerError:
48+
throw new ScriptBloxException(@"An internal server error has occurred on the server side. Please contact ScriptBloxAdmin for assistance.");
49+
}
50+
51+
string responseBody = await response.Content.ReadAsStringAsync();
52+
53+
try
54+
{
55+
JToken.Parse(responseBody);
56+
}
57+
catch (JsonException)
58+
{
59+
throw new ScriptBloxException($"Failed to parse JSON return.\n{responseBody}");
60+
}
61+
62+
return responseBody;
63+
}
64+
65+
[SuppressMessage("ReSharper", "SwitchStatementMissingSomeEnumCasesNoDefault")]
66+
public static string GetSafeString(this HttpClient httpClient, string url)
67+
{
68+
HttpResponseMessage response = httpClient.GetAsync(url).Result;
69+
70+
switch (response.StatusCode)
71+
{
72+
case HttpStatusCode.NotFound:
73+
throw new ScriptBloxException(@$"The resource '{Path.GetFileNameWithoutExtension(url)}' could not be found.");
74+
case HttpStatusCode.BadRequest:
75+
throw new ScriptBloxException(@"An error occurred while trying to perform the request. Please ensure your request is correctly formatted.");
76+
case HttpStatusCode.Forbidden:
77+
throw new ScriptBloxException(@"The request was forbidden. You might have been rate-limited or lack proper permissions.");
78+
case HttpStatusCode.GatewayTimeout:
79+
throw new ScriptBloxException(@"The gateway timed out while processing the request. Please check if ScriptBlox is currently online.");
80+
case HttpStatusCode.InternalServerError:
81+
throw new ScriptBloxException(@"An internal server error has occurred on the server side. Please contact ScriptBloxAdmin for assistance.");
82+
}
83+
84+
string responseBody = response.Content.ReadAsStringAsync().Result;
85+
86+
try
87+
{
88+
JToken.Parse(responseBody);
89+
}
90+
catch (JsonException)
91+
{
92+
throw new ScriptBloxException($"Failed to parse JSON return.\n{responseBody}");
93+
}
94+
95+
return responseBody;
96+
}
97+
98+
2499
internal static DateTime ConvertStringToDateTime(string dateString, string timeFormat = @"MM/dd/yyyy HH:mm:ss")
25100
{
26101
try

Methods/Scripts.cs

Lines changed: 78 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,15 @@
22
using Newtonsoft.Json.Linq;
33
using ScriptBloxAPI.DataTypes;
44
using System.Collections.Generic;
5-
using System.Diagnostics;
65
using System.Linq;
76
using ScriptBloxAPI.Backend_Functions;
87
using System.Threading.Tasks;
9-
using Newtonsoft.Json;
10-
118
// ReSharper disable UnusedMember.Global
129
#pragma warning disable IDE0270
1310

1411
namespace ScriptBloxAPI.Methods
1512
{
16-
public class ScriptsMethods
13+
public static class ScriptsMethods
1714
{
1815

1916
public enum FilterType
@@ -29,16 +26,81 @@ public enum FilterType
2926
Paid
3027
}
3128

32-
#region Non Async
29+
#region Internal Functions
30+
private static bool IsScriptDataInvalid(JToken scriptData)
31+
{
32+
return scriptData["game"] == null ||
33+
scriptData["tags"] == null ||
34+
scriptData["script"] == null ||
35+
scriptData["views"] == null ||
36+
scriptData["verified"] == null ||
37+
scriptData["key"] == null ||
38+
scriptData["isUniversal"] == null ||
39+
scriptData["isPatched"] == null ||
40+
scriptData["createdAt"] == null ||
41+
scriptData["updatedAt"] == null ||
42+
scriptData["likeCount"] == null ||
43+
scriptData["dislikeCount"] == null ||
44+
scriptData["slug"] == null ||
45+
scriptData["id"] == null;
46+
}
47+
48+
private static IEnumerable<string> GetSlugsFromResults(JToken json)
49+
{
50+
List<string> slugs = new();
51+
52+
try
53+
{
54+
json = JToken.Parse(json.ToString());
55+
56+
if (!json.HasValues) return slugs;
57+
if (json["result"] == null) return slugs;
58+
if (json["result"]["scripts"] == null) return slugs;
3359

60+
JArray scripts = json["result"]?["scripts"]?.ToObject<JArray>() ?? new JArray();
61+
62+
slugs.AddRange(scripts.Select(script => script.Value<string>("slug")));
63+
}
64+
catch (Exception ex)
65+
{
66+
throw new ScriptBloxException($"An error occurred in 'GetSlugsFromResults' please create an issue @ github: {ex}\n{ex.StackTrace}");
67+
}
68+
69+
return slugs;
70+
}
71+
72+
private static ScriptObject CreateScriptFromData(JToken scriptData)
73+
{
74+
GameObject game = new(scriptData["game"].Value<long>("gameId"),
75+
scriptData["game"].Value<string>("name"),
76+
scriptData["game"].Value<string>("imageUrl"));
77+
78+
return new ScriptObject(game,
79+
scriptData.Value<string>("title"),
80+
scriptData.Value<string>("_id"),
81+
scriptData.Value<string>("slug"),
82+
scriptData.Value<string>("script"),
83+
scriptData.Value<string>("createdAt"),
84+
scriptData.Value<string>("updatedAt"),
85+
scriptData.Value<long>("views"),
86+
scriptData.Value<long>("likeCount"),
87+
scriptData.Value<long>("dislikeCount"),
88+
scriptData.Value<bool>("isUniversal"),
89+
scriptData.Value<bool>("isPatched"),
90+
scriptData.Value<bool>("key"),
91+
scriptData.Value<bool>("verified"),
92+
new List<string>());
93+
}
94+
#endregion
95+
#region Non Async
3496
/// <summary>
3597
/// Retrieves a script from ScriptBlox based on the provided ScriptBlox ID.
3698
/// </summary>
3799
/// <param name="bloxId">The ScriptBlox ID of the script to retrieve.</param>
38100
/// <returns>The script retrieved from the API, or a default script if the retrieval fails or the data is invalid.</returns>
39101
public static ScriptObject GetScriptFromScriptbloxId(string bloxId)
40102
{
41-
JToken jsonReturn = JToken.Parse(MiscFunctions.HttpClient.GetStringAsync($"https://scriptblox.com/api/script/{bloxId}").Result);
103+
JToken jsonReturn = JToken.Parse(MiscFunctions.HttpClient.GetSafeString($"https://scriptblox.com/api/script/{bloxId}"));
42104

43105
if (jsonReturn == null)
44106
throw new ScriptBloxException("An error has occurred while fetching the json, please submit a bug report.");
@@ -64,7 +126,7 @@ public static List<ScriptObject> GetFrontPageScripts(int pageNumber = 1)
64126
{
65127
if (pageNumber < 1) pageNumber = 1;
66128

67-
JToken jsonReturn = JToken.Parse(MiscFunctions.HttpClient.GetStringAsync($"https://scriptblox.com/api/script/fetch?page={pageNumber}").Result);
129+
JToken jsonReturn = JToken.Parse(MiscFunctions.HttpClient.GetSafeString($"https://scriptblox.com/api/script/fetch?page={pageNumber}"));
68130

69131
if (jsonReturn == null)
70132
throw new ScriptBloxException("An error has occurred while fetching the json, please submit a bug report.");
@@ -95,7 +157,7 @@ public static List<ScriptObject> GetScriptsFromQuery(string searchQuery, int max
95157
{
96158
if (maxResults < 1) maxResults = 1;
97159

98-
JToken jsonReturn = JToken.Parse(MiscFunctions.HttpClient.GetStringAsync($"https://scriptblox.com/api/script/search?q={searchQuery}&page=1&max={maxResults}").Result);
160+
JToken jsonReturn = JToken.Parse(MiscFunctions.HttpClient.GetSafeString($"https://scriptblox.com/api/script/search?q={searchQuery}&page=1&max={maxResults}"));
99161

100162
if (jsonReturn == null)
101163
throw new ScriptBloxException("An error has occurred while fetching the json, please submit a bug report.");
@@ -117,7 +179,7 @@ public static List<ScriptObject> GetScriptsFromQuery(string searchQuery, int max
117179
/// <returns>A list of Script objects representing the scripts owned by the user.</returns>
118180
public static List<ScriptObject> GetScriptsFromUser(string username)
119181
{
120-
JToken jsonReturn = JToken.Parse(MiscFunctions.HttpClient.GetStringAsync($"https://scriptblox.com/api/user/scripts/{username}?page=1").Result);
182+
JToken jsonReturn = JToken.Parse(MiscFunctions.HttpClient.GetSafeString($"https://scriptblox.com/api/user/scripts/{username}?page=1"));
121183

122184
if (jsonReturn == null)
123185
throw new ScriptBloxException("An error has occurred while fetching the json, please submit a bug report.");
@@ -138,7 +200,7 @@ public static List<ScriptObject> GetScriptsFromUser(string username)
138200
/// <returns>A list of ScriptObjects that match the specified filter type.</returns>
139201
public static List<ScriptObject> GetScriptsWithFilter(FilterType filterType)
140202
{
141-
JToken jsonReturn = JToken.Parse(MiscFunctions.HttpClient.GetStringAsync($@"https://scriptblox.com/api/script/fetch?page=1&filters[]={filterType.ToString().ToLower()}").Result);
203+
JToken jsonReturn = JToken.Parse(MiscFunctions.HttpClient.GetSafeString($@"https://scriptblox.com/api/script/fetch?page=1&filters[]={filterType.ToString().ToLower()}"));
142204

143205
if (jsonReturn == null)
144206
throw new ScriptBloxException("An error has occurred while fetching the json, please submit a bug report.");
@@ -151,74 +213,7 @@ public static List<ScriptObject> GetScriptsWithFilter(FilterType filterType)
151213

152214
return slugsToCheck.Select(GetScriptFromScriptbloxId).ToList();
153215
}
154-
155-
#region Internal Functions
156-
private static bool IsScriptDataInvalid(JToken scriptData)
157-
{
158-
return scriptData["game"] == null ||
159-
scriptData["tags"] == null ||
160-
scriptData["script"] == null ||
161-
scriptData["views"] == null ||
162-
scriptData["verified"] == null ||
163-
scriptData["key"] == null ||
164-
scriptData["isUniversal"] == null ||
165-
scriptData["isPatched"] == null ||
166-
scriptData["createdAt"] == null ||
167-
scriptData["updatedAt"] == null ||
168-
scriptData["likeCount"] == null ||
169-
scriptData["dislikeCount"] == null ||
170-
scriptData["slug"] == null ||
171-
scriptData["id"] == null;
172-
}
173-
174-
private static IEnumerable<string> GetSlugsFromResults(JToken json)
175-
{
176-
List<string> slugs = new();
177-
178-
try
179-
{
180-
json = JToken.Parse(json.ToString());
181-
182-
if (!json.HasValues) return slugs;
183-
if (json["result"] == null) return slugs;
184-
if (json["result"]["scripts"] == null) return slugs;
185-
186-
JArray scripts = JArray.Parse(json["result"]?["scripts"].ToString() ?? "[]");
187-
188-
slugs.AddRange(scripts.Select(script => script.Value<string>("slug")));
189-
}
190-
catch (Exception ex)
191-
{
192-
throw new ScriptBloxException($@"An error occurred in 'GetSlugsFromResults' please create an issue @ github: {ex}{"\n"}{ex.StackTrace}");
193-
}
194-
195-
return slugs;
196-
}
197-
198-
private static ScriptObject CreateScriptFromData(JToken scriptData)
199-
{
200-
GameObject game = new(scriptData["game"].Value<long>("gameId"),
201-
scriptData["game"].Value<string>("name"),
202-
scriptData["game"].Value<string>("imageUrl"));
203-
204-
return new ScriptObject(game,
205-
scriptData.Value<string>("title"),
206-
scriptData.Value<string>("_id"),
207-
scriptData.Value<string>("slug"),
208-
scriptData.Value<string>("script"),
209-
scriptData.Value<string>("createdAt"),
210-
scriptData.Value<string>("updatedAt"),
211-
scriptData.Value<long>("views"),
212-
scriptData.Value<long>("likeCount"),
213-
scriptData.Value<long>("dislikeCount"),
214-
scriptData.Value<bool>("isUniversal"),
215-
scriptData.Value<bool>("isPatched"),
216-
scriptData.Value<bool>("key"),
217-
scriptData.Value<bool>("verified"),
218-
new List<string>());
219-
}
220-
#endregion
221-
216+
222217
#endregion
223218
#region Async
224219

@@ -229,7 +224,7 @@ private static ScriptObject CreateScriptFromData(JToken scriptData)
229224
/// <returns>The script retrieved from the API, or a default script if the retrieval fails or the data is invalid.</returns>
230225
public static async Task<ScriptObject> GetScriptFromScriptbloxIdAsync(string bloxId)
231226
{
232-
JToken jsonReturn = JToken.Parse(await MiscFunctions.HttpClient.GetStringAsync($"https://scriptblox.com/api/script/{bloxId}"));
227+
JToken jsonReturn = JToken.Parse(await MiscFunctions.HttpClient.GetSafeStringAsync($"https://scriptblox.com/api/script/{bloxId}"));
233228

234229
if (jsonReturn == null)
235230
throw new ScriptBloxException("An error has occurred while fetching the json, please submit a bug report.");
@@ -255,7 +250,7 @@ public static async Task<List<ScriptObject>> GetFrontPageScriptsAsync(int pageNu
255250
{
256251
if (pageNumber < 1) pageNumber = 1;
257252

258-
JToken jsonReturn = JToken.Parse(await MiscFunctions.HttpClient.GetStringAsync($"https://scriptblox.com/api/script/fetch?page={pageNumber}"));
253+
JToken jsonReturn = JToken.Parse(await MiscFunctions.HttpClient.GetSafeStringAsync($"https://scriptblox.com/api/script/fetch?page={pageNumber}"));
259254

260255
if (jsonReturn == null)
261256
throw new ScriptBloxException("An error has occurred while fetching the json, please submit a bug report.");
@@ -286,7 +281,7 @@ public static async Task<List<ScriptObject>> GetScriptsFromQueryAsync(string sea
286281
{
287282
if (maxResults < 1) maxResults = 1;
288283

289-
JToken jsonReturn = JToken.Parse(await MiscFunctions.HttpClient.GetStringAsync($"https://scriptblox.com/api/script/search?q={searchQuery}&page=1&max={maxResults}"));
284+
JToken jsonReturn = JToken.Parse(await MiscFunctions.HttpClient.GetSafeStringAsync($"https://scriptblox.com/api/script/search?q={searchQuery}&page=1&max={maxResults}"));
290285

291286
if (jsonReturn == null)
292287
throw new ScriptBloxException("An error has occurred while fetching the json, please submit a bug report.");
@@ -311,7 +306,7 @@ public static async Task<List<ScriptObject>> GetScriptsFromQueryAsync(string sea
311306
/// <returns>A list of Script objects representing the scripts owned by the user.</returns>
312307
public static async Task<List<ScriptObject>> GetScriptsFromUserAsync(string username)
313308
{
314-
JToken jsonReturn = JToken.Parse(await MiscFunctions.HttpClient.GetStringAsync($"https://scriptblox.com/api/user/scripts/{username}"));
309+
JToken jsonReturn = JToken.Parse(await MiscFunctions.HttpClient.GetSafeStringAsync($"https://scriptblox.com/api/user/scripts/{username}"));
315310

316311
if (jsonReturn == null)
317312
throw new ScriptBloxException("An error has occurred while fetching the json, please submit a bug report.");
@@ -336,7 +331,7 @@ public static async Task<List<ScriptObject>> GetScriptsFromUserAsync(string user
336331
/// <returns>A list of ScriptObjects that match the specified filter type.</returns>
337332
public static async Task<List<ScriptObject>> GetScriptsWithFilterAsync(FilterType filterType)
338333
{
339-
JToken jsonReturn = JToken.Parse(await MiscFunctions.HttpClient.GetStringAsync($@"https://scriptblox.com/api/script/fetch?page=1&filters[]={filterType.ToString().ToLower()}"));
334+
JToken jsonReturn = JToken.Parse(await MiscFunctions.HttpClient.GetSafeStringAsync($@"https://scriptblox.com/api/script/fetch?page=1&filters[]={filterType.ToString().ToLower()}"));
340335

341336
if (jsonReturn == null)
342337
throw new ScriptBloxException("An error has occurred while fetching the json, please submit a bug report.");

Properties/AssemblyInfo.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,5 +31,5 @@
3131
// You can specify all the values or you can default the Build and Revision Numbers
3232
// by using the '*' as shown below:
3333
// [assembly: AssemblyVersion("1.0.*")]
34-
[assembly: AssemblyVersion("5.0.1.0")]
35-
[assembly: AssemblyFileVersion("5.0.1.0")]
34+
[assembly: AssemblyVersion("5.0.2.0")]
35+
[assembly: AssemblyFileVersion("5.0.2.0")]

0 commit comments

Comments
 (0)