aboutsummaryrefslogtreecommitdiff
path: root/BackEnd/Timeline/SignalRHub/TimelineHub.cs
blob: 0bfda84cd3a94c4c7cdab6404c9df820e901ed60 (plain)
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
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;
using Timeline.Auth;
using Timeline.Services;
using Timeline.Services.Timeline;
using Timeline.Services.User;

namespace Timeline.SignalRHub
{
    public class TimelineHub : Hub<ITimelineClient>
    {
        private readonly ILogger<TimelineHub> _logger;
        private readonly ITimelineService _timelineService;

        public TimelineHub(ILogger<TimelineHub> logger, ITimelineService timelineService)
        {
            _logger = logger;
            _timelineService = timelineService;
        }

        public static string GenerateTimelinePostChangeListeningGroupName(string timelineName)
        {
            return $"timeline-post-change-{timelineName}";
        }

        public async Task SubscribeTimelinePostChange(string timelineName)
        {
            try
            {
                var timelineId = await _timelineService.GetTimelineIdByNameAsync(timelineName);
                var user = Context.User;
                if (!user.HasPermission(UserPermission.AllTimelineManagement) && !await _timelineService.HasReadPermissionAsync(timelineId, user.GetOptionalUserId()))
                    throw new HubException(Resource.MessageForbidden);

                var group = GenerateTimelinePostChangeListeningGroupName(timelineName);
                await Groups.AddToGroupAsync(Context.ConnectionId, group);
                _logger.LogInformation(Resource.LogSubscribeTimelinePostChange, Context.ConnectionId, group);
            }
            catch (ArgumentException)
            {
                throw new HubException(Resource.MessageTimelineNameInvalid);
            }
            catch (EntityNotExistException)
            {
                throw new HubException(Resource.MessageTimelineNotExist);
            }
        }

        public async Task UnsubscribeTimelinePostChange(string timelineName)
        {
            var group = GenerateTimelinePostChangeListeningGroupName(timelineName);
            await Groups.RemoveFromGroupAsync(Context.ConnectionId, group);
            _logger.LogInformation(Resource.LogUnsubscribeTimelinePostChange, Context.ConnectionId, group);
        }
    }
}