LoadImageURLModule.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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.Drawing;
  29. using System.IO;
  30. using System.Net;
  31. using Nini.Config;
  32. using OpenMetaverse;
  33. using OpenMetaverse.Imaging;
  34. using OpenSim.Framework;
  35. using OpenSim.Region.CoreModules.Scripting.DynamicTexture;
  36. using OpenSim.Region.Framework.Interfaces;
  37. using OpenSim.Region.Framework.Scenes;
  38. using log4net;
  39. using System.Reflection;
  40. using Mono.Addins;
  41. namespace OpenSim.Region.CoreModules.Scripting.LoadImageURL
  42. {
  43. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LoadImageURLModule")]
  44. public class LoadImageURLModule : ISharedRegionModule, IDynamicTextureRender
  45. {
  46. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  47. private string m_name = "LoadImageURL";
  48. private Scene m_scene;
  49. private IDynamicTextureManager m_textureManager;
  50. private OutboundUrlFilter m_outboundUrlFilter;
  51. private string m_proxyurl = "";
  52. private string m_proxyexcepts = "";
  53. #region IDynamicTextureRender Members
  54. public string GetName()
  55. {
  56. return m_name;
  57. }
  58. public string GetContentType()
  59. {
  60. return ("image");
  61. }
  62. public bool SupportsAsynchronous()
  63. {
  64. return true;
  65. }
  66. // public bool AlwaysIdenticalConversion(string bodyData, string extraParams)
  67. // {
  68. // // We don't support conversion of body data.
  69. // return false;
  70. // }
  71. public IDynamicTexture ConvertUrl(string url, string extraParams)
  72. {
  73. return null;
  74. }
  75. public IDynamicTexture ConvertData(string bodyData, string extraParams)
  76. {
  77. return null;
  78. }
  79. public bool AsyncConvertUrl(UUID id, string url, string extraParams)
  80. {
  81. return MakeHttpRequest(url, id);
  82. }
  83. public bool AsyncConvertData(UUID id, string bodyData, string extraParams)
  84. {
  85. return false;
  86. }
  87. public void GetDrawStringSize(string text, string fontName, int fontSize,
  88. out double xSize, out double ySize)
  89. {
  90. xSize = 0;
  91. ySize = 0;
  92. }
  93. #endregion
  94. #region ISharedRegionModule Members
  95. public void Initialise(IConfigSource config)
  96. {
  97. m_outboundUrlFilter = new OutboundUrlFilter("Script dynamic texture image module", config);
  98. m_proxyurl = config.Configs["Startup"].GetString("HttpProxy");
  99. m_proxyexcepts = config.Configs["Startup"].GetString("HttpProxyExceptions");
  100. }
  101. public void PostInitialise()
  102. {
  103. }
  104. public void AddRegion(Scene scene)
  105. {
  106. if (m_scene == null)
  107. m_scene = scene;
  108. }
  109. public void RemoveRegion(Scene scene)
  110. {
  111. }
  112. public void RegionLoaded(Scene scene)
  113. {
  114. if (m_textureManager == null && m_scene == scene)
  115. {
  116. m_textureManager = m_scene.RequestModuleInterface<IDynamicTextureManager>();
  117. if (m_textureManager != null)
  118. {
  119. m_textureManager.RegisterRender(GetContentType(), this);
  120. }
  121. }
  122. }
  123. public void Close()
  124. {
  125. }
  126. public string Name
  127. {
  128. get { return m_name; }
  129. }
  130. public Type ReplaceableInterface
  131. {
  132. get { return null; }
  133. }
  134. #endregion
  135. private bool MakeHttpRequest(string url, UUID requestID)
  136. {
  137. if (!m_outboundUrlFilter.CheckAllowed(new Uri(url)))
  138. return false;
  139. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  140. request.AllowAutoRedirect = false;
  141. if (!string.IsNullOrEmpty(m_proxyurl))
  142. {
  143. if (!string.IsNullOrEmpty(m_proxyexcepts))
  144. {
  145. string[] elist = m_proxyexcepts.Split(';');
  146. request.Proxy = new WebProxy(m_proxyurl, true, elist);
  147. }
  148. else
  149. {
  150. request.Proxy = new WebProxy(m_proxyurl, true);
  151. }
  152. }
  153. RequestState state = new RequestState(request, requestID);
  154. // IAsyncResult result = request.BeginGetResponse(new AsyncCallback(HttpRequestReturn), state);
  155. request.BeginGetResponse(new AsyncCallback(HttpRequestReturn), state);
  156. TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
  157. state.TimeOfRequest = (int) t.TotalSeconds;
  158. return true;
  159. }
  160. private void HttpRequestReturn(IAsyncResult result)
  161. {
  162. if (m_textureManager == null)
  163. {
  164. m_log.WarnFormat("[LOADIMAGEURLMODULE]: No texture manager. Can't function.");
  165. return;
  166. }
  167. RequestState state = (RequestState) result.AsyncState;
  168. WebRequest request = (WebRequest) state.Request;
  169. Stream stream = null;
  170. byte[] imageJ2000 = new byte[0];
  171. Size newSize = new Size(0, 0);
  172. HttpWebResponse response = null;
  173. try
  174. {
  175. response = (HttpWebResponse)request.EndGetResponse(result);
  176. if (response != null && response.StatusCode == HttpStatusCode.OK)
  177. {
  178. stream = response.GetResponseStream();
  179. if (stream != null)
  180. {
  181. try
  182. {
  183. Bitmap image = new Bitmap(stream);
  184. // TODO: make this a bit less hard coded
  185. if ((image.Height < 64) && (image.Width < 64))
  186. {
  187. newSize.Width = 32;
  188. newSize.Height = 32;
  189. }
  190. else if ((image.Height < 128) && (image.Width < 128))
  191. {
  192. newSize.Width = 64;
  193. newSize.Height = 64;
  194. }
  195. else if ((image.Height < 256) && (image.Width < 256))
  196. {
  197. newSize.Width = 128;
  198. newSize.Height = 128;
  199. }
  200. else if ((image.Height < 512 && image.Width < 512))
  201. {
  202. newSize.Width = 256;
  203. newSize.Height = 256;
  204. }
  205. else if ((image.Height < 1024 && image.Width < 1024))
  206. {
  207. newSize.Width = 512;
  208. newSize.Height = 512;
  209. }
  210. else
  211. {
  212. newSize.Width = 1024;
  213. newSize.Height = 1024;
  214. }
  215. using (Bitmap resize = new Bitmap(image, newSize))
  216. {
  217. imageJ2000 = OpenJPEG.EncodeFromImage(resize, true);
  218. }
  219. }
  220. catch (Exception)
  221. {
  222. m_log.Error("[LOADIMAGEURLMODULE]: OpenJpeg Conversion Failed. Empty byte data returned!");
  223. }
  224. }
  225. else
  226. {
  227. m_log.WarnFormat("[LOADIMAGEURLMODULE] No data returned");
  228. }
  229. }
  230. }
  231. catch (WebException)
  232. {
  233. }
  234. finally
  235. {
  236. if (stream != null)
  237. stream.Close();
  238. if (response != null)
  239. response.Close();
  240. if (
  241. response.StatusCode == HttpStatusCode.MovedPermanently
  242. || response.StatusCode == HttpStatusCode.Found
  243. || response.StatusCode == HttpStatusCode.SeeOther
  244. || response.StatusCode == HttpStatusCode.TemporaryRedirect)
  245. {
  246. string redirectedUrl = response.Headers["Location"];
  247. MakeHttpRequest(redirectedUrl, state.RequestID);
  248. }
  249. else
  250. {
  251. m_log.DebugFormat("[LOADIMAGEURLMODULE]: Returning {0} bytes of image data for request {1}",
  252. imageJ2000.Length, state.RequestID);
  253. m_textureManager.ReturnData(
  254. state.RequestID,
  255. new OpenSim.Region.CoreModules.Scripting.DynamicTexture.DynamicTexture(
  256. request.RequestUri, null, imageJ2000, newSize, false));
  257. }
  258. }
  259. }
  260. #region Nested type: RequestState
  261. public class RequestState
  262. {
  263. public HttpWebRequest Request = null;
  264. public UUID RequestID = UUID.Zero;
  265. public int TimeOfRequest = 0;
  266. public RequestState(HttpWebRequest request, UUID requestID)
  267. {
  268. Request = request;
  269. RequestID = requestID;
  270. }
  271. }
  272. #endregion
  273. }
  274. }