Skip to content

Commit

Permalink
ANA August Update
Browse files Browse the repository at this point in the history
  • Loading branch information
NizamLZ committed Aug 18, 2017
2 parents 331e52e + 834aa0d commit d566ed2
Show file tree
Hide file tree
Showing 113 changed files with 4,388 additions and 2,449 deletions.
38 changes: 38 additions & 0 deletions ANAConversationPlatform/Attributes/BasicAuthenticationAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using ANAConversationPlatform.Helpers;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ANAConversationPlatform.Attributes
{
public class BasicAuthenticationAttribute : ActionFilterAttribute
{
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
if (Utils.BasicAuth == null || string.IsNullOrWhiteSpace(Utils.BasicAuth.APIKey) || string.IsNullOrWhiteSpace(Utils.BasicAuth.APISecret))
{
await next();
return;
}

var headers = context.HttpContext.Request.Headers;
var authHeader = headers["Authorization"].FirstOrDefault();
if (string.IsNullOrWhiteSpace(authHeader))
{
context.HttpContext.Response.StatusCode = 401;
return;
}
var savedAuthBase64 = Utils.BasicAuth.GetBase64();
var givenAuthBase64 = authHeader.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries).Skip(1).FirstOrDefault()?.Trim();
if (givenAuthBase64 != savedAuthBase64)
{
context.HttpContext.Response.StatusCode = 401;
return;
}
await next();
}
}
}
13 changes: 3 additions & 10 deletions ANAConversationPlatform/Controllers/ActivityController.cs
Original file line number Diff line number Diff line change
@@ -1,24 +1,17 @@
using Microsoft.AspNetCore.Mvc;
using ANAConversationPlatform.Models.Activity;
using ANAConversationPlatform.Helpers;
using System.Threading.Tasks;

namespace ANAConversationPlatform.Controllers
{
[Produces("application/json")]
public class ActivityController : Controller
{
[HttpGet]
public ActionResult Summary(string nodeIds)
{
var nodeIdList = nodeIds.Split(',');

return Ok(new { Message = "Done" });
}

[HttpPost]
public ActionResult Track([FromBody]ChatActivityEvent activityEvent)
public async Task<ActionResult> Track([FromBody]ChatActivityEvent activityEvent)
{
MongoHelper.InsertActivityEvent(activityEvent);
await MongoHelper.InsertActivityEventAsync(activityEvent);
return Ok();
}
}
Expand Down
2 changes: 1 addition & 1 deletion ANAConversationPlatform/Controllers/AgentChatController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public async Task<ActionResult> UserInput(string CHAT_USER_ID, string CHAT_USER_
public async Task<ActionResult> SubmitHistory([FromBody]SubmitChatHistoryModel history)
{
if (string.IsNullOrWhiteSpace(history.CHAT_USER_ID) || string.IsNullOrWhiteSpace(history.CHAT_USER_TOKEN))
return BadRequest("Empty chat user id or chat user token");
return BadRequest(new { Message = "Empty chat user id or chat user token" });
if (history == null || history.HISTORY == null || history.HISTORY.Count <= 0)
return Ok();

Expand Down
91 changes: 59 additions & 32 deletions ANAConversationPlatform/Controllers/ConversationController.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using ANAConversationPlatform.Helpers;
using System.Diagnostics;
using MongoDB.Bson;
using Newtonsoft.Json;
using ANAConversationPlatform.Models;
using ANAConversationPlatform.Models.Sections;
using Microsoft.Extensions.Logging;
using static ANAConversationPlatform.Helpers.Constants;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using System.IO;
using ANAConversationPlatform.Attributes;

namespace ANAConversationPlatform.Controllers
{
Expand All @@ -22,19 +24,30 @@ public ConversationController(ILogger<ConversationController> log)
}

[HttpGet]
public ActionResult Chat()
public async Task<ActionResult> Chat([FromQuery]string projectId = null, [FromQuery]string projectName = null, [FromQuery]bool enableAgentChat = true)
{
try
{
var chatNodes = MongoHelper.RetrieveRecordsFromChatNode();
if (string.IsNullOrWhiteSpace(projectId) && string.IsNullOrWhiteSpace(projectName))
return BadRequest(new { Message = "Either project id or project name has to be provided" });

ChatFlowPack chatFlowPack = null;
if (!string.IsNullOrWhiteSpace(projectId))
chatFlowPack = await MongoHelper.GetChatFlowPackAsync(projectId);
else if (!string.IsNullOrWhiteSpace(projectName))
chatFlowPack = await MongoHelper.GetChatFlowPackByProjectNameAsync(projectName);

if (chatFlowPack == null)
return BadRequest(new { Message = "No chat flow found by the given project id or name" });

var chatNodes = ChatFlowBuilder.Build(chatFlowPack);
if (chatNodes == null || chatNodes.Count == 0)
return Ok(new object[] { });

return Json(chatNodes, new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore,
Converters = new List<JsonConverter> { new CustomStringEnumConverter() }
});
if (enableAgentChat)
AddAgentChatNodes(chatNodes);

return Json(chatNodes, PublishJsonSettings);
}
catch (System.Exception ex)
{
Expand All @@ -44,20 +57,49 @@ public ActionResult Chat()
}

[HttpGet]
public ActionResult RefreshContent()
public ActionResult HybridChat()
{
MongoHelper.RefreshContentInMemory();
return Ok(new { Message = "Done" });
return RedirectToAction(nameof(Chat));
}

[HttpGet]
public ActionResult HybridChat()
[Produces("text/plain"), HttpPost, BasicAuthentication]
public async Task<ActionResult> SaveChatFlow()
{
try
{
var chatNodes = MongoHelper.RetrieveRecordsFromChatNode();
ChatFlowPack req = null;
using (var s = new StreamReader(Request.Body))
req = BsonSerializer.Deserialize<ChatFlowPack>(s.ReadToEnd());

if (req == null)
return BadRequest(new { Message = "No chat flow received to save!" });

var saved = await MongoHelper.SaveChatFlowAsync(req);
if (saved)
return Content(new { Message = "Chat flow saved", Data = req }.ToJson(), "text/plain");
}
catch (System.Exception ex)
{
return BadRequest(new { Message = "Unable to save chat flow!. Ex: " + ex.Message });
}
return BadRequest(new { Message = "Unable to save chat flow!" });
}

[Produces("text/plain"), HttpGet, BasicAuthentication]
public async Task<ActionResult> FetchChatFlow([FromQuery] string projectId)
{
if (string.IsNullOrWhiteSpace(projectId))
return BadRequest(new { Message = "Project Id is not provided!" });

var proj = await MongoHelper.GetChatFlowPackAsync(projectId);
if (proj != null)
return Content(new { Message = "Fetched", Data = proj }.ToJson(), "text/plain");
return BadRequest(new { Message = "Project with the given id was not found or could not be retrieved!" });
}

chatNodes.AddRange(new[]
private void AddAgentChatNodes(List<ChatNode> chatNodes)
{
chatNodes.AddRange(new[]
{
new ChatNode("INIT_CHAT_NODE")
{
Expand Down Expand Up @@ -115,21 +157,6 @@ public ActionResult HybridChat()
VariableName = "TEXT"
}
});

if (chatNodes == null || chatNodes.Count == 0)
return Ok(new object[] { });

return Json(chatNodes, new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore,
Converters = new List<JsonConverter> { new CustomStringEnumConverter() }
});
}
catch (System.Exception ex)
{
_log.LogError(new EventId((int)LoggerEventId.HYBRID_CHAT_ACTION_ERROR), ex, ex.Message);
return StatusCode(500, new { Message = ex.Message });
}
}
}
}
32 changes: 32 additions & 0 deletions ANAConversationPlatform/Controllers/ProjectController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using ANAConversationPlatform.Helpers;
using ANAConversationPlatform.Models;
using System.Collections.Generic;
using ANAConversationPlatform.Attributes;

