-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.cs
More file actions
217 lines (192 loc) · 8.72 KB
/
Main.cs
File metadata and controls
217 lines (192 loc) · 8.72 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
#region Related components
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Dynamic;
using System.Diagnostics;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using net.vieapps.Components.Utility;
using net.vieapps.Components.Security;
using net.vieapps.Components.Caching;
using net.vieapps.Components.Repository;
#endregion
namespace net.vieapps.Services.Notifications
{
public class ServiceComponent : ServiceBase
{
public static Cache Cache { get; } = Cache.CreateInstance("VIEApps-Services-Notifications", Components.Utility.Logger.GetLoggerFactory(), "true".IsEquals(UtilityService.GetAppSetting("Notifications:Cache:L1")));
public override string ServiceName => "Notifications";
string NotificationsKey => this.GetKey("Notifications", "VIEApps-56BA2999-NGX-A2E4-Services-4B54-Notification-83EB-Key-693C250DC95D");
IDisposable CacheCommunicator { get; set; }
void RegisterCacheCommunicator()
{
this.CacheCommunicator?.Dispose();
this.CacheCommunicator = Router.GotBackupRouter()
? Router.BackupChannel.AssignProcessL1CacheRequest(Cache, this)
: Router.IncomingChannel.AssignProcessL1CacheRequest(Cache, this);
Cache.AssignSendL1CacheRequest(this, Router.GotBackupRouter());
}
public override Task RegisterServiceAsync(IEnumerable<string> args, Action<IService> onSuccess = null, Action<Exception> onError = null)
=> base.RegisterServiceAsync
(
args,
_ =>
{
this.RegisterCacheCommunicator();
onSuccess?.Invoke(this);
},
onError
);
public override Task StartAsync(string[] args = null, bool initializeRepository = true, Action<IService> next = null)
{
this.StartTimer(this.CleanNotificationsAsync, 4 * 60 * 60);
return this.StartAsync(args, (_, _) => this.RegisterCacheCommunicator(), initializeRepository, next);
}
public override async Task<JToken> ProcessRequestAsync(RequestInfo requestInfo, CancellationToken cancellationToken = default)
{
var stopwatch = Stopwatch.StartNew();
this.WriteLogs(requestInfo, $"Begin request ({requestInfo.Verb} {requestInfo.GetURI()})");
using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, this.CancellationTokenSource.Token);
try
{
JToken json = null;
var isSystemAdministrator = await this.IsSystemAdministratorAsync(requestInfo, cts.Token).ConfigureAwait(false);
switch (requestInfo.Verb.ToUpper())
{
case "GET":
var objectIdentity = requestInfo.GetObjectIdentity();
json = "search".IsEquals(objectIdentity) || "fetch".IsEquals(objectIdentity)
? await this.SearchNotificationsAsync(requestInfo, "fetch".IsEquals(objectIdentity), cancellationToken).ConfigureAwait(false)
: await this.UpdateNotificationAsync(requestInfo, isSystemAdministrator, cancellationToken).ConfigureAwait(false);
break;
case "POST":
json = await this.CreateNotificationAsync(requestInfo, isSystemAdministrator, cancellationToken).ConfigureAwait(false);
break;
default:
throw new MethodNotAllowedException(requestInfo.Verb);
}
stopwatch.Stop();
this.WriteLogs(requestInfo, $"Success response - Execution times: {stopwatch.GetElapsedTimes()}");
if (this.IsDebugResultsEnabled)
this.WriteLogs(requestInfo, $"- Request: {requestInfo.ToString(this.JsonFormat)}" + "\r\n" + $"- Response: {json?.ToString(this.JsonFormat)}");
return json;
}
catch (Exception ex)
{
throw this.GetRuntimeException(requestInfo, ex, stopwatch);
}
}
async Task<JToken> SearchNotificationsAsync(RequestInfo requestInfo, bool asFetch, CancellationToken cancellationToken)
{
// prepare
var request = requestInfo.GetRequestExpando();
var filter = request.Get<ExpandoObject>("FilterBy")?.ToFilterBy<Notification>() ?? Filters<Notification>.And();
if (filter.GetChild("RecipientID") is not FilterBy<Notification> filterByRecipientID)
(filter as FilterBys<Notification>).Add(Filters<Notification>.Equals("RecipientID", requestInfo.Session.User.ID));
else
filterByRecipientID.Value = requestInfo.Session.User.ID;
filter.Prepare(requestInfo);
var sort = Sorts<Notification>.Descending("Time");
var pagination = request.Get<ExpandoObject>("Pagination")?.GetPagination() ?? (-1, 0, 20, 1);
var pageSize = pagination.PageSize;
var pageNumber = pagination.PageNumber;
// search
var totalRecords = await Notification.CountAsync(filter, null, cancellationToken).ConfigureAwait(false);
var notifications = totalRecords > 0
? await Notification.FindAsync(filter, sort, pageSize, pageNumber, null, cancellationToken).ConfigureAwait(false)
: [];
if (asFetch && pageNumber < 2 && totalRecords > pageSize)
{
pageNumber++;
notifications = notifications.Concat(await Notification.FindAsync(filter, sort, pageSize, pageNumber, null, cancellationToken).ConfigureAwait(false)).ToList();
}
// response
if (asFetch && !"false".IsEquals(requestInfo.GetParameter("x-update-message")))
{
notifications.ForEach(notification => new UpdateMessage
{
Type = this.ServiceName,
DeviceID = requestInfo.Session.DeviceID,
Data = notification.ToJson()
}.Send());
return new JObject();
}
return new JObject
{
{ "FilterBy", filter.ToClientJson() },
{ "SortBy", sort?.ToClientJson() },
{ "Pagination", (totalRecords, Extensions.GetTotalPages(totalRecords, pageSize), pageSize, pageNumber).GetPagination() },
{ "Objects", notifications.Select(notification => notification.ToJson()).ToJArray() }
};
}
async Task<JToken> CreateNotificationAsync(RequestInfo requestInfo, bool isSystemAdministrator, CancellationToken cancellationToken)
{
// check permission
var gotRights = isSystemAdministrator || (requestInfo.Extra != null && requestInfo.Extra.TryGetValue("x-notifications-key", out var notificationsKey) && this.NotificationsKey.IsEquals(notificationsKey));
if (!gotRights)
throw new AccessDeniedException();
// prepare
var request = requestInfo.GetBodyExpando();
var notification = Notification.CreateInstance(request, "Privileges,Created,CreatedID,LastModified,LastModifiedID".ToHashSet());
var response = notification.ToJson();
if (string.IsNullOrWhiteSpace(notification.RecipientID))
{
var recipientIDs = request.Get<List<string>>("Recipients");
if (recipientIDs == null || recipientIDs.Count < 1)
throw new InvalidRequestException("No recipient");
await recipientIDs.ForEachAsync(async userID =>
{
notification.ID = UtilityService.NewUUID;
notification.RecipientID = userID;
await Notification.CreateAsync(notification, cancellationToken).ConfigureAwait(false);
response = notification.ToJson();
(await requestInfo.GetUserSessionsAsync(notification.RecipientID, cancellationToken).ConfigureAwait(false)).Where(info => info.IsOnline).ForEach(info => new UpdateMessage
{
Type = this.ServiceName,
Data = response,
DeviceID = info.DeviceID
}.Send());
}, true, false).ConfigureAwait(false);
}
else
{
await Notification.CreateAsync(notification, cancellationToken).ConfigureAwait(false);
(await requestInfo.GetUserSessionsAsync(notification.RecipientID, cancellationToken).ConfigureAwait(false)).Where(info => info.IsOnline).ForEach(info => new UpdateMessage
{
Type = this.ServiceName,
Data = response,
DeviceID = info.DeviceID
}.Send());
}
return response;
}
async Task<JToken> UpdateNotificationAsync(RequestInfo requestInfo, bool isSystemAdministrator, CancellationToken cancellationToken)
{
var notification = await Notification.GetAsync(requestInfo.GetObjectIdentity(), cancellationToken).ConfigureAwait(false) ?? throw new InformationNotFoundException();
var gotRights = isSystemAdministrator || requestInfo.Session.User.ID.IsEquals(notification.RecipientID);
if (!gotRights)
throw new AccessDeniedException();
var response = notification.ToJson();
if (!notification.Read)
{
notification.Read = true;
await Notification.UpdateAsync(notification, true, cancellationToken).ConfigureAwait(false);
response = notification.ToJson();
(await requestInfo.GetUserSessionsAsync(notification.RecipientID, cancellationToken).ConfigureAwait(false)).Where(info => info.IsOnline).ForEach(info => new UpdateMessage
{
Type = this.ServiceName,
Data = response,
DeviceID = info.DeviceID,
ExcludedDeviceID = requestInfo.Session.DeviceID
}.Send());
}
return response;
}
Task CleanNotificationsAsync()
=> Notification.DeleteManyAsync(Filters<Notification>.LessThan("Time", DateTime.Now.AddDays(-365)), null, this.CancellationToken);
}
[Repository(ServiceName = "Notifications")]
public abstract class Repository<T> : RepositoryBase<T> where T : class { }
}