Skip to content
This repository has been archived by the owner on Mar 15, 2022. It is now read-only.

Commit

Permalink
Code Simplified & Website UI Scaling Fixed
Browse files Browse the repository at this point in the history
  • Loading branch information
PKoldborg committed Jun 22, 2021
1 parent 1f2cf93 commit 27d2577
Show file tree
Hide file tree
Showing 35 changed files with 1,504 additions and 434 deletions.
1,017 changes: 1,017 additions & 0 deletions .idea/config/applicationhost.config

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using CryptSharp.Core;
using CryptSharp.Core;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
Expand Down Expand Up @@ -41,8 +41,6 @@ public ActionResult<AuthToken> LoginTask()
[HttpPost("createUser")]
public ActionResult<string> CreateUserTask()
{


return Ok("Success");
}

Expand All @@ -55,7 +53,6 @@ public ActionResult<string> CreateUserTask()
[HttpPost("refresh")]
public ActionResult<AuthToken> RefreshTask()
{

return Ok("Success");
}
}
Expand Down
108 changes: 43 additions & 65 deletions Assemblies/Pamaxie.Database.Extensions/DbExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,58 +18,44 @@ public static class DbExtensions
public static bool SqlDbCheckup(out string errorReason)
{
errorReason = string.Empty;
bool success = true;
using (var dbContext = new SqlDbContext())
using var dbContext = new SqlDbContext();
if (!dbContext.Database.CanConnect())
{
if (!dbContext.Database.CanConnect())
{
success = false;
errorReason += "SQL Connection was not possible. Please ensure the value is set. For configuration examples please view our documentation at https://wiki.pamaxie.com";
}
else
{
var migrationsAssembly = dbContext.GetService<IMigrationsAssembly>();
var historyRepository = dbContext.GetService<IHistoryRepository>();
var all = migrationsAssembly.Migrations.Keys;
var applied = historyRepository.GetAppliedMigrations().Select(r => r.MigrationId);
var pending = all.Except(applied);
Console.WriteLine("Checking if database exists...");
if (dbContext.Database.EnsureCreated())
{
Console.WriteLine("SQL Database was created and schemas were applied");
}

var applyMigrations = Environment.GetEnvironmentVariable("ApplyMigrations");
bool.TryParse(applyMigrations, out var doMigration);
if (pending.Any())
{
Console.WriteLine($"{pending.Count()} Pending Migrations were found.");
if (!doMigration)
{
errorReason = "Pending Migrations were found, but the \"Apply Migrations\" variable was either not set or set to false.\n";
success = false;
}
else
{
try
{
Console.WriteLine($"Appliying Migrations.");
dbContext.Database.Migrate();
Console.WriteLine($"Migrations were applied successfully");
}
catch (Exception ex)
{
Console.WriteLine("");
errorReason += $"Failed automatically applying {pending.Count()} migrations. Please ensure your database is properly configured.\n";
success = false;
}
}
}
}
errorReason += "SQL Connection was not possible. Please ensure the value is set. For configuration examples please view our documentation at https://wiki.pamaxie.com";
return false;
}
var migrationsAssembly = dbContext.GetService<IMigrationsAssembly>();
var historyRepository = dbContext.GetService<IHistoryRepository>();
var all = migrationsAssembly.Migrations.Keys;
var applied = historyRepository.GetAppliedMigrations().Select(r => r.MigrationId);
var pending = all.Except(applied).ToList();;
Console.WriteLine("Checking if database exists...");
if (dbContext.Database.EnsureCreated())
{
Console.WriteLine("SQL Database was created and schemas were applied");
}



return success;
var applyMigrations = Environment.GetEnvironmentVariable("ApplyMigrations");
bool.TryParse(applyMigrations, out var doMigration);
if (!pending.Any()) return true;
Console.WriteLine($"{pending.Count} Pending Migrations were found.");
if (!doMigration)
{
errorReason = "Pending Migrations were found, but the \"Apply Migrations\" variable was either not set or set to false.\n";
return false;
}
try
{
Console.WriteLine("Applying Migrations.");
dbContext.Database.Migrate();
Console.WriteLine("Migrations were applied successfully");
return true;
}
catch (Exception ex)
{
Console.WriteLine(string.Empty);
errorReason += $"Failed automatically applying {pending.Count} migrations. Please ensure your database is properly configured.\n";
return false;
}
}

