Skip to content

Commit

Permalink
Implement message deletion
Browse files Browse the repository at this point in the history
  • Loading branch information
marvac committed Mar 4, 2019
1 parent 0f1cce9 commit c29bbfe
Show file tree
Hide file tree
Showing 8 changed files with 85 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,11 @@

</div>
<div class="card-footer">
<form action="">
<form #messageForm="ngForm" (ngSubmit)="messageForm.valid && sendMessage()">
<div class="input-group">
<input type="text" class="form-control input-sm" placeholder="Send a message" />
<input [(ngModel)]="newMessage.content" name="content" type="text" class="form-control input-sm" placeholder="Send a message" required />
<div class="input-group-append">
<button class="btn btn-primary">Send</button>
<button class="btn btn-primary" [disabled]="!messageForm.valid">Send</button>
</div>
</div>
</form>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { AlertifyService } from 'src/app/services/alertify.service';
export class MemberMessagesComponent implements OnInit {
@Input() recipientId: number;
messages: Message[];
newMessage: any = {};

constructor(
private userService: UserService,
Expand All @@ -30,4 +31,11 @@ export class MemberMessagesComponent implements OnInit {
});
}

sendMessage() {
this.newMessage.recipientId = this.recipientId;
this.userService.sendMessage(this.authService.decodedToken.nameid, this.newMessage).subscribe((message: Message) => {
this.messages.unshift(message);
this.newMessage.content = '';
}), error => this.alertify.error(error);
}
}
2 changes: 1 addition & 1 deletion Client/src/app/components/messages/messages.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ <h3>No messages</h3>
</td>
<td>{{message.messageSent | timeAgo}}</td>
<td>
<button class="btn btn-danger">Delete</button>
<button class="btn btn-danger" (click)="$event.stopPropagation();deleteMessage(message.id)">Delete</button>
</td>
</tr>
</table>
Expand Down
12 changes: 12 additions & 0 deletions Client/src/app/components/messages/messages.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,18 @@ export class MessagesComponent implements OnInit {
});
}

deleteMessage(messageId: number) {
this.alertify.confirm("Are you sure you want to delete this message?", () => {
this.userService.deleteMessage(this.authService.decodedToken.nameid, messageId).subscribe(result => {
this.messages.splice(this.messages.findIndex(m => m.id == messageId), 1);
this.alertify.success("Message deleted");
}, error => {
this.alertify.error(error);
});
})

}

pageChanged(event: any): void {
this.pagination.currentPage = event.page;
this.loadMessages;
Expand Down
8 changes: 8 additions & 0 deletions Client/src/app/services/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,4 +92,12 @@ export class UserService {
getMessageThread(userId: number, recipientId: number) {
return this.http.get<Message[]>(`${this.usersUrl}${userId}/messages/thread/${recipientId}`);
}

sendMessage(userId: number, message: Message) {
return this.http.post(`${this.usersUrl}${userId}/messages/`, message);
}

deleteMessage(userId: number, messageId: number) {
return this.http.post(`${this.usersUrl}${userId}/messages/${messageId}`, {});
}
}
53 changes: 42 additions & 11 deletions Controllers/MessagesController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,11 @@ public async Task<IActionResult> GetMessageThread(int userId, int recipientId)
[HttpPost]
public async Task<ActionResult> SendMessage(int userId, SendMessageResource sendMessageResource)
{
var sender = await _repo.GetUser(userId);

int id = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

if (id != userId)
if (id != sender.Id)
{
return Unauthorized();
}
Expand All @@ -109,25 +111,54 @@ public async Task<ActionResult> SendMessage(int userId, SendMessageResource send

var message = _mapper.Map<SendMessageResource, Message>(sendMessageResource);
_repo.Add(message);

if (await _repo.SaveChangesAsync())
{
return CreatedAtRoute(nameof(GetMessage), new { messageId = message.Id }, message);
var messageResource = _mapper.Map<Message, MessageResource>(message);

return CreatedAtRoute(nameof(GetMessage), new { messageId = message.Id }, messageResource);
}

throw new Exception("Failed to save message");
}

//[HttpDelete("{messageId}")]
//public async Task<IActionResult> DeleteMessage(int userId, int messageId)
//{
// int id = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
[HttpPost("{messageId}")]
public async Task<IActionResult> DeleteMessage(int userId, int messageId)
{
int id = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

if (id != userId)
{
return Unauthorized();
}

var message = await _repo.GetMessage(messageId);
if (message == null)
{
return NotFound();
}

if (message.SenderId == userId)
{
message.SenderDeleted = true;
}
else if (message.RecipientId == userId)
{
message.RecipientDeleted = true;
}

// if (id != userId)
// {
// return Unauthorized();
// }
if (message.SenderDeleted && message.RecipientDeleted)
{
//both sides have opted to delete the message, remove from database
_repo.Delete(message);
}

if (await _repo.SaveChangesAsync())
{
return NoContent();
}

//}
throw new Exception("Error deleting message");
}
}
}
1 change: 1 addition & 0 deletions Controllers/Resources/SendMessageResource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,6 @@ public class SendMessageResource
public int RecipientId { get; set; }
public string Content { get; set; }
public DateTime MessageSent { get; set; } = DateTime.Now;

}
}
14 changes: 10 additions & 4 deletions Data/FriendRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -134,13 +134,13 @@ public async Task<PagedList<Message>> GetMessages(MessageParameters messageParam
switch (messageParameters.MessageContainer)
{
case "Inbox":
messages = messages.Where(u => u.RecipientId == messageParameters.UserId);
messages = messages.Where(u => u.RecipientId == messageParameters.UserId && !u.RecipientDeleted);
break;
case "Outbox":
messages = messages.Where(u => u.SenderId == messageParameters.UserId);
messages = messages.Where(u => u.SenderId == messageParameters.UserId && !u.SenderDeleted);
break;
default: //just return unread messages
messages = messages.Where(u => u.RecipientId == messageParameters.UserId && !u.MarkedAsRead);
messages = messages.Where(u => u.RecipientId == messageParameters.UserId && !u.MarkedAsRead && !u.RecipientDeleted);
break;
}

Expand All @@ -155,7 +155,13 @@ public async Task<IEnumerable<Message>> GetMessageThread(int userId, int recipie
.ThenInclude(p => p.Photos)
.Include(u => u.Recipient)
.ThenInclude(p => p.Photos)
.Where(m => m.RecipientId == userId && m.SenderId == recipientId || m.RecipientId == recipientId && m.SenderId == userId)
.Where(m =>
m.RecipientId == userId &&
!m.RecipientDeleted &&
m.SenderId == recipientId ||
m.RecipientId == recipientId &&
m.SenderId == userId &&
!m.SenderDeleted)
.OrderByDescending(m => m.MessageSent)
.ToListAsync();

Expand Down

0 comments on commit c29bbfe

Please sign in to comment.