Skip to content

Commit

Permalink
File upload implemented
Browse files Browse the repository at this point in the history
  • Loading branch information
mazumdes committed Jan 26, 2022
1 parent 5610b64 commit ba2625f
Show file tree
Hide file tree
Showing 9 changed files with 162 additions and 121 deletions.
6 changes: 2 additions & 4 deletions Library.Encyclopedia.API/Controllers/EncylopediaController.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
using Library.Encyclopedia.API.Attributes;
using Library.Encyclopedia.DataAccess;
using Library.Encyclopedia.DataAccess;
using Library.Encyclopedia.DataAccess.DataAccess;
using Library.Encyclopedia.Entity.Interfaces;
using Library.Encyclopedia.Entity.Models;
using Library.Encyclopedia.Entity.Models.External;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
using System.Threading.Tasks;

Expand Down Expand Up @@ -45,6 +42,7 @@ public IActionResult Login()
{
using (var context = new PrincipalContext(ContextType.Domain | ContextType.Machine))
{

var usr = UserPrincipal.FindByIdentity(context, this.HttpContext.User.Identity.Name);
return Ok(usr.DisplayName);
}
Expand Down
49 changes: 22 additions & 27 deletions Library.Encyclopedia.API/Controllers/FilesController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using Library.Encyclopedia.DataAccess.DataAccess;
using Library.Encyclopedia.Entity.Interfaces;
using Library.Encyclopedia.Entity.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
Expand Down Expand Up @@ -38,38 +39,34 @@ public FilesController(ILogger<FilesController> logger, IApplicationDbContext db
/// <param name="asc"></param>
/// <returns></returns>
[HttpPost("{id}")]
[ApiKey]
public async Task<IActionResult> Post(Guid id, List<IFormFile> files, [FromForm] Dictionary<string, string> descriptions)
[Authorize(Roles = @"EncyclopediaAdministrators")]
public async Task<IActionResult> Post(Guid id, IFormFile file, string description)
{
try
{
// Store files at remote location
var responses = filesAdapter.UploadFiles(id, files);
var response = await filesAdapter.UploadFile(id, file);

List<Files> fileResponses = new List<Files>();

// filter out the failed uploads
for (int i = 0; i < responses.Count(); i++)
if (response)
{
if (responses.ToList()[i])
string fileNameWithoutExt = Path.GetFileNameWithoutExtension(file.FileName);
Files file_entry = new Files
{
string fileNameWithoutExt = Path.GetFileNameWithoutExtension(files[i].FileName);
fileResponses.Add(new Files
{
Id = Guid.NewGuid(),
MainId = id,
FileName = files[i].FileName,
FilePath = $@"/encyclopedia-media/{id}/{files[i].FileName}",
FileType = files[i].ContentType,
FileDescription = descriptions.ContainsKey(fileNameWithoutExt) ? descriptions[fileNameWithoutExt] : null
});
}
}
Id = Guid.NewGuid(),
MainId = id,
FileName = file.FileName,
FilePath = $@"/{id}/{file.FileName}",
FileType = file.ContentType,
FileDescription = description
};

// Save to database
await filesDataAccess.AddFiles(fileResponses);
// Save to database
await filesDataAccess.AddFiles(new List<Files> { file_entry });

return Ok(fileResponses);
return Ok(file_entry);
}
else
return BadRequest();
}
catch (Exception ex)
{
Expand All @@ -87,14 +84,12 @@ public async Task<IActionResult> Post(Guid id, List<IFormFile> files, [FromForm]
/// <param name="asc"></param>
/// <returns></returns>
[HttpGet("{id}")]
[ApiKey]
[Authorize(Roles = @"EncyclopediaAdministrators")]
public async Task<IActionResult> Get(Guid id, string directory)
{
try
{
var files = await filesDataAccess.GetFiles(id);
var fileResponses = filesAdapter.DownloadFiles(files, directory);
return Ok(fileResponses);
return Ok();
}
catch (Exception ex)
{
Expand Down
12 changes: 10 additions & 2 deletions Library.Encyclopedia.API/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using Library.Encyclopedia.Entity.Interfaces;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Server.IISIntegration;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
Expand Down Expand Up @@ -38,14 +39,21 @@ public void ConfigureServices(IServiceCollection services)

services.AddControllers();

string url = Configuration.GetValue<string>("FTPSettings:url");
string url = Configuration.GetValue<string>("FTPSettings:filePath");
string userName = Configuration.GetValue<string>("FTPSettings:username");
string password = Configuration.GetValue<string>("FTPSettings:password");

services.AddScoped<IApplicationDbContext>(s => new ApplicationDbContext(Configuration.GetConnectionString("DefaultConnection")));
services.AddScoped<IFilesAdapter>(s =>
{
return new FTPAdapter(url, new System.Net.NetworkCredential(userName, password));
return new WindowsFileSaveAdapter(url);
});

services.Configure<FormOptions>(x =>
{
x.ValueLengthLimit = int.MaxValue;
x.MultipartBodyLengthLimit = int.MaxValue;
x.MultipartHeadersLengthLimit = int.MaxValue;
});
}

Expand Down
14 changes: 9 additions & 5 deletions Library.Encyclopedia.API/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,17 @@
"App-Base-Url": "https://tools.library.pfw.edu/encyclopedia",
"AllowedHosts": "*",
"ConnectionStrings": {
//"DefaultConnection": "Server=localhost;Database=Encyclopedia;User=root;Password=root"
"DefaultConnection": "Server=localhost;Database=Encyclopedia;User=root;Password=RW_qh+-ta5hW*2s"
"DefaultConnection": "Server=localhost;Database=Encyclopedia;User=root;Password=root"
//"DefaultConnection": "Server=localhost;Database=Encyclopedia;User=root;Password=RW_qh+-ta5hW*2s"
},
"ApiKey": "5929b003-8895-4fb3-bbb0-2eb101c48f66",
"FTPSettings": {
"url": "10.161.100.82",
"username": "mazus01",
"password": ""
// For Linux
//"url": "10.161.100.82",
//"username": "mazus01",
//"password": ""

// For Windows
"filePath": "O:\\Library\\Departments\\Applications\\PFW Encyclopedia Files\\"
}
}
13 changes: 13 additions & 0 deletions Library.Encyclopedia.API/web.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>

<system.webServer>
<security>
<requestFiltering>
<!-- 1 GB -->
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
</system.webServer>

</configuration>
62 changes: 50 additions & 12 deletions Library.Encyclopedia.DataAccess/DataAccess/MainDataAccess.cs
Original file line number Diff line number Diff line change
Expand Up @@ -241,11 +241,13 @@ private Main ReplaceLineBreaks(Main model)
return model;
}

private Main ReplaceInternalLinks(Main model)
private Main ReplaceInternalLinks(Main model, bool isUpdate = false)
{
string searchStartString = "<a href=";
string searchEndString = "</a>";
model.Links = new List<Links>();
model.Links ??= new List<Links>();
var newCreatedLinks = new List<Links>();
var updatedLinks = new List<Links>();

if (model.RichDescription != null)
{
Expand Down Expand Up @@ -283,21 +285,42 @@ private Main ReplaceInternalLinks(Main model)
newDesc = newDesc.Replace(value, $"$$${id}$$$");
newDesc2 = newDesc2.Replace(value, desc);

// add to links list
model.Links.Add(new Links
if (!model.Links.Any(s => s.ReferenceId == Guid.Parse(id)))
{
Id = Guid.NewGuid(),
MainId = model.Id,
ReferenceId = Guid.Parse(id),
Link = value,
Description = desc,
IsInternal = true
});
// add to links list
Links item = new Links
{
Id = Guid.NewGuid(),
MainId = model.Id,
ReferenceId = Guid.Parse(id),
Link = value,
Description = desc,
IsInternal = true
};
model.Links.Add(item);

newCreatedLinks.Add(item);
}
else
{
model.Links.FirstOrDefault(s => s.ReferenceId == Guid.Parse(id)).Link = value;
model.Links.FirstOrDefault(s => s.ReferenceId == Guid.Parse(id)).Description = desc;
updatedLinks.Add(model.Links.FirstOrDefault(s => s.ReferenceId == Guid.Parse(id)));
}

}
}

model.RichDescription = newDesc;
model.RawDescription = newDesc2;

if (isUpdate)
{
_dbcontext.Links.AddRangeAsync(newCreatedLinks);
_dbcontext.Links.UpdateRange(updatedLinks);
_dbcontext.SaveChanges().Wait();
}

}

