1
0

HGInstantMessageService.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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 IOfflineIMService m_OfflineIMService;
  58. protected static IInstantMessageSimConnector m_IMSimConnector;
  59. protected static Dictionary<UUID, object> m_UserLocationMap = new Dictionary<UUID, object>();
  60. private static ExpiringCache<UUID, GridRegion> m_RegionCache;
  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_ForwardOfflineGroupMessages = cnf.GetBoolean("ForwardOfflineGroupMessages", false);
  95. if (m_InGatekeeper)
  96. {
  97. string offlineIMService = cnf.GetString("OfflineIMService", string.Empty);
  98. if (offlineIMService != string.Empty)
  99. m_OfflineIMService = ServerUtils.LoadPlugin<IOfflineIMService>(offlineIMService, args);
  100. }
  101. }
  102. }
  103. public bool IncomingInstantMessage(GridInstantMessage im)
  104. {
  105. // m_log.DebugFormat("[HG IM SERVICE]: Received message from {0} to {1}", im.fromAgentID, im.toAgentID);
  106. // UUID toAgentID = new UUID(im.toAgentID);
  107. bool success = false;
  108. if (m_IMSimConnector != null)
  109. {
  110. //m_log.DebugFormat("[XXX] SendIMToRegion local im connector");
  111. success = m_IMSimConnector.SendInstantMessage(im);
  112. }
  113. else
  114. {
  115. success = TrySendInstantMessage(im, "", true, false);
  116. }
  117. if (!success && m_InGatekeeper) // we do this only in the Gatekeeper IM service
  118. UndeliveredMessage(im);
  119. return success;
  120. }
  121. public bool OutgoingInstantMessage(GridInstantMessage im, string url, bool foreigner)
  122. {
  123. // m_log.DebugFormat("[HG IM SERVICE]: Sending message from {0} to {1}@{2}", im.fromAgentID, im.toAgentID, url);
  124. if (url != string.Empty)
  125. return TrySendInstantMessage(im, url, true, foreigner);
  126. else
  127. {
  128. PresenceInfo upd = new PresenceInfo();
  129. upd.RegionID = UUID.Zero;
  130. return TrySendInstantMessage(im, upd, true, foreigner);
  131. }
  132. }
  133. protected bool TrySendInstantMessage(GridInstantMessage im, object previousLocation, bool firstTime, bool foreigner)
  134. {
  135. UUID toAgentID = new UUID(im.toAgentID);
  136. PresenceInfo upd = null;
  137. string url = string.Empty;
  138. bool lookupAgent = false;
  139. lock (m_UserLocationMap)
  140. {
  141. if (m_UserLocationMap.ContainsKey(toAgentID))
  142. {
  143. object o = m_UserLocationMap[toAgentID];
  144. if (o is PresenceInfo)
  145. upd = (PresenceInfo)o;
  146. else if (o is string)
  147. url = (string)o;
  148. // We need to compare the current location with the previous
  149. // or the recursive loop will never end because it will never try to lookup the agent again
  150. if (!firstTime)
  151. {
  152. lookupAgent = true;
  153. upd = null;
  154. }
  155. }
  156. else
  157. {
  158. lookupAgent = true;
  159. }
  160. }
  161. //m_log.DebugFormat("[XXX] Neeed lookup ? {0}", (lookupAgent ? "yes" : "no"));
  162. // Are we needing to look-up an agent?
  163. if (lookupAgent)
  164. {
  165. // Non-cached user agent lookup.
  166. PresenceInfo[] presences = m_PresenceService.GetAgents(new string[] { toAgentID.ToString() });
  167. if (presences != null && presences.Length > 0)
  168. {
  169. foreach (PresenceInfo p in presences)
  170. {
  171. if (p.RegionID != UUID.Zero)
  172. {
  173. //m_log.DebugFormat("[XXX]: Found presence in {0}", p.RegionID);
  174. upd = p;
  175. break;
  176. }
  177. }
  178. }
  179. if (upd == null && !foreigner)
  180. {
  181. // Let's check with the UAS if the user is elsewhere
  182. m_log.DebugFormat("[HG IM SERVICE]: User is not present. Checking location with User Agent service");
  183. try
  184. {
  185. url = m_UserAgentService.LocateUser(toAgentID);
  186. }
  187. catch (Exception e)
  188. {
  189. m_log.Warn("[HG IM SERVICE]: LocateUser call failed ", e);
  190. url = string.Empty;
  191. }
  192. }
  193. // check if we've tried this before..
  194. // This is one way to end the recursive loop
  195. //
  196. if (!firstTime && ((previousLocation is PresenceInfo && upd != null && upd.RegionID == ((PresenceInfo)previousLocation).RegionID) ||
  197. (previousLocation is string && upd == null && previousLocation.Equals(url))))
  198. {
  199. // m_log.Error("[GRID INSTANT MESSAGE]: Unable to deliver an instant message");
  200. m_log.DebugFormat("[HG IM SERVICE]: Fail 2 {0} {1}", previousLocation, url);
  201. return false;
  202. }
  203. }
  204. if (upd != null)
  205. {
  206. // ok, the user is around somewhere. Let's send back the reply with "success"
  207. // even though the IM may still fail. Just don't keep the caller waiting for
  208. // the entire time we're trying to deliver the IM
  209. return SendIMToRegion(upd, im, toAgentID, foreigner);
  210. }
  211. else if (url != string.Empty)
  212. {
  213. // ok, the user is around somewhere. Let's send back the reply with "success"
  214. // even though the IM may still fail. Just don't keep the caller waiting for
  215. // the entire time we're trying to deliver the IM
  216. return ForwardIMToGrid(url, im, toAgentID, foreigner);
  217. }
  218. else if (firstTime && previousLocation is string && (string)previousLocation != string.Empty)
  219. {
  220. return ForwardIMToGrid((string)previousLocation, im, toAgentID, foreigner);
  221. }
  222. else
  223. m_log.DebugFormat("[HG IM SERVICE]: Unable to locate user {0}", toAgentID);
  224. return false;
  225. }
  226. bool SendIMToRegion(PresenceInfo upd, GridInstantMessage im, UUID toAgentID, bool foreigner)
  227. {
  228. bool imresult = false;
  229. GridRegion reginfo = null;
  230. if (!m_RegionCache.TryGetValue(upd.RegionID, out reginfo))
  231. {
  232. reginfo = m_GridService.GetRegionByUUID(UUID.Zero /*!!!*/, upd.RegionID);
  233. if (reginfo != null)
  234. m_RegionCache.AddOrUpdate(upd.RegionID, reginfo, CACHE_EXPIRATION_SECONDS);
  235. }
  236. if (reginfo != null)
  237. {
  238. imresult = InstantMessageServiceConnector.SendInstantMessage(reginfo.ServerURI, im);
  239. }
  240. else
  241. {
  242. m_log.DebugFormat("[HG IM SERVICE]: Failed to deliver message to {0}", reginfo.ServerURI);
  243. return false;
  244. }
  245. if (imresult)
  246. {
  247. // IM delivery successful, so store the Agent's location in our local cache.
  248. lock (m_UserLocationMap)
  249. {
  250. if (m_UserLocationMap.ContainsKey(toAgentID))
  251. {
  252. m_UserLocationMap[toAgentID] = upd;
  253. }
  254. else
  255. {
  256. m_UserLocationMap.Add(toAgentID, upd);
  257. }
  258. }
  259. return true;
  260. }
  261. else
  262. {
  263. // try again, but lookup user this time.
  264. // Warning, this must call the Async version
  265. // of this method or we'll be making thousands of threads
  266. // The version within the spawned thread is SendGridInstantMessageViaXMLRPCAsync
  267. // The version that spawns the thread is SendGridInstantMessageViaXMLRPC
  268. // This is recursive!!!!!
  269. return TrySendInstantMessage(im, upd, false, foreigner);
  270. }
  271. }
  272. bool ForwardIMToGrid(string url, GridInstantMessage im, UUID toAgentID, bool foreigner)
  273. {
  274. if (InstantMessageServiceConnector.SendInstantMessage(url, im))
  275. {
  276. // IM delivery successful, so store the Agent's location in our local cache.
  277. lock (m_UserLocationMap)
  278. {
  279. if (m_UserLocationMap.ContainsKey(toAgentID))
  280. {
  281. m_UserLocationMap[toAgentID] = url;
  282. }
  283. else
  284. {
  285. m_UserLocationMap.Add(toAgentID, url);
  286. }
  287. }
  288. return true;
  289. }
  290. else
  291. {
  292. // try again, but lookup user this time.
  293. // This is recursive!!!!!
  294. return TrySendInstantMessage(im, url, false, foreigner);
  295. }
  296. }
  297. private bool UndeliveredMessage(GridInstantMessage im)
  298. {
  299. if (m_OfflineIMService == null)
  300. return false;
  301. if (im.dialog != (byte)InstantMessageDialog.MessageFromObject &&
  302. im.dialog != (byte)InstantMessageDialog.MessageFromAgent &&
  303. im.dialog != (byte)InstantMessageDialog.GroupNotice &&
  304. im.dialog != (byte)InstantMessageDialog.GroupInvitation &&
  305. im.dialog != (byte)InstantMessageDialog.InventoryOffered)
  306. {
  307. return false;
  308. }
  309. if (!m_ForwardOfflineGroupMessages)
  310. {
  311. if (im.dialog == (byte)InstantMessageDialog.GroupNotice ||
  312. im.dialog == (byte)InstantMessageDialog.GroupInvitation)
  313. return false;
  314. }
  315. // m_log.DebugFormat("[HG IM SERVICE]: Message saved");
  316. string reason = string.Empty;
  317. return m_OfflineIMService.StoreMessage(im, out reason);
  318. }
  319. }
  320. }