Skip to content

Commit

Permalink
Implemented comments and suggestions
Browse files Browse the repository at this point in the history
  • Loading branch information
mazumdes committed Feb 3, 2022
1 parent dc9ce87 commit d37d4a4
Show file tree
Hide file tree
Showing 11 changed files with 459 additions and 7 deletions.
197 changes: 197 additions & 0 deletions Library.Encyclopedia.API/Controllers/CommentController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
using Library.Encyclopedia.DataAccess;
using Library.Encyclopedia.DataAccess.DataAccess;
using Library.Encyclopedia.Entity.Interfaces;
using Library.Encyclopedia.Entity.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
using System.Linq;
using System.Threading.Tasks;

namespace Library.Encyclopedia.API.Controllers
{
[ApiController]
[Route("[controller]")]
public class CommentController : ControllerBase
{
private readonly ILogger<CommentController> _logger;
private readonly ICommentsDataAccess dataAccess;
private readonly ILikesDataAccess likesDataAccess;

public CommentController(ILogger<CommentController> logger, IApplicationDbContext dbContext)
{
this._logger = logger;
dataAccess = new CommentsDataAccess(dbContext);
likesDataAccess = new LikesDataAccess(dbContext);
}

[HttpGet]
[Authorize(Roles = @"EncyclopediaAdministrators")]
public async Task<IActionResult> Get(int offset = 0, int limit = 10, bool asc = false)
{
try
{
var result = await dataAccess.Get(offset, limit, asc);
var likes = await likesDataAccess.GetLikes(result.Result.Select(s => s.Id).ToList());

if (likes != null)
{
foreach (var item in result.Result)
item.Likes = likes.ContainsKey(item.Id) ? likes[item.Id] : 0;
}

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

[HttpPost("Resolve/{id}")]
[Authorize(Roles = @"EncyclopediaAdministrators")]
public async Task<IActionResult> ResolveComment(Guid id, bool flag = true)
{
try
{
await dataAccess.Resolve(id, flag);

return Ok();
}
catch (Exception ex)
{
_logger.LogError(ex, $"an error has occured {ex.Message}");
throw;
}
}

[HttpGet("{id}")]
public async Task<IActionResult> Get(Guid id)
{
try
{
var result = await dataAccess.Get(id);
var likes = await likesDataAccess.GetLikes(result.Select(s => s.Id).ToList());

if (likes != null)
{
foreach (var item in result)
item.Likes = likes.ContainsKey(item.Id) ? likes[item.Id] : 0;
}

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

[HttpPost]
[Authorize]
public async Task<IActionResult> Post([FromBody]Comments comments)
{
try
{
using (var context = new PrincipalContext(ContextType.Domain | ContextType.Machine))
{
var usr = UserPrincipal.FindByIdentity(context, this.HttpContext.User.Identity.Name);
comments.UserName = usr.DisplayName;
comments.UserSid = usr.Sid.Value;

var result = await dataAccess.CreateComment(comments);

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

[HttpDelete("{id}")]
[Authorize]
public async Task<IActionResult> Delete(Guid id)
{
try
{
using (var context = new PrincipalContext(ContextType.Domain | ContextType.Machine))
{
var usr = UserPrincipal.FindByIdentity(context, this.HttpContext.User.Identity.Name);

if (usr.GetAuthorizationGroups().Select(s => s.Name).Contains("EncyclopediaAdministrators"))
await dataAccess.DeleteComment(id, string.Empty, true);
else
await dataAccess.DeleteComment(id, usr.Sid.Value);

return Ok();
}
}
catch (Exception ex)
{
_logger.LogError(ex, $"an error has occured {ex.Message}");
throw;
}
}

[HttpPut("{id}")]
[Authorize]
public async Task<IActionResult> Update(Guid id, string comment)
{
try
{
using (var context = new PrincipalContext(ContextType.Domain | ContextType.Machine))
{
var usr = UserPrincipal.FindByIdentity(context, this.HttpContext.User.Identity.Name);

await dataAccess.UpdateComment(id, comment, usr.Sid.Value);

return Ok();
}
}
catch (Exception ex)
{
_logger.LogError(ex, $"an error has occured {ex.Message}");
throw;
}
}

[HttpPost("Like/{id}")]
[Authorize]
public async Task<IActionResult> LikeComment(Guid id, bool flag = true)
{
try
{
using (var context = new PrincipalContext(ContextType.Domain | ContextType.Machine))
{
var usr = UserPrincipal.FindByIdentity(context, this.HttpContext.User.Identity.Name);

await likesDataAccess.Like(id, usr.Sid.Value, flag);

return Ok();
}
}
catch (Exception ex)
{
_logger.LogError(ex, $"an error has occured {ex.Message}");
throw;
}
}
}
}
7 changes: 2 additions & 5 deletions Library.Encyclopedia.DataAccess/ApplicationDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,12 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
public DbSet<Files> Files { get; set; }
public DbSet<Links> Links { get; set; }
public DbSet<QueryStats> QueryStats { get; set; }
public DbSet<Comments> Comments { get; set; }
public DbSet<Likes> Likes { get; set; }

public new async Task<int> SaveChanges()
{
return await base.SaveChangesAsync();
}

public async Task<IDbContextTransaction> BeginTransactionAsync()
{
return await base.Database.BeginTransactionAsync();
}
}
}
106 changes: 106 additions & 0 deletions Library.Encyclopedia.DataAccess/DataAccess/CommentsDataAccess.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
using Library.Encyclopedia.Entity.Interfaces;
using Library.Encyclopedia.Entity.Models;
using Library.Encyclopedia.Entity.Models.External;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Library.Encyclopedia.DataAccess.DataAccess
{
public class CommentsDataAccess : ICommentsDataAccess
{
private readonly IApplicationDbContext dbContext;

public CommentsDataAccess(IApplicationDbContext dbContext)
{
this.dbContext = dbContext;
}

public async Task<Comments> CreateComment(Comments comments)
{
comments.Id = Guid.NewGuid();
comments.PostedTime = DateTime.Now;

await dbContext.Comments.AddAsync(comments);
await dbContext.SaveChanges();

return comments;
}

public async Task DeleteComment(Guid id, string userSid, bool isAdmin = false)
{
var item = await dbContext.Comments.FirstOrDefaultAsync(s => s.Id == id);

if (item != null)
{
if (!isAdmin)
{
if (item.UserSid == userSid)
{
dbContext.Comments.Remove(item);
dbContext.Likes.RemoveRange(await dbContext.Likes.Where(s=>s.CommentId == item.Id).ToListAsync());
await dbContext.SaveChanges();
}
else
throw new Exception("This user did not post this comment!");
}
else
{
dbContext.Comments.Remove(item);
dbContext.Likes.RemoveRange(await dbContext.Likes.Where(s => s.CommentId == item.Id).ToListAsync());
await dbContext.SaveChanges();
}
}
else
throw new Exception("Comment not found!");
}

public async Task<CommentsExternalCollection> Get(int offset = 0, int limit = 10, bool asc = false)
{
if(asc)
return new CommentsExternalCollection(await dbContext.Comments.OrderBy(s => s.PostedTime).Skip(offset).Take(limit).ToListAsync(), await dbContext.Comments.CountAsync());
else
return new CommentsExternalCollection(await dbContext.Comments.OrderByDescending(s => s.PostedTime).Skip(offset).Take(limit).ToListAsync(), await dbContext.Comments.CountAsync());
}

public async Task<IEnumerable<Comments>> Get(Guid mainId)
{
return await dbContext.Comments.Where(s => s.MainId == mainId).OrderByDescending(s => s.PostedTime).ToListAsync();
}

public async Task Resolve(Guid id, bool flag = true)
{
var comment = await dbContext.Comments.FirstOrDefaultAsync(s => s.Id == id);

if(comment != null)
{
comment.IsResolved = flag;
dbContext.Comments.Update(comment);
await dbContext.SaveChanges();
}
}

public async Task UpdateComment(Guid id, string comment, string userSid)
{
var commentObj = await dbContext.Comments.FirstOrDefaultAsync(s => s.Id == id);

if (commentObj != null)
{
if (commentObj.UserSid == userSid)
{
commentObj.Comment = comment;
dbContext.Comments.Update(commentObj);
await dbContext.SaveChanges();
}
else
throw new Exception("This user did not post this comment!");
}
else
throw new Exception("Comment not found!");

}
}
}
54 changes: 54 additions & 0 deletions Library.Encyclopedia.DataAccess/DataAccess/LikesDataAccess.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using Library.Encyclopedia.Entity.Interfaces;
using Library.Encyclopedia.Entity.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Library.Encyclopedia.DataAccess.DataAccess
{
public class LikesDataAccess : ILikesDataAccess
{
private readonly IApplicationDbContext dbContext;

public LikesDataAccess(IApplicationDbContext dbContext)
{
this.dbContext = dbContext;
}

public Task DeleteLikes(List<Guid> commentIds)
{
throw new NotImplementedException();
}

public async Task<Dictionary<Guid, long>> GetLikes(List<Guid> commentIds)
{
return (await dbContext.Likes.Where(s => commentIds.Contains(s.CommentId)).ToListAsync()).GroupBy(s => s.CommentId).ToDictionary(s => s.Key, s => s.LongCount());
}

public async Task Like(Guid commentId, string userSid, bool flag = true)
{
var result = await dbContext.Likes.FirstOrDefaultAsync(s => s.CommentId == commentId && s.UserSid == userSid);
if (result != null)
{
// if disliked
if (!flag)
{
dbContext.Likes.Remove(result);
await dbContext.SaveChanges();
}
else throw new Exception("Already Liked");
}
else
{
if (flag)
{
await dbContext.Likes.AddAsync(new Likes { CommentId = commentId, UserSid = userSid });
await dbContext.SaveChanges();
}
}
}
}
}
Loading

0 comments on commit d37d4a4

Please sign in to comment.