aboutsummaryrefslogtreecommitdiff
path: root/backend/api/api/Services/ChatHub.cs
blob: 72febce1bd1f1b61603eab5bab033fdc1024faf6 (plain) (blame)
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
using api.Models;
using Microsoft.AspNetCore.SignalR;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Threading.Tasks;



namespace api.Services
{
    public class ChatHub :Hub
    {
        static public readonly Dictionary<string,string> Users=new Dictionary<string,string>();
        private readonly IJwtToken _tokenService;
        public ChatHub(IJwtToken tokenService)
        {
            _tokenService=tokenService;
        }

        public override async Task OnConnectedAsync()
        {
            string token=Context.GetHttpContext().Request.Query["access_token"];
            if (token == null)
                return;
            string id=_tokenService.TokenToId(token);
            Users.Add(id,Context.ConnectionId);
            //await SendDirect(id, "poruka");
            //await Send(Context.ConnectionId);
            await base.OnConnectedAsync();

        }
        public override async Task OnDisconnectedAsync(Exception? exception)
        {
            string id = Users.FirstOrDefault(u => u.Value == Context.ConnectionId).Key;
            Users.Remove(id);
        }
        public async Task SendDirect(string id,string message)
        {
            if (Users[id]==null)
                return;

            await Clients.Client(Users[id]).SendAsync("Notify",message);
        }
        public async Task Send(string message)
        {
            await Clients.All.SendAsync("Notify",message);
        }
        public static bool CheckUser(string id)
        {
            if (Users[id] == null)
                return false;
            return true;
        }
    }
    

}