Expand All @@ -82,7 +68,6 @@ public static bool SqlDbCheckup(out string errorReason)
public static bool RedisDbCheckup(out string errorReason)
{
errorReason = string.Empty;
bool sucess = true;
var connectionMultiplexer =
#if DEBUG
ConnectionMultiplexer.Connect(Environment.GetEnvironmentVariable("PamaxiePublicRedisAddr") ?? string.Empty);
Expand All @@ -91,35 +76,28 @@ public static bool RedisDbCheckup(out string errorReason)
#endif
if (connectionMultiplexer.IsConnected)
{
IDatabase db = connectionMultiplexer.GetDatabase();
var db = connectionMultiplexer.GetDatabase();

if (!db.StringSet("testKey", "testValue"))
{
errorReason += "We tried setting a value but it didn't seem to get set. Please verify if your Redis Database is setup properly. The TTL for this key is 10 minutes. The key is: \"testKey\" the value should be \"testValue\"";
sucess = false;
return false;
}


if (db.StringGet("testKey") != "testValue")
{
errorReason += "We tried setting a value but it didn't seem to get set to the right value. Please verify if your Redis Database is setup properly. The TTL for this key is 10 minutes. The key is: \"testKey\" the value should be \"testValue\"";
sucess = false;
return false;
}

if (!db.KeyDelete("testKey"))
{
errorReason += "We deleting our test key but it didn't seem to happen. This should not be the case. Please verify if your Redis Database is setup properly. The TTL for this key is 10 minutes. The key is: \"testKey\" the value should be \"testValue\"";
sucess = false;
return false;
}
db.KeyDelete("testKey");
return sucess;
}
else
{
errorReason += "Redis Connection was not possible. Please ensure the value is set. For configuration examples please view our documentation at https://wiki.pamaxie.com";
return sucess;
return true;
}
errorReason += "Redis Connection was not possible. Please ensure the value is set. For configuration examples please view our documentation at https://wiki.pamaxie.com";
return true;
}

}
}
47 changes: 15 additions & 32 deletions Pamaxie.Api/Controllers/AuthController.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using PamaxieML.Api.Security;
using PamaxieML.Api.Data;
using Pamaxie.Database.Sql.DataClasses;
using Pamaxie.Extensions;
using System;
using PamaxieML.Api.Security;
using PamaxieML.Api.Data;
using System.IO;

namespace Pamaxie.Api.Controllers
{
Expand All @@ -25,69 +22,55 @@ public AuthController(TokenGenerator generator)
}

/// <summary>
/// Signs in a user via Basic authentication and returns a token.
/// Signs in a user via Basic authentication and returns a token.
/// </summary>
/// <returns><see cref="AuthToken"/> Token for Authentication</returns>
[AllowAnonymous]
[HttpPost("login")]
public ActionResult<AuthToken> LoginTask()
{
StreamReader reader = new StreamReader(Request.Body);
StreamReader reader = new(Request.Body);
string result = reader.ReadToEndAsync().GetAwaiter().GetResult();
if (string.IsNullOrEmpty(result)) return BadRequest(ErrorHandler.BadData());

Application? appData = JsonConvert.DeserializeObject<Application>(result);

Application appData = JsonConvert.DeserializeObject<Application>(result);

if (string.IsNullOrEmpty(appData.AppToken) || default(long) == appData.ApplicationId)
return Unauthorized(ErrorHandler.UnAuthorized());

if (!appData.VerifyAuth())
if (string.IsNullOrEmpty(appData?.AppToken) || default == appData.ApplicationId)
return Unauthorized(ErrorHandler.UnAuthorized());

if (!appData.VerifyAuth()) return Unauthorized(ErrorHandler.UnAuthorized());

AuthToken token = _generator.CreateToken(appData.ApplicationId.ToString());


if (token == null)
return StatusCode(500);
if (token == null) return StatusCode(500);

return Ok(token);
}

