LoadImageURLModule.cs 11 KB

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