aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Framework/Capabilities/Caps.cs
diff options
context:
space:
mode:
authorDiva Canto2011-04-30 11:03:22 -0700
committerDiva Canto2011-04-30 11:03:22 -0700
commit3e79842312ace5b4294e3d6501b1d35ffea5f1b5 (patch)
treef8832e79c25dec366cbf78bc5c6dcbc0c5bf0ea4 /OpenSim/Framework/Capabilities/Caps.cs
parentFirst stab at cleaning up Caps. Compiles. Untested. (diff)
downloadopensim-SC_OLD-3e79842312ace5b4294e3d6501b1d35ffea5f1b5.zip
opensim-SC_OLD-3e79842312ace5b4294e3d6501b1d35ffea5f1b5.tar.gz
opensim-SC_OLD-3e79842312ace5b4294e3d6501b1d35ffea5f1b5.tar.bz2
opensim-SC_OLD-3e79842312ace5b4294e3d6501b1d35ffea5f1b5.tar.xz
Renamed OpenSim.Framework.Capabilities.dll to OpenSim.Capabilities.dll
Diffstat (limited to 'OpenSim/Framework/Capabilities/Caps.cs')
-rw-r--r--OpenSim/Framework/Capabilities/Caps.cs1368
1 files changed, 0 insertions, 1368 deletions
diff --git a/OpenSim/Framework/Capabilities/Caps.cs b/OpenSim/Framework/Capabilities/Caps.cs
deleted file mode 100644
index 3be97b5..0000000
--- a/OpenSim/Framework/Capabilities/Caps.cs
+++ /dev/null
@@ -1,1368 +0,0 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections;
30using System.Collections.Generic;
31using System.IO;
32using System.Reflection;
33using log4net;
34using Nini.Config;
35using OpenMetaverse;
36using OpenSim.Framework.Servers;
37using OpenSim.Framework.Servers.HttpServer;
38using OpenSim.Services.Interfaces;
39
40// using OpenSim.Region.Framework.Interfaces;
41
42namespace OpenSim.Framework.Capabilities
43{
44 public delegate void UpLoadedAsset(
45 string assetName, string description, UUID assetID, UUID inventoryItem, UUID parentFolder,
46 byte[] data, string inventoryType, string assetType);
47
48 public delegate void UploadedBakedTexture(UUID assetID, byte[] data);
49
50 public delegate UUID UpdateItem(UUID itemID, byte[] data);
51
52 public delegate void UpdateTaskScript(UUID itemID, UUID primID, bool isScriptRunning, byte[] data, ref ArrayList errors);
53
54 public delegate void NewInventoryItem(UUID userID, InventoryItemBase item);
55
56 public delegate void NewAsset(AssetBase asset);
57
58 public delegate UUID ItemUpdatedCallback(UUID userID, UUID itemID, byte[] data);
59
60 public delegate ArrayList TaskScriptUpdatedCallback(UUID userID, UUID itemID, UUID primID,
61 bool isScriptRunning, byte[] data);
62
63 public delegate InventoryCollection FetchInventoryDescendentsCAPS(UUID agentID, UUID folderID, UUID ownerID,
64 bool fetchFolders, bool fetchItems, int sortOrder, out int version);
65
66 /// <summary>
67 /// XXX Probably not a particularly nice way of allow us to get the scene presence from the scene (chiefly so that
68 /// we can popup a message on the user's client if the inventory service has permanently failed). But I didn't want
69 /// to just pass the whole Scene into CAPS.
70 /// </summary>
71 public delegate IClientAPI GetClientDelegate(UUID agentID);
72
73 public class Caps
74 {
75 private static readonly ILog m_log =
76 LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
77
78 private string m_httpListenerHostName;
79 private uint m_httpListenPort;
80
81 /// <summary>
82 /// This is the uuid portion of every CAPS path. It is used to make capability urls private to the requester.
83 /// </summary>
84 private string m_capsObjectPath;
85 public string CapsObjectPath { get { return m_capsObjectPath; } }
86
87 private CapsHandlers m_capsHandlers;
88
89 private static readonly string m_requestPath = "0000/";
90 // private static readonly string m_mapLayerPath = "0001/";
91 private static readonly string m_newInventory = "0002/";
92 //private static readonly string m_requestTexture = "0003/";
93 private static readonly string m_notecardUpdatePath = "0004/";
94 private static readonly string m_notecardTaskUpdatePath = "0005/";
95// private static readonly string m_fetchInventoryPath = "0006/";
96
97 // The following entries are in a module, however, they are also here so that we don't re-assign
98 // the path to another cap by mistake.
99 // private static readonly string m_parcelVoiceInfoRequestPath = "0007/"; // This is in a module.
100 // private static readonly string m_provisionVoiceAccountRequestPath = "0008/";// This is in a module.
101
102 // private static readonly string m_remoteParcelRequestPath = "0009/";// This is in the LandManagementModule.
103 private static readonly string m_uploadBakedTexturePath = "0010/";// This is in the LandManagementModule.
104
105 //private string eventQueue = "0100/";
106 private IScene m_Scene;
107 private IHttpServer m_httpListener;
108 private UUID m_agentID;
109 private IAssetService m_assetCache;
110 private int m_eventQueueCount = 1;
111 private Queue<string> m_capsEventQueue = new Queue<string>();
112 private bool m_dumpAssetsToFile;
113 private string m_regionName;
114 private object m_fetchLock = new Object();
115
116 private bool m_persistBakedTextures = false;
117
118 public bool SSLCaps
119 {
120 get { return m_httpListener.UseSSL; }
121 }
122 public string SSLCommonName
123 {
124 get { return m_httpListener.SSLCommonName; }
125 }
126 public CapsHandlers CapsHandlers
127 {
128 get { return m_capsHandlers; }
129 }
130
131 // These are callbacks which will be setup by the scene so that we can update scene data when we
132 // receive capability calls
133 public NewInventoryItem AddNewInventoryItem = null;
134 public NewAsset AddNewAsset = null;
135 public ItemUpdatedCallback ItemUpdatedCall = null;
136 public TaskScriptUpdatedCallback TaskScriptUpdatedCall = null;
137 public FetchInventoryDescendentsCAPS CAPSFetchInventoryDescendents = null;
138 public GetClientDelegate GetClient = null;
139
140 public Caps(IScene scene, IAssetService assetCache, IHttpServer httpServer, string httpListen, uint httpPort, string capsPath,
141 UUID agent, bool dumpAssetsToFile, string regionName)
142 {
143 m_Scene = scene;
144 m_assetCache = assetCache;
145 m_capsObjectPath = capsPath;
146 m_httpListener = httpServer;
147 m_httpListenerHostName = httpListen;
148
149 m_httpListenPort = httpPort;
150
151 m_persistBakedTextures = false;
152 IConfigSource config = m_Scene.Config;
153 if (config != null)
154 {
155 IConfig sconfig = config.Configs["Startup"];
156 if (sconfig != null)
157 m_persistBakedTextures = sconfig.GetBoolean("PersistBakedTextures",m_persistBakedTextures);
158 }
159
160 if (httpServer != null && httpServer.UseSSL)
161 {
162 m_httpListenPort = httpServer.SSLPort;
163 httpListen = httpServer.SSLCommonName;
164 httpPort = httpServer.SSLPort;
165 }
166
167 m_agentID = agent;
168 m_dumpAssetsToFile = dumpAssetsToFile;
169 m_capsHandlers = new CapsHandlers(httpServer, httpListen, httpPort, (httpServer == null) ? false : httpServer.UseSSL);
170 m_regionName = regionName;
171 }
172
173 /// <summary>
174 /// Register all CAPS http service handlers
175 /// </summary>
176 public void RegisterHandlers()
177 {
178 DeregisterHandlers();
179
180 string capsBase = "/CAPS/" + m_capsObjectPath;
181
182 RegisterRegionServiceHandlers(capsBase);
183 RegisterInventoryServiceHandlers(capsBase);
184 }
185
186 public void RegisterRegionServiceHandlers(string capsBase)
187 {
188 try
189 {
190 // the root of all evil
191 m_capsHandlers["SEED"] = new RestStreamHandler("POST", capsBase + m_requestPath, CapsRequest);
192 m_log.DebugFormat(
193 "[CAPS]: Registered seed capability {0} for {1}", capsBase + m_requestPath, m_agentID);
194
195 //m_capsHandlers["MapLayer"] =
196 // new LLSDStreamhandler<OSDMapRequest, OSDMapLayerResponse>("POST",
197 // capsBase + m_mapLayerPath,
198 // GetMapLayer);
199 m_capsHandlers["UpdateScriptTaskInventory"] =
200 new RestStreamHandler("POST", capsBase + m_notecardTaskUpdatePath, ScriptTaskInventory);
201 m_capsHandlers["UpdateScriptTask"] = m_capsHandlers["UpdateScriptTaskInventory"];
202 m_capsHandlers["UploadBakedTexture"] =
203 new RestStreamHandler("POST", capsBase + m_uploadBakedTexturePath, UploadBakedTexture);
204
205 }
206 catch (Exception e)
207 {
208 m_log.Error("[CAPS]: " + e.ToString());
209 }
210 }
211
212 public void RegisterInventoryServiceHandlers(string capsBase)
213 {
214 try
215 {
216 // I don't think this one works...
217 m_capsHandlers["NewFileAgentInventory"] =
218 new LLSDStreamhandler<LLSDAssetUploadRequest, LLSDAssetUploadResponse>("POST",
219 capsBase + m_newInventory,
220 NewAgentInventoryRequest);
221 m_capsHandlers["UpdateNotecardAgentInventory"] =
222 new RestStreamHandler("POST", capsBase + m_notecardUpdatePath, NoteCardAgentInventory);
223 m_capsHandlers["UpdateScriptAgentInventory"] = m_capsHandlers["UpdateNotecardAgentInventory"];
224 m_capsHandlers["UpdateScriptAgent"] = m_capsHandlers["UpdateScriptAgentInventory"];
225
226 // As of RC 1.22.9 of the Linden client this is
227 // supported
228
229 //m_capsHandlers["WebFetchInventoryDescendents"] =new RestStreamHandler("POST", capsBase + m_fetchInventoryPath, FetchInventoryDescendentsRequest);
230
231 // justincc: I've disabled the CAPS service for now to fix problems with selecting textures, and
232 // subsequent inventory breakage, in the edit object pane (such as mantis 1085). This requires
233 // enhancements (probably filling out the folder part of the LLSD reply) to our CAPS service,
234 // but when I went on the Linden grid, the
235 // simulators I visited (version 1.21) were, surprisingly, no longer supplying this capability. Instead,
236 // the 1.19.1.4 client appeared to be happily flowing inventory data over UDP
237 //
238 // This is very probably just a temporary measure - once the CAPS service appears again on the Linden grid
239 // we will be
240 // able to get the data we need to implement the necessary part of the protocol to fix the issue above.
241 // m_capsHandlers["FetchInventoryDescendents"] =
242 // new RestStreamHandler("POST", capsBase + m_fetchInventoryPath, FetchInventoryRequest);
243
244 // m_capsHandlers["FetchInventoryDescendents"] =
245 // new LLSDStreamhandler<LLSDFetchInventoryDescendents, LLSDInventoryDescendents>("POST",
246 // capsBase + m_fetchInventory,
247 // FetchInventory));
248 // m_capsHandlers["RequestTextureDownload"] = new RestStreamHandler("POST",
249 // capsBase + m_requestTexture,
250 // RequestTexture);
251 }
252 catch (Exception e)
253 {
254 m_log.Error("[CAPS]: " + e.ToString());
255 }
256 }
257
258 /// <summary>
259 /// Register a handler. This allows modules to register handlers.
260 /// </summary>
261 /// <param name="capName"></param>
262 /// <param name="handler"></param>
263 public void RegisterHandler(string capName, IRequestHandler handler)
264 {
265 m_capsHandlers[capName] = handler;
266 //m_log.DebugFormat("[CAPS]: Registering handler for \"{0}\": path {1}", capName, handler.Path);
267 }
268
269 /// <summary>
270 /// Remove all CAPS service handlers.
271 ///
272 /// </summary>
273 /// <param name="httpListener"></param>
274 /// <param name="path"></param>
275 /// <param name="restMethod"></param>
276 public void DeregisterHandlers()
277 {
278 if (m_capsHandlers != null)
279 {
280 foreach (string capsName in m_capsHandlers.Caps)
281 {
282 m_capsHandlers.Remove(capsName);
283 }
284 }
285 }
286
287 /// <summary>
288 /// Construct a client response detailing all the capabilities this server can provide.
289 /// </summary>
290 /// <param name="request"></param>
291 /// <param name="path"></param>
292 /// <param name="param"></param>
293 /// <param name="httpRequest">HTTP request header object</param>
294 /// <param name="httpResponse">HTTP response header object</param>
295 /// <returns></returns>
296 public string CapsRequest(string request, string path, string param,
297 OSHttpRequest httpRequest, OSHttpResponse httpResponse)
298 {
299 m_log.Debug("[CAPS]: Seed Caps Request in region: " + m_regionName);
300
301 if (!m_Scene.CheckClient(m_agentID, httpRequest.RemoteIPEndPoint))
302 {
303 m_log.DebugFormat("[CAPS]: Unauthorized CAPS client");
304 return string.Empty;
305 }
306
307 string result = LLSDHelpers.SerialiseLLSDReply(m_capsHandlers.CapsDetails);
308
309 //m_log.DebugFormat("[CAPS] CapsRequest {0}", result);
310
311 return result;
312 }
313
314 // FIXME: these all should probably go into the respective region
315 // modules
316
317 /// <summary>
318 /// Processes a fetch inventory request and sends the reply
319
320 /// </summary>
321 /// <param name="request"></param>
322 /// <param name="path"></param>
323 /// <param name="param"></param>
324 /// <returns></returns>
325 // Request is like:
326 //<llsd>
327 // <map><key>folders</key>
328 // <array>
329 // <map>
330 // <key>fetch-folders</key><boolean>1</boolean><key>fetch-items</key><boolean>1</boolean><key>folder-id</key><uuid>8e1e3a30-b9bf-11dc-95ff-0800200c9a66</uuid><key>owner-id</key><uuid>11111111-1111-0000-0000-000100bba000</uuid><key>sort-order</key><integer>1</integer>
331 // </map>
332 // </array>
333 // </map>
334 //</llsd>
335 //
336 // multiple fetch-folder maps are allowed within the larger folders map.
337 public string FetchInventoryRequest(string request, string path, string param)
338 {
339 // string unmodifiedRequest = request.ToString();
340
341 //m_log.DebugFormat("[AGENT INVENTORY]: Received CAPS fetch inventory request {0}", unmodifiedRequest);
342 m_log.Debug("[CAPS]: Inventory Request in region: " + m_regionName);
343
344 Hashtable hash = new Hashtable();
345 try
346 {
347 hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request));
348 }
349 catch (LLSD.LLSDParseException pe)
350 {
351 m_log.Error("[AGENT INVENTORY]: Fetch error: " + pe.Message);
352 m_log.Error("Request: " + request.ToString());
353 }
354
355 ArrayList foldersrequested = (ArrayList)hash["folders"];
356
357 string response = "";
358
359 for (int i = 0; i < foldersrequested.Count; i++)
360 {
361 string inventoryitemstr = "";
362 Hashtable inventoryhash = (Hashtable)foldersrequested[i];
363
364 LLSDFetchInventoryDescendents llsdRequest = new LLSDFetchInventoryDescendents();
365 LLSDHelpers.DeserialiseOSDMap(inventoryhash, llsdRequest);
366 LLSDInventoryDescendents reply = FetchInventoryReply(llsdRequest);
367
368 inventoryitemstr = LLSDHelpers.SerialiseLLSDReply(reply);
369 inventoryitemstr = inventoryitemstr.Replace("<llsd><map><key>folders</key><array>", "");
370 inventoryitemstr = inventoryitemstr.Replace("</array></map></llsd>", "");
371
372 response += inventoryitemstr;
373 }
374
375 if (response.Length == 0)
376 {
377 // Ter-guess: If requests fail a lot, the client seems to stop requesting descendants.
378 // Therefore, I'm concluding that the client only has so many threads available to do requests
379 // and when a thread stalls.. is stays stalled.
380 // Therefore we need to return something valid
381 response = "<llsd><map><key>folders</key><array /></map></llsd>";
382 }
383 else
384 {
385 response = "<llsd><map><key>folders</key><array>" + response + "</array></map></llsd>";
386 }
387
388 //m_log.DebugFormat("[AGENT INVENTORY]: Replying to CAPS fetch inventory request with following xml");
389 //m_log.Debug(Util.GetFormattedXml(response));
390
391 return response;
392 }
393
394 public string FetchInventoryDescendentsRequest(string request, string path, string param,OSHttpRequest httpRequest, OSHttpResponse httpResponse)
395 {
396 // nasty temporary hack here, the linden client falsely
397 // identifies the uuid 00000000-0000-0000-0000-000000000000
398 // as a string which breaks us
399 //
400 // correctly mark it as a uuid
401 //
402 request = request.Replace("<string>00000000-0000-0000-0000-000000000000</string>", "<uuid>00000000-0000-0000-0000-000000000000</uuid>");
403
404 // another hack <integer>1</integer> results in a
405 // System.ArgumentException: Object type System.Int32 cannot
406 // be converted to target type: System.Boolean
407 //
408 request = request.Replace("<key>fetch_folders</key><integer>0</integer>", "<key>fetch_folders</key><boolean>0</boolean>");
409 request = request.Replace("<key>fetch_folders</key><integer>1</integer>", "<key>fetch_folders</key><boolean>1</boolean>");
410
411 Hashtable hash = new Hashtable();
412 try
413 {
414 hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request));
415 }
416 catch (LLSD.LLSDParseException pe)
417 {
418 m_log.Error("[AGENT INVENTORY]: Fetch error: " + pe.Message);
419 m_log.Error("Request: " + request.ToString());
420 }
421
422 ArrayList foldersrequested = (ArrayList)hash["folders"];
423
424 string response = "";
425 lock (m_fetchLock)
426 {
427 for (int i = 0; i < foldersrequested.Count; i++)
428 {
429 string inventoryitemstr = "";
430 Hashtable inventoryhash = (Hashtable)foldersrequested[i];
431
432 LLSDFetchInventoryDescendents llsdRequest = new LLSDFetchInventoryDescendents();
433
434 try{
435 LLSDHelpers.DeserialiseOSDMap(inventoryhash, llsdRequest);
436 }
437 catch(Exception e)
438 {
439 m_log.Debug("[CAPS]: caught exception doing OSD deserialize" + e);
440 }
441 LLSDInventoryDescendents reply = FetchInventoryReply(llsdRequest);
442
443 inventoryitemstr = LLSDHelpers.SerialiseLLSDReply(reply);
444 inventoryitemstr = inventoryitemstr.Replace("<llsd><map><key>folders</key><array>", "");
445 inventoryitemstr = inventoryitemstr.Replace("</array></map></llsd>", "");
446
447 response += inventoryitemstr;
448 }
449
450
451 if (response.Length == 0)
452 {
453 // Ter-guess: If requests fail a lot, the client seems to stop requesting descendants.
454 // Therefore, I'm concluding that the client only has so many threads available to do requests
455 // and when a thread stalls.. is stays stalled.
456 // Therefore we need to return something valid
457 response = "<llsd><map><key>folders</key><array /></map></llsd>";
458 }
459 else
460 {
461 response = "<llsd><map><key>folders</key><array>" + response + "</array></map></llsd>";
462 }
463
464 //m_log.DebugFormat("[CAPS]: Replying to CAPS fetch inventory request with following xml");
465 //m_log.Debug("[CAPS] "+response);
466
467 }
468 return response;
469 }
470
471
472
473 /// <summary>
474 /// Construct an LLSD reply packet to a CAPS inventory request
475 /// </summary>
476 /// <param name="invFetch"></param>
477 /// <returns></returns>
478 private LLSDInventoryDescendents FetchInventoryReply(LLSDFetchInventoryDescendents invFetch)
479 {
480 LLSDInventoryDescendents reply = new LLSDInventoryDescendents();
481 LLSDInventoryFolderContents contents = new LLSDInventoryFolderContents();
482 contents.agent_id = m_agentID;
483 contents.owner_id = invFetch.owner_id;
484 contents.folder_id = invFetch.folder_id;
485
486 reply.folders.Array.Add(contents);
487 InventoryCollection inv = new InventoryCollection();
488 inv.Folders = new List<InventoryFolderBase>();
489 inv.Items = new List<InventoryItemBase>();
490 int version = 0;
491 if (CAPSFetchInventoryDescendents != null)
492 {
493 inv = CAPSFetchInventoryDescendents(m_agentID, invFetch.folder_id, invFetch.owner_id, invFetch.fetch_folders, invFetch.fetch_items, invFetch.sort_order, out version);
494 }
495
496 if (inv.Folders != null)
497 {
498 foreach (InventoryFolderBase invFolder in inv.Folders)
499 {
500 contents.categories.Array.Add(ConvertInventoryFolder(invFolder));
501 }
502 }
503
504 if (inv.Items != null)
505 {
506 foreach (InventoryItemBase invItem in inv.Items)
507 {
508 contents.items.Array.Add(ConvertInventoryItem(invItem));
509 }
510 }
511
512 contents.descendents = contents.items.Array.Count + contents.categories.Array.Count;
513 contents.version = version;
514
515 return reply;
516 }
517
518 /// <summary>
519 /// Convert an internal inventory folder object into an LLSD object.
520 /// </summary>
521 /// <param name="invFolder"></param>
522 /// <returns></returns>
523 private LLSDInventoryFolder ConvertInventoryFolder(InventoryFolderBase invFolder)
524 {
525 LLSDInventoryFolder llsdFolder = new LLSDInventoryFolder();
526 llsdFolder.folder_id = invFolder.ID;
527 llsdFolder.parent_id = invFolder.ParentID;
528 llsdFolder.name = invFolder.Name;
529 if (invFolder.Type < 0 || invFolder.Type >= TaskInventoryItem.Types.Length)
530 llsdFolder.type = "-1";
531 else
532 llsdFolder.type = TaskInventoryItem.Types[invFolder.Type];
533 llsdFolder.preferred_type = "-1";
534
535 return llsdFolder;
536 }
537
538 /// <summary>
539 /// Convert an internal inventory item object into an LLSD object.
540 /// </summary>
541 /// <param name="invItem"></param>
542 /// <returns></returns>
543 private LLSDInventoryItem ConvertInventoryItem(InventoryItemBase invItem)
544 {
545 LLSDInventoryItem llsdItem = new LLSDInventoryItem();
546 llsdItem.asset_id = invItem.AssetID;
547 llsdItem.created_at = invItem.CreationDate;
548 llsdItem.desc = invItem.Description;
549 llsdItem.flags = (int)invItem.Flags;
550 llsdItem.item_id = invItem.ID;
551 llsdItem.name = invItem.Name;
552 llsdItem.parent_id = invItem.Folder;
553 try
554 {
555 // TODO reevaluate after upgrade to libomv >= r2566. Probably should use UtilsConversions.
556 llsdItem.type = TaskInventoryItem.Types[invItem.AssetType];
557 llsdItem.inv_type = TaskInventoryItem.InvTypes[invItem.InvType];
558 }
559 catch (Exception e)
560 {
561 m_log.Error("[CAPS]: Problem setting asset/inventory type while converting inventory item " + invItem.Name + " to LLSD:", e);
562 }
563 llsdItem.permissions = new LLSDPermissions();
564 llsdItem.permissions.creator_id = invItem.CreatorIdAsUuid;
565 llsdItem.permissions.base_mask = (int)invItem.CurrentPermissions;
566 llsdItem.permissions.everyone_mask = (int)invItem.EveryOnePermissions;
567 llsdItem.permissions.group_id = invItem.GroupID;
568 llsdItem.permissions.group_mask = (int)invItem.GroupPermissions;
569 llsdItem.permissions.is_owner_group = invItem.GroupOwned;
570 llsdItem.permissions.next_owner_mask = (int)invItem.NextPermissions;
571 llsdItem.permissions.owner_id = m_agentID;
572 llsdItem.permissions.owner_mask = (int)invItem.CurrentPermissions;
573 llsdItem.sale_info = new LLSDSaleInfo();
574 llsdItem.sale_info.sale_price = invItem.SalePrice;
575 switch (invItem.SaleType)
576 {
577 default:
578 llsdItem.sale_info.sale_type = "not";
579 break;
580 case 1:
581 llsdItem.sale_info.sale_type = "original";
582 break;
583 case 2:
584 llsdItem.sale_info.sale_type = "copy";
585 break;
586 case 3:
587 llsdItem.sale_info.sale_type = "contents";
588 break;
589 }
590
591 return llsdItem;
592 }
593
594 /// <summary>
595 ///
596 /// </summary>
597 /// <param name="mapReq"></param>
598 /// <returns></returns>
599 public LLSDMapLayerResponse GetMapLayer(LLSDMapRequest mapReq)
600 {
601 m_log.Debug("[CAPS]: MapLayer Request in region: " + m_regionName);
602 LLSDMapLayerResponse mapResponse = new LLSDMapLayerResponse();
603 mapResponse.LayerData.Array.Add(GetOSDMapLayerResponse());
604 return mapResponse;
605 }
606
607 /// <summary>
608 ///
609 /// </summary>
610 /// <returns></returns>
611 protected static OSDMapLayer GetOSDMapLayerResponse()
612 {
613 OSDMapLayer mapLayer = new OSDMapLayer();
614 mapLayer.Right = 5000;
615 mapLayer.Top = 5000;
616 mapLayer.ImageID = new UUID("00000000-0000-1111-9999-000000000006");
617
618 return mapLayer;
619 }
620
621 /// <summary>
622 ///
623 /// </summary>
624 /// <param name="request"></param>
625 /// <param name="path"></param>
626 /// <param name="param"></param>
627 /// <returns></returns>
628 public string RequestTexture(string request, string path, string param)
629 {
630 m_log.Debug("texture request " + request);
631 // Needs implementing (added to remove compiler warning)
632 return String.Empty;
633 }
634
635 #region EventQueue (Currently not enabled)
636
637 /// <summary>
638 ///
639 /// </summary>
640 /// <param name="request"></param>
641 /// <param name="path"></param>
642 /// <param name="param"></param>
643 /// <returns></returns>
644 public string ProcessEventQueue(string request, string path, string param)
645 {
646 string res = String.Empty;
647
648 if (m_capsEventQueue.Count > 0)
649 {
650 lock (m_capsEventQueue)
651 {
652 string item = m_capsEventQueue.Dequeue();
653 res = item;
654 }
655 }
656 else
657 {
658 res = CreateEmptyEventResponse();
659 }
660 return res;
661 }
662
663 /// <summary>
664 ///
665 /// </summary>
666 /// <param name="caps"></param>
667 /// <param name="ipAddressPort"></param>
668 /// <returns></returns>
669 public string CreateEstablishAgentComms(string caps, string ipAddressPort)
670 {
671 LLSDCapEvent eventItem = new LLSDCapEvent();
672 eventItem.id = m_eventQueueCount;
673 //should be creating a EstablishAgentComms item, but there isn't a class for it yet
674 eventItem.events.Array.Add(new LLSDEmpty());
675 string res = LLSDHelpers.SerialiseLLSDReply(eventItem);
676 m_eventQueueCount++;
677
678 m_capsEventQueue.Enqueue(res);
679 return res;
680 }
681
682 /// <summary>
683 ///
684 /// </summary>
685 /// <returns></returns>
686 public string CreateEmptyEventResponse()
687 {
688 LLSDCapEvent eventItem = new LLSDCapEvent();
689 eventItem.id = m_eventQueueCount;
690 eventItem.events.Array.Add(new LLSDEmpty());
691 string res = LLSDHelpers.SerialiseLLSDReply(eventItem);
692 m_eventQueueCount++;
693 return res;
694 }
695
696 #endregion
697
698 /// <summary>
699 /// Called by the script task update handler. Provides a URL to which the client can upload a new asset.
700 /// </summary>
701 /// <param name="request"></param>
702 /// <param name="path"></param>
703 /// <param name="param"></param>
704 /// <param name="httpRequest">HTTP request header object</param>
705 /// <param name="httpResponse">HTTP response header object</param>
706 /// <returns></returns>
707 public string ScriptTaskInventory(string request, string path, string param,
708 OSHttpRequest httpRequest, OSHttpResponse httpResponse)
709 {
710 try
711 {
712 m_log.Debug("[CAPS]: ScriptTaskInventory Request in region: " + m_regionName);
713 //m_log.DebugFormat("[CAPS]: request: {0}, path: {1}, param: {2}", request, path, param);
714
715 Hashtable hash = (Hashtable) LLSD.LLSDDeserialize(Utils.StringToBytes(request));
716 LLSDTaskScriptUpdate llsdUpdateRequest = new LLSDTaskScriptUpdate();
717 LLSDHelpers.DeserialiseOSDMap(hash, llsdUpdateRequest);
718
719 string capsBase = "/CAPS/" + m_capsObjectPath;
720 string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
721
722 TaskInventoryScriptUpdater uploader =
723 new TaskInventoryScriptUpdater(
724 llsdUpdateRequest.item_id,
725 llsdUpdateRequest.task_id,
726 llsdUpdateRequest.is_script_running,
727 capsBase + uploaderPath,
728 m_httpListener,
729 m_dumpAssetsToFile);
730 uploader.OnUpLoad += TaskScriptUpdated;
731
732 m_httpListener.AddStreamHandler(
733 new BinaryStreamHandler("POST", capsBase + uploaderPath, uploader.uploaderCaps));
734
735 string protocol = "http://";
736
737 if (m_httpListener.UseSSL)
738 protocol = "https://";
739
740 string uploaderURL = protocol + m_httpListenerHostName + ":" + m_httpListenPort.ToString() + capsBase +
741 uploaderPath;
742
743 LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
744 uploadResponse.uploader = uploaderURL;
745 uploadResponse.state = "upload";
746
747// m_log.InfoFormat("[CAPS]: " +
748// "ScriptTaskInventory response: {0}",
749// LLSDHelpers.SerialiseLLSDReply(uploadResponse)));
750
751 return LLSDHelpers.SerialiseLLSDReply(uploadResponse);
752 }
753 catch (Exception e)
754 {
755 m_log.Error("[CAPS]: " + e.ToString());
756 }
757
758 return null;
759 }
760
761 public string UploadBakedTexture(string request, string path,
762 string param, OSHttpRequest httpRequest,
763 OSHttpResponse httpResponse)
764 {
765 try
766 {
767// m_log.Debug("[CAPS]: UploadBakedTexture Request in region: " +
768// m_regionName);
769
770 string capsBase = "/CAPS/" + m_capsObjectPath;
771 string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
772
773 BakedTextureUploader uploader =
774 new BakedTextureUploader(capsBase + uploaderPath,
775 m_httpListener);
776 uploader.OnUpLoad += BakedTextureUploaded;
777
778 m_httpListener.AddStreamHandler(
779 new BinaryStreamHandler("POST", capsBase + uploaderPath,
780 uploader.uploaderCaps));
781
782 string protocol = "http://";
783
784 if (m_httpListener.UseSSL)
785 protocol = "https://";
786
787 string uploaderURL = protocol + m_httpListenerHostName + ":" +
788 m_httpListenPort.ToString() + capsBase + uploaderPath;
789
790 LLSDAssetUploadResponse uploadResponse =
791 new LLSDAssetUploadResponse();
792 uploadResponse.uploader = uploaderURL;
793 uploadResponse.state = "upload";
794
795 return LLSDHelpers.SerialiseLLSDReply(uploadResponse);
796 }
797 catch (Exception e)
798 {
799 m_log.Error("[CAPS]: " + e.ToString());
800 }
801
802 return null;
803 }
804
805 /// <summary>
806 /// Called by the notecard update handler. Provides a URL to which the client can upload a new asset.
807 /// </summary>
808 /// <param name="request"></param>
809 /// <param name="path"></param>
810 /// <param name="param"></param>
811 /// <returns></returns>
812 public string NoteCardAgentInventory(string request, string path, string param,
813 OSHttpRequest httpRequest, OSHttpResponse httpResponse)
814 {
815 //m_log.Debug("[CAPS]: NoteCardAgentInventory Request in region: " + m_regionName + "\n" + request);
816 //m_log.Debug("[CAPS]: NoteCardAgentInventory Request is: " + request);
817
818 //OpenMetaverse.StructuredData.OSDMap hash = (OpenMetaverse.StructuredData.OSDMap)OpenMetaverse.StructuredData.LLSDParser.DeserializeBinary(Utils.StringToBytes(request));
819 Hashtable hash = (Hashtable) LLSD.LLSDDeserialize(Utils.StringToBytes(request));
820 LLSDItemUpdate llsdRequest = new LLSDItemUpdate();
821 LLSDHelpers.DeserialiseOSDMap(hash, llsdRequest);
822
823 string capsBase = "/CAPS/" + m_capsObjectPath;
824 string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
825
826 ItemUpdater uploader =
827 new ItemUpdater(llsdRequest.item_id, capsBase + uploaderPath, m_httpListener, m_dumpAssetsToFile);
828 uploader.OnUpLoad += ItemUpdated;
829
830 m_httpListener.AddStreamHandler(
831 new BinaryStreamHandler("POST", capsBase + uploaderPath, uploader.uploaderCaps));
832
833 string protocol = "http://";
834
835 if (m_httpListener.UseSSL)
836 protocol = "https://";
837
838 string uploaderURL = protocol + m_httpListenerHostName + ":" + m_httpListenPort.ToString() + capsBase +
839 uploaderPath;
840
841 LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
842 uploadResponse.uploader = uploaderURL;
843 uploadResponse.state = "upload";
844
845// m_log.InfoFormat("[CAPS]: " +
846// "NoteCardAgentInventory response: {0}",
847// LLSDHelpers.SerialiseLLSDReply(uploadResponse)));
848
849 return LLSDHelpers.SerialiseLLSDReply(uploadResponse);
850 }
851
852 /// <summary>
853 ///
854 /// </summary>
855 /// <param name="llsdRequest"></param>
856 /// <returns></returns>
857 public LLSDAssetUploadResponse NewAgentInventoryRequest(LLSDAssetUploadRequest llsdRequest)
858 {
859 //m_log.Debug("[CAPS]: NewAgentInventoryRequest Request is: " + llsdRequest.ToString());
860 //m_log.Debug("asset upload request via CAPS" + llsdRequest.inventory_type + " , " + llsdRequest.asset_type);
861
862 if (llsdRequest.asset_type == "texture" ||
863 llsdRequest.asset_type == "animation" ||
864 llsdRequest.asset_type == "sound")
865 {
866 IClientAPI client = null;
867 IScene scene = null;
868 if (GetClient != null)
869 {
870 client = GetClient(m_agentID);
871 scene = client.Scene;
872
873 IMoneyModule mm = scene.RequestModuleInterface<IMoneyModule>();
874
875 if (mm != null)
876 {
877 if (!mm.UploadCovered(client, mm.UploadCharge))
878 {
879 if (client != null)
880 client.SendAgentAlertMessage("Unable to upload asset. Insufficient funds.", false);
881
882 LLSDAssetUploadResponse errorResponse = new LLSDAssetUploadResponse();
883 errorResponse.uploader = "";
884 errorResponse.state = "error";
885 return errorResponse;
886 }
887 }
888 }
889 }
890
891
892 string assetName = llsdRequest.name;
893 string assetDes = llsdRequest.description;
894 string capsBase = "/CAPS/" + m_capsObjectPath;
895 UUID newAsset = UUID.Random();
896 UUID newInvItem = UUID.Random();
897 UUID parentFolder = llsdRequest.folder_id;
898 string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
899
900 AssetUploader uploader =
901 new AssetUploader(assetName, assetDes, newAsset, newInvItem, parentFolder, llsdRequest.inventory_type,
902 llsdRequest.asset_type, capsBase + uploaderPath, m_httpListener, m_dumpAssetsToFile);
903 m_httpListener.AddStreamHandler(
904 new BinaryStreamHandler("POST", capsBase + uploaderPath, uploader.uploaderCaps));
905
906 string protocol = "http://";
907
908 if (m_httpListener.UseSSL)
909 protocol = "https://";
910
911 string uploaderURL = protocol + m_httpListenerHostName + ":" + m_httpListenPort.ToString() + capsBase +
912 uploaderPath;
913
914 LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
915 uploadResponse.uploader = uploaderURL;
916 uploadResponse.state = "upload";
917 uploader.OnUpLoad += UploadCompleteHandler;
918 return uploadResponse;
919 }
920
921 /// <summary>
922 ///
923 /// </summary>
924 /// <param name="assetID"></param>
925 /// <param name="inventoryItem"></param>
926 /// <param name="data"></param>
927 public void UploadCompleteHandler(string assetName, string assetDescription, UUID assetID,
928 UUID inventoryItem, UUID parentFolder, byte[] data, string inventoryType,
929 string assetType)
930 {
931 sbyte assType = 0;
932 sbyte inType = 0;
933
934 if (inventoryType == "sound")
935 {
936 inType = 1;
937 assType = 1;
938 }
939 else if (inventoryType == "animation")
940 {
941 inType = 19;
942 assType = 20;
943 }
944 else if (inventoryType == "wearable")
945 {
946 inType = 18;
947 switch (assetType)
948 {
949 case "bodypart":
950 assType = 13;
951 break;
952 case "clothing":
953 assType = 5;
954 break;
955 }
956 }
957
958 AssetBase asset;
959 asset = new AssetBase(assetID, assetName, assType, m_agentID.ToString());
960 asset.Data = data;
961 if (AddNewAsset != null)
962 AddNewAsset(asset);
963 else if (m_assetCache != null)
964 m_assetCache.Store(asset);
965
966 InventoryItemBase item = new InventoryItemBase();
967 item.Owner = m_agentID;
968 item.CreatorId = m_agentID.ToString();
969 item.CreatorData = String.Empty;
970 item.ID = inventoryItem;
971 item.AssetID = asset.FullID;
972 item.Description = assetDescription;
973 item.Name = assetName;
974 item.AssetType = assType;
975 item.InvType = inType;
976 item.Folder = parentFolder;
977 item.CurrentPermissions = (uint)PermissionMask.All;
978 item.BasePermissions = (uint)PermissionMask.All;
979 item.EveryOnePermissions = 0;
980 item.NextPermissions = (uint)(PermissionMask.Move | PermissionMask.Modify | PermissionMask.Transfer);
981 item.CreationDate = Util.UnixTimeSinceEpoch();
982
983 if (AddNewInventoryItem != null)
984 {
985 AddNewInventoryItem(m_agentID, item);
986 }
987 }
988
989 public void BakedTextureUploaded(UUID assetID, byte[] data)
990 {
991// m_log.WarnFormat("[CAPS]: Received baked texture {0}", assetID.ToString());
992
993 AssetBase asset;
994 asset = new AssetBase(assetID, "Baked Texture", (sbyte)AssetType.Texture, m_agentID.ToString());
995 asset.Data = data;
996 asset.Temporary = true;
997 asset.Local = ! m_persistBakedTextures; // Local assets aren't persisted, non-local are
998 m_assetCache.Store(asset);
999 }
1000
1001 /// <summary>
1002 /// Called when new asset data for an agent inventory item update has been uploaded.
1003 /// </summary>
1004 /// <param name="itemID">Item to update</param>
1005 /// <param name="data">New asset data</param>
1006 /// <returns></returns>
1007 public UUID ItemUpdated(UUID itemID, byte[] data)
1008 {
1009 if (ItemUpdatedCall != null)
1010 {
1011 return ItemUpdatedCall(m_agentID, itemID, data);
1012 }
1013
1014 return UUID.Zero;
1015 }
1016
1017 /// <summary>
1018 /// Called when new asset data for an agent inventory item update has been uploaded.
1019 /// </summary>
1020 /// <param name="itemID">Item to update</param>
1021 /// <param name="primID">Prim containing item to update</param>
1022 /// <param name="isScriptRunning">Signals whether the script to update is currently running</param>
1023 /// <param name="data">New asset data</param>
1024 public void TaskScriptUpdated(UUID itemID, UUID primID, bool isScriptRunning, byte[] data, ref ArrayList errors)
1025 {
1026 if (TaskScriptUpdatedCall != null)
1027 {
1028 ArrayList e = TaskScriptUpdatedCall(m_agentID, itemID, primID, isScriptRunning, data);
1029 foreach (Object item in e)
1030 errors.Add(item);
1031 }
1032 }
1033
1034 public class AssetUploader
1035 {
1036 public event UpLoadedAsset OnUpLoad;
1037 private UpLoadedAsset handlerUpLoad = null;
1038
1039 private string uploaderPath = String.Empty;
1040 private UUID newAssetID;
1041 private UUID inventoryItemID;
1042 private UUID parentFolder;
1043 private IHttpServer httpListener;
1044 private bool m_dumpAssetsToFile;
1045 private string m_assetName = String.Empty;
1046 private string m_assetDes = String.Empty;
1047
1048 private string m_invType = String.Empty;
1049 private string m_assetType = String.Empty;
1050
1051 public AssetUploader(string assetName, string description, UUID assetID, UUID inventoryItem,
1052 UUID parentFolderID, string invType, string assetType, string path,
1053 IHttpServer httpServer, bool dumpAssetsToFile)
1054 {
1055 m_assetName = assetName;
1056 m_assetDes = description;
1057 newAssetID = assetID;
1058 inventoryItemID = inventoryItem;
1059 uploaderPath = path;
1060 httpListener = httpServer;
1061 parentFolder = parentFolderID;
1062 m_assetType = assetType;
1063 m_invType = invType;
1064 m_dumpAssetsToFile = dumpAssetsToFile;
1065 }
1066
1067 /// <summary>
1068 ///
1069 /// </summary>
1070 /// <param name="data"></param>
1071 /// <param name="path"></param>
1072 /// <param name="param"></param>
1073 /// <returns></returns>
1074 public string uploaderCaps(byte[] data, string path, string param)
1075 {
1076 UUID inv = inventoryItemID;
1077 string res = String.Empty;
1078 LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
1079 uploadComplete.new_asset = newAssetID.ToString();
1080 uploadComplete.new_inventory_item = inv;
1081 uploadComplete.state = "complete";
1082
1083 res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
1084
1085 httpListener.RemoveStreamHandler("POST", uploaderPath);
1086
1087 // TODO: probably make this a better set of extensions here
1088 string extension = ".jp2";
1089 if (m_invType != "image")
1090 {
1091 extension = ".dat";
1092 }
1093
1094 if (m_dumpAssetsToFile)
1095 {
1096 SaveAssetToFile(m_assetName + extension, data);
1097 }
1098 handlerUpLoad = OnUpLoad;
1099 if (handlerUpLoad != null)
1100 {
1101 handlerUpLoad(m_assetName, m_assetDes, newAssetID, inv, parentFolder, data, m_invType, m_assetType);
1102 }
1103
1104 return res;
1105 }
1106 ///Left this in and commented in case there are unforseen issues
1107 //private void SaveAssetToFile(string filename, byte[] data)
1108 //{
1109 // FileStream fs = File.Create(filename);
1110 // BinaryWriter bw = new BinaryWriter(fs);
1111 // bw.Write(data);
1112 // bw.Close();
1113 // fs.Close();
1114 //}
1115 private static void SaveAssetToFile(string filename, byte[] data)
1116 {
1117 string assetPath = "UserAssets";
1118 if (!Directory.Exists(assetPath))
1119 {
1120 Directory.CreateDirectory(assetPath);
1121 }
1122 FileStream fs = File.Create(Path.Combine(assetPath, Util.safeFileName(filename)));
1123 BinaryWriter bw = new BinaryWriter(fs);
1124 bw.Write(data);
1125 bw.Close();
1126 fs.Close();
1127 }
1128 }
1129
1130 /// <summary>
1131 /// This class is a callback invoked when a client sends asset data to
1132 /// an agent inventory notecard update url
1133 /// </summary>
1134 public class ItemUpdater
1135 {
1136 public event UpdateItem OnUpLoad;
1137
1138 private UpdateItem handlerUpdateItem = null;
1139
1140 private string uploaderPath = String.Empty;
1141 private UUID inventoryItemID;
1142 private IHttpServer httpListener;
1143 private bool m_dumpAssetToFile;
1144
1145 public ItemUpdater(UUID inventoryItem, string path, IHttpServer httpServer, bool dumpAssetToFile)
1146 {
1147 m_dumpAssetToFile = dumpAssetToFile;
1148
1149 inventoryItemID = inventoryItem;
1150 uploaderPath = path;
1151 httpListener = httpServer;
1152 }
1153
1154 /// <summary>
1155 ///
1156 /// </summary>
1157 /// <param name="data"></param>
1158 /// <param name="path"></param>
1159 /// <param name="param"></param>
1160 /// <returns></returns>
1161 public string uploaderCaps(byte[] data, string path, string param)
1162 {
1163 UUID inv = inventoryItemID;
1164 string res = String.Empty;
1165 LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
1166 UUID assetID = UUID.Zero;
1167 handlerUpdateItem = OnUpLoad;
1168 if (handlerUpdateItem != null)
1169 {
1170 assetID = handlerUpdateItem(inv, data);
1171 }
1172
1173 uploadComplete.new_asset = assetID.ToString();
1174 uploadComplete.new_inventory_item = inv;
1175 uploadComplete.state = "complete";
1176
1177 res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
1178
1179 httpListener.RemoveStreamHandler("POST", uploaderPath);
1180
1181 if (m_dumpAssetToFile)
1182 {
1183 SaveAssetToFile("updateditem" + Util.RandomClass.Next(1, 1000) + ".dat", data);
1184 }
1185
1186 return res;
1187 }
1188 ///Left this in and commented in case there are unforseen issues
1189 //private void SaveAssetToFile(string filename, byte[] data)
1190 //{
1191 // FileStream fs = File.Create(filename);
1192 // BinaryWriter bw = new BinaryWriter(fs);
1193 // bw.Write(data);
1194 // bw.Close();
1195 // fs.Close();
1196 //}
1197 private static void SaveAssetToFile(string filename, byte[] data)
1198 {
1199 string assetPath = "UserAssets";
1200 if (!Directory.Exists(assetPath))
1201 {
1202 Directory.CreateDirectory(assetPath);
1203 }
1204 FileStream fs = File.Create(Path.Combine(assetPath, filename));
1205 BinaryWriter bw = new BinaryWriter(fs);
1206 bw.Write(data);
1207 bw.Close();
1208 fs.Close();
1209 }
1210 }
1211
1212 /// <summary>
1213 /// This class is a callback invoked when a client sends asset data to
1214 /// a task inventory script update url
1215 /// </summary>
1216 public class TaskInventoryScriptUpdater
1217 {
1218 public event UpdateTaskScript OnUpLoad;
1219
1220 private UpdateTaskScript handlerUpdateTaskScript = null;
1221
1222 private string uploaderPath = String.Empty;
1223 private UUID inventoryItemID;
1224 private UUID primID;
1225 private bool isScriptRunning;
1226 private IHttpServer httpListener;
1227 private bool m_dumpAssetToFile;
1228
1229 public TaskInventoryScriptUpdater(UUID inventoryItemID, UUID primID, int isScriptRunning,
1230 string path, IHttpServer httpServer, bool dumpAssetToFile)
1231 {
1232 m_dumpAssetToFile = dumpAssetToFile;
1233
1234 this.inventoryItemID = inventoryItemID;
1235 this.primID = primID;
1236
1237 // This comes in over the packet as an integer, but actually appears to be treated as a bool
1238 this.isScriptRunning = (0 == isScriptRunning ? false : true);
1239
1240 uploaderPath = path;
1241 httpListener = httpServer;
1242 }
1243
1244 /// <summary>
1245 ///
1246 /// </summary>
1247 /// <param name="data"></param>
1248 /// <param name="path"></param>
1249 /// <param name="param"></param>
1250 /// <returns></returns>
1251 public string uploaderCaps(byte[] data, string path, string param)
1252 {
1253 try
1254 {
1255// m_log.InfoFormat("[CAPS]: " +
1256// "TaskInventoryScriptUpdater received data: {0}, path: {1}, param: {2}",
1257// data, path, param));
1258
1259 string res = String.Empty;
1260 LLSDTaskScriptUploadComplete uploadComplete = new LLSDTaskScriptUploadComplete();
1261
1262 ArrayList errors = new ArrayList();
1263 handlerUpdateTaskScript = OnUpLoad;
1264 if (handlerUpdateTaskScript != null)
1265 {
1266 handlerUpdateTaskScript(inventoryItemID, primID, isScriptRunning, data, ref errors);
1267 }
1268
1269 uploadComplete.new_asset = inventoryItemID;
1270 uploadComplete.compiled = errors.Count > 0 ? false : true;
1271 uploadComplete.state = "complete";
1272 uploadComplete.errors = new OSDArray();
1273 uploadComplete.errors.Array = errors;
1274
1275 res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
1276
1277 httpListener.RemoveStreamHandler("POST", uploaderPath);
1278
1279 if (m_dumpAssetToFile)
1280 {
1281 SaveAssetToFile("updatedtaskscript" + Util.RandomClass.Next(1, 1000) + ".dat", data);
1282 }
1283
1284// m_log.InfoFormat("[CAPS]: TaskInventoryScriptUpdater.uploaderCaps res: {0}", res);
1285
1286 return res;
1287 }
1288 catch (Exception e)
1289 {
1290 m_log.Error("[CAPS]: " + e.ToString());
1291 }
1292
1293 // XXX Maybe this should be some meaningful error packet
1294 return null;
1295 }
1296 ///Left this in and commented in case there are unforseen issues
1297 //private void SaveAssetToFile(string filename, byte[] data)
1298 //{
1299 // FileStream fs = File.Create(filename);
1300 // BinaryWriter bw = new BinaryWriter(fs);
1301 // bw.Write(data);
1302 // bw.Close();
1303 // fs.Close();
1304 //}
1305 private static void SaveAssetToFile(string filename, byte[] data)
1306 {
1307 string assetPath = "UserAssets";
1308 if (!Directory.Exists(assetPath))
1309 {
1310 Directory.CreateDirectory(assetPath);
1311 }
1312 FileStream fs = File.Create(Path.Combine(assetPath, filename));
1313 BinaryWriter bw = new BinaryWriter(fs);
1314 bw.Write(data);
1315 bw.Close();
1316 fs.Close();
1317 }
1318 }
1319
1320 public class BakedTextureUploader
1321 {
1322 public event UploadedBakedTexture OnUpLoad;
1323 private UploadedBakedTexture handlerUpLoad = null;
1324
1325 private string uploaderPath = String.Empty;
1326 private UUID newAssetID;
1327 private IHttpServer httpListener;
1328
1329 public BakedTextureUploader(string path, IHttpServer httpServer)
1330 {
1331 newAssetID = UUID.Random();
1332 uploaderPath = path;
1333 httpListener = httpServer;
1334// m_log.InfoFormat("[CAPS] baked texture upload starting for {0}",newAssetID);
1335 }
1336
1337 /// <summary>
1338 ///
1339 /// </summary>
1340 /// <param name="data"></param>
1341 /// <param name="path"></param>
1342 /// <param name="param"></param>
1343 /// <returns></returns>
1344 public string uploaderCaps(byte[] data, string path, string param)
1345 {
1346 handlerUpLoad = OnUpLoad;
1347 if (handlerUpLoad != null)
1348 {
1349 Util.FireAndForget(delegate(object o) { handlerUpLoad(newAssetID, data); });
1350 }
1351
1352 string res = String.Empty;
1353 LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
1354 uploadComplete.new_asset = newAssetID.ToString();
1355 uploadComplete.new_inventory_item = UUID.Zero;
1356 uploadComplete.state = "complete";
1357
1358 res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
1359
1360 httpListener.RemoveStreamHandler("POST", uploaderPath);
1361
1362// m_log.InfoFormat("[CAPS] baked texture upload completed for {0}",newAssetID);
1363
1364 return res;
1365 }
1366 }
1367 }
1368}