Skip to content

Commit

Permalink
Preview Files
Browse files Browse the repository at this point in the history
  • Loading branch information
mazumdes committed Feb 1, 2022
1 parent b9b2f42 commit d58d681
Show file tree
Hide file tree
Showing 8 changed files with 165 additions and 48 deletions.
4 changes: 4 additions & 0 deletions Library.Encyclopedia.API/Attributes/ApiKeyAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@

namespace Library.Encyclopedia.API.Attributes
{
/// <summary>
/// This is a custom attribute for API Kay validation
/// Extracts API key from the header and then checks it with the API KEY hardcoded in appsettings
/// </summary>
[AttributeUsage(validOn: AttributeTargets.Class | AttributeTargets.Method)]
public class ApiKeyAttribute : Attribute, IAsyncActionFilter
{
Expand Down
84 changes: 52 additions & 32 deletions Library.Encyclopedia.API/Controllers/EncylopediaController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,26 +14,37 @@
namespace Library.Encyclopedia.Controllers
{
/// <summary>
/// CRUD operations on Main Table
/// Controller to perform CRUD operations on Main Table
/// </summary>
[ApiController]
[Route("[controller]")]
public class EncylopediaController : ControllerBase
{
#region PRIVATE FIELDS
private readonly ILogger<EncylopediaController> _logger;
private readonly IMainDataAccess mainDataAccess;
#endregion

#region CONSTRUCTOR
/// <summary>
/// Constructor
/// Contructor for EncylopediaController
/// </summary>
/// <param name="logger"></param>
/// <param name="dbContext"></param>
/// <param name="logger">logger instance</param>
/// <param name="dbContext">db instance</param>
/// <param name="configuration">appsettings configuration</param>
/// <param name="filesAdapter">file upload/download/delete layer</param>
public EncylopediaController(ILogger<EncylopediaController> logger, IApplicationDbContext dbContext, IConfiguration configuration, IFilesAdapter filesAdapter)
{
_logger = logger;
this.mainDataAccess = new MainDataAccess(dbContext, configuration, filesAdapter);
}
}
#endregion

#region LOGIN
/// <summary>
/// Login to perform POST/PUT/DELETE operations on the database
/// </summary>
/// <returns></returns>
[HttpGet("Login")]
[Authorize(Roles = @"EncyclopediaAdministrators")]
public IActionResult Login()
Expand All @@ -53,7 +64,9 @@ public IActionResult Login()
throw;
}
}
#endregion

#region GET
/// <summary>
/// Get all items based on search query
/// </summary>
Expand Down Expand Up @@ -185,21 +198,19 @@ public async Task<IActionResult> Get(Guid id)
}

