forked from cinderblocks/libremetaverse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCaps.cs
More file actions
443 lines (404 loc) · 16.9 KB
/
Copy pathCaps.cs
File metadata and controls
443 lines (404 loc) · 16.9 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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
/*
* Copyright (c) 2006-2016, openmetaverse.co
* Copyright (c) 2019-2026, Sjofn LLC.
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.co nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using LibreMetaverse.Packets;
using LibreMetaverse.StructuredData;
using LibreMetaverse.Interfaces;
using LibreMetaverse.Http;
using System.Net.Http;
namespace LibreMetaverse
{
/// <summary>
/// Capabilities is the name of the bidirectional HTTP REST protocol
/// used to communicate non-real-time transactions such as teleporting or
/// group messaging
/// </summary>
public partial class Caps
{
/// <summary>
/// Triggered when an event is received via the EventQueueGet
/// capability
/// </summary>
/// <param name="capsKey">Event name</param>
/// <param name="message">Decoded event data</param>
/// <param name="simulator">The simulator that generated the event</param>
//public delegate void EventQueueCallback(string message, StructuredData.OSD body, Simulator simulator);
public delegate void EventQueueCallback(string capsKey, IMessage message, Simulator simulator);
/// <summary>Reference to the simulator this system is connected to</summary>
public Simulator Simulator;
internal Uri _SeedCapsURI;
internal Dictionary<string, Uri> _Caps = new Dictionary<string, Uri>();
private readonly CancellationTokenSource _HttpCts = new CancellationTokenSource();
private EventQueueClient? _EventQueueClient = null;
/// <summary>Capabilities URI this system was initialized with</summary>
public Uri SeedCapsURI => _SeedCapsURI;
/// <summary>Whether the capabilities event queue is connected and
/// listening for incoming events</summary>
public bool IsEventQueueRunning => _EventQueueClient != null && _EventQueueClient.Running;
public EventQueueClient? EventQueue => _EventQueueClient;
/// <summary>
/// Default constructor
/// </summary>
/// <param name="simulator"></param>
/// <param name="seedcaps"></param>
internal Caps(Simulator simulator, Uri seedcaps)
{
Simulator = simulator;
_SeedCapsURI = seedcaps;
_ = MakeSeedRequestAsync();
}
public void Disconnect(bool immediate)
{
Logger.Info($"Caps system for {Simulator} is {(immediate ? "aborting" : "disconnecting")}", Simulator.Client);
DisposalHelper.SafeCancelAndDispose(_HttpCts, (m, e) => { if (e != null) Logger.Debug(m, e); else Logger.Debug(m); });
_EventQueueClient?.Dispose();
}
/// <summary>
/// Request the URI of a named capability
/// </summary>
/// <param name="capability">Name of the capability to request</param>
/// <returns>The URI of the requested capability, or null if not found</returns>
public Uri? CapabilityURI(string capability)
{
return _Caps.TryGetValue(capability, out var cap) ? cap : null;
}
/// <summary>
/// Return the cap names.
/// </summary>
public Dictionary<string, Uri>.KeyCollection Capabilities()
{
return _Caps.Keys;
}
/// <summary>
/// Useful for debugging, but not particularly a good idea
/// </summary>
/// <param name="cap">Capability address</param>
/// <returns>Name of capability if it exists</returns>
public string CapabilityNameFromURI(Uri cap)
{
return _Caps.First(x => x.Value == cap).Key;
}
/// <summary>
/// Request preferred URI for texture fetch capability
/// </summary>
/// <returns>URI of preferred capability or null, or null if not found</returns>
public Uri? GetTextureCapURI()
{
if (_Caps.TryGetValue("ViewerAsset", out var cap)) { return cap; }
return _Caps.TryGetValue("GetTexture", out cap) ? cap : null;
}
/// <summary>
/// Request preferred URI for object mesh fetch capability
/// </summary>
/// <returns>URI of preferred capability or null, or null if not found</returns>
public Uri? GetMeshCapURI()
{
if (_Caps.TryGetValue("ViewerAsset", out var cap)) { return cap; }
if (_Caps.TryGetValue("GetMesh2", out cap)) { return cap; }
return _Caps.TryGetValue("GetMesh", out cap) ? cap : null;
}
public static OSDArray AllCapabilities = new OSDArray
{
"AbuseCategories",
"AcceptFriendship",
"AcceptGroupInvite",
"AgentPreferences",
"AgentProfile",
"AgentState",
"AttachmentResources",
"AvatarPickerSearch",
"AvatarRenderInfo",
"CharacterProperties",
"ChatSessionRequest",
"CopyInventoryFromNotecard",
"CreateInventoryCategory",
"CreateTaskInventoryItem",
"DeclineFriendship",
"DeclineGroupInvite",
"DispatchRegionInfo",
"DirectDelivery",
"EnvironmentSettings",
"EstateAccess",
"EstateChangeInfo",
"EventQueueGet",
"ExtEnvironment",
"FetchLib2",
"FetchLibDescendents2",
"FetchInventory2",
"FetchInventoryDescendents2",
"IncrementCOFVersion",
"RequestTaskInventory",
"InterestList",
"InventoryThumbnailUpload",
"GetDisplayNames",
"GetExperiences",
"AgentExperiences",
"FindExperienceByName",
"GetExperienceInfo",
"GetAdminExperiences",
"GetCreatorExperiences",
"ExperiencePreferences",
"GroupExperiences",
"UpdateExperience",
"IsExperienceAdmin",
"IsExperienceContributor",
"RegionExperiences",
"ExperienceQuery",
"GetMesh",
"GetMesh2",
"GetMetadata",
"GetObjectCost",
"GetObjectPhysicsData",
"GetTexture",
"GroupAPIv1",
"GroupMemberData",
"GroupProposalBallot",
"HomeLocation",
"LandResources",
"LSLSyntax",
"MapLayer",
"MapLayerGod",
"MeshUploadFlag",
"ModifyMaterialParams",
"ModifyRegion",
"NavMeshGenerationStatus",
"NewFileAgentInventory",
"NewFileAgentInventoryVariablePrice",
"ObjectAnimation",
"ObjectMedia",
"ObjectMediaNavigate",
"ObjectNavMeshProperties",
"ParcelPropertiesUpdate",
"ParcelVoiceInfoRequest",
"ProductInfoRequest",
"ProvisionVoiceAccountRequest",
"ReadOfflineMsgs",
"RegionObjects",
"RegionSchedule",
"RemoteParcelRequest",
"RenderMaterials",
"RequestTextureDownload",
"ResourceCostSelected",
"RetrieveNavMeshSrc",
"SearchStatRequest",
"SearchStatTracking",
"SendPostcard",
"SendUserReport",
"SendUserReportWithScreenshot",
"ServerReleaseNotes",
"SetDisplayName",
"SimConsoleAsync",
"SimulatorFeatures",
"StartGroupProposal",
"TerrainNavMeshProperties",
"TextureStats",
"UntrustedSimulatorMessage",
"UpdateAgentInformation",
"UpdateAgentLanguage",
"UpdateAvatarAppearance",
"UpdateGestureAgentInventory",
"UpdateGestureTaskInventory",
"UpdateNotecardAgentInventory",
"UpdateNotecardTaskInventory",
"UpdateScriptAgent",
"UpdateScriptTask",
"UpdateSettingsAgentInventory",
"UpdateSettingsTaskInventory",
"UploadAgentProfileImage",
"UpdateMaterialAgentInventory",
"UpdateMaterialTaskInventory",
"UploadBakedTexture",
"UserInfo",
"ViewerAsset",
"ViewerBenefits",
"ViewerMetrics",
"ViewerStartAuction",
"ViewerStats",
"VoiceSignalingRequest",
// AIS3
"InventoryAPIv3",
"LibraryAPIv3"
};
private async Task MakeSeedRequestAsync()
{
if (Simulator == null || !Simulator.Client.Network.Connected) { return; }
try
{
var (response, data) = await Simulator.Client.HttpCapsClient.PostAsync(_SeedCapsURI, OSDFormat.Xml, Caps.AllCapabilities, _HttpCts.Token);
SeedRequestCompleteHandler(response, data, null);
}
catch (Exception ex)
{
SeedRequestCompleteHandler(null, null, ex);
}
}
private void SeedRequestCompleteHandler(HttpResponseMessage? response, byte[]? responseData, Exception? error)
{
if (error != null)
{
if (response != null && response.StatusCode == HttpStatusCode.NotFound)
{
Logger.Error("Seed capability returned a 404, capability system is aborting");
}
else
{
Logger.Warn($"Seed capability returned {(response == null ? "no response" : response.StatusCode.ToString())}. Trying again.");
// Retry the seed request after disposing/renewing the previous CTS to avoid using canceled token
DisposalHelper.SafeCancelAndDispose(_HttpCts, (m, e) => { if (e != null) Logger.Debug(m, e); else Logger.Debug(m); });
// Create a fresh CTS for retry
// Note: _HttpCts is readonly, so we cannot reassign; instead, call MakeSeedRequest only if the original CTS hasn't been disposed.
_ = MakeSeedRequestAsync();
}
return;
}
try
{
if (responseData == null) return;
OSD result = OSDParser.Deserialize(responseData);
if (result is OSDMap respMap)
{
foreach (var cap in respMap.Keys)
{
var maybeUri = respMap[cap]?.AsUri();
if (maybeUri != null)
{
_Caps[cap] = maybeUri;
Simulator.Client.CapsRateLimiter.RegisterCapUri(cap, maybeUri);
}
}
if (_Caps.TryGetValue("EventQueueGet", out var eventQueueGetCap))
{
Logger.Trace($"Starting event queue for {Simulator}", Simulator.Client);
_EventQueueClient = new EventQueueClient(eventQueueGetCap, Simulator);
_EventQueueClient.OnConnected += EventQueueConnectedHandler;
_EventQueueClient.OnEvent += EventQueueEventHandler;
_EventQueueClient.Start();
}
if (_Caps.TryGetValue("SimulatorFeatures", out var simFeaturesCap))
{
Logger.Trace($"Retrieving Simulator Features for {Simulator}", Simulator.Client);
Simulator.Features = new SimulatorFeatures(Simulator);
_ = FetchSimulatorFeaturesAsync(simFeaturesCap);
}
OnCapabilitiesReceived(Simulator);
}
}
catch (System.Text.Json.JsonException)
{
var respText = responseData != null ? System.Text.Encoding.UTF8.GetString(responseData) : string.Empty;
Logger.Warn($"Invalid caps response; '{respText}' for seed request.", Simulator.Client);
}
}
private async Task FetchSimulatorFeaturesAsync(Uri cap)
{
try
{
var (response, data) = await Simulator.Client.HttpCapsClient.GetAsync(cap, _HttpCts.Token);
Simulator.Features.SetFeatures(response, data, null);
}
catch (Exception ex)
{
Simulator.Features.SetFeatures(null, null, ex);
}
}
private void EventQueueConnectedHandler()
{
Simulator.Client.Network.RaiseConnectedEvent(Simulator);
}
/// <summary>
/// Process any incoming events, check to see if we have a message created for the event,
/// </summary>
/// <param name="eventName"></param>
/// <param name="body"></param>
private void EventQueueEventHandler(string eventName, OSDMap body)
{
IMessage? message = Messages.MessageUtils.DecodeEvent(eventName, body);
if (message != null)
{
Simulator.Client.Network.CapsEvents.BeginRaiseEvent(eventName, message, Simulator);
#region Stats Tracking
if (Simulator.Client.Settings.Packets.TrackUtilization)
{
Simulator.Client.Stats.Update(eventName, LibreMetaverse.Stats.Type.Message, 0, body.ToString().Length);
}
#endregion
}
else
{
Logger.Warn($"No Message handler exists for event {eventName}. Unable to decode. Will try Generic Handler next");
Logger.Debug("Please report this information at https://github.com/cinderblocks/libremetaverse/issues: " + Environment.NewLine + body);
// try generic decoder next which takes a caps event and tries to match it to an existing packet
if (body.Type == OSDType.Map)
{
OSDMap map = body;
Packet? packet = Packet.BuildPacket(eventName, map);
if (packet != null)
{
var incomingPacket = new NetworkManager.IncomingPacket
{
Simulator = Simulator,
Packet = packet
};
Logger.DebugLog($"Serializing {packet.Type} capability with generic handler",
Simulator.Client);
Simulator.Client.Network.EnqueueIncoming(incomingPacket);
}
else
{
Logger.Warn($"No Packet or Message handler exists for {eventName}");
}
}
}
}
/// <summary>Raised whenever the capabilities have been received from a simulator</summary>
public event EventHandler<CapabilitiesReceivedEventArgs>? CapabilitiesReceived;
/// <summary>
/// Raises the CapabilitiesReceived event
/// </summary>
/// <param name="simulator">Simulator we received the capabilities from</param>
private void OnCapabilitiesReceived(Simulator simulator)
{
CapabilitiesReceived?.Invoke(this, new CapabilitiesReceivedEventArgs(simulator));
}
}
#region EventArgs
public class CapabilitiesReceivedEventArgs : EventArgs
{
/// <summary>The simulator that received a capabilities</summary>
public Simulator Simulator { get; }
public CapabilitiesReceivedEventArgs(Simulator simulator)
{
Simulator = simulator;
}
}
#endregion
}