BunchOfCaps.cs 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309
  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. using System;
  28. using System.Collections;
  29. using System.Collections.Generic;
  30. using System.IO;
  31. using System.Reflection;
  32. using System.Text;
  33. using OpenMetaverse;
  34. using OpenMetaverse.StructuredData;
  35. using Nini.Config;
  36. using log4net;
  37. using OpenSim.Framework;
  38. using OpenSim.Framework.Capabilities;
  39. using OpenSim.Region.Framework;
  40. using OpenSim.Region.Framework.Scenes;
  41. using OpenSim.Region.Framework.Scenes.Serialization;
  42. using OpenSim.Framework.Servers;
  43. using OpenSim.Framework.Servers.HttpServer;
  44. using OpenSim.Framework.Client;
  45. using OpenSim.Services.Interfaces;
  46. using Caps = OpenSim.Framework.Capabilities.Caps;
  47. using OSDArray = OpenMetaverse.StructuredData.OSDArray;
  48. using OSDMap = OpenMetaverse.StructuredData.OSDMap;
  49. using PermissionMask = OpenSim.Framework.PermissionMask;
  50. namespace OpenSim.Region.ClientStack.Linden
  51. {
  52. public delegate void UpLoadedAsset(
  53. string assetName, string description, UUID assetID, UUID inventoryItem, UUID parentFolder,
  54. byte[] data, string inventoryType, string assetType);
  55. public delegate UUID UpdateItem(UUID itemID, byte[] data);
  56. public delegate void UpdateTaskScript(UUID itemID, UUID primID, bool isScriptRunning, byte[] data, ref ArrayList errors);
  57. public delegate void NewInventoryItem(UUID userID, InventoryItemBase item);
  58. public delegate void NewAsset(AssetBase asset);
  59. public delegate UUID ItemUpdatedCallback(UUID userID, UUID itemID, byte[] data);
  60. public delegate ArrayList TaskScriptUpdatedCallback(UUID userID, UUID itemID, UUID primID,
  61. bool isScriptRunning, byte[] data);
  62. public delegate InventoryCollection FetchInventoryDescendentsCAPS(UUID agentID, UUID folderID, UUID ownerID,
  63. bool fetchFolders, bool fetchItems, int sortOrder, out int version);
  64. /// <summary>
  65. /// XXX Probably not a particularly nice way of allow us to get the scene presence from the scene (chiefly so that
  66. /// we can popup a message on the user's client if the inventory service has permanently failed). But I didn't want
  67. /// to just pass the whole Scene into CAPS.
  68. /// </summary>
  69. public delegate IClientAPI GetClientDelegate(UUID agentID);
  70. public class BunchOfCaps
  71. {
  72. private static readonly ILog m_log =
  73. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  74. private Scene m_Scene;
  75. private Caps m_HostCapsObj;
  76. private static readonly string m_requestPath = "0000/";
  77. // private static readonly string m_mapLayerPath = "0001/";
  78. private static readonly string m_newInventory = "0002/";
  79. //private static readonly string m_requestTexture = "0003/";
  80. private static readonly string m_notecardUpdatePath = "0004/";
  81. private static readonly string m_notecardTaskUpdatePath = "0005/";
  82. // private static readonly string m_fetchInventoryPath = "0006/";
  83. private static readonly string m_copyFromNotecardPath = "0007/";
  84. // private static readonly string m_remoteParcelRequestPath = "0009/";// This is in the LandManagementModule.
  85. private static readonly string m_getObjectPhysicsDataPath = "0101/";
  86. /* 0102 - 0103 RESERVED */
  87. private static readonly string m_UpdateAgentInformationPath = "0500/";
  88. // These are callbacks which will be setup by the scene so that we can update scene data when we
  89. // receive capability calls
  90. public NewInventoryItem AddNewInventoryItem = null;
  91. public NewAsset AddNewAsset = null;
  92. public ItemUpdatedCallback ItemUpdatedCall = null;
  93. public TaskScriptUpdatedCallback TaskScriptUpdatedCall = null;
  94. public FetchInventoryDescendentsCAPS CAPSFetchInventoryDescendents = null;
  95. public GetClientDelegate GetClient = null;
  96. private bool m_persistBakedTextures = false;
  97. private IAssetService m_assetService;
  98. private bool m_dumpAssetsToFile = false;
  99. private string m_regionName;
  100. private int m_levelUpload = 0;
  101. public BunchOfCaps(Scene scene, Caps caps)
  102. {
  103. m_Scene = scene;
  104. m_HostCapsObj = caps;
  105. IConfigSource config = m_Scene.Config;
  106. if (config != null)
  107. {
  108. IConfig sconfig = config.Configs["Startup"];
  109. if (sconfig != null)
  110. {
  111. m_levelUpload = sconfig.GetInt("LevelUpload", 0);
  112. }
  113. IConfig appearanceConfig = config.Configs["Appearance"];
  114. if (appearanceConfig != null)
  115. {
  116. m_persistBakedTextures = appearanceConfig.GetBoolean("PersistBakedTextures", m_persistBakedTextures);
  117. }
  118. }
  119. m_assetService = m_Scene.AssetService;
  120. m_regionName = m_Scene.RegionInfo.RegionName;
  121. RegisterHandlers();
  122. AddNewInventoryItem = m_Scene.AddUploadedInventoryItem;
  123. ItemUpdatedCall = m_Scene.CapsUpdateInventoryItemAsset;
  124. TaskScriptUpdatedCall = m_Scene.CapsUpdateTaskInventoryScriptAsset;
  125. GetClient = m_Scene.SceneGraph.GetControllingClient;
  126. }
  127. /// <summary>
  128. /// Register a bunch of CAPS http service handlers
  129. /// </summary>
  130. public void RegisterHandlers()
  131. {
  132. string capsBase = "/CAPS/" + m_HostCapsObj.CapsObjectPath;
  133. RegisterRegionServiceHandlers(capsBase);
  134. RegisterInventoryServiceHandlers(capsBase);
  135. }
  136. public void RegisterRegionServiceHandlers(string capsBase)
  137. {
  138. try
  139. {
  140. // the root of all evil
  141. m_HostCapsObj.RegisterHandler(
  142. "SEED", new RestStreamHandler("POST", capsBase + m_requestPath, SeedCapRequest, "SEED", null));
  143. // m_log.DebugFormat(
  144. // "[CAPS]: Registered seed capability {0} for {1}", capsBase + m_requestPath, m_HostCapsObj.AgentID);
  145. //m_capsHandlers["MapLayer"] =
  146. // new LLSDStreamhandler<OSDMapRequest, OSDMapLayerResponse>("POST",
  147. // capsBase + m_mapLayerPath,
  148. // GetMapLayer);
  149. IRequestHandler req
  150. = new RestStreamHandler(
  151. "POST", capsBase + m_notecardTaskUpdatePath, ScriptTaskInventory, "UpdateScript", null);
  152. m_HostCapsObj.RegisterHandler("UpdateScriptTaskInventory", req);
  153. m_HostCapsObj.RegisterHandler("UpdateScriptTask", req);
  154. }
  155. catch (Exception e)
  156. {
  157. m_log.Error("[CAPS]: " + e.ToString());
  158. }
  159. }
  160. public void RegisterInventoryServiceHandlers(string capsBase)
  161. {
  162. try
  163. {
  164. // I don't think this one works...
  165. m_HostCapsObj.RegisterHandler(
  166. "NewFileAgentInventory",
  167. new LLSDStreamhandler<LLSDAssetUploadRequest, LLSDAssetUploadResponse>(
  168. "POST",
  169. capsBase + m_newInventory,
  170. NewAgentInventoryRequest,
  171. "NewFileAgentInventory",
  172. null));
  173. IRequestHandler req
  174. = new RestStreamHandler(
  175. "POST", capsBase + m_notecardUpdatePath, NoteCardAgentInventory, "Update*", null);
  176. m_HostCapsObj.RegisterHandler("UpdateNotecardAgentInventory", req);
  177. m_HostCapsObj.RegisterHandler("UpdateScriptAgentInventory", req);
  178. m_HostCapsObj.RegisterHandler("UpdateScriptAgent", req);
  179. IRequestHandler getObjectPhysicsDataHandler
  180. = new RestStreamHandler(
  181. "POST", capsBase + m_getObjectPhysicsDataPath, GetObjectPhysicsData, "GetObjectPhysicsData", null);
  182. m_HostCapsObj.RegisterHandler("GetObjectPhysicsData", getObjectPhysicsDataHandler);
  183. IRequestHandler UpdateAgentInformationHandler
  184. = new RestStreamHandler(
  185. "POST", capsBase + m_UpdateAgentInformationPath, UpdateAgentInformation, "UpdateAgentInformation", null);
  186. m_HostCapsObj.RegisterHandler("UpdateAgentInformation", UpdateAgentInformationHandler);
  187. m_HostCapsObj.RegisterHandler(
  188. "CopyInventoryFromNotecard",
  189. new RestStreamHandler(
  190. "POST", capsBase + m_copyFromNotecardPath, CopyInventoryFromNotecard, "CopyInventoryFromNotecard", null));
  191. // As of RC 1.22.9 of the Linden client this is
  192. // supported
  193. //m_capsHandlers["WebFetchInventoryDescendents"] =new RestStreamHandler("POST", capsBase + m_fetchInventoryPath, FetchInventoryDescendentsRequest);
  194. // justincc: I've disabled the CAPS service for now to fix problems with selecting textures, and
  195. // subsequent inventory breakage, in the edit object pane (such as mantis 1085). This requires
  196. // enhancements (probably filling out the folder part of the LLSD reply) to our CAPS service,
  197. // but when I went on the Linden grid, the
  198. // simulators I visited (version 1.21) were, surprisingly, no longer supplying this capability. Instead,
  199. // the 1.19.1.4 client appeared to be happily flowing inventory data over UDP
  200. //
  201. // This is very probably just a temporary measure - once the CAPS service appears again on the Linden grid
  202. // we will be
  203. // able to get the data we need to implement the necessary part of the protocol to fix the issue above.
  204. // m_capsHandlers["FetchInventoryDescendents"] =
  205. // new RestStreamHandler("POST", capsBase + m_fetchInventoryPath, FetchInventoryRequest);
  206. // m_capsHandlers["FetchInventoryDescendents"] =
  207. // new LLSDStreamhandler<LLSDFetchInventoryDescendents, LLSDInventoryDescendents>("POST",
  208. // capsBase + m_fetchInventory,
  209. // FetchInventory));
  210. // m_capsHandlers["RequestTextureDownload"] = new RestStreamHandler("POST",
  211. // capsBase + m_requestTexture,
  212. // RequestTexture);
  213. }
  214. catch (Exception e)
  215. {
  216. m_log.Error("[CAPS]: " + e.ToString());
  217. }
  218. }
  219. /// <summary>
  220. /// Construct a client response detailing all the capabilities this server can provide.
  221. /// </summary>
  222. /// <param name="request"></param>
  223. /// <param name="path"></param>
  224. /// <param name="param"></param>
  225. /// <param name="httpRequest">HTTP request header object</param>
  226. /// <param name="httpResponse">HTTP response header object</param>
  227. /// <returns></returns>
  228. public string SeedCapRequest(string request, string path, string param,
  229. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  230. {
  231. // m_log.DebugFormat(
  232. // "[CAPS]: Received SEED caps request in {0} for agent {1}", m_regionName, m_HostCapsObj.AgentID);
  233. if (!m_Scene.CheckClient(m_HostCapsObj.AgentID, httpRequest.RemoteIPEndPoint))
  234. {
  235. m_log.WarnFormat(
  236. "[CAPS]: Unauthorized CAPS client {0} from {1}",
  237. m_HostCapsObj.AgentID, httpRequest.RemoteIPEndPoint);
  238. return string.Empty;
  239. }
  240. OSDArray capsRequested = (OSDArray)OSDParser.DeserializeLLSDXml(request);
  241. List<string> validCaps = new List<string>();
  242. foreach (OSD c in capsRequested)
  243. validCaps.Add(c.AsString());
  244. string result = LLSDHelpers.SerialiseLLSDReply(m_HostCapsObj.GetCapsDetails(true, validCaps));
  245. //m_log.DebugFormat("[CAPS] CapsRequest {0}", result);
  246. return result;
  247. }
  248. /// <summary>
  249. /// Called by the script task update handler. Provides a URL to which the client can upload a new asset.
  250. /// </summary>
  251. /// <param name="request"></param>
  252. /// <param name="path"></param>
  253. /// <param name="param"></param>
  254. /// <param name="httpRequest">HTTP request header object</param>
  255. /// <param name="httpResponse">HTTP response header object</param>
  256. /// <returns></returns>
  257. public string ScriptTaskInventory(string request, string path, string param,
  258. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  259. {
  260. try
  261. {
  262. // m_log.Debug("[CAPS]: ScriptTaskInventory Request in region: " + m_regionName);
  263. //m_log.DebugFormat("[CAPS]: request: {0}, path: {1}, param: {2}", request, path, param);
  264. Hashtable hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request));
  265. LLSDTaskScriptUpdate llsdUpdateRequest = new LLSDTaskScriptUpdate();
  266. LLSDHelpers.DeserialiseOSDMap(hash, llsdUpdateRequest);
  267. string capsBase = "/CAPS/" + m_HostCapsObj.CapsObjectPath;
  268. string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
  269. TaskInventoryScriptUpdater uploader =
  270. new TaskInventoryScriptUpdater(
  271. llsdUpdateRequest.item_id,
  272. llsdUpdateRequest.task_id,
  273. llsdUpdateRequest.is_script_running,
  274. capsBase + uploaderPath,
  275. m_HostCapsObj.HttpListener,
  276. m_dumpAssetsToFile);
  277. uploader.OnUpLoad += TaskScriptUpdated;
  278. m_HostCapsObj.HttpListener.AddStreamHandler(
  279. new BinaryStreamHandler(
  280. "POST", capsBase + uploaderPath, uploader.uploaderCaps, "TaskInventoryScriptUpdater", null));
  281. string protocol = "http://";
  282. if (m_HostCapsObj.SSLCaps)
  283. protocol = "https://";
  284. string uploaderURL = protocol + m_HostCapsObj.HostName + ":" + m_HostCapsObj.Port.ToString() + capsBase +
  285. uploaderPath;
  286. LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
  287. uploadResponse.uploader = uploaderURL;
  288. uploadResponse.state = "upload";
  289. // m_log.InfoFormat("[CAPS]: " +
  290. // "ScriptTaskInventory response: {0}",
  291. // LLSDHelpers.SerialiseLLSDReply(uploadResponse)));
  292. return LLSDHelpers.SerialiseLLSDReply(uploadResponse);
  293. }
  294. catch (Exception e)
  295. {
  296. m_log.Error("[CAPS]: " + e.ToString());
  297. }
  298. return null;
  299. }
  300. /// <summary>
  301. /// Called when new asset data for an agent inventory item update has been uploaded.
  302. /// </summary>
  303. /// <param name="itemID">Item to update</param>
  304. /// <param name="primID">Prim containing item to update</param>
  305. /// <param name="isScriptRunning">Signals whether the script to update is currently running</param>
  306. /// <param name="data">New asset data</param>
  307. public void TaskScriptUpdated(UUID itemID, UUID primID, bool isScriptRunning, byte[] data, ref ArrayList errors)
  308. {
  309. if (TaskScriptUpdatedCall != null)
  310. {
  311. ArrayList e = TaskScriptUpdatedCall(m_HostCapsObj.AgentID, itemID, primID, isScriptRunning, data);
  312. foreach (Object item in e)
  313. errors.Add(item);
  314. }
  315. }
  316. /// <summary>
  317. /// Called when new asset data for an agent inventory item update has been uploaded.
  318. /// </summary>
  319. /// <param name="itemID">Item to update</param>
  320. /// <param name="data">New asset data</param>
  321. /// <returns></returns>
  322. public UUID ItemUpdated(UUID itemID, byte[] data)
  323. {
  324. if (ItemUpdatedCall != null)
  325. {
  326. return ItemUpdatedCall(m_HostCapsObj.AgentID, itemID, data);
  327. }
  328. return UUID.Zero;
  329. }
  330. /// <summary>
  331. ///
  332. /// </summary>
  333. /// <param name="llsdRequest"></param>
  334. /// <returns></returns>
  335. public LLSDAssetUploadResponse NewAgentInventoryRequest(LLSDAssetUploadRequest llsdRequest)
  336. {
  337. //m_log.Debug("[CAPS]: NewAgentInventoryRequest Request is: " + llsdRequest.ToString());
  338. //m_log.Debug("asset upload request via CAPS" + llsdRequest.inventory_type + " , " + llsdRequest.asset_type);
  339. if (llsdRequest.asset_type == "texture" ||
  340. llsdRequest.asset_type == "animation" ||
  341. llsdRequest.asset_type == "sound")
  342. {
  343. ScenePresence avatar = null;
  344. IClientAPI client = null;
  345. m_Scene.TryGetScenePresence(m_HostCapsObj.AgentID, out avatar);
  346. // check user level
  347. if (avatar != null)
  348. {
  349. client = avatar.ControllingClient;
  350. if (avatar.UserLevel < m_levelUpload)
  351. {
  352. if (client != null)
  353. client.SendAgentAlertMessage("Unable to upload asset. Insufficient permissions.", false);
  354. LLSDAssetUploadResponse errorResponse = new LLSDAssetUploadResponse();
  355. errorResponse.uploader = "";
  356. errorResponse.state = "error";
  357. return errorResponse;
  358. }
  359. }
  360. // check funds
  361. if (client != null)
  362. {
  363. IMoneyModule mm = m_Scene.RequestModuleInterface<IMoneyModule>();
  364. if (mm != null)
  365. {
  366. if (!mm.UploadCovered(client.AgentId, mm.UploadCharge))
  367. {
  368. client.SendAgentAlertMessage("Unable to upload asset. Insufficient funds.", false);
  369. LLSDAssetUploadResponse errorResponse = new LLSDAssetUploadResponse();
  370. errorResponse.uploader = "";
  371. errorResponse.state = "error";
  372. return errorResponse;
  373. }
  374. }
  375. }
  376. }
  377. string assetName = llsdRequest.name;
  378. string assetDes = llsdRequest.description;
  379. string capsBase = "/CAPS/" + m_HostCapsObj.CapsObjectPath;
  380. UUID newAsset = UUID.Random();
  381. UUID newInvItem = UUID.Random();
  382. UUID parentFolder = llsdRequest.folder_id;
  383. string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
  384. AssetUploader uploader =
  385. new AssetUploader(assetName, assetDes, newAsset, newInvItem, parentFolder, llsdRequest.inventory_type,
  386. llsdRequest.asset_type, capsBase + uploaderPath, m_HostCapsObj.HttpListener, m_dumpAssetsToFile);
  387. m_HostCapsObj.HttpListener.AddStreamHandler(
  388. new BinaryStreamHandler(
  389. "POST",
  390. capsBase + uploaderPath,
  391. uploader.uploaderCaps,
  392. "NewAgentInventoryRequest",
  393. m_HostCapsObj.AgentID.ToString()));
  394. string protocol = "http://";
  395. if (m_HostCapsObj.SSLCaps)
  396. protocol = "https://";
  397. string uploaderURL = protocol + m_HostCapsObj.HostName + ":" + m_HostCapsObj.Port.ToString() + capsBase +
  398. uploaderPath;
  399. LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
  400. uploadResponse.uploader = uploaderURL;
  401. uploadResponse.state = "upload";
  402. uploader.OnUpLoad += UploadCompleteHandler;
  403. return uploadResponse;
  404. }
  405. /// <summary>
  406. /// Convert raw uploaded data into the appropriate asset and item.
  407. /// </summary>
  408. /// <param name="assetID"></param>
  409. /// <param name="inventoryItem"></param>
  410. /// <param name="data"></param>
  411. public void UploadCompleteHandler(string assetName, string assetDescription, UUID assetID,
  412. UUID inventoryItem, UUID parentFolder, byte[] data, string inventoryType,
  413. string assetType)
  414. {
  415. m_log.DebugFormat(
  416. "[BUNCH OF CAPS]: Uploaded asset {0} for inventory item {1}, inv type {2}, asset type {3}",
  417. assetID, inventoryItem, inventoryType, assetType);
  418. sbyte assType = 0;
  419. sbyte inType = 0;
  420. if (inventoryType == "sound")
  421. {
  422. inType = (sbyte)InventoryType.Sound;
  423. assType = (sbyte)AssetType.Sound;
  424. }
  425. else if (inventoryType == "snapshot")
  426. {
  427. inType = (sbyte)InventoryType.Snapshot;
  428. }
  429. else if (inventoryType == "animation")
  430. {
  431. inType = (sbyte)InventoryType.Animation;
  432. assType = (sbyte)AssetType.Animation;
  433. }
  434. else if (inventoryType == "wearable")
  435. {
  436. inType = (sbyte)InventoryType.Wearable;
  437. switch (assetType)
  438. {
  439. case "bodypart":
  440. assType = (sbyte)AssetType.Bodypart;
  441. break;
  442. case "clothing":
  443. assType = (sbyte)AssetType.Clothing;
  444. break;
  445. }
  446. }
  447. else if (inventoryType == "object")
  448. {
  449. inType = (sbyte)InventoryType.Object;
  450. assType = (sbyte)AssetType.Object;
  451. List<Vector3> positions = new List<Vector3>();
  452. List<Quaternion> rotations = new List<Quaternion>();
  453. OSDMap request = (OSDMap)OSDParser.DeserializeLLSDXml(data);
  454. OSDArray instance_list = (OSDArray)request["instance_list"];
  455. OSDArray mesh_list = (OSDArray)request["mesh_list"];
  456. OSDArray texture_list = (OSDArray)request["texture_list"];
  457. SceneObjectGroup grp = null;
  458. InventoryFolderBase textureUploadFolder = null;
  459. List<InventoryFolderBase> foldersToUpdate = new List<InventoryFolderBase>();
  460. List<InventoryItemBase> itemsToUpdate = new List<InventoryItemBase>();
  461. IClientInventory clientInv = null;
  462. if (texture_list.Count > 0)
  463. {
  464. ScenePresence avatar = null;
  465. m_Scene.TryGetScenePresence(m_HostCapsObj.AgentID, out avatar);
  466. if (avatar != null)
  467. {
  468. IClientCore core = (IClientCore)avatar.ControllingClient;
  469. if (core.TryGet<IClientInventory>(out clientInv))
  470. {
  471. var systemTextureFolder = m_Scene.InventoryService.GetFolderForType(m_HostCapsObj.AgentID, AssetType.Texture);
  472. textureUploadFolder = new InventoryFolderBase(UUID.Random(), assetName, m_HostCapsObj.AgentID, (short)AssetType.Unknown, systemTextureFolder.ID, 1);
  473. if (m_Scene.InventoryService.AddFolder(textureUploadFolder))
  474. {
  475. foldersToUpdate.Add(textureUploadFolder);
  476. m_log.DebugFormat(
  477. "[BUNCH OF CAPS]: Created new folder '{0}' ({1}) for textures uploaded with mesh object {2}",
  478. textureUploadFolder.Name, textureUploadFolder.ID, assetName);
  479. }
  480. else
  481. {
  482. textureUploadFolder = null;
  483. }
  484. }
  485. }
  486. }
  487. List<UUID> textures = new List<UUID>();
  488. for (int i = 0; i < texture_list.Count; i++)
  489. {
  490. AssetBase textureAsset = new AssetBase(UUID.Random(), assetName, (sbyte)AssetType.Texture, "");
  491. textureAsset.Data = texture_list[i].AsBinary();
  492. m_assetService.Store(textureAsset);
  493. textures.Add(textureAsset.FullID);
  494. if (textureUploadFolder != null)
  495. {
  496. InventoryItemBase textureItem = new InventoryItemBase();
  497. textureItem.Owner = m_HostCapsObj.AgentID;
  498. textureItem.CreatorId = m_HostCapsObj.AgentID.ToString();
  499. textureItem.CreatorData = String.Empty;
  500. textureItem.ID = UUID.Random();
  501. textureItem.AssetID = textureAsset.FullID;
  502. textureItem.Description = assetDescription;
  503. textureItem.Name = assetName + " - Texture " + (i + 1).ToString();
  504. textureItem.AssetType = (int)AssetType.Texture;
  505. textureItem.InvType = (int)InventoryType.Texture;
  506. textureItem.Folder = textureUploadFolder.ID;
  507. textureItem.CurrentPermissions
  508. = (uint)(PermissionMask.Move | PermissionMask.Copy | PermissionMask.Modify | PermissionMask.Transfer | PermissionMask.Export);
  509. textureItem.BasePermissions = (uint)PermissionMask.All | (uint)PermissionMask.Export;
  510. textureItem.EveryOnePermissions = 0;
  511. textureItem.NextPermissions = (uint)PermissionMask.All;
  512. textureItem.CreationDate = Util.UnixTimeSinceEpoch();
  513. m_Scene.InventoryService.AddItem(textureItem);
  514. itemsToUpdate.Add(textureItem);
  515. m_log.DebugFormat(
  516. "[BUNCH OF CAPS]: Created new inventory item '{0}' ({1}) for texture uploaded with mesh object {2}",
  517. textureItem.Name, textureItem.ID, assetName);
  518. }
  519. }
  520. if (clientInv != null && (foldersToUpdate.Count > 0 || itemsToUpdate.Count > 0))
  521. {
  522. clientInv.SendBulkUpdateInventory(foldersToUpdate.ToArray(), itemsToUpdate.ToArray());
  523. }
  524. for (int i = 0; i < mesh_list.Count; i++)
  525. {
  526. PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox();
  527. Primitive.TextureEntry textureEntry
  528. = new Primitive.TextureEntry(Primitive.TextureEntry.WHITE_TEXTURE);
  529. OSDMap inner_instance_list = (OSDMap)instance_list[i];
  530. OSDArray face_list = (OSDArray)inner_instance_list["face_list"];
  531. for (uint face = 0; face < face_list.Count; face++)
  532. {
  533. OSDMap faceMap = (OSDMap)face_list[(int)face];
  534. Primitive.TextureEntryFace f = pbs.Textures.CreateFace(face);
  535. if(faceMap.ContainsKey("fullbright"))
  536. f.Fullbright = faceMap["fullbright"].AsBoolean();
  537. if (faceMap.ContainsKey ("diffuse_color"))
  538. f.RGBA = faceMap["diffuse_color"].AsColor4();
  539. int textureNum = faceMap["image"].AsInteger();
  540. float imagerot = faceMap["imagerot"].AsInteger();
  541. float offsets = (float)faceMap["offsets"].AsReal();
  542. float offsett = (float)faceMap["offsett"].AsReal();
  543. float scales = (float)faceMap["scales"].AsReal();
  544. float scalet = (float)faceMap["scalet"].AsReal();
  545. if(imagerot != 0)
  546. f.Rotation = imagerot;
  547. if(offsets != 0)
  548. f.OffsetU = offsets;
  549. if (offsett != 0)
  550. f.OffsetV = offsett;
  551. if (scales != 0)
  552. f.RepeatU = scales;
  553. if (scalet != 0)
  554. f.RepeatV = scalet;
  555. if (textures.Count > textureNum)
  556. f.TextureID = textures[textureNum];
  557. else
  558. f.TextureID = Primitive.TextureEntry.WHITE_TEXTURE;
  559. textureEntry.FaceTextures[face] = f;
  560. }
  561. pbs.TextureEntry = textureEntry.GetBytes();
  562. AssetBase meshAsset = new AssetBase(UUID.Random(), assetName, (sbyte)AssetType.Mesh, "");
  563. meshAsset.Data = mesh_list[i].AsBinary();
  564. m_assetService.Store(meshAsset);
  565. pbs.SculptEntry = true;
  566. pbs.SculptTexture = meshAsset.FullID;
  567. pbs.SculptType = (byte)SculptType.Mesh;
  568. pbs.SculptData = meshAsset.Data;
  569. Vector3 position = inner_instance_list["position"].AsVector3();
  570. Vector3 scale = inner_instance_list["scale"].AsVector3();
  571. Quaternion rotation = inner_instance_list["rotation"].AsQuaternion();
  572. // no longer used - begin ------------------------
  573. // int physicsShapeType = inner_instance_list["physics_shape_type"].AsInteger();
  574. // int material = inner_instance_list["material"].AsInteger();
  575. // int mesh = inner_instance_list["mesh"].AsInteger();
  576. // OSDMap permissions = (OSDMap)inner_instance_list["permissions"];
  577. // int base_mask = permissions["base_mask"].AsInteger();
  578. // int everyone_mask = permissions["everyone_mask"].AsInteger();
  579. // UUID creator_id = permissions["creator_id"].AsUUID();
  580. // UUID group_id = permissions["group_id"].AsUUID();
  581. // int group_mask = permissions["group_mask"].AsInteger();
  582. // bool is_owner_group = permissions["is_owner_group"].AsBoolean();
  583. // UUID last_owner_id = permissions["last_owner_id"].AsUUID();
  584. // int next_owner_mask = permissions["next_owner_mask"].AsInteger();
  585. // UUID owner_id = permissions["owner_id"].AsUUID();
  586. // int owner_mask = permissions["owner_mask"].AsInteger();
  587. // no longer used - end ------------------------
  588. UUID owner_id = m_HostCapsObj.AgentID;
  589. SceneObjectPart prim
  590. = new SceneObjectPart(owner_id, pbs, position, Quaternion.Identity, Vector3.Zero);
  591. prim.Scale = scale;
  592. //prim.OffsetPosition = position;
  593. rotations.Add(rotation);
  594. positions.Add(position);
  595. prim.UUID = UUID.Random();
  596. prim.CreatorID = owner_id;
  597. prim.OwnerID = owner_id;
  598. prim.GroupID = UUID.Zero;
  599. prim.LastOwnerID = prim.OwnerID;
  600. prim.CreationDate = Util.UnixTimeSinceEpoch();
  601. prim.Name = assetName;
  602. prim.Description = "";
  603. // prim.BaseMask = (uint)base_mask;
  604. // prim.EveryoneMask = (uint)everyone_mask;
  605. // prim.GroupMask = (uint)group_mask;
  606. // prim.NextOwnerMask = (uint)next_owner_mask;
  607. // prim.OwnerMask = (uint)owner_mask;
  608. if (grp == null)
  609. grp = new SceneObjectGroup(prim);
  610. else
  611. grp.AddPart(prim);
  612. }
  613. Vector3 rootPos = positions[0];
  614. if (grp.Parts.Length > 1)
  615. {
  616. // Fix first link number
  617. grp.RootPart.LinkNum++;
  618. Quaternion rootRotConj = Quaternion.Conjugate(rotations[0]);
  619. Quaternion tmprot;
  620. Vector3 offset;
  621. // fix children rotations and positions
  622. for (int i = 1; i < rotations.Count; i++)
  623. {
  624. tmprot = rotations[i];
  625. tmprot = rootRotConj * tmprot;
  626. grp.Parts[i].RotationOffset = tmprot;
  627. offset = positions[i] - rootPos;
  628. offset *= rootRotConj;
  629. grp.Parts[i].OffsetPosition = offset;
  630. }
  631. grp.AbsolutePosition = rootPos;
  632. grp.UpdateGroupRotationR(rotations[0]);
  633. }
  634. else
  635. {
  636. grp.AbsolutePosition = rootPos;
  637. grp.UpdateGroupRotationR(rotations[0]);
  638. }
  639. data = ASCIIEncoding.ASCII.GetBytes(SceneObjectSerializer.ToOriginalXmlFormat(grp));
  640. }
  641. AssetBase asset;
  642. asset = new AssetBase(assetID, assetName, assType, m_HostCapsObj.AgentID.ToString());
  643. asset.Data = data;
  644. if (AddNewAsset != null)
  645. AddNewAsset(asset);
  646. else if (m_assetService != null)
  647. m_assetService.Store(asset);
  648. InventoryItemBase item = new InventoryItemBase();
  649. item.Owner = m_HostCapsObj.AgentID;
  650. item.CreatorId = m_HostCapsObj.AgentID.ToString();
  651. item.CreatorData = String.Empty;
  652. item.ID = inventoryItem;
  653. item.AssetID = asset.FullID;
  654. item.Description = assetDescription;
  655. item.Name = assetName;
  656. item.AssetType = assType;
  657. item.InvType = inType;
  658. item.Folder = parentFolder;
  659. // If we set PermissionMask.All then when we rez the item the next permissions will replace the current
  660. // (owner) permissions. This becomes a problem if next permissions are changed.
  661. item.CurrentPermissions
  662. = (uint)(PermissionMask.Move | PermissionMask.Copy | PermissionMask.Modify | PermissionMask.Transfer | PermissionMask.Export);
  663. item.BasePermissions = (uint)PermissionMask.All | (uint)PermissionMask.Export;
  664. item.EveryOnePermissions = 0;
  665. item.NextPermissions = (uint)PermissionMask.All;
  666. item.CreationDate = Util.UnixTimeSinceEpoch();
  667. if (AddNewInventoryItem != null)
  668. {
  669. AddNewInventoryItem(m_HostCapsObj.AgentID, item);
  670. }
  671. }
  672. /// <summary>
  673. ///
  674. /// </summary>
  675. /// <param name="mapReq"></param>
  676. /// <returns></returns>
  677. public LLSDMapLayerResponse GetMapLayer(LLSDMapRequest mapReq)
  678. {
  679. m_log.Debug("[CAPS]: MapLayer Request in region: " + m_regionName);
  680. LLSDMapLayerResponse mapResponse = new LLSDMapLayerResponse();
  681. mapResponse.LayerData.Array.Add(GetOSDMapLayerResponse());
  682. return mapResponse;
  683. }
  684. /// <summary>
  685. ///
  686. /// </summary>
  687. /// <returns></returns>
  688. protected static OSDMapLayer GetOSDMapLayerResponse()
  689. {
  690. OSDMapLayer mapLayer = new OSDMapLayer();
  691. mapLayer.Right = 5000;
  692. mapLayer.Top = 5000;
  693. mapLayer.ImageID = new UUID("00000000-0000-1111-9999-000000000006");
  694. return mapLayer;
  695. }
  696. /// <summary>
  697. ///
  698. /// </summary>
  699. /// <param name="request"></param>
  700. /// <param name="path"></param>
  701. /// <param name="param"></param>
  702. /// <returns></returns>
  703. public string RequestTexture(string request, string path, string param)
  704. {
  705. m_log.Debug("texture request " + request);
  706. // Needs implementing (added to remove compiler warning)
  707. return String.Empty;
  708. }
  709. /// <summary>
  710. /// Called by the notecard update handler. Provides a URL to which the client can upload a new asset.
  711. /// </summary>
  712. /// <param name="request"></param>
  713. /// <param name="path"></param>
  714. /// <param name="param"></param>
  715. /// <returns></returns>
  716. public string NoteCardAgentInventory(string request, string path, string param,
  717. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  718. {
  719. //m_log.Debug("[CAPS]: NoteCardAgentInventory Request in region: " + m_regionName + "\n" + request);
  720. //m_log.Debug("[CAPS]: NoteCardAgentInventory Request is: " + request);
  721. //OpenMetaverse.StructuredData.OSDMap hash = (OpenMetaverse.StructuredData.OSDMap)OpenMetaverse.StructuredData.LLSDParser.DeserializeBinary(Utils.StringToBytes(request));
  722. Hashtable hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request));
  723. LLSDItemUpdate llsdRequest = new LLSDItemUpdate();
  724. LLSDHelpers.DeserialiseOSDMap(hash, llsdRequest);
  725. string capsBase = "/CAPS/" + m_HostCapsObj.CapsObjectPath;
  726. string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000");
  727. ItemUpdater uploader =
  728. new ItemUpdater(llsdRequest.item_id, capsBase + uploaderPath, m_HostCapsObj.HttpListener, m_dumpAssetsToFile);
  729. uploader.OnUpLoad += ItemUpdated;
  730. m_HostCapsObj.HttpListener.AddStreamHandler(
  731. new BinaryStreamHandler(
  732. "POST", capsBase + uploaderPath, uploader.uploaderCaps, "NoteCardAgentInventory", null));
  733. string protocol = "http://";
  734. if (m_HostCapsObj.SSLCaps)
  735. protocol = "https://";
  736. string uploaderURL = protocol + m_HostCapsObj.HostName + ":" + m_HostCapsObj.Port.ToString() + capsBase +
  737. uploaderPath;
  738. LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
  739. uploadResponse.uploader = uploaderURL;
  740. uploadResponse.state = "upload";
  741. // m_log.InfoFormat("[CAPS]: " +
  742. // "NoteCardAgentInventory response: {0}",
  743. // LLSDHelpers.SerialiseLLSDReply(uploadResponse)));
  744. return LLSDHelpers.SerialiseLLSDReply(uploadResponse);
  745. }
  746. /// <summary>
  747. /// Called by the CopyInventoryFromNotecard caps handler.
  748. /// </summary>
  749. /// <param name="request"></param>
  750. /// <param name="path"></param>
  751. /// <param name="param"></param>
  752. public string CopyInventoryFromNotecard(string request, string path, string param,
  753. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  754. {
  755. Hashtable response = new Hashtable();
  756. response["int_response_code"] = 404;
  757. response["content_type"] = "text/plain";
  758. response["keepalive"] = false;
  759. response["str_response_string"] = "";
  760. try
  761. {
  762. OSDMap content = (OSDMap)OSDParser.DeserializeLLSDXml(request);
  763. UUID objectID = content["object-id"].AsUUID();
  764. UUID notecardID = content["notecard-id"].AsUUID();
  765. UUID folderID = content["folder-id"].AsUUID();
  766. UUID itemID = content["item-id"].AsUUID();
  767. // m_log.InfoFormat("[CAPS]: CopyInventoryFromNotecard, FolderID:{0}, ItemID:{1}, NotecardID:{2}, ObjectID:{3}", folderID, itemID, notecardID, objectID);
  768. if (objectID != UUID.Zero)
  769. {
  770. SceneObjectPart part = m_Scene.GetSceneObjectPart(objectID);
  771. if (part != null)
  772. {
  773. // TaskInventoryItem taskItem = part.Inventory.GetInventoryItem(notecardID);
  774. if (!m_Scene.Permissions.CanCopyObjectInventory(notecardID, objectID, m_HostCapsObj.AgentID))
  775. {
  776. return LLSDHelpers.SerialiseLLSDReply(response);
  777. }
  778. }
  779. }
  780. InventoryItemBase item = null;
  781. InventoryItemBase copyItem = null;
  782. IClientAPI client = null;
  783. m_Scene.TryGetClient(m_HostCapsObj.AgentID, out client);
  784. item = m_Scene.InventoryService.GetItem(new InventoryItemBase(itemID));
  785. if (item != null)
  786. {
  787. string message;
  788. copyItem = m_Scene.GiveInventoryItem(m_HostCapsObj.AgentID, item.Owner, itemID, folderID, out message);
  789. if (client != null)
  790. {
  791. if (copyItem != null)
  792. {
  793. m_log.InfoFormat("[CAPS]: CopyInventoryFromNotecard, ItemID:{0}, FolderID:{1}", copyItem.ID, copyItem.Folder);
  794. client.SendBulkUpdateInventory(copyItem);
  795. }
  796. else
  797. {
  798. client.SendAgentAlertMessage(message, false);
  799. }
  800. }
  801. }
  802. else
  803. {
  804. m_log.ErrorFormat("[CAPS]: CopyInventoryFromNotecard - Failed to retrieve item {0} from notecard {1}", itemID, notecardID);
  805. if (client != null)
  806. client.SendAgentAlertMessage("Failed to retrieve item", false);
  807. }
  808. }
  809. catch (Exception e)
  810. {
  811. m_log.ErrorFormat("[CAPS]: CopyInventoryFromNotecard : {0}", e.ToString());
  812. }
  813. response["int_response_code"] = 200;
  814. return LLSDHelpers.SerialiseLLSDReply(response);
  815. }
  816. public string GetObjectPhysicsData(string request, string path,
  817. string param, IOSHttpRequest httpRequest,
  818. IOSHttpResponse httpResponse)
  819. {
  820. OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request);
  821. OSDMap resp = new OSDMap();
  822. OSDArray object_ids = (OSDArray)req["object_ids"];
  823. for (int i = 0 ; i < object_ids.Count ; i++)
  824. {
  825. UUID uuid = object_ids[i].AsUUID();
  826. SceneObjectPart obj = m_Scene.GetSceneObjectPart(uuid);
  827. if (obj != null)
  828. {
  829. OSDMap object_data = new OSDMap();
  830. object_data["PhysicsShapeType"] = obj.PhysicsShapeType;
  831. object_data["Density"] = obj.Density;
  832. object_data["Friction"] = obj.Friction;
  833. object_data["Restitution"] = obj.Restitution;
  834. object_data["GravityMultiplier"] = obj.GravityModifier;
  835. resp[uuid.ToString()] = object_data;
  836. }
  837. }
  838. string response = OSDParser.SerializeLLSDXmlString(resp);
  839. return response;
  840. }
  841. public string UpdateAgentInformation(string request, string path,
  842. string param, IOSHttpRequest httpRequest,
  843. IOSHttpResponse httpResponse)
  844. {
  845. OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request);
  846. OSDMap accessPrefs = (OSDMap)req["access_prefs"];
  847. string desiredMaturity = accessPrefs["max"];
  848. OSDMap resp = new OSDMap();
  849. OSDMap respAccessPrefs = new OSDMap();
  850. respAccessPrefs["max"] = desiredMaturity; // echoing the maturity back means success
  851. resp["access_prefs"] = respAccessPrefs;
  852. string response = OSDParser.SerializeLLSDXmlString(resp);
  853. return response;
  854. }
  855. }
  856. public class AssetUploader
  857. {
  858. public event UpLoadedAsset OnUpLoad;
  859. private UpLoadedAsset handlerUpLoad = null;
  860. private string uploaderPath = String.Empty;
  861. private UUID newAssetID;
  862. private UUID inventoryItemID;
  863. private UUID parentFolder;
  864. private IHttpServer httpListener;
  865. private bool m_dumpAssetsToFile;
  866. private string m_assetName = String.Empty;
  867. private string m_assetDes = String.Empty;
  868. private string m_invType = String.Empty;
  869. private string m_assetType = String.Empty;
  870. public AssetUploader(string assetName, string description, UUID assetID, UUID inventoryItem,
  871. UUID parentFolderID, string invType, string assetType, string path,
  872. IHttpServer httpServer, bool dumpAssetsToFile)
  873. {
  874. m_assetName = assetName;
  875. m_assetDes = description;
  876. newAssetID = assetID;
  877. inventoryItemID = inventoryItem;
  878. uploaderPath = path;
  879. httpListener = httpServer;
  880. parentFolder = parentFolderID;
  881. m_assetType = assetType;
  882. m_invType = invType;
  883. m_dumpAssetsToFile = dumpAssetsToFile;
  884. }
  885. /// <summary>
  886. /// Handle raw asset upload data via the capability.
  887. /// </summary>
  888. /// <param name="data"></param>
  889. /// <param name="path"></param>
  890. /// <param name="param"></param>
  891. /// <returns></returns>
  892. public string uploaderCaps(byte[] data, string path, string param)
  893. {
  894. UUID inv = inventoryItemID;
  895. string res = String.Empty;
  896. LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
  897. uploadComplete.new_asset = newAssetID.ToString();
  898. uploadComplete.new_inventory_item = inv;
  899. uploadComplete.state = "complete";
  900. res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
  901. httpListener.RemoveStreamHandler("POST", uploaderPath);
  902. // TODO: probably make this a better set of extensions here
  903. string extension = ".jp2";
  904. if (m_invType != "image")
  905. {
  906. extension = ".dat";
  907. }
  908. if (m_dumpAssetsToFile)
  909. {
  910. SaveAssetToFile(m_assetName + extension, data);
  911. }
  912. handlerUpLoad = OnUpLoad;
  913. if (handlerUpLoad != null)
  914. {
  915. handlerUpLoad(m_assetName, m_assetDes, newAssetID, inv, parentFolder, data, m_invType, m_assetType);
  916. }
  917. return res;
  918. }
  919. ///Left this in and commented in case there are unforseen issues
  920. //private void SaveAssetToFile(string filename, byte[] data)
  921. //{
  922. // FileStream fs = File.Create(filename);
  923. // BinaryWriter bw = new BinaryWriter(fs);
  924. // bw.Write(data);
  925. // bw.Close();
  926. // fs.Close();
  927. //}
  928. private static void SaveAssetToFile(string filename, byte[] data)
  929. {
  930. string assetPath = "UserAssets";
  931. if (!Directory.Exists(assetPath))
  932. {
  933. Directory.CreateDirectory(assetPath);
  934. }
  935. FileStream fs = File.Create(Path.Combine(assetPath, Util.safeFileName(filename)));
  936. BinaryWriter bw = new BinaryWriter(fs);
  937. bw.Write(data);
  938. bw.Close();
  939. fs.Close();
  940. }
  941. }
  942. /// <summary>
  943. /// This class is a callback invoked when a client sends asset data to
  944. /// an agent inventory notecard update url
  945. /// </summary>
  946. public class ItemUpdater
  947. {
  948. public event UpdateItem OnUpLoad;
  949. private UpdateItem handlerUpdateItem = null;
  950. private string uploaderPath = String.Empty;
  951. private UUID inventoryItemID;
  952. private IHttpServer httpListener;
  953. private bool m_dumpAssetToFile;
  954. public ItemUpdater(UUID inventoryItem, string path, IHttpServer httpServer, bool dumpAssetToFile)
  955. {
  956. m_dumpAssetToFile = dumpAssetToFile;
  957. inventoryItemID = inventoryItem;
  958. uploaderPath = path;
  959. httpListener = httpServer;
  960. }
  961. /// <summary>
  962. /// Handle raw uploaded asset data.
  963. /// </summary>
  964. /// <param name="data"></param>
  965. /// <param name="path"></param>
  966. /// <param name="param"></param>
  967. /// <returns></returns>
  968. public string uploaderCaps(byte[] data, string path, string param)
  969. {
  970. UUID inv = inventoryItemID;
  971. string res = String.Empty;
  972. LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
  973. UUID assetID = UUID.Zero;
  974. handlerUpdateItem = OnUpLoad;
  975. if (handlerUpdateItem != null)
  976. {
  977. assetID = handlerUpdateItem(inv, data);
  978. }
  979. uploadComplete.new_asset = assetID.ToString();
  980. uploadComplete.new_inventory_item = inv;
  981. uploadComplete.state = "complete";
  982. res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
  983. httpListener.RemoveStreamHandler("POST", uploaderPath);
  984. if (m_dumpAssetToFile)
  985. {
  986. SaveAssetToFile("updateditem" + Util.RandomClass.Next(1, 1000) + ".dat", data);
  987. }
  988. return res;
  989. }
  990. ///Left this in and commented in case there are unforseen issues
  991. //private void SaveAssetToFile(string filename, byte[] data)
  992. //{
  993. // FileStream fs = File.Create(filename);
  994. // BinaryWriter bw = new BinaryWriter(fs);
  995. // bw.Write(data);
  996. // bw.Close();
  997. // fs.Close();
  998. //}
  999. private static void SaveAssetToFile(string filename, byte[] data)
  1000. {
  1001. string assetPath = "UserAssets";
  1002. if (!Directory.Exists(assetPath))
  1003. {
  1004. Directory.CreateDirectory(assetPath);
  1005. }
  1006. FileStream fs = File.Create(Path.Combine(assetPath, filename));
  1007. BinaryWriter bw = new BinaryWriter(fs);
  1008. bw.Write(data);
  1009. bw.Close();
  1010. fs.Close();
  1011. }
  1012. }
  1013. /// <summary>
  1014. /// This class is a callback invoked when a client sends asset data to
  1015. /// a task inventory script update url
  1016. /// </summary>
  1017. public class TaskInventoryScriptUpdater
  1018. {
  1019. private static readonly ILog m_log =
  1020. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  1021. public event UpdateTaskScript OnUpLoad;
  1022. private UpdateTaskScript handlerUpdateTaskScript = null;
  1023. private string uploaderPath = String.Empty;
  1024. private UUID inventoryItemID;
  1025. private UUID primID;
  1026. private bool isScriptRunning;
  1027. private IHttpServer httpListener;
  1028. private bool m_dumpAssetToFile;
  1029. public TaskInventoryScriptUpdater(UUID inventoryItemID, UUID primID, int isScriptRunning,
  1030. string path, IHttpServer httpServer, bool dumpAssetToFile)
  1031. {
  1032. m_dumpAssetToFile = dumpAssetToFile;
  1033. this.inventoryItemID = inventoryItemID;
  1034. this.primID = primID;
  1035. // This comes in over the packet as an integer, but actually appears to be treated as a bool
  1036. this.isScriptRunning = (0 == isScriptRunning ? false : true);
  1037. uploaderPath = path;
  1038. httpListener = httpServer;
  1039. }
  1040. /// <summary>
  1041. ///
  1042. /// </summary>
  1043. /// <param name="data"></param>
  1044. /// <param name="path"></param>
  1045. /// <param name="param"></param>
  1046. /// <returns></returns>
  1047. public string uploaderCaps(byte[] data, string path, string param)
  1048. {
  1049. try
  1050. {
  1051. // m_log.InfoFormat("[CAPS]: " +
  1052. // "TaskInventoryScriptUpdater received data: {0}, path: {1}, param: {2}",
  1053. // data, path, param));
  1054. string res = String.Empty;
  1055. LLSDTaskScriptUploadComplete uploadComplete = new LLSDTaskScriptUploadComplete();
  1056. ArrayList errors = new ArrayList();
  1057. handlerUpdateTaskScript = OnUpLoad;
  1058. if (handlerUpdateTaskScript != null)
  1059. {
  1060. handlerUpdateTaskScript(inventoryItemID, primID, isScriptRunning, data, ref errors);
  1061. }
  1062. uploadComplete.new_asset = inventoryItemID;
  1063. uploadComplete.compiled = errors.Count > 0 ? false : true;
  1064. uploadComplete.state = "complete";
  1065. uploadComplete.errors = new OpenSim.Framework.Capabilities.OSDArray();
  1066. uploadComplete.errors.Array = errors;
  1067. res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
  1068. httpListener.RemoveStreamHandler("POST", uploaderPath);
  1069. if (m_dumpAssetToFile)
  1070. {
  1071. SaveAssetToFile("updatedtaskscript" + Util.RandomClass.Next(1, 1000) + ".dat", data);
  1072. }
  1073. // m_log.InfoFormat("[CAPS]: TaskInventoryScriptUpdater.uploaderCaps res: {0}", res);
  1074. return res;
  1075. }
  1076. catch (Exception e)
  1077. {
  1078. m_log.Error("[CAPS]: " + e.ToString());
  1079. }
  1080. // XXX Maybe this should be some meaningful error packet
  1081. return null;
  1082. }
  1083. ///Left this in and commented in case there are unforseen issues
  1084. //private void SaveAssetToFile(string filename, byte[] data)
  1085. //{
  1086. // FileStream fs = File.Create(filename);
  1087. // BinaryWriter bw = new BinaryWriter(fs);
  1088. // bw.Write(data);
  1089. // bw.Close();
  1090. // fs.Close();
  1091. //}
  1092. private static void SaveAssetToFile(string filename, byte[] data)
  1093. {
  1094. string assetPath = "UserAssets";
  1095. if (!Directory.Exists(assetPath))
  1096. {
  1097. Directory.CreateDirectory(assetPath);
  1098. }
  1099. FileStream fs = File.Create(Path.Combine(assetPath, filename));
  1100. BinaryWriter bw = new BinaryWriter(fs);
  1101. bw.Write(data);
  1102. bw.Close();
  1103. fs.Close();
  1104. }
  1105. }
  1106. }