1
0

BunchOfCaps.cs 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346
  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.Timers;
  29. using System.Collections;
  30. using System.Collections.Generic;
  31. using System.Collections.Specialized;
  32. using System.IO;
  33. using System.Reflection;
  34. using System.Text;
  35. using System.Web;
  36. using OpenMetaverse;
  37. using OpenMetaverse.StructuredData;
  38. using Nini.Config;
  39. using log4net;
  40. using OpenSim.Framework;
  41. using OpenSim.Framework.Capabilities;
  42. using OpenSim.Region.Framework;
  43. using OpenSim.Region.Framework.Interfaces;
  44. using OpenSim.Region.Framework.Scenes;
  45. using OpenSim.Region.Framework.Scenes.Serialization;
  46. using OpenSim.Framework.Servers;
  47. using OpenSim.Framework.Servers.HttpServer;
  48. using OpenSim.Services.Interfaces;
  49. using Caps = OpenSim.Framework.Capabilities.Caps;
  50. using OSDArray = OpenMetaverse.StructuredData.OSDArray;
  51. using OSDMap = OpenMetaverse.StructuredData.OSDMap;
  52. using PermissionMask = OpenSim.Framework.PermissionMask;
  53. namespace OpenSim.Region.ClientStack.Linden
  54. {
  55. public delegate void UpLoadedAsset(
  56. string assetName, string description, UUID assetID, UUID inventoryItem, UUID parentFolder,
  57. byte[] data, string inventoryType, string assetType,
  58. int cost, UUID texturesFolder, int nreqtextures, int nreqmeshs, int nreqinstances,
  59. bool IsAtestUpload, ref string error, ref int nextOwnerMask, ref int groupMask, ref int everyoneMask);
  60. public delegate UUID UpdateItem(UUID itemID, byte[] data);
  61. public delegate void UpdateTaskScript(UUID itemID, UUID primID, bool isScriptRunning, byte[] data, ref ArrayList errors);
  62. public delegate void NewInventoryItem(UUID userID, InventoryItemBase item, uint cost);
  63. public delegate void NewAsset(AssetBase asset);
  64. public delegate UUID ItemUpdatedCallback(UUID userID, UUID itemID, byte[] data);
  65. public delegate ArrayList TaskScriptUpdatedCallback(UUID userID, UUID itemID, UUID primID,
  66. bool isScriptRunning, byte[] data);
  67. public delegate InventoryCollection FetchInventoryDescendentsCAPS(UUID agentID, UUID folderID, UUID ownerID,
  68. bool fetchFolders, bool fetchItems, int sortOrder, out int version);
  69. /// <summary>
  70. /// XXX Probably not a particularly nice way of allow us to get the scene presence from the scene (chiefly so that
  71. /// we can popup a message on the user's client if the inventory service has permanently failed). But I didn't want
  72. /// to just pass the whole Scene into CAPS.
  73. /// </summary>
  74. public delegate IClientAPI GetClientDelegate(UUID agentID);
  75. public class BunchOfCaps
  76. {
  77. private static readonly ILog m_log =
  78. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  79. private Scene m_Scene;
  80. private UUID m_AgentID;
  81. private Caps m_HostCapsObj;
  82. private ModelCost m_ModelCost;
  83. // private static readonly string m_remoteParcelRequestPath = "0009/";// This is in the LandManagementModule.
  84. // These are callbacks which will be setup by the scene so that we can update scene data when we
  85. // receive capability calls
  86. public NewInventoryItem AddNewInventoryItem = null;
  87. public NewAsset AddNewAsset = null;
  88. public ItemUpdatedCallback ItemUpdatedCall = null;
  89. public TaskScriptUpdatedCallback TaskScriptUpdatedCall = null;
  90. public FetchInventoryDescendentsCAPS CAPSFetchInventoryDescendents = null;
  91. public GetClientDelegate GetClient = null;
  92. private bool m_persistBakedTextures = false;
  93. private IAssetService m_assetService;
  94. private bool m_dumpAssetsToFile = false;
  95. private string m_regionName;
  96. private int m_levelUpload = 0;
  97. private bool m_enableFreeTestUpload = false; // allows "TEST-" prefix hack
  98. private bool m_ForceFreeTestUpload = false; // forces all uploads to be test
  99. private bool m_enableModelUploadTextureToInventory = false; // place uploaded textures also in inventory
  100. // may not be visible till relog
  101. private bool m_RestrictFreeTestUploadPerms = false; // reduces also the permitions. Needs a creator defined!!
  102. private UUID m_testAssetsCreatorID = UUID.Zero;
  103. private float m_PrimScaleMin = 0.001f;
  104. private bool m_AllowCapHomeLocation = true;
  105. private bool m_AllowCapGroupMemberData = true;
  106. private IUserManagement m_UserManager;
  107. private enum FileAgentInventoryState : int
  108. {
  109. idle = 0,
  110. processRequest = 1,
  111. waitUpload = 2,
  112. processUpload = 3
  113. }
  114. private FileAgentInventoryState m_FileAgentInventoryState = FileAgentInventoryState.idle;
  115. public BunchOfCaps(Scene scene, UUID agentID, Caps caps)
  116. {
  117. m_Scene = scene;
  118. m_AgentID = agentID;
  119. m_HostCapsObj = caps;
  120. // create a model upload cost provider
  121. m_ModelCost = new ModelCost(scene);
  122. m_PrimScaleMin = m_ModelCost.PrimScaleMin;
  123. IConfigSource config = m_Scene.Config;
  124. if (config != null)
  125. {
  126. IConfig sconfig = config.Configs["Startup"];
  127. if (sconfig != null)
  128. {
  129. m_levelUpload = sconfig.GetInt("LevelUpload", 0);
  130. }
  131. IConfig appearanceConfig = config.Configs["Appearance"];
  132. if (appearanceConfig != null)
  133. {
  134. m_persistBakedTextures = appearanceConfig.GetBoolean("PersistBakedTextures", m_persistBakedTextures);
  135. }
  136. // economy for model upload
  137. IConfig EconomyConfig = config.Configs["Economy"];
  138. if (EconomyConfig != null)
  139. {
  140. m_ModelCost.Econfig(EconomyConfig);
  141. m_enableModelUploadTextureToInventory = EconomyConfig.GetBoolean("MeshModelAllowTextureToInventory", m_enableModelUploadTextureToInventory);
  142. m_RestrictFreeTestUploadPerms = EconomyConfig.GetBoolean("m_RestrictFreeTestUploadPerms", m_RestrictFreeTestUploadPerms);
  143. m_enableFreeTestUpload = EconomyConfig.GetBoolean("AllowFreeTestUpload", m_enableFreeTestUpload);
  144. m_ForceFreeTestUpload = EconomyConfig.GetBoolean("ForceFreeTestUpload", m_ForceFreeTestUpload);
  145. string testcreator = EconomyConfig.GetString("TestAssetsCreatorID", "");
  146. if (testcreator != "")
  147. {
  148. UUID id;
  149. UUID.TryParse(testcreator, out id);
  150. if (id != null)
  151. m_testAssetsCreatorID = id;
  152. }
  153. }
  154. IConfig CapsConfig = config.Configs["ClientStack.LindenCaps"];
  155. if (CapsConfig != null)
  156. {
  157. string homeLocationUrl = CapsConfig.GetString("Cap_HomeLocation", "localhost");
  158. if(homeLocationUrl == String.Empty)
  159. m_AllowCapHomeLocation = false;
  160. string GroupMemberDataUrl = CapsConfig.GetString("Cap_GroupMemberData", "localhost");
  161. if(GroupMemberDataUrl == String.Empty)
  162. m_AllowCapGroupMemberData = false;
  163. }
  164. }
  165. m_assetService = m_Scene.AssetService;
  166. m_regionName = m_Scene.RegionInfo.RegionName;
  167. m_UserManager = m_Scene.RequestModuleInterface<IUserManagement>();
  168. if (m_UserManager == null)
  169. m_log.Error("[CAPS]: GetDisplayNames disabled because user management component not found");
  170. RegisterHandlers();
  171. AddNewInventoryItem = m_Scene.AddUploadedInventoryItem;
  172. ItemUpdatedCall = m_Scene.CapsUpdateInventoryItemAsset;
  173. TaskScriptUpdatedCall = m_Scene.CapsUpdateTaskInventoryScriptAsset;
  174. GetClient = m_Scene.SceneGraph.GetControllingClient;
  175. m_FileAgentInventoryState = FileAgentInventoryState.idle;
  176. }
  177. public string GetNewCapPath()
  178. {
  179. return "/CAPS/" + UUID.Random();
  180. }
  181. /// <summary>
  182. /// Register a bunch of CAPS http service handlers
  183. /// </summary>
  184. public void RegisterHandlers()
  185. {
  186. // this path is also defined elsewhere so keeping it
  187. string seedcapsBase = "/CAPS/" + m_HostCapsObj.CapsObjectPath +"0000/";
  188. // the root of all evil path needs to be capsBase + m_requestPath
  189. m_HostCapsObj.RegisterHandler(
  190. "SEED", new RestStreamHandler("POST", seedcapsBase, SeedCapRequest, "SEED", null));
  191. // m_log.DebugFormat(
  192. // "[CAPS]: Registered seed capability {0} for {1}", seedcapsBase, m_HostCapsObj.AgentID);
  193. RegisterRegionServiceHandlers();
  194. RegisterInventoryServiceHandlers();
  195. RegisterOtherHandlers();
  196. }
  197. public void RegisterRegionServiceHandlers()
  198. {
  199. try
  200. {
  201. //m_capsHandlers["MapLayer"] =
  202. // new LLSDStreamhandler<OSDMapRequest, OSDMapLayerResponse>("POST",
  203. // GetNewCapPath(),
  204. // GetMapLayer);
  205. IRequestHandler getObjectPhysicsDataHandler = new RestStreamHandler(
  206. "POST", GetNewCapPath(), GetObjectPhysicsData, "GetObjectPhysicsData", null);
  207. m_HostCapsObj.RegisterHandler("GetObjectPhysicsData", getObjectPhysicsDataHandler);
  208. IRequestHandler getObjectCostHandler = new RestStreamHandler(
  209. "POST", GetNewCapPath(), GetObjectCost, "GetObjectCost", null );
  210. m_HostCapsObj.RegisterHandler("GetObjectCost", getObjectCostHandler);
  211. IRequestHandler ResourceCostSelectedHandler = new RestStreamHandler(
  212. "POST", GetNewCapPath(), ResourceCostSelected, "ResourceCostSelected", null);
  213. m_HostCapsObj.RegisterHandler("ResourceCostSelected", ResourceCostSelectedHandler);
  214. IRequestHandler req = new RestStreamHandler(
  215. "POST", GetNewCapPath(), ScriptTaskInventory, "UpdateScript", null);
  216. m_HostCapsObj.RegisterHandler("UpdateScriptTaskInventory", req);
  217. m_HostCapsObj.RegisterHandler("UpdateScriptTask", req);
  218. if(m_AllowCapHomeLocation)
  219. {
  220. IRequestHandler HomeLocationHandler = new RestStreamHandler(
  221. "POST", GetNewCapPath(), HomeLocation, "HomeLocation", null);
  222. m_HostCapsObj.RegisterHandler("HomeLocation", HomeLocationHandler);
  223. }
  224. if(m_AllowCapGroupMemberData)
  225. {
  226. IRequestHandler GroupMemberDataHandler = new RestStreamHandler(
  227. "POST", GetNewCapPath(), GroupMemberData, "GroupMemberData", null);
  228. m_HostCapsObj.RegisterHandler("GroupMemberData", GroupMemberDataHandler);
  229. }
  230. // IRequestHandler animSetRequestHandler
  231. // = new RestStreamHandler(
  232. // "POST", capsBase + m_animSetTaskUpdatePath, AnimSetTaskInventory, "UpdateScript", null);
  233. // m_HostCapsObj.RegisterHandler("UpdateAnimSetTaskInventory", animSetRequestHandler);
  234. }
  235. catch (Exception e)
  236. {
  237. m_log.Error("[CAPS]: " + e.ToString());
  238. }
  239. }
  240. public void RegisterInventoryServiceHandlers()
  241. {
  242. try
  243. {
  244. m_HostCapsObj.RegisterHandler("NewFileAgentInventory",
  245. new LLSDStreamhandler<LLSDAssetUploadRequest, LLSDAssetUploadResponse>(
  246. "POST", GetNewCapPath(), NewAgentInventoryRequest, "NewFileAgentInventory", null));
  247. IRequestHandler req = new RestStreamHandler(
  248. "POST", GetNewCapPath(), NoteCardAgentInventory, "Update*", null);
  249. m_HostCapsObj.RegisterHandler("UpdateNotecardAgentInventory", req);
  250. m_HostCapsObj.RegisterHandler("UpdateAnimSetAgentInventory", req);
  251. m_HostCapsObj.RegisterHandler("UpdateScriptAgentInventory", req);
  252. m_HostCapsObj.RegisterHandler("UpdateScriptAgent", req);
  253. IRequestHandler UpdateAgentInformationHandler = new RestStreamHandler(
  254. "POST", GetNewCapPath(), UpdateAgentInformation, "UpdateAgentInformation", null);
  255. m_HostCapsObj.RegisterHandler("UpdateAgentInformation", UpdateAgentInformationHandler);
  256. IRequestHandler CopyInventoryFromNotecardHandler = new RestStreamHandler(
  257. "POST", GetNewCapPath(), CopyInventoryFromNotecard, "CopyInventoryFromNotecard", null);
  258. m_HostCapsObj.RegisterHandler("CopyInventoryFromNotecard", CopyInventoryFromNotecardHandler);
  259. IRequestHandler CreateInventoryCategoryHandler = new RestStreamHandler(
  260. "POST", GetNewCapPath(), CreateInventoryCategory, "CreateInventoryCategory", null);
  261. m_HostCapsObj.RegisterHandler("CreateInventoryCategory", CreateInventoryCategoryHandler);
  262. }
  263. catch (Exception e)
  264. {
  265. m_log.Error("[CAPS]: " + e.ToString());
  266. }
  267. }
  268. public void RegisterOtherHandlers()
  269. {
  270. try
  271. {
  272. if (m_UserManager != null)
  273. {
  274. IRequestHandler GetDisplayNamesHandler = new RestStreamHandler(
  275. "GET", GetNewCapPath(), GetDisplayNames, "GetDisplayNames", null);
  276. m_HostCapsObj.RegisterHandler("GetDisplayNames", GetDisplayNamesHandler);
  277. }
  278. }
  279. catch (Exception e)
  280. {
  281. m_log.Error("[CAPS]: " + e.ToString());
  282. }
  283. }
  284. /// <summary>
  285. /// Construct a client response detailing all the capabilities this server can provide.
  286. /// </summary>
  287. /// <param name="request"></param>
  288. /// <param name="path"></param>
  289. /// <param name="param"></param>
  290. /// <param name="httpRequest">HTTP request header object</param>
  291. /// <param name="httpResponse">HTTP response header object</param>
  292. /// <returns></returns>
  293. public string SeedCapRequest(string request, string path, string param,
  294. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  295. {
  296. UUID agentID = m_HostCapsObj.AgentID;
  297. m_log.DebugFormat(
  298. "[CAPS]: Received SEED caps request in {0} for agent {1}", m_regionName, agentID);
  299. if (!m_HostCapsObj.WaitForActivation())
  300. return string.Empty;
  301. if (!m_Scene.CheckClient(agentID, httpRequest.RemoteIPEndPoint))
  302. {
  303. m_log.WarnFormat(
  304. "[CAPS]: Unauthorized CAPS client {0} from {1}",
  305. agentID, httpRequest.RemoteIPEndPoint);
  306. return string.Empty;
  307. }
  308. OSDArray capsRequested = (OSDArray)OSDParser.DeserializeLLSDXml(request);
  309. List<string> validCaps = new List<string>();
  310. foreach (OSD c in capsRequested)
  311. {
  312. string cstr = c.AsString();
  313. if(cstr == "ObjectAnimation")
  314. m_HostCapsObj.Flags |= Caps.CapsFlags.ObjectAnim;
  315. validCaps.Add(cstr);
  316. }
  317. string result = LLSDHelpers.SerialiseLLSDReply(m_HostCapsObj.GetCapsDetails(true, validCaps));
  318. //m_log.DebugFormat("[CAPS] CapsRequest {0}", result);
  319. return result;
  320. }
  321. /// <summary>
  322. /// Called by the script task update handler. Provides a URL to which the client can upload a new asset.
  323. /// </summary>
  324. /// <param name="request"></param>
  325. /// <param name="path"></param>
  326. /// <param name="param"></param>
  327. /// <param name="httpRequest">HTTP request header object</param>
  328. /// <param name="httpResponse">HTTP response header object</param>
  329. /// <returns></returns>
  330. public string ScriptTaskInventory(string request, string path, string param,
  331. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  332. {
  333. try
  334. {
  335. // m_log.Debug("[CAPS]: ScriptTaskInventory Request in region: " + m_regionName);
  336. //m_log.DebugFormat("[CAPS]: request: {0}, path: {1}, param: {2}", request, path, param);
  337. Hashtable hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request));
  338. LLSDTaskScriptUpdate llsdUpdateRequest = new LLSDTaskScriptUpdate();
  339. LLSDHelpers.DeserialiseOSDMap(hash, llsdUpdateRequest);
  340. string uploaderPath = GetNewCapPath();
  341. TaskInventoryScriptUpdater uploader =
  342. new TaskInventoryScriptUpdater(
  343. llsdUpdateRequest.item_id,
  344. llsdUpdateRequest.task_id,
  345. llsdUpdateRequest.is_script_running,
  346. uploaderPath,
  347. m_HostCapsObj.HttpListener,
  348. m_dumpAssetsToFile);
  349. uploader.OnUpLoad += TaskScriptUpdated;
  350. m_HostCapsObj.HttpListener.AddStreamHandler(
  351. new BinaryStreamHandler(
  352. "POST", uploaderPath, uploader.uploaderCaps, "TaskInventoryScriptUpdater", null));
  353. string protocol = "http://";
  354. if (m_HostCapsObj.SSLCaps)
  355. protocol = "https://";
  356. string uploaderURL = protocol + m_HostCapsObj.HostName + ":" + m_HostCapsObj.Port.ToString() + uploaderPath;
  357. LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
  358. uploadResponse.uploader = uploaderURL;
  359. uploadResponse.state = "upload";
  360. // m_log.InfoFormat("[CAPS]: " +
  361. // "ScriptTaskInventory response: {0}",
  362. // LLSDHelpers.SerialiseLLSDReply(uploadResponse)));
  363. return LLSDHelpers.SerialiseLLSDReply(uploadResponse);
  364. }
  365. catch (Exception e)
  366. {
  367. m_log.Error("[CAPS]: " + e.ToString());
  368. }
  369. return null;
  370. }
  371. /// <summary>
  372. /// Called when new asset data for an agent inventory item update has been uploaded.
  373. /// </summary>
  374. /// <param name="itemID">Item to update</param>
  375. /// <param name="primID">Prim containing item to update</param>
  376. /// <param name="isScriptRunning">Signals whether the script to update is currently running</param>
  377. /// <param name="data">New asset data</param>
  378. public void TaskScriptUpdated(UUID itemID, UUID primID, bool isScriptRunning, byte[] data, ref ArrayList errors)
  379. {
  380. if (TaskScriptUpdatedCall != null)
  381. {
  382. ArrayList e = TaskScriptUpdatedCall(m_HostCapsObj.AgentID, itemID, primID, isScriptRunning, data);
  383. foreach (Object item in e)
  384. errors.Add(item);
  385. }
  386. }
  387. /// <summary>
  388. /// Called when new asset data for an agent inventory item update has been uploaded.
  389. /// </summary>
  390. /// <param name="itemID">Item to update</param>
  391. /// <param name="data">New asset data</param>
  392. /// <returns></returns>
  393. public UUID ItemUpdated(UUID itemID, byte[] data)
  394. {
  395. if (ItemUpdatedCall != null)
  396. {
  397. return ItemUpdatedCall(m_HostCapsObj.AgentID, itemID, data);
  398. }
  399. return UUID.Zero;
  400. }
  401. /// <summary>
  402. ///
  403. /// </summary>
  404. /// <param name="llsdRequest"></param>
  405. /// <returns></returns>
  406. public LLSDAssetUploadResponse NewAgentInventoryRequest(LLSDAssetUploadRequest llsdRequest)
  407. {
  408. //m_log.Debug("[CAPS]: NewAgentInventoryRequest Request is: " + llsdRequest.ToString());
  409. //m_log.Debug("asset upload request via CAPS" + llsdRequest.inventory_type + " , " + llsdRequest.asset_type);
  410. // start by getting the client
  411. IClientAPI client = null;
  412. m_Scene.TryGetClient(m_HostCapsObj.AgentID, out client);
  413. // check current state so we only have one service at a time
  414. lock (m_ModelCost)
  415. {
  416. switch (m_FileAgentInventoryState)
  417. {
  418. case FileAgentInventoryState.processRequest:
  419. case FileAgentInventoryState.processUpload:
  420. LLSDAssetUploadError resperror = new LLSDAssetUploadError();
  421. resperror.message = "Uploader busy processing previus request";
  422. resperror.identifier = UUID.Zero;
  423. LLSDAssetUploadResponse errorResponse = new LLSDAssetUploadResponse();
  424. errorResponse.uploader = "";
  425. errorResponse.state = "error";
  426. errorResponse.error = resperror;
  427. return errorResponse;
  428. case FileAgentInventoryState.waitUpload:
  429. // todo stop current uploader server
  430. break;
  431. case FileAgentInventoryState.idle:
  432. default:
  433. break;
  434. }
  435. m_FileAgentInventoryState = FileAgentInventoryState.processRequest;
  436. }
  437. int cost = 0;
  438. int nreqtextures = 0;
  439. int nreqmeshs= 0;
  440. int nreqinstances = 0;
  441. bool IsAtestUpload = false;
  442. string assetName = llsdRequest.name;
  443. LLSDAssetUploadResponseData meshcostdata = new LLSDAssetUploadResponseData();
  444. if (llsdRequest.asset_type == "texture" ||
  445. llsdRequest.asset_type == "animation" ||
  446. llsdRequest.asset_type == "animatn" || // this is the asset name actually used by viewers
  447. llsdRequest.asset_type == "mesh" ||
  448. llsdRequest.asset_type == "sound")
  449. {
  450. ScenePresence avatar = null;
  451. m_Scene.TryGetScenePresence(m_HostCapsObj.AgentID, out avatar);
  452. // check user level
  453. if (avatar != null)
  454. {
  455. if (avatar.GodController.UserLevel < m_levelUpload)
  456. {
  457. LLSDAssetUploadError resperror = new LLSDAssetUploadError();
  458. resperror.message = "Insufficient permissions to upload";
  459. resperror.identifier = UUID.Zero;
  460. LLSDAssetUploadResponse errorResponse = new LLSDAssetUploadResponse();
  461. errorResponse.uploader = "";
  462. errorResponse.state = "error";
  463. errorResponse.error = resperror;
  464. lock (m_ModelCost)
  465. m_FileAgentInventoryState = FileAgentInventoryState.idle;
  466. return errorResponse;
  467. }
  468. }
  469. // check test upload and funds
  470. if (client != null)
  471. {
  472. IMoneyModule mm = m_Scene.RequestModuleInterface<IMoneyModule>();
  473. int baseCost = 0;
  474. if (mm != null)
  475. baseCost = mm.UploadCharge;
  476. string warning = String.Empty;
  477. if (llsdRequest.asset_type == "mesh")
  478. {
  479. string error;
  480. int modelcost;
  481. if (!m_ModelCost.MeshModelCost(llsdRequest.asset_resources, baseCost, out modelcost,
  482. meshcostdata, out error, ref warning))
  483. {
  484. LLSDAssetUploadError resperror = new LLSDAssetUploadError();
  485. resperror.message = error;
  486. resperror.identifier = UUID.Zero;
  487. LLSDAssetUploadResponse errorResponse = new LLSDAssetUploadResponse();
  488. errorResponse.uploader = "";
  489. errorResponse.state = "error";
  490. errorResponse.error = resperror;
  491. lock (m_ModelCost)
  492. m_FileAgentInventoryState = FileAgentInventoryState.idle;
  493. return errorResponse;
  494. }
  495. cost = modelcost;
  496. }
  497. else
  498. {
  499. cost = baseCost;
  500. }
  501. if (cost > 0 && mm != null)
  502. {
  503. // check for test upload
  504. if (m_ForceFreeTestUpload) // all are test
  505. {
  506. if (!(assetName.Length > 5 && assetName.StartsWith("TEST-"))) // has normal name lets change it
  507. assetName = "TEST-" + assetName;
  508. IsAtestUpload = true;
  509. }
  510. else if (m_enableFreeTestUpload) // only if prefixed with "TEST-"
  511. {
  512. IsAtestUpload = (assetName.Length > 5 && assetName.StartsWith("TEST-"));
  513. }
  514. if(IsAtestUpload) // let user know, still showing cost estimation
  515. warning += "Upload will have no cost, for testing purposes only. Other uses are prohibited. Items will be local to region only, Inventory entry will be lost on logout";
  516. // check funds
  517. else
  518. {
  519. if (!mm.UploadCovered(client.AgentId, (int)cost))
  520. {
  521. LLSDAssetUploadError resperror = new LLSDAssetUploadError();
  522. resperror.message = "Insuficient funds";
  523. resperror.identifier = UUID.Zero;
  524. LLSDAssetUploadResponse errorResponse = new LLSDAssetUploadResponse();
  525. errorResponse.uploader = "";
  526. errorResponse.state = "error";
  527. errorResponse.error = resperror;
  528. lock (m_ModelCost)
  529. m_FileAgentInventoryState = FileAgentInventoryState.idle;
  530. return errorResponse;
  531. }
  532. }
  533. }
  534. else if (m_enableFreeTestUpload) // only if prefixed with "TEST-"
  535. {
  536. IsAtestUpload = (assetName.Length > 5 && assetName.StartsWith("TEST-"));
  537. if(IsAtestUpload)
  538. warning += "Upload for testing purposes only. Items will be local to region only, Inventory entry will be lost on logout";
  539. }
  540. if (client != null && warning != String.Empty)
  541. client.SendAgentAlertMessage(warning, true);
  542. }
  543. }
  544. string assetDes = llsdRequest.description;
  545. UUID newAsset = UUID.Random();
  546. UUID newInvItem = UUID.Random();
  547. UUID parentFolder = llsdRequest.folder_id;
  548. string uploaderPath = GetNewCapPath();
  549. UUID texturesFolder = UUID.Zero;
  550. if(!IsAtestUpload && m_enableModelUploadTextureToInventory)
  551. texturesFolder = llsdRequest.texture_folder_id;
  552. AssetUploader uploader =
  553. new AssetUploader(assetName, assetDes, newAsset, newInvItem, parentFolder, llsdRequest.inventory_type,
  554. llsdRequest.asset_type, uploaderPath, m_HostCapsObj.HttpListener, m_dumpAssetsToFile, cost,
  555. texturesFolder, nreqtextures, nreqmeshs, nreqinstances, IsAtestUpload,
  556. llsdRequest.next_owner_mask, llsdRequest.group_mask, llsdRequest.everyone_mask);
  557. m_HostCapsObj.HttpListener.AddStreamHandler(
  558. new BinaryStreamHandler(
  559. "POST",
  560. uploaderPath,
  561. uploader.uploaderCaps,
  562. "NewAgentInventoryRequest",
  563. m_HostCapsObj.AgentID.ToString()));
  564. string protocol = "http://";
  565. if (m_HostCapsObj.SSLCaps)
  566. protocol = "https://";
  567. string uploaderURL = protocol + m_HostCapsObj.HostName + ":" + m_HostCapsObj.Port.ToString() + uploaderPath;
  568. LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
  569. uploadResponse.uploader = uploaderURL;
  570. uploadResponse.state = "upload";
  571. uploadResponse.upload_price = (int)cost;
  572. if (llsdRequest.asset_type == "mesh")
  573. {
  574. uploadResponse.data = meshcostdata;
  575. }
  576. uploader.OnUpLoad += UploadCompleteHandler;
  577. lock (m_ModelCost)
  578. m_FileAgentInventoryState = FileAgentInventoryState.waitUpload;
  579. return uploadResponse;
  580. }
  581. /// <summary>
  582. /// Convert raw uploaded data into the appropriate asset and item.
  583. /// </summary>
  584. /// <param name="assetID"></param>
  585. /// <param name="inventoryItem"></param>
  586. /// <param name="data"></param>
  587. public void UploadCompleteHandler(string assetName, string assetDescription, UUID assetID,
  588. UUID inventoryItem, UUID parentFolder, byte[] data, string inventoryType,
  589. string assetType, int cost,
  590. UUID texturesFolder, int nreqtextures, int nreqmeshs, int nreqinstances,
  591. bool IsAtestUpload, ref string error,
  592. ref int nextOwnerMask, ref int groupMask, ref int everyoneMask)
  593. {
  594. lock (m_ModelCost)
  595. m_FileAgentInventoryState = FileAgentInventoryState.processUpload;
  596. m_log.DebugFormat(
  597. "[BUNCH OF CAPS]: Uploaded asset {0} for inventory item {1}, inv type {2}, asset type {3}",
  598. assetID, inventoryItem, inventoryType, assetType);
  599. sbyte assType = 0;
  600. sbyte inType = 0;
  601. IClientAPI client = null;
  602. UUID owner_id = m_HostCapsObj.AgentID;
  603. UUID creatorID;
  604. bool istest = IsAtestUpload && m_enableFreeTestUpload;
  605. bool restrictPerms = m_RestrictFreeTestUploadPerms && istest;
  606. if (istest && m_testAssetsCreatorID != UUID.Zero)
  607. creatorID = m_testAssetsCreatorID;
  608. else
  609. creatorID = owner_id;
  610. string creatorIDstr = creatorID.ToString();
  611. IMoneyModule mm = m_Scene.RequestModuleInterface<IMoneyModule>();
  612. if (mm != null)
  613. {
  614. // make sure client still has enougth credit
  615. if (!mm.UploadCovered(m_HostCapsObj.AgentID, (int)cost))
  616. {
  617. error = "Insufficient funds.";
  618. return;
  619. }
  620. }
  621. // strings to types
  622. if (inventoryType == "sound")
  623. {
  624. inType = (sbyte)InventoryType.Sound;
  625. assType = (sbyte)AssetType.Sound;
  626. }
  627. else if (inventoryType == "snapshot")
  628. {
  629. inType = (sbyte)InventoryType.Snapshot;
  630. }
  631. else if (inventoryType == "animation")
  632. {
  633. inType = (sbyte)InventoryType.Animation;
  634. assType = (sbyte)AssetType.Animation;
  635. }
  636. else if (inventoryType == "animset")
  637. {
  638. inType = (sbyte)CustomInventoryType.AnimationSet;
  639. assType = (sbyte)CustomAssetType.AnimationSet;
  640. m_log.Debug("got animset upload request");
  641. }
  642. else if (inventoryType == "wearable")
  643. {
  644. inType = (sbyte)InventoryType.Wearable;
  645. switch (assetType)
  646. {
  647. case "bodypart":
  648. assType = (sbyte)AssetType.Bodypart;
  649. break;
  650. case "clothing":
  651. assType = (sbyte)AssetType.Clothing;
  652. break;
  653. }
  654. }
  655. else if (inventoryType == "object")
  656. {
  657. if (assetType == "mesh") // this code for now is for mesh models uploads only
  658. {
  659. inType = (sbyte)InventoryType.Object;
  660. assType = (sbyte)AssetType.Object;
  661. List<Vector3> positions = new List<Vector3>();
  662. List<Quaternion> rotations = new List<Quaternion>();
  663. OSDMap request = (OSDMap)OSDParser.DeserializeLLSDXml(data);
  664. // compare and get updated information
  665. /* does nothing still we do need something to avoid special viewer to upload something diferent from the cost estimation
  666. bool mismatchError = true;
  667. while (mismatchError)
  668. {
  669. mismatchError = false;
  670. }
  671. if (mismatchError)
  672. {
  673. error = "Upload and fee estimation information don't match";
  674. lock (m_ModelCost)
  675. m_FileAgentInventoryState = FileAgentInventoryState.idle;
  676. return;
  677. }
  678. */
  679. OSDArray instance_list = (OSDArray)request["instance_list"];
  680. OSDArray mesh_list = (OSDArray)request["mesh_list"];
  681. OSDArray texture_list = (OSDArray)request["texture_list"];
  682. SceneObjectGroup grp = null;
  683. // create and store texture assets
  684. bool doTextInv = (!istest && m_enableModelUploadTextureToInventory &&
  685. texturesFolder != UUID.Zero);
  686. List<UUID> textures = new List<UUID>();
  687. // if (doTextInv)
  688. m_Scene.TryGetClient(m_HostCapsObj.AgentID, out client);
  689. if(client == null) // don't put textures in inventory if there is no client
  690. doTextInv = false;
  691. for (int i = 0; i < texture_list.Count; i++)
  692. {
  693. AssetBase textureAsset = new AssetBase(UUID.Random(), assetName, (sbyte)AssetType.Texture, creatorIDstr);
  694. textureAsset.Data = texture_list[i].AsBinary();
  695. if (istest)
  696. textureAsset.Local = true;
  697. m_assetService.Store(textureAsset);
  698. textures.Add(textureAsset.FullID);
  699. if (doTextInv)
  700. {
  701. string name = assetName;
  702. if (name.Length > 25)
  703. name = name.Substring(0, 24);
  704. name += "_Texture#" + i.ToString();
  705. InventoryItemBase texitem = new InventoryItemBase();
  706. texitem.Owner = m_HostCapsObj.AgentID;
  707. texitem.CreatorId = creatorIDstr;
  708. texitem.CreatorData = String.Empty;
  709. texitem.ID = UUID.Random();
  710. texitem.AssetID = textureAsset.FullID;
  711. texitem.Description = "mesh model texture";
  712. texitem.Name = name;
  713. texitem.AssetType = (int)AssetType.Texture;
  714. texitem.InvType = (int)InventoryType.Texture;
  715. texitem.Folder = texturesFolder;
  716. texitem.CurrentPermissions
  717. = (uint)(PermissionMask.Move | PermissionMask.Copy | PermissionMask.Modify | PermissionMask.Transfer | PermissionMask.Export);
  718. texitem.BasePermissions = (uint)PermissionMask.All | (uint)PermissionMask.Export;
  719. texitem.EveryOnePermissions = 0;
  720. texitem.NextPermissions = (uint)PermissionMask.All;
  721. texitem.CreationDate = Util.UnixTimeSinceEpoch();
  722. m_Scene.AddInventoryItem(client, texitem);
  723. texitem = null;
  724. }
  725. }
  726. // create and store meshs assets
  727. List<UUID> meshAssets = new List<UUID>();
  728. List<bool> meshAvatarSkeletons = new List<bool>();
  729. List<bool> meshAvatarColliders = new List<bool>();
  730. bool curAvSkeleton;
  731. bool curAvCollider;
  732. for (int i = 0; i < mesh_list.Count; i++)
  733. {
  734. curAvSkeleton = false;
  735. curAvCollider = false;
  736. // we do need to parse the mesh now
  737. OSD osd = OSDParser.DeserializeLLSDBinary(mesh_list[i]);
  738. if (osd is OSDMap)
  739. {
  740. OSDMap mosd = (OSDMap)osd;
  741. if (mosd.ContainsKey("skeleton"))
  742. {
  743. OSDMap skeleton = (OSDMap)mosd["skeleton"];
  744. int sksize = skeleton["size"].AsInteger();
  745. if (sksize > 0)
  746. curAvSkeleton = true;
  747. }
  748. }
  749. AssetBase meshAsset = new AssetBase(UUID.Random(), assetName, (sbyte)AssetType.Mesh, creatorIDstr);
  750. meshAsset.Data = mesh_list[i].AsBinary();
  751. if (istest)
  752. meshAsset.Local = true;
  753. m_assetService.Store(meshAsset);
  754. meshAssets.Add(meshAsset.FullID);
  755. meshAvatarSkeletons.Add(curAvSkeleton);
  756. meshAvatarColliders.Add(curAvCollider);
  757. // test code
  758. if (curAvSkeleton && client != null)
  759. {
  760. string name = assetName;
  761. if (name.Length > 25)
  762. name = name.Substring(0, 24);
  763. name += "_Mesh#" + i.ToString();
  764. InventoryItemBase meshitem = new InventoryItemBase();
  765. meshitem.Owner = m_HostCapsObj.AgentID;
  766. meshitem.CreatorId = creatorIDstr;
  767. meshitem.CreatorData = String.Empty;
  768. meshitem.ID = UUID.Random();
  769. meshitem.AssetID = meshAsset.FullID;
  770. meshitem.Description = "mesh ";
  771. meshitem.Name = name;
  772. meshitem.AssetType = (int)AssetType.Mesh;
  773. meshitem.InvType = (int)InventoryType.Mesh;
  774. // meshitem.Folder = UUID.Zero; // send to default
  775. meshitem.Folder = parentFolder; // dont let it go to folder Meshes that viewers dont show
  776. // If we set PermissionMask.All then when we rez the item the next permissions will replace the current
  777. // (owner) permissions. This becomes a problem if next permissions are changed.
  778. meshitem.CurrentPermissions
  779. = (uint)(PermissionMask.Move | PermissionMask.Copy | PermissionMask.Modify | PermissionMask.Transfer);
  780. meshitem.BasePermissions = (uint)PermissionMask.All;
  781. meshitem.EveryOnePermissions = 0;
  782. meshitem.NextPermissions = (uint)PermissionMask.All;
  783. meshitem.CreationDate = Util.UnixTimeSinceEpoch();
  784. m_Scene.AddInventoryItem(client, meshitem);
  785. meshitem = null;
  786. }
  787. }
  788. int skipedMeshs = 0;
  789. // build prims from instances
  790. for (int i = 0; i < instance_list.Count; i++)
  791. {
  792. OSDMap inner_instance_list = (OSDMap)instance_list[i];
  793. // skip prims that are 2 small
  794. Vector3 scale = inner_instance_list["scale"].AsVector3();
  795. if (scale.X < m_PrimScaleMin || scale.Y < m_PrimScaleMin || scale.Z < m_PrimScaleMin)
  796. {
  797. skipedMeshs++;
  798. continue;
  799. }
  800. OSDArray face_list = (OSDArray)inner_instance_list["face_list"];
  801. PrimitiveBaseShape pbs = null;
  802. if (inner_instance_list.ContainsKey("mesh")) // seems to happen always but ...
  803. {
  804. int meshindx = inner_instance_list["mesh"].AsInteger();
  805. if (meshAssets.Count > meshindx)
  806. pbs = PrimitiveBaseShape.CreateMesh(face_list.Count, meshAssets[meshindx]);
  807. }
  808. if(pbs == null) // fallback
  809. pbs = PrimitiveBaseShape.CreateBox();
  810. Primitive.TextureEntry textureEntry
  811. = new Primitive.TextureEntry(Primitive.TextureEntry.WHITE_TEXTURE);
  812. for (uint face = 0; face < face_list.Count; face++)
  813. {
  814. OSDMap faceMap = (OSDMap)face_list[(int)face];
  815. Primitive.TextureEntryFace f = textureEntry.CreateFace(face); //clone the default
  816. if (faceMap.ContainsKey("fullbright"))
  817. f.Fullbright = faceMap["fullbright"].AsBoolean();
  818. if (faceMap.ContainsKey("diffuse_color"))
  819. f.RGBA = faceMap["diffuse_color"].AsColor4();
  820. int textureNum = faceMap["image"].AsInteger();
  821. float imagerot = faceMap["imagerot"].AsInteger();
  822. float offsets = (float)faceMap["offsets"].AsReal();
  823. float offsett = (float)faceMap["offsett"].AsReal();
  824. float scales = (float)faceMap["scales"].AsReal();
  825. float scalet = (float)faceMap["scalet"].AsReal();
  826. if (imagerot != 0)
  827. f.Rotation = imagerot;
  828. if (offsets != 0)
  829. f.OffsetU = offsets;
  830. if (offsett != 0)
  831. f.OffsetV = offsett;
  832. if (scales != 0)
  833. f.RepeatU = scales;
  834. if (scalet != 0)
  835. f.RepeatV = scalet;
  836. if (textures.Count > textureNum)
  837. f.TextureID = textures[textureNum];
  838. textureEntry.FaceTextures[face] = f;
  839. }
  840. pbs.TextureEntry = textureEntry.GetBytes();
  841. Vector3 position = inner_instance_list["position"].AsVector3();
  842. Quaternion rotation = inner_instance_list["rotation"].AsQuaternion();
  843. // for now viwers do send fixed defaults
  844. // but this may change
  845. // int physicsShapeType = inner_instance_list["physics_shape_type"].AsInteger();
  846. byte physicsShapeType = (byte)PhysShapeType.convex; // default is simple convex
  847. // int material = inner_instance_list["material"].AsInteger();
  848. byte material = (byte)Material.Wood;
  849. SceneObjectPart prim
  850. = new SceneObjectPart(owner_id, pbs, position, Quaternion.Identity, Vector3.Zero);
  851. prim.Scale = scale;
  852. rotations.Add(rotation);
  853. positions.Add(position);
  854. prim.UUID = UUID.Random();
  855. prim.CreatorID = creatorID;
  856. prim.OwnerID = owner_id;
  857. prim.GroupID = UUID.Zero;
  858. prim.LastOwnerID = creatorID;
  859. prim.RezzerID = creatorID;
  860. prim.CreationDate = Util.UnixTimeSinceEpoch();
  861. if (grp == null)
  862. prim.Name = assetName;
  863. else
  864. prim.Name = assetName + "#" + i.ToString();
  865. prim.EveryoneMask = 0;
  866. prim.GroupMask = 0;
  867. if (restrictPerms)
  868. {
  869. prim.BaseMask = (uint)(PermissionMask.Move | PermissionMask.Modify);
  870. prim.OwnerMask = (uint)(PermissionMask.Move | PermissionMask.Modify);
  871. prim.NextOwnerMask = 0;
  872. }
  873. else
  874. {
  875. prim.BaseMask = (uint)PermissionMask.All | (uint)PermissionMask.Export;
  876. prim.OwnerMask = (uint)PermissionMask.All | (uint)PermissionMask.Export;
  877. prim.GroupMask = prim.BaseMask & (uint)groupMask;
  878. prim.EveryoneMask = prim.BaseMask & (uint)everyoneMask;
  879. prim.NextOwnerMask = prim.BaseMask & (uint)nextOwnerMask;
  880. // If the viewer gives us bogus permissions, revert to the SL
  881. // default of transfer only.
  882. if ((prim.NextOwnerMask & (uint)PermissionMask.All) == 0)
  883. prim.NextOwnerMask = (uint)PermissionMask.Transfer;
  884. }
  885. if(istest)
  886. prim.Description = "For testing only. Other uses are prohibited";
  887. else
  888. prim.Description = "";
  889. prim.Material = material;
  890. prim.PhysicsShapeType = physicsShapeType;
  891. // prim.BaseMask = (uint)base_mask;
  892. // prim.EveryoneMask = (uint)everyone_mask;
  893. // prim.GroupMask = (uint)group_mask;
  894. // prim.NextOwnerMask = (uint)next_owner_mask;
  895. // prim.OwnerMask = (uint)owner_mask;
  896. if (grp == null)
  897. {
  898. grp = new SceneObjectGroup(prim);
  899. grp.LastOwnerID = creatorID;
  900. grp.RezzerID = creatorID;
  901. }
  902. else
  903. grp.AddPart(prim);
  904. }
  905. Vector3 rootPos = positions[0];
  906. if (grp.Parts.Length > 1)
  907. {
  908. // Fix first link number
  909. grp.RootPart.LinkNum++;
  910. Quaternion rootRotConj = Quaternion.Conjugate(rotations[0]);
  911. Quaternion tmprot;
  912. Vector3 offset;
  913. // fix children rotations and positions
  914. for (int i = 1; i < rotations.Count; i++)
  915. {
  916. tmprot = rotations[i];
  917. tmprot = rootRotConj * tmprot;
  918. grp.Parts[i].RotationOffset = tmprot;
  919. offset = positions[i] - rootPos;
  920. offset *= rootRotConj;
  921. grp.Parts[i].OffsetPosition = offset;
  922. }
  923. grp.AbsolutePosition = rootPos;
  924. grp.UpdateGroupRotationR(rotations[0]);
  925. }
  926. else
  927. {
  928. grp.AbsolutePosition = rootPos;
  929. grp.UpdateGroupRotationR(rotations[0]);
  930. }
  931. data = ASCIIEncoding.ASCII.GetBytes(SceneObjectSerializer.ToOriginalXmlFormat(grp));
  932. }
  933. else // not a mesh model
  934. {
  935. m_log.ErrorFormat("[CAPS Asset Upload] got unsuported assetType for object upload");
  936. return;
  937. }
  938. }
  939. AssetBase asset;
  940. asset = new AssetBase(assetID, assetName, assType, creatorIDstr);
  941. asset.Data = data;
  942. if (istest)
  943. asset.Local = true;
  944. if (AddNewAsset != null)
  945. AddNewAsset(asset);
  946. else if (m_assetService != null)
  947. m_assetService.Store(asset);
  948. InventoryItemBase item = new InventoryItemBase();
  949. item.Owner = m_HostCapsObj.AgentID;
  950. item.CreatorId = creatorIDstr;
  951. item.CreatorData = String.Empty;
  952. item.ID = inventoryItem;
  953. item.AssetID = asset.FullID;
  954. if (istest)
  955. {
  956. item.Description = "For testing only. Other uses are prohibited";
  957. item.Flags = (uint) (InventoryItemFlags.SharedSingleReference);
  958. }
  959. else
  960. item.Description = assetDescription;
  961. item.Name = assetName;
  962. item.AssetType = assType;
  963. item.InvType = inType;
  964. item.Folder = parentFolder;
  965. // If we set PermissionMask.All then when we rez the item the next permissions will replace the current
  966. // (owner) permissions. This becomes a problem if next permissions are changed.
  967. if (inType == (sbyte)CustomInventoryType.AnimationSet)
  968. {
  969. AnimationSet.setCreateItemPermitions(item);
  970. }
  971. else if (restrictPerms)
  972. {
  973. item.BasePermissions = (uint)(PermissionMask.Move | PermissionMask.Modify);
  974. item.CurrentPermissions = (uint)(PermissionMask.Move | PermissionMask.Modify);
  975. item.GroupPermissions = 0;
  976. item.EveryOnePermissions = 0;
  977. item.NextPermissions = 0;
  978. }
  979. else
  980. {
  981. item.BasePermissions = (uint)PermissionMask.All | (uint)PermissionMask.Export;
  982. item.CurrentPermissions = (uint)PermissionMask.All | (uint)PermissionMask.Export;
  983. item.GroupPermissions = item.BasePermissions & (uint)groupMask;
  984. item.EveryOnePermissions = item.BasePermissions & (uint)everyoneMask;
  985. item.NextPermissions = item.BasePermissions & (uint)nextOwnerMask;
  986. if ((item.NextPermissions & (uint)PermissionMask.All) == 0)
  987. item.NextPermissions = (uint)PermissionMask.Transfer;
  988. }
  989. item.CreationDate = Util.UnixTimeSinceEpoch();
  990. everyoneMask = (int)item.EveryOnePermissions;
  991. groupMask = (int)item.GroupPermissions;
  992. nextOwnerMask = (int)item.NextPermissions;
  993. m_Scene.TryGetClient(m_HostCapsObj.AgentID, out client);
  994. if (AddNewInventoryItem != null)
  995. {
  996. if (istest)
  997. {
  998. m_Scene.AddInventoryItem(client, item);
  999. /*
  1000. AddNewInventoryItem(m_HostCapsObj.AgentID, item, 0);
  1001. if (client != null)
  1002. client.SendAgentAlertMessage("Upload will have no cost, for personal test purposes only. Other uses are forbiden. Items may not work on a another region" , true);
  1003. */
  1004. }
  1005. else
  1006. {
  1007. AddNewInventoryItem(m_HostCapsObj.AgentID, item, (uint)cost);
  1008. // if (client != null)
  1009. // {
  1010. // // let users see anything.. i don't so far
  1011. // string str;
  1012. // if (cost > 0)
  1013. // // dont remember where is money unit name to put here
  1014. // str = "Upload complete. charged " + cost.ToString() + "$";
  1015. // else
  1016. // str = "Upload complete";
  1017. // client.SendAgentAlertMessage(str, true);
  1018. // }
  1019. }
  1020. }
  1021. lock (m_ModelCost)
  1022. m_FileAgentInventoryState = FileAgentInventoryState.idle;
  1023. }
  1024. /// <summary>
  1025. ///
  1026. /// </summary>
  1027. /// <param name="mapReq"></param>
  1028. /// <returns></returns>
  1029. public LLSDMapLayerResponse GetMapLayer(LLSDMapRequest mapReq)
  1030. {
  1031. m_log.Debug("[CAPS]: MapLayer Request in region: " + m_regionName);
  1032. LLSDMapLayerResponse mapResponse = new LLSDMapLayerResponse();
  1033. mapResponse.LayerData.Array.Add(GetOSDMapLayerResponse());
  1034. return mapResponse;
  1035. }
  1036. /// <summary>
  1037. ///
  1038. /// </summary>
  1039. /// <returns></returns>
  1040. protected static OSDMapLayer GetOSDMapLayerResponse()
  1041. {
  1042. OSDMapLayer mapLayer = new OSDMapLayer();
  1043. mapLayer.Right = 5000;
  1044. mapLayer.Top = 5000;
  1045. mapLayer.ImageID = new UUID("00000000-0000-1111-9999-000000000006");
  1046. return mapLayer;
  1047. }
  1048. /// <summary>
  1049. ///
  1050. /// </summary>
  1051. /// <param name="request"></param>
  1052. /// <param name="path"></param>
  1053. /// <param name="param"></param>
  1054. /// <returns></returns>
  1055. public string RequestTexture(string request, string path, string param)
  1056. {
  1057. m_log.Debug("texture request " + request);
  1058. // Needs implementing (added to remove compiler warning)
  1059. return String.Empty;
  1060. }
  1061. public string CreateInventoryCategory(string request, string path, string param,
  1062. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  1063. {
  1064. if (m_Scene.InventoryService == null)
  1065. {
  1066. httpResponse.StatusCode = (int)System.Net.HttpStatusCode.ServiceUnavailable;
  1067. httpResponse.StatusDescription = "Service not avaiable";
  1068. return "";
  1069. }
  1070. ScenePresence sp = m_Scene.GetScenePresence(m_AgentID);
  1071. if (sp == null || sp.IsDeleted)
  1072. {
  1073. httpResponse.StatusCode = (int)System.Net.HttpStatusCode.ServiceUnavailable;
  1074. httpResponse.StatusDescription = "Retry later";
  1075. httpResponse.AddHeader("Retry-After", "30");
  1076. return "";
  1077. }
  1078. Hashtable hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request));
  1079. while (true) // kinda goto
  1080. {
  1081. if (!hash.Contains("folder_id") || !(hash["folder_id"] is UUID))
  1082. break;
  1083. UUID folderID = (UUID)hash["folder_id"];
  1084. if (!hash.Contains("parent_id") || !(hash["parent_id"] is UUID))
  1085. break;
  1086. UUID parentID = (UUID)hash["parent_id"];
  1087. if (!hash.Contains("name") || !(hash["name"] is string))
  1088. break;
  1089. string folderName = (string)hash["name"];
  1090. if (!hash.Contains("type") || !(hash["type"] is int))
  1091. break;
  1092. int folderType = (int)hash["type"];
  1093. InventoryFolderBase folder = new InventoryFolderBase(folderID, folderName, m_AgentID, (short)folderType, parentID, 1);
  1094. if (!m_Scene.InventoryService.AddFolder(folder))
  1095. break;
  1096. // costly double check plus possible service changes
  1097. folder = m_Scene.InventoryService.GetFolder(m_AgentID, folderID);
  1098. if(folder == null)
  1099. break;
  1100. StringBuilder sb = LLSDxmlEncode.Start();
  1101. LLSDxmlEncode.AddMap(sb);
  1102. LLSDxmlEncode.AddElem("folder_id", folder.ID, sb);
  1103. LLSDxmlEncode.AddElem("name", folder.Name, sb);
  1104. LLSDxmlEncode.AddElem("parent_id", folder.ParentID, sb);
  1105. LLSDxmlEncode.AddElem("type", folder.Type, sb);
  1106. LLSDxmlEncode.AddEndMap(sb);
  1107. string resp = LLSDxmlEncode.End(sb);
  1108. return resp;
  1109. }
  1110. httpResponse.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
  1111. return "";
  1112. }
  1113. /// <summary>
  1114. /// Called by the notecard update handler. Provides a URL to which the client can upload a new asset.
  1115. /// </summary>
  1116. /// <param name="request"></param>
  1117. /// <param name="path"></param>
  1118. /// <param name="param"></param>
  1119. /// <returns></returns>
  1120. public string NoteCardAgentInventory(string request, string path, string param,
  1121. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  1122. {
  1123. //m_log.Debug("[CAPS]: NoteCardAgentInventory Request in region: " + m_regionName + "\n" + request);
  1124. //m_log.Debug("[CAPS]: NoteCardAgentInventory Request is: " + request);
  1125. //OpenMetaverse.StructuredData.OSDMap hash = (OpenMetaverse.StructuredData.OSDMap)OpenMetaverse.StructuredData.LLSDParser.DeserializeBinary(Utils.StringToBytes(request));
  1126. Hashtable hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request));
  1127. LLSDItemUpdate llsdRequest = new LLSDItemUpdate();
  1128. LLSDHelpers.DeserialiseOSDMap(hash, llsdRequest);
  1129. string uploaderPath = GetNewCapPath();
  1130. ItemUpdater uploader =
  1131. new ItemUpdater(llsdRequest.item_id, uploaderPath, m_HostCapsObj.HttpListener, m_dumpAssetsToFile);
  1132. uploader.OnUpLoad += ItemUpdated;
  1133. m_HostCapsObj.HttpListener.AddStreamHandler(
  1134. new BinaryStreamHandler(
  1135. "POST", uploaderPath, uploader.uploaderCaps, "NoteCardAgentInventory", null));
  1136. string protocol = "http://";
  1137. if (m_HostCapsObj.SSLCaps)
  1138. protocol = "https://";
  1139. string uploaderURL = protocol + m_HostCapsObj.HostName + ":" + m_HostCapsObj.Port.ToString() + uploaderPath;
  1140. LLSDAssetUploadResponse uploadResponse = new LLSDAssetUploadResponse();
  1141. uploadResponse.uploader = uploaderURL;
  1142. uploadResponse.state = "upload";
  1143. // m_log.InfoFormat("[CAPS]: " +
  1144. // "NoteCardAgentInventory response: {0}",
  1145. // LLSDHelpers.SerialiseLLSDReply(uploadResponse)));
  1146. return LLSDHelpers.SerialiseLLSDReply(uploadResponse);
  1147. }
  1148. private string CopyInventoryFromNotecardError(IOSHttpResponse response)
  1149. {
  1150. response.StatusCode = (int)System.Net.HttpStatusCode.NotFound;
  1151. response.StatusDescription = "";
  1152. return "";
  1153. }
  1154. /// <summary>
  1155. /// Called by the CopyInventoryFromNotecard caps handler.
  1156. /// </summary>
  1157. /// <param name="request"></param>
  1158. /// <param name="path"></param>
  1159. /// <param name="param"></param>
  1160. public string CopyInventoryFromNotecard(string request, string path, string param,
  1161. IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
  1162. {
  1163. InventoryItemBase copyItem = null;
  1164. try
  1165. {
  1166. OSDMap content = (OSDMap)OSDParser.DeserializeLLSDXml(request);
  1167. UUID objectID = content["object-id"].AsUUID();
  1168. UUID notecardID = content["notecard-id"].AsUUID();
  1169. UUID folderID = content["folder-id"].AsUUID();
  1170. UUID itemID = content["item-id"].AsUUID();
  1171. // m_log.InfoFormat("[CAPS]: CopyInventoryFromNotecard, FolderID:{0}, ItemID:{1}, NotecardID:{2}, ObjectID:{3}", folderID, itemID, notecardID, objectID);
  1172. if (objectID != UUID.Zero)
  1173. {
  1174. SceneObjectPart part = m_Scene.GetSceneObjectPart(objectID);
  1175. if (part != null)
  1176. {
  1177. // TaskInventoryItem taskItem = part.Inventory.GetInventoryItem(notecardID);
  1178. if (!m_Scene.Permissions.CanCopyObjectInventory(notecardID, objectID, m_HostCapsObj.AgentID))
  1179. return CopyInventoryFromNotecardError(httpResponse);
  1180. }
  1181. }
  1182. InventoryItemBase item = null;
  1183. IClientAPI client = null;
  1184. m_Scene.TryGetClient(m_HostCapsObj.AgentID, out client);
  1185. item = m_Scene.InventoryService.GetItem(m_HostCapsObj.AgentID, itemID);
  1186. if (item != null)
  1187. {
  1188. string message;
  1189. copyItem = m_Scene.GiveInventoryItem(m_HostCapsObj.AgentID, item.Owner, itemID, folderID, out message);
  1190. if (copyItem != null && client != null)
  1191. {
  1192. m_log.InfoFormat("[CAPS]: CopyInventoryFromNotecard, ItemID:{0}, FolderID:{1}", copyItem.ID, copyItem.Folder);
  1193. client.SendBulkUpdateInventory(copyItem);
  1194. }
  1195. }
  1196. else
  1197. {
  1198. m_log.ErrorFormat("[CAPS]: CopyInventoryFromNotecard - Failed to retrieve item {0} from notecard {1}", itemID, notecardID);
  1199. if (client != null)
  1200. client.SendAlertMessage("Failed to retrieve item");
  1201. }
  1202. }
  1203. catch (Exception e)
  1204. {
  1205. m_log.ErrorFormat("[CAPS]: CopyInventoryFromNotecard : {0}", e.ToString());
  1206. copyItem = null;
  1207. }
  1208. if(copyItem == null)
  1209. return CopyInventoryFromNotecardError(httpResponse);
  1210. return "";
  1211. }
  1212. public string GetObjectPhysicsData(string request, string path,
  1213. string param, IOSHttpRequest httpRequest,
  1214. IOSHttpResponse httpResponse)
  1215. {
  1216. OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request);
  1217. OSDArray object_ids = (OSDArray)req["object_ids"];
  1218. StringBuilder lsl = LLSDxmlEncode.Start();
  1219. if(object_ids.Count == 0)
  1220. LLSDxmlEncode.AddEmptyMap(lsl);
  1221. else
  1222. {
  1223. LLSDxmlEncode.AddMap(lsl);
  1224. for (int i = 0 ; i < object_ids.Count ; i++)
  1225. {
  1226. UUID uuid = object_ids[i].AsUUID();
  1227. SceneObjectPart obj = m_Scene.GetSceneObjectPart(uuid);
  1228. if (obj != null)
  1229. {
  1230. LLSDxmlEncode.AddMap(uuid.ToString(),lsl);
  1231. LLSDxmlEncode.AddElem("PhysicsShapeType", obj.PhysicsShapeType, lsl);
  1232. LLSDxmlEncode.AddElem("Density", obj.Density, lsl);
  1233. LLSDxmlEncode.AddElem("Friction", obj.Friction, lsl);
  1234. LLSDxmlEncode.AddElem("Restitution", obj.Restitution, lsl);
  1235. LLSDxmlEncode.AddElem("GravityMultiplier", obj.GravityModifier, lsl);
  1236. LLSDxmlEncode.AddEndMap(lsl);
  1237. }
  1238. LLSDxmlEncode.AddEndMap(lsl);
  1239. }
  1240. }
  1241. return LLSDxmlEncode.End(lsl);
  1242. }
  1243. public string GetObjectCost(string request, string path,
  1244. string param, IOSHttpRequest httpRequest,
  1245. IOSHttpResponse httpResponse)
  1246. {
  1247. OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request);
  1248. OSDArray object_ids = (OSDArray)req["object_ids"];
  1249. StringBuilder lsl = LLSDxmlEncode.Start(512);
  1250. if(object_ids.Count == 0)
  1251. LLSDxmlEncode.AddEmptyMap(lsl);
  1252. else
  1253. {
  1254. bool haveone = false;
  1255. LLSDxmlEncode.AddMap(lsl);
  1256. for (int i = 0; i < object_ids.Count; i++)
  1257. {
  1258. UUID uuid = object_ids[i].AsUUID();
  1259. SceneObjectPart part = m_Scene.GetSceneObjectPart(uuid);
  1260. SceneObjectGroup grp = null;
  1261. if (part != null)
  1262. grp = part.ParentGroup;
  1263. if (grp != null)
  1264. {
  1265. haveone = true;
  1266. float linksetCost;
  1267. float linksetPhysCost;
  1268. float partCost;
  1269. float partPhysCost;
  1270. grp.GetResourcesCosts(part,out linksetCost,out linksetPhysCost,out partCost,out partPhysCost);
  1271. LLSDxmlEncode.AddMap(uuid.ToString(), lsl);
  1272. LLSDxmlEncode.AddElem("linked_set_resource_cost", linksetCost, lsl);
  1273. LLSDxmlEncode.AddElem("resource_cost", partCost, lsl);
  1274. LLSDxmlEncode.AddElem("physics_cost", partPhysCost, lsl);
  1275. LLSDxmlEncode.AddElem("linked_set_physics_cost", linksetPhysCost, lsl);
  1276. LLSDxmlEncode.AddElem("resource_limiting_type", "legacy", lsl);
  1277. LLSDxmlEncode.AddEndMap(lsl);
  1278. }
  1279. }
  1280. if(!haveone)
  1281. {
  1282. LLSDxmlEncode.AddMap(UUID.Zero.ToString(), lsl);
  1283. LLSDxmlEncode.AddElem("linked_set_resource_cost", 0, lsl);
  1284. LLSDxmlEncode.AddElem("resource_cost", 0, lsl);
  1285. LLSDxmlEncode.AddElem("physics_cost", 0, lsl);
  1286. LLSDxmlEncode.AddElem("linked_set_physics_cost", 0, lsl);
  1287. LLSDxmlEncode.AddElem("resource_limiting_type", "legacy", lsl);
  1288. LLSDxmlEncode.AddEndMap(lsl);
  1289. }
  1290. LLSDxmlEncode.AddEndMap(lsl);
  1291. }
  1292. return LLSDxmlEncode.End(lsl);
  1293. }
  1294. public string ResourceCostSelected(string request, string path,
  1295. string param, IOSHttpRequest httpRequest,
  1296. IOSHttpResponse httpResponse)
  1297. {
  1298. OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request);
  1299. float phys=0;
  1300. float stream=0;
  1301. float simul=0;
  1302. if (req.ContainsKey("selected_roots"))
  1303. {
  1304. OSDArray object_ids = (OSDArray)req["selected_roots"];
  1305. // should go by SOG suming costs for all parts
  1306. // ll v3 works ok with several objects select we get the list and adds ok
  1307. // FS calls per object so results are wrong guess fs bug
  1308. for (int i = 0; i < object_ids.Count; i++)
  1309. {
  1310. UUID uuid = object_ids[i].AsUUID();
  1311. float Physc;
  1312. float simulc;
  1313. float streamc;
  1314. SceneObjectGroup grp = m_Scene.GetGroupByPrim(uuid);
  1315. if (grp != null)
  1316. {
  1317. grp.GetSelectedCosts(out Physc, out streamc, out simulc);
  1318. phys += Physc;
  1319. stream += streamc;
  1320. simul += simulc;
  1321. }
  1322. }
  1323. }
  1324. else if (req.ContainsKey("selected_prims"))
  1325. {
  1326. OSDArray object_ids = (OSDArray)req["selected_prims"];
  1327. // don't see in use in any of the 2 viewers
  1328. // guess it should be for edit linked but... nothing
  1329. // should go to SOP per part
  1330. for (int i = 0; i < object_ids.Count; i++)
  1331. {
  1332. UUID uuid = object_ids[i].AsUUID();
  1333. SceneObjectPart part = m_Scene.GetSceneObjectPart(uuid);
  1334. if (part != null)
  1335. {
  1336. phys += part.PhysicsCost;
  1337. stream += part.StreamingCost;
  1338. simul += part.SimulationCost;
  1339. }
  1340. }
  1341. }
  1342. StringBuilder lsl = LLSDxmlEncode.Start();
  1343. LLSDxmlEncode.AddMap(lsl);
  1344. LLSDxmlEncode.AddMap("selected", lsl);
  1345. LLSDxmlEncode.AddElem("physics", phys, lsl);
  1346. LLSDxmlEncode.AddElem("streaming", stream, lsl);
  1347. LLSDxmlEncode.AddElem("simulation", simul, lsl);
  1348. LLSDxmlEncode.AddEndMap(lsl);
  1349. LLSDxmlEncode.AddEndMap(lsl);
  1350. // resp["transaction_id"] = "undef";
  1351. return LLSDxmlEncode.End(lsl);
  1352. }
  1353. public string UpdateAgentInformation(string request, string path,
  1354. string param, IOSHttpRequest httpRequest,
  1355. IOSHttpResponse httpResponse)
  1356. {
  1357. // OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request);
  1358. OSDMap resp = new OSDMap();
  1359. OSDMap accessPrefs = new OSDMap();
  1360. accessPrefs["max"] = "A";
  1361. resp["access_prefs"] = accessPrefs;
  1362. string response = OSDParser.SerializeLLSDXmlString(resp);
  1363. return response;
  1364. }
  1365. public bool OSDMapTOVector3(OSDMap map, out Vector3 v)
  1366. {
  1367. v = Vector3.Zero;
  1368. if(!map.ContainsKey("X"))
  1369. return false;
  1370. if(!map.ContainsKey("Y"))
  1371. return false;
  1372. if(!map.ContainsKey("Z"))
  1373. return false;
  1374. v.X = (float)map["X"].AsReal();
  1375. v.Y = (float)map["Y"].AsReal();
  1376. v.Z = (float)map["Z"].AsReal();
  1377. return true;
  1378. }
  1379. public string HomeLocation(string request, string path, string param, IOSHttpRequest httpRequest,
  1380. IOSHttpResponse httpResponse)
  1381. {
  1382. OSDMap resp = new OSDMap();
  1383. resp["success"] = "false";
  1384. bool fail = true;
  1385. string message = "Set Home request failed";
  1386. int locationID = 1;
  1387. Vector3 pos = Vector3.Zero;
  1388. Vector3 lookAt = Vector3.Zero;
  1389. IClientAPI client = null;
  1390. ScenePresence sp;
  1391. while(true)
  1392. {
  1393. if(m_Scene.GridUserService == null)
  1394. break;
  1395. if(m_Scene.UserManagementModule == null)
  1396. break;
  1397. m_Scene.TryGetScenePresence(m_AgentID, out sp);
  1398. if(sp == null || sp.IsChildAgent || sp.IsDeleted)
  1399. break;
  1400. if(sp.IsInTransit && !sp.IsInLocalTransit)
  1401. break;
  1402. client = sp.ControllingClient;
  1403. if(!m_Scene.UserManagementModule.IsLocalGridUser(m_AgentID))
  1404. break;
  1405. OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request);
  1406. if(!req.ContainsKey("HomeLocation"))
  1407. break;
  1408. OSDMap HLocation = (OSDMap)req["HomeLocation"];
  1409. if(!HLocation.ContainsKey("LocationPos"))
  1410. break;
  1411. if(!HLocation.ContainsKey("LocationLookAt"))
  1412. break;
  1413. locationID = HLocation["LocationId"].AsInteger();
  1414. if(!OSDMapTOVector3((OSDMap)HLocation["LocationPos"], out pos))
  1415. break;
  1416. if(!OSDMapTOVector3((OSDMap)HLocation["LocationLookAt"], out lookAt))
  1417. break;
  1418. ILandObject land = m_Scene.LandChannel.GetLandObject(pos);
  1419. if(land == null)
  1420. break;
  1421. ulong gpowers = client.GetGroupPowers(land.LandData.GroupID);
  1422. SceneObjectGroup telehub = null;
  1423. if (m_Scene.RegionInfo.RegionSettings.TelehubObject != UUID.Zero)
  1424. // Does the telehub exist in the scene?
  1425. telehub = m_Scene.GetSceneObjectGroup(m_Scene.RegionInfo.RegionSettings.TelehubObject);
  1426. if (!m_Scene.Permissions.IsAdministrator(m_AgentID) && // (a) gods and land managers can set home
  1427. !m_Scene.Permissions.IsGod(m_AgentID) &&
  1428. m_AgentID != land.LandData.OwnerID && // (b) land owners can set home
  1429. // (c) members of the land-associated group in roles that can set home
  1430. ((gpowers & (ulong)GroupPowers.AllowSetHome) != (ulong)GroupPowers.AllowSetHome) &&
  1431. // (d) parcels with telehubs can be the home of anyone
  1432. (telehub == null || !land.ContainsPoint((int)telehub.AbsolutePosition.X, (int)telehub.AbsolutePosition.Y)))
  1433. {
  1434. message = "You are not allowed to set your home location in this parcel.";
  1435. break;
  1436. }
  1437. string userId;
  1438. UUID test;
  1439. if (!m_Scene.UserManagementModule.GetUserUUI(m_AgentID, out userId))
  1440. {
  1441. message = "Set Home request failed. (User Lookup)";
  1442. break;
  1443. }
  1444. if (!UUID.TryParse(userId, out test))
  1445. {
  1446. message = "Set Home request failed. (HG visitor)";
  1447. break;
  1448. }
  1449. if (m_Scene.GridUserService.SetHome(userId, land.RegionUUID, pos, lookAt))
  1450. fail = false;
  1451. break;
  1452. }
  1453. string response;
  1454. if(fail)
  1455. {
  1456. if(client != null)
  1457. client.SendAlertMessage(message);
  1458. response = OSDParser.SerializeLLSDXmlString(resp);
  1459. return response;
  1460. }
  1461. // so its http but still needs a udp reply to inform user? crap :p
  1462. if(client != null)
  1463. client.SendAlertMessage("Home position set.","HomePositionSet");
  1464. resp["success"] = "true";
  1465. OSDMap homeloc = new OSDMap();
  1466. OSDMap homelocpos = new OSDMap();
  1467. // for some odd reason viewers send pos as reals but read as integer
  1468. homelocpos["X"] = new OSDReal(pos.X);
  1469. homelocpos["Y"] = new OSDReal(pos.Y);
  1470. homelocpos["Z"] = new OSDReal(pos.Z);
  1471. homeloc["LocationPos"] = homelocpos;
  1472. resp["HomeLocation"] = homeloc;
  1473. response = OSDParser.SerializeLLSDXmlString(resp);
  1474. return response;
  1475. }
  1476. private static int CompareRolesByMembersDesc(GroupRolesData x, GroupRolesData y)
  1477. {
  1478. return -(x.Members.CompareTo(y.Members));
  1479. }
  1480. public string GroupMemberData(string request, string path, string param, IOSHttpRequest httpRequest,
  1481. IOSHttpResponse httpResponse)
  1482. {
  1483. OSDMap resp = new OSDMap();
  1484. string response;
  1485. bool fail = true;
  1486. IClientAPI client = null;
  1487. ScenePresence sp;
  1488. IGroupsModule m_GroupsModule;
  1489. UUID groupID = UUID.Zero;
  1490. while(true)
  1491. {
  1492. m_GroupsModule = m_Scene.RequestModuleInterface<IGroupsModule>();
  1493. if(m_GroupsModule == null)
  1494. break;
  1495. m_Scene.TryGetScenePresence(m_AgentID, out sp);
  1496. if(sp == null || sp.IsChildAgent || sp.IsDeleted)
  1497. break;
  1498. if(sp.IsInTransit && !sp.IsInLocalTransit)
  1499. break;
  1500. client = sp.ControllingClient;
  1501. OSDMap req = (OSDMap)OSDParser.DeserializeLLSDXml(request);
  1502. if(!req.ContainsKey("group_id"))
  1503. break;
  1504. groupID = req["group_id"].AsUUID();
  1505. if(groupID == UUID.Zero)
  1506. break;
  1507. List<GroupRolesData> roles = m_GroupsModule.GroupRoleDataRequest(client, groupID);
  1508. if(roles == null || roles.Count == 0)
  1509. break;
  1510. List<GroupMembersData> members = m_GroupsModule.GroupMembersRequest(client, groupID);
  1511. if(members == null || members.Count == 0)
  1512. break;
  1513. int memberCount = members.Count;
  1514. Dictionary<string,int> titles = new Dictionary<string,int>();
  1515. int i = 0;
  1516. ulong defaultPowers = 0;
  1517. // build titles array and index
  1518. roles.Sort(CompareRolesByMembersDesc);
  1519. OSDArray osdtitles = new OSDArray();
  1520. foreach(GroupRolesData grd in roles)
  1521. {
  1522. if(grd.Title == null)
  1523. continue;
  1524. string title = grd.Title;
  1525. if(i==0)
  1526. defaultPowers = grd.Powers;
  1527. if(!titles.ContainsKey(title))
  1528. {
  1529. titles[title] = i++;
  1530. osdtitles.Add(new OSDString(title));
  1531. }
  1532. }
  1533. if(titles.Count == 0)
  1534. break;
  1535. OSDMap osdmembers = new OSDMap();
  1536. foreach(GroupMembersData gmd in members)
  1537. {
  1538. OSDMap m = new OSDMap();
  1539. if(gmd.OnlineStatus != null && gmd.OnlineStatus != "")
  1540. m["last_login"] = new OSDString(gmd.OnlineStatus);
  1541. if(gmd.AgentPowers != defaultPowers)
  1542. m["powers"] = new OSDString((gmd.AgentPowers).ToString("X"));
  1543. if(gmd.Title != null && titles.ContainsKey(gmd.Title) && titles[gmd.Title] != 0)
  1544. m["title"] = new OSDInteger(titles[gmd.Title]);
  1545. if(gmd.IsOwner)
  1546. m["owner"] = new OSDString("true");
  1547. if(gmd.Contribution != 0)
  1548. m["donated_square_meters"] = new OSDInteger(gmd.Contribution);
  1549. osdmembers[(gmd.AgentID).ToString()] = m;
  1550. }
  1551. OSDMap osddefaults = new OSDMap();
  1552. osddefaults["default_powers"] = new OSDString(defaultPowers.ToString("X"));
  1553. resp["group_id"] = new OSDUUID(groupID);
  1554. resp["agent_id"] = new OSDUUID(m_AgentID);
  1555. resp["member_count"] = new OSDInteger(memberCount);
  1556. resp["defaults"] = osddefaults;
  1557. resp["titles"] = osdtitles;
  1558. resp["members"] = osdmembers;
  1559. fail = false;
  1560. break;
  1561. }
  1562. if(fail)
  1563. {
  1564. resp["group_id"] = new OSDUUID(groupID);
  1565. resp["agent_id"] = new OSDUUID(m_AgentID);
  1566. resp["member_count"] = new OSDInteger(0);
  1567. resp["defaults"] = new OSDMap();
  1568. resp["titles"] = new OSDArray();
  1569. resp["members"] = new OSDMap();
  1570. }
  1571. response = OSDParser.SerializeLLSDXmlString(resp);
  1572. return response;
  1573. }
  1574. public string GetDisplayNames(string request, string path,
  1575. string param, IOSHttpRequest httpRequest,
  1576. IOSHttpResponse httpResponse)
  1577. {
  1578. httpResponse.StatusCode = (int)System.Net.HttpStatusCode.Gone;
  1579. httpResponse.ContentType = "text/plain";
  1580. ScenePresence sp = m_Scene.GetScenePresence(m_AgentID);
  1581. if(sp == null || sp.IsDeleted)
  1582. return "";
  1583. if(sp.IsInTransit && !sp.IsInLocalTransit)
  1584. {
  1585. httpResponse.StatusCode = (int)System.Net.HttpStatusCode.ServiceUnavailable;
  1586. httpResponse.AddHeader("Retry-After","30");
  1587. return "";
  1588. }
  1589. // Full content request
  1590. httpResponse.StatusCode = (int)System.Net.HttpStatusCode.OK;
  1591. //httpResponse.ContentLength = ??;
  1592. httpResponse.ContentType = "application/llsd+xml";
  1593. NameValueCollection query = HttpUtility.ParseQueryString(httpRequest.Url.Query);
  1594. string[] ids = query.GetValues("ids");
  1595. Dictionary<UUID,string> names = m_UserManager.GetUsersNames(ids);
  1596. StringBuilder lsl = LLSDxmlEncode.Start(names.Count * 256 + 256);
  1597. LLSDxmlEncode.AddMap(lsl);
  1598. if(names.Count == 0)
  1599. LLSDxmlEncode.AddEmptyArray("agents", lsl);
  1600. else
  1601. {
  1602. LLSDxmlEncode.AddArray("agents", lsl);
  1603. foreach (KeyValuePair<UUID,string> kvp in names)
  1604. {
  1605. if (string.IsNullOrEmpty(kvp.Value))
  1606. continue;
  1607. if(kvp.Key == UUID.Zero)
  1608. continue;
  1609. string[] parts = kvp.Value.Split(new char[] {' '});
  1610. // dont tell about unknown users, we can't send them back on Bad either
  1611. if(parts[0] == "Unknown")
  1612. continue;
  1613. LLSDxmlEncode.AddMap(lsl);
  1614. LLSDxmlEncode.AddElem("display_name_next_update", DateTime.UtcNow.AddDays(8), lsl);
  1615. LLSDxmlEncode.AddElem("display_name_expires", DateTime.UtcNow.AddMonths(1), lsl);
  1616. LLSDxmlEncode.AddElem("display_name", kvp.Value, lsl);
  1617. LLSDxmlEncode.AddElem("legacy_first_name", parts[0], lsl);
  1618. LLSDxmlEncode.AddElem("legacy_last_name", parts[1], lsl);
  1619. LLSDxmlEncode.AddElem("username", kvp.Value, lsl);
  1620. LLSDxmlEncode.AddElem("id", kvp.Key, lsl);
  1621. LLSDxmlEncode.AddElem("is_display_name_default", true, lsl);
  1622. LLSDxmlEncode.AddEndMap(lsl);
  1623. }
  1624. LLSDxmlEncode.AddEndArray(lsl);
  1625. }
  1626. LLSDxmlEncode.AddEndMap(lsl);
  1627. return LLSDxmlEncode.End(lsl);;
  1628. }
  1629. }
  1630. public class AssetUploader
  1631. {
  1632. private static readonly ILog m_log =
  1633. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  1634. public event UpLoadedAsset OnUpLoad;
  1635. private UpLoadedAsset handlerUpLoad = null;
  1636. private string uploaderPath = String.Empty;
  1637. private UUID newAssetID;
  1638. private UUID inventoryItemID;
  1639. private UUID parentFolder;
  1640. private IHttpServer httpListener;
  1641. private bool m_dumpAssetsToFile;
  1642. private string m_assetName = String.Empty;
  1643. private string m_assetDes = String.Empty;
  1644. private string m_invType = String.Empty;
  1645. private string m_assetType = String.Empty;
  1646. private int m_cost;
  1647. private string m_error = String.Empty;
  1648. private Timer m_timeoutTimer = new Timer();
  1649. private UUID m_texturesFolder;
  1650. private int m_nreqtextures;
  1651. private int m_nreqmeshs;
  1652. private int m_nreqinstances;
  1653. private bool m_IsAtestUpload;
  1654. private int m_nextOwnerMask;
  1655. private int m_groupMask;
  1656. private int m_everyoneMask;
  1657. public AssetUploader(string assetName, string description, UUID assetID, UUID inventoryItem,
  1658. UUID parentFolderID, string invType, string assetType, string path,
  1659. IHttpServer httpServer, bool dumpAssetsToFile,
  1660. int totalCost, UUID texturesFolder, int nreqtextures, int nreqmeshs, int nreqinstances,
  1661. bool IsAtestUpload, int nextOwnerMask, int groupMask, int everyoneMask)
  1662. {
  1663. m_assetName = assetName;
  1664. m_assetDes = description;
  1665. newAssetID = assetID;
  1666. inventoryItemID = inventoryItem;
  1667. uploaderPath = path;
  1668. httpListener = httpServer;
  1669. parentFolder = parentFolderID;
  1670. m_assetType = assetType;
  1671. m_invType = invType;
  1672. m_dumpAssetsToFile = dumpAssetsToFile;
  1673. m_cost = totalCost;
  1674. m_texturesFolder = texturesFolder;
  1675. m_nreqtextures = nreqtextures;
  1676. m_nreqmeshs = nreqmeshs;
  1677. m_nreqinstances = nreqinstances;
  1678. m_IsAtestUpload = IsAtestUpload;
  1679. m_timeoutTimer.Elapsed += TimedOut;
  1680. m_timeoutTimer.Interval = 120000;
  1681. m_timeoutTimer.AutoReset = false;
  1682. m_timeoutTimer.Start();
  1683. m_nextOwnerMask = nextOwnerMask;
  1684. m_groupMask = groupMask;
  1685. m_everyoneMask = everyoneMask;
  1686. }
  1687. /// <summary>
  1688. /// Handle raw asset upload data via the capability.
  1689. /// </summary>
  1690. /// <param name="data"></param>
  1691. /// <param name="path"></param>
  1692. /// <param name="param"></param>
  1693. /// <returns></returns>
  1694. public string uploaderCaps(byte[] data, string path, string param)
  1695. {
  1696. UUID inv = inventoryItemID;
  1697. string res = String.Empty;
  1698. LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
  1699. /*
  1700. uploadComplete.new_asset = newAssetID.ToString();
  1701. uploadComplete.new_inventory_item = inv;
  1702. uploadComplete.state = "complete";
  1703. res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
  1704. */
  1705. m_timeoutTimer.Stop();
  1706. httpListener.RemoveStreamHandler("POST", uploaderPath);
  1707. // TODO: probably make this a better set of extensions here
  1708. string extension = ".jp2";
  1709. if (m_invType != "image")
  1710. {
  1711. extension = ".dat";
  1712. }
  1713. if (m_dumpAssetsToFile)
  1714. {
  1715. SaveAssetToFile(m_assetName + extension, data);
  1716. }
  1717. handlerUpLoad = OnUpLoad;
  1718. if (handlerUpLoad != null)
  1719. {
  1720. handlerUpLoad(m_assetName, m_assetDes, newAssetID, inv, parentFolder, data, m_invType, m_assetType,
  1721. m_cost, m_texturesFolder, m_nreqtextures, m_nreqmeshs, m_nreqinstances, m_IsAtestUpload,
  1722. ref m_error, ref m_nextOwnerMask, ref m_groupMask, ref m_everyoneMask);
  1723. }
  1724. uploadComplete.new_next_owner_mask = m_nextOwnerMask;
  1725. uploadComplete.new_group_mask = m_groupMask;
  1726. uploadComplete.new_everyone_mask = m_everyoneMask;
  1727. if (m_error == String.Empty)
  1728. {
  1729. uploadComplete.new_asset = newAssetID.ToString();
  1730. uploadComplete.new_inventory_item = inv;
  1731. // if (m_texturesFolder != UUID.Zero)
  1732. // uploadComplete.new_texture_folder_id = m_texturesFolder;
  1733. if (m_IsAtestUpload)
  1734. {
  1735. LLSDAssetUploadError resperror = new LLSDAssetUploadError();
  1736. resperror.message = "Upload SUCCESSFUL for testing purposes only. Other uses are prohibited. Item will not work after 48 hours or on other regions";
  1737. resperror.identifier = inv;
  1738. uploadComplete.error = resperror;
  1739. }
  1740. uploadComplete.state = "complete";
  1741. }
  1742. else
  1743. {
  1744. LLSDAssetUploadError resperror = new LLSDAssetUploadError();
  1745. resperror.message = m_error;
  1746. resperror.identifier = inv;
  1747. uploadComplete.error = resperror;
  1748. uploadComplete.state = "failed";
  1749. }
  1750. res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
  1751. return res;
  1752. }
  1753. private void TimedOut(object sender, ElapsedEventArgs args)
  1754. {
  1755. m_log.InfoFormat("[CAPS]: Removing URL and handler for timed out mesh upload");
  1756. httpListener.RemoveStreamHandler("POST", uploaderPath);
  1757. }
  1758. ///Left this in and commented in case there are unforseen issues
  1759. //private void SaveAssetToFile(string filename, byte[] data)
  1760. //{
  1761. // FileStream fs = File.Create(filename);
  1762. // BinaryWriter bw = new BinaryWriter(fs);
  1763. // bw.Write(data);
  1764. // bw.Close();
  1765. // fs.Close();
  1766. //}
  1767. private static void SaveAssetToFile(string filename, byte[] data)
  1768. {
  1769. string assetPath = "UserAssets";
  1770. if (!Directory.Exists(assetPath))
  1771. {
  1772. Directory.CreateDirectory(assetPath);
  1773. }
  1774. FileStream fs = File.Create(Path.Combine(assetPath, Util.safeFileName(filename)));
  1775. BinaryWriter bw = new BinaryWriter(fs);
  1776. bw.Write(data);
  1777. bw.Close();
  1778. fs.Close();
  1779. }
  1780. }
  1781. /// <summary>
  1782. /// This class is a callback invoked when a client sends asset data to
  1783. /// an agent inventory notecard update url
  1784. /// </summary>
  1785. public class ItemUpdater
  1786. {
  1787. public event UpdateItem OnUpLoad;
  1788. private UpdateItem handlerUpdateItem = null;
  1789. private string uploaderPath = String.Empty;
  1790. private UUID inventoryItemID;
  1791. private IHttpServer httpListener;
  1792. private bool m_dumpAssetToFile;
  1793. public ItemUpdater(UUID inventoryItem, string path, IHttpServer httpServer, bool dumpAssetToFile)
  1794. {
  1795. m_dumpAssetToFile = dumpAssetToFile;
  1796. inventoryItemID = inventoryItem;
  1797. uploaderPath = path;
  1798. httpListener = httpServer;
  1799. }
  1800. /// <summary>
  1801. /// Handle raw uploaded asset data.
  1802. /// </summary>
  1803. /// <param name="data"></param>
  1804. /// <param name="path"></param>
  1805. /// <param name="param"></param>
  1806. /// <returns></returns>
  1807. public string uploaderCaps(byte[] data, string path, string param)
  1808. {
  1809. UUID inv = inventoryItemID;
  1810. string res = String.Empty;
  1811. LLSDAssetUploadComplete uploadComplete = new LLSDAssetUploadComplete();
  1812. UUID assetID = UUID.Zero;
  1813. handlerUpdateItem = OnUpLoad;
  1814. if (handlerUpdateItem != null)
  1815. {
  1816. assetID = handlerUpdateItem(inv, data);
  1817. }
  1818. uploadComplete.new_asset = assetID.ToString();
  1819. uploadComplete.new_inventory_item = inv;
  1820. uploadComplete.state = "complete";
  1821. res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
  1822. httpListener.RemoveStreamHandler("POST", uploaderPath);
  1823. if (m_dumpAssetToFile)
  1824. {
  1825. SaveAssetToFile("updateditem" + Util.RandomClass.Next(1, 1000) + ".dat", data);
  1826. }
  1827. return res;
  1828. }
  1829. ///Left this in and commented in case there are unforseen issues
  1830. //private void SaveAssetToFile(string filename, byte[] data)
  1831. //{
  1832. // FileStream fs = File.Create(filename);
  1833. // BinaryWriter bw = new BinaryWriter(fs);
  1834. // bw.Write(data);
  1835. // bw.Close();
  1836. // fs.Close();
  1837. //}
  1838. private static void SaveAssetToFile(string filename, byte[] data)
  1839. {
  1840. string assetPath = "UserAssets";
  1841. if (!Directory.Exists(assetPath))
  1842. {
  1843. Directory.CreateDirectory(assetPath);
  1844. }
  1845. FileStream fs = File.Create(Path.Combine(assetPath, filename));
  1846. BinaryWriter bw = new BinaryWriter(fs);
  1847. bw.Write(data);
  1848. bw.Close();
  1849. fs.Close();
  1850. }
  1851. }
  1852. /// <summary>
  1853. /// This class is a callback invoked when a client sends asset data to
  1854. /// a task inventory script update url
  1855. /// </summary>
  1856. public class TaskInventoryScriptUpdater
  1857. {
  1858. private static readonly ILog m_log =
  1859. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  1860. public event UpdateTaskScript OnUpLoad;
  1861. private UpdateTaskScript handlerUpdateTaskScript = null;
  1862. private string uploaderPath = String.Empty;
  1863. private UUID inventoryItemID;
  1864. private UUID primID;
  1865. private bool isScriptRunning;
  1866. private IHttpServer httpListener;
  1867. private bool m_dumpAssetToFile;
  1868. public TaskInventoryScriptUpdater(UUID inventoryItemID, UUID primID, int isScriptRunning,
  1869. string path, IHttpServer httpServer, bool dumpAssetToFile)
  1870. {
  1871. m_dumpAssetToFile = dumpAssetToFile;
  1872. this.inventoryItemID = inventoryItemID;
  1873. this.primID = primID;
  1874. // This comes in over the packet as an integer, but actually appears to be treated as a bool
  1875. this.isScriptRunning = (0 == isScriptRunning ? false : true);
  1876. uploaderPath = path;
  1877. httpListener = httpServer;
  1878. }
  1879. /// <summary>
  1880. ///
  1881. /// </summary>
  1882. /// <param name="data"></param>
  1883. /// <param name="path"></param>
  1884. /// <param name="param"></param>
  1885. /// <returns></returns>
  1886. public string uploaderCaps(byte[] data, string path, string param)
  1887. {
  1888. try
  1889. {
  1890. // m_log.InfoFormat("[CAPS]: " +
  1891. // "TaskInventoryScriptUpdater received data: {0}, path: {1}, param: {2}",
  1892. // data, path, param));
  1893. string res = String.Empty;
  1894. LLSDTaskScriptUploadComplete uploadComplete = new LLSDTaskScriptUploadComplete();
  1895. ArrayList errors = new ArrayList();
  1896. handlerUpdateTaskScript = OnUpLoad;
  1897. if (handlerUpdateTaskScript != null)
  1898. {
  1899. handlerUpdateTaskScript(inventoryItemID, primID, isScriptRunning, data, ref errors);
  1900. }
  1901. uploadComplete.new_asset = inventoryItemID;
  1902. uploadComplete.compiled = errors.Count > 0 ? false : true;
  1903. uploadComplete.state = "complete";
  1904. uploadComplete.errors = new OpenSim.Framework.Capabilities.OSDArray();
  1905. uploadComplete.errors.Array = errors;
  1906. res = LLSDHelpers.SerialiseLLSDReply(uploadComplete);
  1907. httpListener.RemoveStreamHandler("POST", uploaderPath);
  1908. if (m_dumpAssetToFile)
  1909. {
  1910. SaveAssetToFile("updatedtaskscript" + Util.RandomClass.Next(1, 1000) + ".dat", data);
  1911. }
  1912. // m_log.InfoFormat("[CAPS]: TaskInventoryScriptUpdater.uploaderCaps res: {0}", res);
  1913. return res;
  1914. }
  1915. catch (Exception e)
  1916. {
  1917. m_log.Error("[CAPS]: " + e.ToString());
  1918. }
  1919. // XXX Maybe this should be some meaningful error packet
  1920. return null;
  1921. }
  1922. ///Left this in and commented in case there are unforseen issues
  1923. //private void SaveAssetToFile(string filename, byte[] data)
  1924. //{
  1925. // FileStream fs = File.Create(filename);
  1926. // BinaryWriter bw = new BinaryWriter(fs);
  1927. // bw.Write(data);
  1928. // bw.Close();
  1929. // fs.Close();
  1930. //}
  1931. private static void SaveAssetToFile(string filename, byte[] data)
  1932. {
  1933. string assetPath = "UserAssets";
  1934. if (!Directory.Exists(assetPath))
  1935. {
  1936. Directory.CreateDirectory(assetPath);
  1937. }
  1938. FileStream fs = File.Create(Path.Combine(assetPath, filename));
  1939. BinaryWriter bw = new BinaryWriter(fs);
  1940. bw.Write(data);
  1941. bw.Close();
  1942. fs.Close();
  1943. }
  1944. }
  1945. }