1
0

HGInstantMessageService.cs 15 KB

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