-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathConsoleService.cs
More file actions
331 lines (278 loc) · 11.4 KB
/
ConsoleService.cs
File metadata and controls
331 lines (278 loc) · 11.4 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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
// If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
using System.Reflection;
using System.Text.Json.Serialization;
using ActivityPub.Client;
using ActivityPub.Types.AS;
using ActivityPub.Types.Conversion;
using ActivityPub.Types.Internal;
using ActivityPub.Types.Util;
using Microsoft.Extensions.Hosting;
namespace SimpleClient;
public class ConsoleService(IActivityPubClient apClient, IHostApplicationLifetime hostLifetime, IJsonLdSerializer jsonLdSerializer)
: BackgroundService
{
private readonly Stack<object?> _focus = new();
private bool _isRunning = true;
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// This has to be here
// https://github.com/dotnet/runtime/issues/36063
await Task.Yield();
try
{
// Process line by line
while (_isRunning && !stoppingToken.IsCancellationRequested)
{
await Console.Out.WriteAsync("> ");
// Read line
var line = (await Console.In.ReadLineAsync(stoppingToken))?.Trim();
if (line == null)
break;
// Respond to next statement
await ProcessLine(line, stoppingToken);
await Console.Out.WriteLineAsync();
}
}
catch (OperationCanceledException)
{
// Ignored
}
finally
{
_isRunning = true;
}
}
private async Task ProcessLine(string line, CancellationToken stoppingToken)
{
try
{
// Parse line
var parts = line.Split(' ', 2);
var directive = parts[0].ToLower();
var parameter = parts.Length >= 2 ? parts[1] : null;
switch (directive)
{
case "quit":
case "exit":
case "close":
case "stop":
await Console.Out.WriteLineAsync("Bye 👋");
hostLifetime.StopApplication();
_isRunning = false;
break;
case "help":
await Console.Out.WriteLineAsync("Not implemented.");
break;
case "back":
case "pop":
case "out":
await HandlePop(stoppingToken);
break;
case "open":
case "push":
case "in":
await HandlePush(parameter, stoppingToken);
break;
case "show":
case "dump":
case "print":
await HandlePrint(parameter, stoppingToken);
break;
case "expand":
case "populate":
case "fill":
case "resolve":
await HandlePopulate(parameter, stoppingToken);
break;
default:
await Console.Out.WriteLineAsync($"Unknown directive '{directive}'");
break;
}
}
catch (Exception e)
{
await Console.Out.WriteLineAsync(e.ToString());
}
}
private async Task HandlePop(CancellationToken stoppingToken)
{
if (_focus.Count == 0)
{
await Console.Out.WriteLineAsync("Can't go back - no objects are in focus");
return;
}
_focus.Pop();
await HandlePrint(null, stoppingToken);
}
private async Task HandlePush(string? parameter, CancellationToken stoppingToken)
{
if (string.IsNullOrEmpty(parameter))
{
await Console.Out.WriteLineAsync("Please specify a URI or property to push.");
return;
}
// If param is a URI, then its a new object
if (Uri.TryCreate(parameter, UriKind.Absolute, out var uri))
{
await PushUri(uri, stoppingToken);
await HandlePrint(null, stoppingToken);
}
// Otherwise, its a selector
else if (_focus.TryPeek(out var current))
{
if (current == null)
{
await Console.Out.WriteLineAsync("Can't select from null.");
return;
}
await PushSelector(current, parameter, stoppingToken);
await HandlePrint(null, stoppingToken);
}
// Fallback
else
{
await Console.Out.WriteLineAsync("Can't open - no object is in focus and input is not a URI");
}
}
private async Task PushUri(Uri uri, CancellationToken stoppingToken)
{
var newObj = await apClient.Get<ASType>(uri, cancellationToken: stoppingToken);
_focus.Push(newObj);
}
private async Task PushSelector(object current, string parameter, CancellationToken stoppingToken)
{
var newObject = await SelectObject(current, parameter, stoppingToken);
_focus.Push(newObject);
}
private async Task HandlePrint(string? parameter, CancellationToken stoppingToken)
{
if (!_focus.TryPeek(out var current))
{
await Console.Out.WriteLineAsync("Can't print - no object in focus.");
return;
}
var toPrint = current;
if (parameter != null)
{
if (current == null)
{
await Console.Out.WriteLineAsync("Can't select from null.");
return;
}
toPrint = await SelectObject(current, parameter, stoppingToken);
}
var json = jsonLdSerializer.Serialize(toPrint);
await Console.Out.WriteLineAsync(json);
}
private async Task HandlePopulate(string? parameter, CancellationToken stoppingToken)
{
if (!_focus.TryPeek(out var current))
{
await Console.Out.WriteLineAsync("Can't populate - no object in focus.");
return;
}
if (current == null)
{
await Console.Out.WriteLineAsync("Can't populate a null object.");
return;
}
if (current is ASObject asObj)
{
if (parameter == null)
{
await Console.Out.WriteLineAsync("Please specify a property to populate.");
return;
}
var prop = FindProperty(asObj, parameter);
var value = await SelectObject(asObj, prop, stoppingToken);
// Verify and set
if (value != null && !value.GetType().IsAssignableTo(prop.PropertyType))
throw new ApplicationException($"Selected property is not compatible: {value.GetType()} is not assignable to {prop.PropertyType}");
prop.SetValue(asObj, value);
}
else if (current is ASLink asLink)
{
current = await apClient.Get<ASObject>(asLink, cancellationToken: stoppingToken);
_focus.Push(current);
}
else
{
await Console.Out.WriteLineAsync($"Unsupported type: {current.GetType()}");
}
await HandlePrint(null, stoppingToken);
}
private async Task<object?> SelectObject(object obj, string propertyName, CancellationToken stoppingToken)
{
var property = FindProperty(obj, propertyName);
return await SelectObject(obj, property, stoppingToken);
}
private async Task<object?> SelectObject(object obj, PropertyInfo property, CancellationToken stoppingToken)
{
// Get and populate property value
var value = property.GetValue(obj);
return await ResolveValue(value, stoppingToken);
}
private async Task<object?> ResolveValue(object? value, CancellationToken stoppingToken)
{
if (value == null)
return null;
// If its ASLink, then call Get<ASType>
if (value is ASLink link)
return await apClient.Get<ASType>(link, cancellationToken: stoppingToken);
var valueType = value.GetType();
// If its Linkable<T>, then extract T and call ResolveValueOfLinkable(object) which pivots to ResolveValueOfLinkableOf<T>)(Linkable<T>)
if (valueType.TryGetGenericArgumentsFor(typeof(Linkable<>), out var linkableSlots))
return await ResolveValueOfLinkable(value, linkableSlots[0], stoppingToken);
// If its LinkableList<T>, then extract T and call ResolveValueOfLinkableList(object) which pivots to ResolveValueOfLinkableListOf<T>(LinkableList<T>)
if (valueType.TryGetGenericArgumentsFor(typeof(Linkable<>), out var linkableListSlots))
return await ResolveValueOfLinkableList(value, linkableListSlots[0], stoppingToken);
// Otherwise, we can't resolve so return as-is
return value;
}
private async Task<object?> ResolveValueOfLinkable(object value, Type valueType, CancellationToken stoppingToken)
{
var method = typeof(ConsoleService)
.GetMethod(nameof(ResolveValueOfLinkableOf), BindingFlags.NonPublic | BindingFlags.Instance)
?.MakeGenericMethod(valueType)
?? throw new MissingMethodException($"Missing method ResolveValueOfLinkableOf<{valueType}>(Linkable<{valueType}>, CancellationToken)");
return await (Task<object?>)method.Invoke(this, [value, stoppingToken])!;
}
private async Task<object?> ResolveValueOfLinkableOf<T>(Linkable<T> value, CancellationToken stoppingToken)
where T : ASObject
{
var result = await apClient.Resolve(value, cancellationToken: stoppingToken);
return new Linkable<T>(result);
}
private async Task<object?> ResolveValueOfLinkableList(object value, Type valueType, CancellationToken stoppingToken)
{
var method = typeof(ConsoleService)
.GetMethod(nameof(ResolveValueOfLinkableListOf), BindingFlags.NonPublic | BindingFlags.Instance)
?.MakeGenericMethod(valueType)
?? throw new MissingMethodException($"Missing method ResolveValueOfLinkableListOf<{valueType}>(LinkableList<{valueType}>, CancellationToken)");
return await (Task<object?>)method.Invoke(this, [value, stoppingToken])!;
}
private async Task<object?> ResolveValueOfLinkableListOf<T>(LinkableList<T> value, CancellationToken stoppingToken)
where T : ASObject
{
var results = await apClient.Resolve(value, cancellationToken: stoppingToken);
return new LinkableList<T>(results);
}
private static PropertyInfo FindProperty(object obj, string propertyName)
{
// Try to find a property with a matching name (case-insensitive)
var properties = obj.GetType().GetProperties();
var property = Array.Find(properties, p => p.Name.Equals(propertyName, StringComparison.OrdinalIgnoreCase));
if (property != null)
return property;
// Try to find a property with a JsonPropertyName attribute that matches the parameter
property = Array.Find(
properties,
p =>
p.GetCustomAttribute<JsonPropertyNameAttribute>()?.Name.Equals(propertyName, StringComparison.OrdinalIgnoreCase) ?? false
);
if (property != null)
return property;
throw new MissingMemberException("Can't find that property within the object in focus.");
}
}