-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChatHub.cs
73 lines (63 loc) · 2.18 KB
/
ChatHub.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using ChatApp.API.Data;
using ChatApp.API.Models;
using Microsoft.AspNetCore.SignalR;
namespace ChatApp.API
{
public class ChatHub : Hub
{
private readonly IChatRepository _repo;
public ChatHub(IChatRepository repo)
{
_repo = repo;
}
public override async Task OnConnectedAsync()
{
// add user to users online on connect
var httpContext = Context.GetHttpContext();
var username = httpContext.Request.Query["name"];
var connectionId = Context.ConnectionId;
var userToAdd = new User
{
ConnectionId = connectionId,
Username = username
};
var onlineUsers = await _repo.AddOnlineUser(userToAdd);
await Clients.All.SendAsync("GetOnlineUsers", onlineUsers);
var messages = await _repo.GetChatHistory();
await Clients.Caller.SendAsync("ChatHistory", messages);
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception exception)
{
// remove user from users online on disconnect
var onlineUsers = await _repo.RemoveOnlineUser(Context.ConnectionId);
await Clients.All.SendAsync("GetOnlineUsers", onlineUsers);
await base.OnDisconnectedAsync(exception);
}
public async Task SendMessage(string user, string message)
{
try
{
var msgToSave = new ChatMessage
{
User = user,
Message = message,
Sent = DateTime.UtcNow
};
_repo.Add(msgToSave);
await _repo.SaveAllAsync();
await Clients.All.SendAsync("ReceiveMessage", msgToSave);
}
catch { }
}
public async Task GetHistory()
{
var messages = await _repo.GetChatHistory();
await Clients.Caller.SendAsync("ChatHistory", messages);
}
}
}