1
0

HGInstantMessageService.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Net;
  30. using System.Reflection;
  31. using OpenSim.Framework;
  32. using OpenSim.Services.Connectors.Friends;
  33. using OpenSim.Services.Connectors.Hypergrid;
  34. using OpenSim.Services.Interfaces;
  35. using OpenSim.Services.Connectors.InstantMessage;
  36. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  37. using OpenSim.Server.Base;
  38. using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
  39. using OpenMetaverse;
  40. using log4net;
  41. using Nini.Config;
  42. namespace OpenSim.Services.HypergridService
  43. {
  44. /// <summary>
  45. /// Inter-grid IM
  46. /// </summary>
  47. public class HGInstantMessageService : IInstantMessage
  48. {
  49. private static readonly ILog m_log =
  50. LogManager.GetLogger(
  51. MethodBase.GetCurrentMethod().DeclaringType);
  52. private const double CACHE_EXPIRATION_SECONDS = 120000.0; // 33 hours
  53. static bool m_Initialized = false;
  54. protected static IGridService m_GridService;
  55. protected static IPresenceService m_PresenceService;
  56. protected static IUserAgentService m_UserAgentService;
  57. protected static IInstantMessageSimConnector m_IMSimConnector;
  58. protected static Dictionary<UUID, object> m_UserLocationMap = new Dictionary<UUID, object>();
  59. private static ExpiringCache<UUID, GridRegion> m_RegionCache;
  60. private static string m_RestURL;
  61. private static bool m_ForwardOfflineGroupMessages;
  62. private static bool m_InGatekeeper;
  63. public HGInstantMessageService(IConfigSource config)
  64. : this(config, null)
  65. {
  66. }
  67. public HGInstantMessageService(IConfigSource config, IInstantMessageSimConnector imConnector)
  68. {
  69. if (imConnector != null)
  70. m_IMSimConnector = imConnector;
  71. if (!m_Initialized)
  72. {
  73. m_Initialized = true;
  74. IConfig serverConfig = config.Configs["HGInstantMessageService"];
  75. if (serverConfig == null)
  76. throw new Exception(String.Format("No section HGInstantMessageService in config file"));
  77. string gridService = serverConfig.GetString("GridService", String.Empty);
  78. string presenceService = serverConfig.GetString("PresenceService", String.Empty);
  79. string userAgentService = serverConfig.GetString("UserAgentService", String.Empty);
  80. m_InGatekeeper = serverConfig.GetBoolean("InGatekeeper", false);
  81. m_log.DebugFormat("[HG IM SERVICE]: Starting... InRobust? {0}", m_InGatekeeper);
  82. if (gridService == string.Empty || presenceService == string.Empty)
  83. throw new Exception(String.Format("Incomplete specifications, InstantMessage Service cannot function."));
  84. Object[] args = new Object[] { config };
  85. m_GridService = ServerUtils.LoadPlugin<IGridService>(gridService, args);
  86. m_PresenceService = ServerUtils.LoadPlugin<IPresenceService>(presenceService, args);
  87. m_UserAgentService = ServerUtils.LoadPlugin<IUserAgentService>(userAgentService, args);
  88. m_RegionCache = new ExpiringCache<UUID, GridRegion>();
  89. IConfig cnf = config.Configs["Messaging"];
  90. if (cnf == null)
  91. {
  92. return;
  93. }
  94. m_RestURL = cnf.GetString("OfflineMessageURL", string.Empty);
  95. m_ForwardOfflineGroupMessages = cnf.GetBoolean("ForwardOfflineGroupMessages", false);
  96. }
  97. }
  98. public bool IncomingInstantMessage(GridInstantMessage im)
  99. {
  100. // m_log.DebugFormat("[HG IM SERVICE]: Received message from {0} to {1}", im.fromAgentID, im.toAgentID);
  101. // UUID toAgentID = new UUID(im.toAgentID);
  102. bool success = false;
  103. if (m_IMSimConnector != null)
  104. {
  105. //m_log.DebugFormat("[XXX] SendIMToRegion local im connector");
  106. success = m_IMSimConnector.SendInstantMessage(im);
  107. }
  108. else
  109. {
  110. success = TrySendInstantMessage(im, "", true, false);
  111. }
  112. if (!success && m_InGatekeeper) // we do this only in the Gatekeeper IM service
  113. UndeliveredMessage(im);
  114. return success;
  115. }
  116. public bool OutgoingInstantMessage(GridInstantMessage im, string url, bool foreigner)
  117. {
  118. // m_log.DebugFormat("[HG IM SERVICE]: Sending message from {0} to {1}@{2}", im.fromAgentID, im.toAgentID, url);
  119. if (url != string.Empty)
  120. return TrySendInstantMessage(im, url, true, foreigner);
  121. else
  122. {
  123. PresenceInfo upd = new PresenceInfo();
  124. upd.RegionID = UUID.Zero;
  125. return TrySendInstantMessage(im, upd, true, foreigner);
  126. }
  127. }
  128. protected bool TrySendInstantMessage(GridInstantMessage im, object previousLocation, bool firstTime, bool foreigner)
  129. {
  130. UUID toAgentID = new UUID(im.toAgentID);
  131. PresenceInfo upd = null;
  132. string url = string.Empty;
  133. bool lookupAgent = false;
  134. lock (m_UserLocationMap)
  135. {
  136. if (m_UserLocationMap.ContainsKey(toAgentID))
  137. {
  138. object o = m_UserLocationMap[toAgentID];
  139. if (o is PresenceInfo)
  140. upd = (PresenceInfo)o;
  141. else if (o is string)
  142. url = (string)o;
  143. // We need to compare the current location with the previous
  144. // or the recursive loop will never end because it will never try to lookup the agent again
  145. if (!firstTime)
  146. {
  147. lookupAgent = true;
  148. upd = null;
  149. }
  150. }
  151. else
  152. {
  153. lookupAgent = true;
  154. }
  155. }
  156. //m_log.DebugFormat("[XXX] Neeed lookup ? {0}", (lookupAgent ? "yes" : "no"));
  157. // Are we needing to look-up an agent?
  158. if (lookupAgent)
  159. {
  160. // Non-cached user agent lookup.
  161. PresenceInfo[] presences = m_PresenceService.GetAgents(new string[] { toAgentID.ToString() });
  162. if (presences != null && presences.Length > 0)
  163. {
  164. foreach (PresenceInfo p in presences)
  165. {
  166. if (p.RegionID != UUID.Zero)
  167. {
  168. //m_log.DebugFormat("[XXX]: Found presence in {0}", p.RegionID);
  169. upd = p;
  170. break;
  171. }
  172. }
  173. }
  174. if (upd == null && !foreigner)
  175. {
  176. // Let's check with the UAS if the user is elsewhere
  177. m_log.DebugFormat("[HG IM SERVICE]: User is not present. Checking location with User Agent service");
  178. url = m_UserAgentService.LocateUser(toAgentID);
  179. }
  180. // check if we've tried this before..
  181. // This is one way to end the recursive loop
  182. //
  183. if (!firstTime && ((previousLocation is PresenceInfo && upd != null && upd.RegionID == ((PresenceInfo)previousLocation).RegionID) ||
  184. (previousLocation is string && upd == null && previousLocation.Equals(url))))
  185. {
  186. // m_log.Error("[GRID INSTANT MESSAGE]: Unable to deliver an instant message");
  187. m_log.DebugFormat("[HG IM SERVICE]: Fail 2 {0} {1}", previousLocation, url);
  188. return false;
  189. }
  190. }
  191. if (upd != null)
  192. {
  193. // ok, the user is around somewhere. Let's send back the reply with "success"
  194. // even though the IM may still fail. Just don't keep the caller waiting for
  195. // the entire time we're trying to deliver the IM
  196. return SendIMToRegion(upd, im, toAgentID, foreigner);
  197. }
  198. else if (url != string.Empty)
  199. {
  200. // ok, the user is around somewhere. Let's send back the reply with "success"
  201. // even though the IM may still fail. Just don't keep the caller waiting for
  202. // the entire time we're trying to deliver the IM
  203. return ForwardIMToGrid(url, im, toAgentID, foreigner);
  204. }
  205. else if (firstTime && previousLocation is string && (string)previousLocation != string.Empty)
  206. {
  207. return ForwardIMToGrid((string)previousLocation, im, toAgentID, foreigner);
  208. }
  209. else
  210. m_log.DebugFormat("[HG IM SERVICE]: Unable to locate user {0}", toAgentID);
  211. return false;
  212. }
  213. bool SendIMToRegion(PresenceInfo upd, GridInstantMessage im, UUID toAgentID, bool foreigner)
  214. {
  215. bool imresult = false;
  216. GridRegion reginfo = null;
  217. if (!m_RegionCache.TryGetValue(upd.RegionID, out reginfo))
  218. {
  219. reginfo = m_GridService.GetRegionByUUID(UUID.Zero /*!!!*/, upd.RegionID);
  220. if (reginfo != null)
  221. m_RegionCache.AddOrUpdate(upd.RegionID, reginfo, CACHE_EXPIRATION_SECONDS);
  222. }
  223. if (reginfo != null)
  224. {
  225. imresult = InstantMessageServiceConnector.SendInstantMessage(reginfo.ServerURI, im);
  226. }
  227. else
  228. {
  229. m_log.DebugFormat("[HG IM SERVICE]: Failed to deliver message to {0}", reginfo.ServerURI);
  230. return false;
  231. }
  232. if (imresult)
  233. {
  234. // IM delivery successful, so store the Agent's location in our local cache.
  235. lock (m_UserLocationMap)
  236. {
  237. if (m_UserLocationMap.ContainsKey(toAgentID))
  238. {
  239. m_UserLocationMap[toAgentID] = upd;
  240. }
  241. else
  242. {
  243. m_UserLocationMap.Add(toAgentID, upd);
  244. }
  245. }
  246. return true;
  247. }
  248. else
  249. {
  250. // try again, but lookup user this time.
  251. // Warning, this must call the Async version
  252. // of this method or we'll be making thousands of threads
  253. // The version within the spawned thread is SendGridInstantMessageViaXMLRPCAsync
  254. // The version that spawns the thread is SendGridInstantMessageViaXMLRPC
  255. // This is recursive!!!!!
  256. return TrySendInstantMessage(im, upd, false, foreigner);
  257. }
  258. }
  259. bool ForwardIMToGrid(string url, GridInstantMessage im, UUID toAgentID, bool foreigner)
  260. {
  261. if (InstantMessageServiceConnector.SendInstantMessage(url, im))
  262. {
  263. // IM delivery successful, so store the Agent's location in our local cache.
  264. lock (m_UserLocationMap)
  265. {
  266. if (m_UserLocationMap.ContainsKey(toAgentID))
  267. {
  268. m_UserLocationMap[toAgentID] = url;
  269. }
  270. else
  271. {
  272. m_UserLocationMap.Add(toAgentID, url);
  273. }
  274. }
  275. return true;
  276. }
  277. else
  278. {
  279. // try again, but lookup user this time.
  280. // This is recursive!!!!!
  281. return TrySendInstantMessage(im, url, false, foreigner);
  282. }
  283. }
  284. private bool UndeliveredMessage(GridInstantMessage im)
  285. {
  286. if (m_RestURL != string.Empty && (im.offline != 0)
  287. && (!im.fromGroup || (im.fromGroup && m_ForwardOfflineGroupMessages)))
  288. {
  289. // m_log.DebugFormat("[HG IM SERVICE]: Message saved");
  290. return SynchronousRestObjectRequester.MakeRequest<GridInstantMessage, bool>(
  291. "POST", m_RestURL + "/SaveMessage/", im);
  292. }
  293. else
  294. {
  295. return false;
  296. }
  297. }
  298. }
  299. }