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
218
219
220
221
|
@using LibMatrix.EventTypes.Spec.State.Policy
@using System.Reflection
@using ArcaneLibs.Attributes
@using LibMatrix
@using System.Collections.Frozen
@using LibMatrix.EventTypes
@using LibMatrix.RoomTypes
<ModalWindow
Title="@("Creating many new " + (PolicyTypes.ContainsKey(MappedType ?? "") ? PolicyTypes[MappedType!].GetFriendlyNamePluralOrNull()?.ToLower() ?? PolicyTypes[MappedType!].Name : "event"))"
OnCloseClicked="@OnClose" X="60" Y="60" MinWidth="600">
<span>Policy type:</span>
<select @bind="@MappedType">
<option>Select a value</option>
@foreach (var (type, mappedType) in PolicyTypes) {
<option value="@type">@mappedType.GetFriendlyName().ToLower()</option>
}
</select><br/>
<span>Reason:</span>
<FancyTextBox @bind-Value="@Reason"></FancyTextBox>
<br/>
<span>Recommendation:</span>
<FancyTextBox @bind-Value="@Recommendation"></FancyTextBox>
<br/>
<span>Entities:</span><br/>
<FancyTextBox Multiline="true" @bind-Value="@Entities"></FancyTextBox>
<br/>
@* <details> *@
@* <summary>JSON data</summary> *@
@* <pre> *@
@* $1$ @PolicyEvent.ToJson(true, true) #1# *@
@* </pre> *@
@* </details> *@
@if (!VerifyIntent) {
<LinkButton OnClickAsync="@(() => {
OnClose.Invoke();
return Task.CompletedTask;
})"> Cancel
</LinkButton>
<LinkButton OnClickAsync="@(() => {
_ = Save();
return Task.CompletedTask;
})"> Save
</LinkButton>
@if (!string.IsNullOrWhiteSpace(Response)) {
<pre style="color: red;">@Response</pre>
}
}
else {
<b class="blink">WARNING!!!</b>
<br/>
@if (!string.IsNullOrWhiteSpace(Response)) {
<pre style="color: red;">@Response</pre>
}
<span>Are you sure you want to do this?</span>
<LinkButton Color="#00FF00" OnClick="@(() => {
VerifyIntent = false;
Response = null;
StateHasChanged();
})">No
</LinkButton>
<LinkButton Color="#FF0000" OnClick="@(() => { _ = Save(force: true); })">Yes</LinkButton>
}
</ModalWindow>
@code {
[Parameter]
public required Action OnClose { get; set; }
[Parameter]
public required Action OnSaved { get; set; }
[Parameter]
public required GenericRoom Room { get; set; }
private string Recommendation { get; set; } = "m.ban";
private string Reason { get; set; } = "spam";
private string Entities { get; set; } = "";
private string? Response {
get;
set {
field = value;
StateHasChanged();
}
}
private bool VerifyIntent { get; set; }
private static FrozenSet<Type> KnownPolicyTypes = MatrixEvent.KnownEventTypes.Where(x => x.IsAssignableTo(typeof(PolicyRuleEventContent))).ToFrozenSet();
private static Dictionary<string, Type> PolicyTypes = KnownPolicyTypes
.ToDictionary(x => x.GetCustomAttributes<MatrixEventAttribute>().First(y => !string.IsNullOrWhiteSpace(y.EventName)).EventName, x => x);
private static FrozenSet<string> AllKnownPolicyTypes = KnownPolicyTypes
.SelectMany(x => x.GetCustomAttributes<MatrixEventAttribute>().Select(y => y.EventName))
.ToFrozenSet();
private string? MappedType { get; set; }
private async Task Save(bool force = false) {
if (string.IsNullOrWhiteSpace(MappedType)) {
Response = "No type selected";
return;
}
if (string.IsNullOrWhiteSpace(Entities)) {
Response = "No users selected";
return;
}
Console.WriteLine("Saving ---");
var entities = Entities.Split("\n", StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.Select(x => x.Trim())
.Distinct()
.ToList();
if (!force && !Validate(entities, PolicyTypes[MappedType])) {
List<string> distinctTypes = entities
.Select(GuessType)
.Where(x => x != null)
.Distinct()
.Select(x => x!.Name)
.ToList();
VerifyIntent = true;
Response = $"Invalid entities. Expected {PolicyTypes[MappedType].Name}, got:\n - " +
string.Join("\n - ", distinctTypes);
return;
}
try {
await SaveAll(entities);
}
catch (Exception e) {
Response = $"Failed to save: {e}";
}
}
private bool Validate(List<string> entities, Type expectedType) {
return entities.All(x => GuessType(x) == expectedType);
}
private Type? GuessType(string entity) {
var sigil = entity[0];
return TypesBySigil.GetValueOrDefault(sigil.ToString(), typeof(ServerPolicyRuleEventContent));
}
private Dictionary<string, Type> TypesBySigil = new() {
{ "@", typeof(UserPolicyRuleEventContent) },
{ "!", typeof(RoomPolicyRuleEventContent) },
{ "#", typeof(RoomPolicyRuleEventContent) }
};
private async Task SaveAll(List<string> entities) {
await foreach (var evt in Room.GetFullStateAsync()) {
if (evt is null
|| !AllKnownPolicyTypes.Contains(evt.Type)
|| !evt.TypedContent!.GetType().IsAssignableTo(PolicyTypes[MappedType!])
) continue;
if (evt.TypedContent is PolicyRuleEventContent content && content.Recommendation == Recommendation && content.Reason == Reason) {
if (content.Entity != null && entities.Contains(content.Entity))
entities.Remove(content.Entity);
}
}
// var tasks = entities.Select(x => ExecuteBan(Room, x)).ToList();
// await Task.WhenAll(tasks);
var events = entities.Select(entity => {
var content = Activator.CreateInstance(PolicyTypes[MappedType!]) as PolicyRuleEventContent ?? throw new InvalidOperationException("Failed to create event content");
content.Recommendation = Recommendation;
content.Reason = Reason;
content.Entity = entity;
return new MatrixEvent() {
Type = MappedType,
TypedContent = content,
StateKey = content.GetDraupnir2StateKey()
};
});
foreach (var chunk in events.Chunk(50))
await Room.BulkSendEventsAsync(chunk);
OnSaved.Invoke();
}
private async Task ExecuteBan(GenericRoom room, string entity) {
bool success = false;
while (!success) {
try {
var content = Activator.CreateInstance(PolicyTypes[MappedType!]) as PolicyRuleEventContent ?? throw new InvalidOperationException("Failed to create event content");
content.Recommendation = Recommendation;
content.Reason = Reason;
content.Entity = entity;
await room.SendStateEventAsync(MappedType!, content.GetDraupnir2StateKey(), content);
success = true;
}
catch (MatrixException e) {
if (e is not { ErrorCode: MatrixException.ErrorCodes.M_FORBIDDEN }) throw;
Console.WriteLine(e);
}
catch (Exception e) {
//ignored
Console.WriteLine(e);
}
}
}
}
|