namespace ANAConversationPlatform.Controllers
{
[Produces("application/json"), BasicAuthentication]
public class ProjectController : Controller
{
[HttpGet]
public async Task<ActionResult> List()
{
var projs = await MongoHelper.GetProjectsAsync();
if (projs != null)
return Json(new { Message = "Projects list", Data = projs });
return BadRequest(new { Message = "Unable to list the projects!" });
}

[HttpPost]
public ActionResult Save([FromBody] List<ANAProject> projects)
{
var projs = MongoHelper.SaveProjects(projects);
if (projs != null)
return Ok(new { Message = "Saved", Data = projects });

return BadRequest(new { Message = "Unable to save!" });
}
}
}
6 changes: 3 additions & 3 deletions ANAConversationPlatform/Controllers/ServicesController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,21 @@ public ServicesController(IHostingEnvironment env)
[HttpPost]
public ActionResult ReceiveFile(string fileName)
{
if (string.IsNullOrWhiteSpace(fileName)) return BadRequest("fileName cannot be empty");
if (string.IsNullOrWhiteSpace(fileName)) return BadRequest(new { Message = "fileName cannot be empty" });

fileName = Path.GetFileNameWithoutExtension(fileName) + "-" + Guid.NewGuid() + Path.GetExtension(fileName);

using (var fileStream = Request.Body)
{
if (fileStream == null)
return BadRequest("Unable to read file content");
return BadRequest(new { Message = "Unable to read file content" });

var fullFileName = Path.Combine(_env.WebRootPath, Constants.CHAT_MEDIA_FOLDER_NAME, fileName);
var done = FileSaveHelper.Save(fullFileName, fileStream);
if (done)
return Ok(new { Url = $"{Request.Scheme}://{Request.Host}/{Constants.CHAT_MEDIA_FOLDER_NAME}/{fileName}" });
else
return StatusCode(500, "Unable to save received file");
return StatusCode(500, "Unable to save received file");
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public ActionResult Latest()
});
}
}
return BadRequest("Studio Distribution Status Unknown");
return BadRequest(new { Message = "Studio Distribution Status Unknown" });
}

[HttpGet]
Expand Down
Loading

0 comments on commit d566ed2

Please sign in to comment.