-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathChatHub.cs
70 lines (63 loc) · 2.07 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
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.SignalR;
using Twitter.Models;
namespace Twitter
{
public class ChatHub: Hub
{
private readonly TwitterDBContext _context;
private readonly UserManager<User> _userManager;
private static readonly HashSet<string> OnlineUsers = new HashSet<string>();
public ChatHub(UserManager<User> userManager, TwitterDBContext context)
{
_userManager = userManager;
_context = context;
}
public async Task MarkOnline(string user)
{
if (OnlineUsers.Contains(user))
{
return;
}
OnlineUsers.Add(user);
await IsOnline(user);
}
public async Task MarkOffline(string user)
{
OnlineUsers.Remove(user);
await IsOnline(user);
}
public async Task IsOnline(string user)
{
if (OnlineUsers.Contains(user))
{
await Clients.All.SendAsync("IsOnline", user, true);
}
else
{
await Clients.All.SendAsync("IsOnline", user, false);
}
}
public async Task Send(string sendedByUsername, string sendedToUsername, string message)
{
var sendByUser = await _userManager.FindByNameAsync(sendedByUsername);
var sendToUser = await _userManager.FindByNameAsync(sendedToUsername);
var messageObj = new Message()
{
SendedBy = sendByUser,
SendedTo = sendToUser,
DateTime = DateTime.Now,
Text = message
};
await _context.Messages.AddAsync(messageObj);
await _context.SaveChangesAsync();
await Clients
.Users(sendByUser.Id, sendToUser.Id)
.SendAsync("Send", sendByUser.Name, sendByUser.UserName,
sendToUser.UserName, message);
}
}
}