return model;
Expand All @@ -323,7 +346,7 @@ public async Task<Main> UpdateAsync(Guid id, MainUpdateModel model)

entry.RichDescription = model.RichDescription;

entry = ReplaceInternalLinks(entry);
entry = ReplaceInternalLinks(entry, true);
entry = ReplaceLineBreaks(entry);

//santize data
Expand All @@ -334,6 +357,21 @@ public async Task<Main> UpdateAsync(Guid id, MainUpdateModel model)

_dbcontext.Main.Update(entry);
await _dbcontext.SaveChanges();

if (entry.RichDescription != null)
{
// replace links in item
while (entry.RichDescription.IndexOf("$$$") != -1)
{
var startIndex = entry.RichDescription.IndexOf("$$$") + 3;
var endIndex = entry.RichDescription.Substring(startIndex).IndexOf("$$$");

var referenceid = entry.RichDescription.Substring(startIndex, endIndex);

entry.RichDescription = entry.RichDescription.Replace($"$$${referenceid}$$$", $"<a href=\"{APP_BASE_URL}/{referenceid}\">{entry.Links.FirstOrDefault(s => s.ReferenceId.ToString() == referenceid).Description}</a>");
}
}

return entry;
}
}
Expand Down
69 changes: 0 additions & 69 deletions Library.Encyclopedia.DataAccess/FileAccess/FTPAdapter.cs

This file was deleted.

Loading

0 comments on commit ba2625f

Please sign in to comment.