/// <summary>
/// Refreshes an exiting oAuth Token
/// Refreshes an exiting oAuth Token
/// </summary>
/// <returns><see cref="AuthToken"/> Refreshed Token</returns>
[Authorize]
[HttpPost("refresh")]
public ActionResult<AuthToken> RefreshTask()
{
StreamReader reader = new StreamReader(Request.Body);
StreamReader reader = new(Request.Body);
string result = reader.ReadToEndAsync().GetAwaiter().GetResult();

if (string.IsNullOrEmpty(result))
return BadRequest(ErrorHandler.BadData());
if (string.IsNullOrEmpty(result)) return BadRequest(ErrorHandler.BadData());
Application appData;
try
{
appData = JsonConvert.DeserializeObject<Application>(result);
}
catch (Exception ex)
{
return StatusCode(400);
}

catch { return StatusCode(400); }


if (default(long) == appData.ApplicationId)
return BadRequest(ErrorHandler.UnAuthorized());
if (default == appData?.ApplicationId) return BadRequest(ErrorHandler.UnAuthorized());

string userId = appData.ApplicationId.ToString();
AuthToken token = _generator.CreateToken(userId);

if (token == null)
return StatusCode(500);
if (token == null) return StatusCode(500);
return Ok(token);
}
}
Expand Down
35 changes: 15 additions & 20 deletions Pamaxie.Api/Controllers/VisionController.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
using System;
using System.Drawing;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Pamaxie.Database.Redis.DataClasses;
using PamaxieML.Api.Data;
using PamaxieML.Model;
using System.IO;
using System.Threading.Tasks;

namespace PamaxieML.Api.Controllers
{
Expand All @@ -33,7 +29,7 @@ public VisionController(ILogger<VisionController> logger)
/// <returns>oAuth Token</returns>
[HttpGet("status")]
[AllowAnonymous]
public ActionResult<string> ProbeApiTask()
public static ActionResult<string> ProbeApiTask()
{
return "API is available";
}
Expand All @@ -46,33 +42,32 @@ public ActionResult<string> ProbeApiTask()
[HttpPost("scanImage")]
public async Task<ActionResult<string>> ScanImageTask()
{
var reader = new StreamReader(Request.Body);
var result = reader.ReadToEndAsync().GetAwaiter().GetResult();
StreamReader reader = new(Request.Body);
string result = reader.ReadToEndAsync().GetAwaiter().GetResult();
if (string.IsNullOrEmpty(result)) return BadRequest(ErrorHandler.BadData());
var filehash = await ImageProcessing.GetFileHash(result);
MediaPredictionData data = new MediaPredictionData(filehash);
if (data.TryLoadData(out var knownResult))
string filehash = await ImageProcessing.GetFileHash(result);
MediaPredictionData data = new(filehash);
if (data.TryLoadData(out MediaData knownResult))
{
return JsonConvert.SerializeObject(knownResult);
}


var image = ImageProcessing.DownloadFile(result);
FileInfo? image = ImageProcessing.DownloadFile(result);
// Add input data
var input = new ModelInput
ModelInput input = new()
{
ImageSource = image.FullName
ImageSource = image?.FullName
};
// Load model and predict output of sample data
ConsumeModel.Predict(input, out var labelResult);
ConsumeModel.Predict(input, out OutputProperties labelResult);

var predictionData = new MediaData()
MediaData predictionData = new()
{
DetectedLabels = labelResult
};

data.Data = predictionData;
image.Delete();
image?.Delete();
//scanFile.Dispose();
// Create the response
return JsonConvert.SerializeObject(labelResult);
Expand Down
19 changes: 8 additions & 11 deletions Pamaxie.Api/Data/ErrorHandler.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;

namespace PamaxieML.Api.Data
namespace PamaxieML.Api.Data
{
public class ErrorHandler
public static class ErrorHandler
{
public static string Deleted()
{
Expand Down Expand Up @@ -43,11 +40,11 @@ public static string InvalidToken()
public static string UserNotFound()
{
return "User or Guild could not be found";
}

internal static string InvalidFormat()
{
return "Image format of sent url is not supported. Please check the documentation for supported file types for image scans.";
}
}

internal static string InvalidFormat()
{
return "Image format of sent url is not supported. Please check the documentation for supported file types for image scans.";
}
}
}
Loading

0 comments on commit 27d2577

Please sign in to comment.