/// <summary>
/// Create new entry
/// Get all categories
/// </summary>
/// <returns></returns>
[HttpPost]
//[ApiKey]
[Authorize(Roles = @"EncyclopediaAdministrators")]
public async Task<IActionResult> Create([FromBody]Main model)
[HttpGet("fetchallcategories")]
public async Task<IActionResult> GetAllCategories()
{
try
{
var response = await mainDataAccess.CreateAsync(model);
var response = await mainDataAccess.GetAllCategoriesAsync();

if (response == null)
{
return StatusCode(500);
return StatusCode(204);
}
else
{
Expand All @@ -212,19 +223,21 @@ public async Task<IActionResult> Create([FromBody]Main model)
throw;
}
}
#endregion

#region POST
/// <summary>
/// Create new entry
/// </summary>
/// <returns></returns>
[HttpPut("{id}")]
[HttpPost]
//[ApiKey]
[Authorize(Roles = @"EncyclopediaAdministrators")]
public async Task<IActionResult> Update(Guid id, [FromBody]MainUpdateModel model)
public async Task<IActionResult> Create([FromBody]Main model)
{
try
{
var response = await mainDataAccess.UpdateAsync(id, model);
var response = await mainDataAccess.CreateAsync(model);

if (response == null)
{
Expand All @@ -241,54 +254,61 @@ public async Task<IActionResult> Update(Guid id, [FromBody]MainUpdateModel model
throw;
}
}
#endregion

#region PUT
/// <summary>
/// Create new entry
/// </summary>
/// <returns></returns>
[HttpDelete("{id}")]
[HttpPut("{id}")]
//[ApiKey]
[Authorize(Roles = @"EncyclopediaAdministrators")]
public async Task<IActionResult> Delete(Guid id)
public async Task<IActionResult> Update(Guid id, [FromBody]MainUpdateModel model)
{
try
{
await mainDataAccess.DeleteAsync(id);
var response = await mainDataAccess.UpdateAsync(id, model);

return Ok();
if (response == null)
{
return StatusCode(500);
}
else
{
return Ok(response);
}
}
catch (Exception ex)
{
_logger.LogError(ex, $"an error has occured {ex.Message}");
throw;
}
}
#endregion

#region DELETE
/// <summary>
/// Get all categories
/// Create new entry
/// </summary>
/// <returns></returns>
[HttpGet("fetchallcategories")]
public async Task<IActionResult> GetAllCategories()
[HttpDelete("{id}")]
//[ApiKey]
[Authorize(Roles = @"EncyclopediaAdministrators")]
public async Task<IActionResult> Delete(Guid id)
{
try
{
var response = await mainDataAccess.GetAllCategoriesAsync();
await mainDataAccess.DeleteAsync(id);

if (response == null)
{
return StatusCode(204);
}
else
{
return Ok(response);
}
return Ok();
}
catch (Exception ex)
{
_logger.LogError(ex, $"an error has occured {ex.Message}");
throw;
}
}
}
#endregion
}
}
56 changes: 54 additions & 2 deletions Library.Encyclopedia.API/Controllers/FilesController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
Expand All @@ -21,12 +22,14 @@ public class FilesController : ControllerBase
{
private readonly ILogger<FilesController> _logger;
private readonly IFilesAdapter filesAdapter;
private readonly IConfiguration configuration;
private readonly IFilesDataAccess filesDataAccess;

public FilesController(ILogger<FilesController> logger, IApplicationDbContext dbContext, IFilesAdapter filesAdapter)
public FilesController(ILogger<FilesController> logger, IApplicationDbContext dbContext, IFilesAdapter filesAdapter, IConfiguration configuration)
{
_logger = logger;
this.filesAdapter = filesAdapter;
this.configuration = configuration;
this.filesDataAccess = new FilesDataAccess(dbContext);
}

Expand Down Expand Up @@ -77,7 +80,7 @@ public async Task<IActionResult> Post(Guid id, IFormFile file, string descriptio
}

/// <summary>
/// Upload Files
/// Download Files
/// </summary>
/// <param name="query"></param>
/// <param name="offset"></param>
Expand All @@ -100,6 +103,55 @@ public IActionResult Get(string id, string name, string contentType)
}
}

/// <summary>
/// Create Viewable link
/// </summary>
/// <param name="query"></param>
/// <param name="offset"></param>
/// <param name="size"></param>
/// <param name="asc"></param>
/// <returns></returns>
[HttpGet("CreateViewableLink/{id}")]
[Authorize(Roles = @"EncyclopediaAdministrators")]
public IActionResult CreateViewableLink(string id, string name)
{
try
{
this.filesAdapter.CreateViewableLink(id, name);
var baseUrl = configuration.GetSection("TempAssetsBaseUrl").Value;
return Ok(baseUrl + '/' + id + '/' + name);
}
catch (Exception ex)
{
_logger.LogError(ex, $"an error has occured {ex.Message}");
throw;
}
}

/// <summary>
/// Destroy Viewable link
/// </summary>
/// <param name="query"></param>
/// <param name="offset"></param>
/// <param name="size"></param>
/// <param name="asc"></param>
/// <returns></returns>
[HttpDelete("DestroyViewableLink/{id}")]
[Authorize(Roles = @"EncyclopediaAdministrators")]
public IActionResult DestroyViewableLink(string id, string name)
{
try
{
this.filesAdapter.DestroyViewableLink(id, name);
return Ok();
}
catch (Exception ex)
{
_logger.LogError(ex, $"an error has occured {ex.Message}");
throw;
}
}

/// <summary>
/// Delete File
/// </summary>
Expand Down
10 changes: 6 additions & 4 deletions Library.Encyclopedia.API/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,24 +46,26 @@ public void ConfigureServices(IServiceCollection services)
string userName = Configuration.GetValue<string>("FileAdapterSettings:username");
string password = Configuration.GetValue<string>("FileAdapterSettings:password");
string basePath = Configuration.GetValue<string>("FileAdapterSettings:basePath");
string tempAssetsFilePath = Configuration.GetValue<string>("TempAssetsLocation");

services.AddSingleton<IFilesAdapter>(s =>
{
return new LinuxFileSaveAdapter(url, userName, password, basePath);
return new LinuxFileSaveAdapter(url, userName, password, basePath, tempAssetsFilePath);
});
}
else if(Configuration.GetValue<string>("FileAdapterSettings:type").Equals("windows", System.StringComparison.OrdinalIgnoreCase))
else if (Configuration.GetValue<string>("FileAdapterSettings:type").Equals("windows", System.StringComparison.OrdinalIgnoreCase))
{
string filePath = Configuration.GetValue<string>("FileAdapterSettings:filePath");
string tempAssetsFilePath = Configuration.GetValue<string>("TempAssetsLocation");

services.AddSingleton<IFilesAdapter>(s =>
{
return new WindowsFileSaveAdapter(filePath);
return new WindowsFileSaveAdapter(filePath, tempAssetsFilePath);
});
}

services.AddScoped<IApplicationDbContext>(s => new ApplicationDbContext(Configuration.GetConnectionString("DefaultConnection")));

services.Configure<FormOptions>(x =>
{
x.ValueLengthLimit = int.MaxValue;
Expand Down
14 changes: 8 additions & 6 deletions Library.Encyclopedia.API/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,19 @@
"DefaultConnection": "Server=localhost;Database=Encyclopedia;User=root;Password=RW_qh+-ta5hW*2s"
},
"ApiKey": "5929b003-8895-4fb3-bbb0-2eb101c48f66",
"TempAssetsBaseUrl": "https://tools.library.pfw.edu/encyclopedia/pfwencyclopediaassets",
"TempAssetsLocation": "C:\\inetpub\\wwwroot\\pfwencyclopediaassets",
"FileAdapterSettings": {
// linux or windows
"type": "linux",
"type": "windows",

// For Linux
"url": "10.161.100.82",
"username": "serviceuser",
"password": "P!ssword+007",
"basePath": "Applications/PFW Encyclopedia Files"
//"url": "10.161.100.82",
//"username": "serviceuser",
//"password": "P!ssword+007",
//"basePath": "Applications/PFW Encyclopedia Files"

// For Windows
//"filePath": "C:\\inetpub\\wwwroot\\PFW Encyclopedia Files\\"
"filePath": "C:\\inetpub\\wwwroot\\PFW Encyclopedia Files\\"
}
}
23 changes: 21 additions & 2 deletions Library.Encyclopedia.DataAccess/FileAccess/LinuxFileSaveAdapter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,33 @@ public class LinuxFileSaveAdapter : IFilesAdapter, IDisposable
{
private readonly string url;
private readonly string basePath;
private readonly string tempAssetsFilePath;
private readonly NetworkCredential networkCredential;
private SftpClient client;

public LinuxFileSaveAdapter(string url, string userName, string password, string basePath)
public LinuxFileSaveAdapter(string url, string userName, string password, string basePath, string tempAssetsFilePath)
{
this.url = url;
this.basePath = basePath;
this.tempAssetsFilePath = tempAssetsFilePath;
this.networkCredential = new NetworkCredential(userName, password);

client = new SftpClient(url, 22, networkCredential.UserName, networkCredential.Password);
client.Connect();
}

public void CreateViewableLink(string id, string name)
{
if (!Directory.Exists(Path.Combine(tempAssetsFilePath, id)))
Directory.CreateDirectory(Path.Combine(tempAssetsFilePath, id));

var remotePath = $@"/home/{networkCredential.UserName}/" + basePath + '/' + id.ToString() + '/' + name;
using (Stream fileStream = File.Create(Path.Combine(tempAssetsFilePath, id, name)))
{
client.DownloadFile(remotePath, fileStream);
}
}

public void DeleteFile(string id, string name)
{
var completeUrl = $@"/home/{networkCredential.UserName}/" + basePath + '/' + id.ToString() + '/' + name;
Expand All @@ -47,14 +61,19 @@ public void DeleteFiles(string id)
{
if (file.Name != "." && file.Name != "..")
{
client.DeleteFile(file.FullName);
client.DeleteFile(file.FullName);
}
}

client.DeleteDirectory(completeUrl);
}
}

public void DestroyViewableLink(string id, string name)
{
File.Delete(Path.Combine(tempAssetsFilePath, id, name));
}

public void Dispose()
{
this.client.Disconnect();
Expand Down
Loading

0 comments on commit d58d681

Please sign in to comment.