GroupsMessagingModule.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813
  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.Linq;
  30. using System.Reflection;
  31. using log4net;
  32. using Mono.Addins;
  33. using Nini.Config;
  34. using OpenMetaverse;
  35. using OpenMetaverse.StructuredData;
  36. using OpenSim.Framework;
  37. using OpenSim.Region.Framework.Interfaces;
  38. using OpenSim.Region.Framework.Scenes;
  39. using OpenSim.Services.Interfaces;
  40. using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
  41. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  42. namespace OpenSim.Groups
  43. {
  44. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "GroupsMessagingModule")]
  45. public class GroupsMessagingModule : ISharedRegionModule, IGroupsMessagingModule
  46. {
  47. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  48. private List<Scene> m_sceneList = new List<Scene>();
  49. private IPresenceService m_presenceService;
  50. private IMessageTransferModule m_msgTransferModule = null;
  51. private IUserManagement m_UserManagement = null;
  52. private IGroupsServicesConnector m_groupData = null;
  53. // Config Options
  54. private bool m_groupMessagingEnabled = false;
  55. private bool m_debugEnabled = true;
  56. /// <summary>
  57. /// If enabled, module only tries to send group IMs to online users by querying cached presence information.
  58. /// </summary>
  59. private bool m_messageOnlineAgentsOnly;
  60. /// <summary>
  61. /// Cache for online users.
  62. /// </summary>
  63. /// <remarks>
  64. /// Group ID is key, presence information for online members is value.
  65. /// Will only be non-null if m_messageOnlineAgentsOnly = true
  66. /// We cache here so that group messages don't constantly have to re-request the online user list to avoid
  67. /// attempted expensive sending of messages to offline users.
  68. /// The tradeoff is that a user that comes online will not receive messages consistently from all other users
  69. /// until caches have updated.
  70. /// Therefore, we set the cache expiry to just 20 seconds.
  71. /// </remarks>
  72. private ExpiringCache<UUID, PresenceInfo[]> m_usersOnlineCache;
  73. private int m_usersOnlineCacheExpirySeconds = 20;
  74. private Dictionary<UUID, List<string>> m_groupsAgentsDroppedFromChatSession = new Dictionary<UUID, List<string>>();
  75. private Dictionary<UUID, List<string>> m_groupsAgentsInvitedToChatSession = new Dictionary<UUID, List<string>>();
  76. #region Region Module interfaceBase Members
  77. public void Initialise(IConfigSource config)
  78. {
  79. IConfig groupsConfig = config.Configs["Groups"];
  80. if (groupsConfig == null)
  81. // Do not run this module by default.
  82. return;
  83. // if groups aren't enabled, we're not needed.
  84. // if we're not specified as the connector to use, then we're not wanted
  85. if ((groupsConfig.GetBoolean("Enabled", false) == false)
  86. || (groupsConfig.GetString("MessagingModule", "") != Name))
  87. {
  88. m_groupMessagingEnabled = false;
  89. return;
  90. }
  91. m_groupMessagingEnabled = groupsConfig.GetBoolean("MessagingEnabled", true);
  92. if (!m_groupMessagingEnabled)
  93. return;
  94. m_messageOnlineAgentsOnly = groupsConfig.GetBoolean("MessageOnlineUsersOnly", false);
  95. if (m_messageOnlineAgentsOnly)
  96. {
  97. m_usersOnlineCache = new ExpiringCache<UUID, PresenceInfo[]>();
  98. }
  99. else
  100. {
  101. m_log.Error("[Groups.Messaging]: GroupsMessagingModule V2 requires MessageOnlineUsersOnly = true");
  102. m_groupMessagingEnabled = false;
  103. return;
  104. }
  105. m_debugEnabled = groupsConfig.GetBoolean("DebugEnabled", true);
  106. m_log.InfoFormat(
  107. "[Groups.Messaging]: GroupsMessagingModule enabled with MessageOnlineOnly = {0}, DebugEnabled = {1}",
  108. m_messageOnlineAgentsOnly, m_debugEnabled);
  109. }
  110. public void AddRegion(Scene scene)
  111. {
  112. if (!m_groupMessagingEnabled)
  113. return;
  114. scene.RegisterModuleInterface<IGroupsMessagingModule>(this);
  115. m_sceneList.Add(scene);
  116. scene.EventManager.OnNewClient += OnNewClient;
  117. scene.EventManager.OnMakeRootAgent += OnMakeRootAgent;
  118. scene.EventManager.OnMakeChildAgent += OnMakeChildAgent;
  119. scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage;
  120. scene.EventManager.OnClientLogin += OnClientLogin;
  121. }
  122. public void RegionLoaded(Scene scene)
  123. {
  124. if (!m_groupMessagingEnabled)
  125. return;
  126. if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
  127. m_groupData = scene.RequestModuleInterface<IGroupsServicesConnector>();
  128. // No groups module, no groups messaging
  129. if (m_groupData == null)
  130. {
  131. m_log.Error("[Groups.Messaging]: Could not get IGroupsServicesConnector, GroupsMessagingModule is now disabled.");
  132. RemoveRegion(scene);
  133. return;
  134. }
  135. m_msgTransferModule = scene.RequestModuleInterface<IMessageTransferModule>();
  136. // No message transfer module, no groups messaging
  137. if (m_msgTransferModule == null)
  138. {
  139. m_log.Error("[Groups.Messaging]: Could not get MessageTransferModule");
  140. RemoveRegion(scene);
  141. return;
  142. }
  143. m_UserManagement = scene.RequestModuleInterface<IUserManagement>();
  144. // No groups module, no groups messaging
  145. if (m_UserManagement == null)
  146. {
  147. m_log.Error("[Groups.Messaging]: Could not get IUserManagement, GroupsMessagingModule is now disabled.");
  148. RemoveRegion(scene);
  149. return;
  150. }
  151. if (m_presenceService == null)
  152. m_presenceService = scene.PresenceService;
  153. }
  154. public void RemoveRegion(Scene scene)
  155. {
  156. if (!m_groupMessagingEnabled)
  157. return;
  158. if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
  159. m_sceneList.Remove(scene);
  160. scene.EventManager.OnNewClient -= OnNewClient;
  161. scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage;
  162. scene.EventManager.OnClientLogin -= OnClientLogin;
  163. scene.UnregisterModuleInterface<IGroupsMessagingModule>(this);
  164. }
  165. public void Close()
  166. {
  167. if (!m_groupMessagingEnabled)
  168. return;
  169. if (m_debugEnabled) m_log.Debug("[Groups.Messaging]: Shutting down GroupsMessagingModule module.");
  170. m_sceneList.Clear();
  171. m_groupData = null;
  172. m_msgTransferModule = null;
  173. }
  174. public Type ReplaceableInterface
  175. {
  176. get { return null; }
  177. }
  178. public string Name
  179. {
  180. get { return "Groups Messaging Module V2"; }
  181. }
  182. public void PostInitialise()
  183. {
  184. // NoOp
  185. }
  186. #endregion
  187. /// <summary>
  188. /// Not really needed, but does confirm that the group exists.
  189. /// </summary>
  190. public bool StartGroupChatSession(UUID agentID, UUID groupID)
  191. {
  192. if (m_debugEnabled)
  193. m_log.DebugFormat("[Groups.Messaging]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
  194. GroupRecord groupInfo = m_groupData.GetGroupRecord(agentID.ToString(), groupID, null);
  195. if (groupInfo != null)
  196. {
  197. return true;
  198. }
  199. else
  200. {
  201. return false;
  202. }
  203. }
  204. public void SendMessageToGroup(GridInstantMessage im, UUID groupID)
  205. {
  206. SendMessageToGroup(im, groupID, UUID.Zero, null);
  207. }
  208. public void SendMessageToGroup(
  209. GridInstantMessage im, UUID groupID, UUID sendingAgentForGroupCalls, Func<GroupMembersData, bool> sendCondition)
  210. {
  211. UUID fromAgentID = new UUID(im.fromAgentID);
  212. // Unlike current XmlRpcGroups, Groups V2 can accept UUID.Zero when a perms check for the requesting agent
  213. // is not necessary.
  214. List<GroupMembersData> groupMembers = m_groupData.GetGroupMembers(UUID.Zero.ToString(), groupID);
  215. int groupMembersCount = groupMembers.Count;
  216. PresenceInfo[] onlineAgents = null;
  217. // In V2 we always only send to online members.
  218. // Sending to offline members is not an option.
  219. string[] t1 = groupMembers.ConvertAll<string>(gmd => gmd.AgentID.ToString()).ToArray();
  220. // We cache in order not to overwhelm the presence service on large grids with many groups. This does
  221. // mean that members coming online will not see all group members until after m_usersOnlineCacheExpirySeconds has elapsed.
  222. // (assuming this is the same across all grid simulators).
  223. if (!m_usersOnlineCache.TryGetValue(groupID, out onlineAgents))
  224. {
  225. onlineAgents = m_presenceService.GetAgents(t1);
  226. m_usersOnlineCache.Add(groupID, onlineAgents, m_usersOnlineCacheExpirySeconds);
  227. }
  228. HashSet<string> onlineAgentsUuidSet = new HashSet<string>();
  229. Array.ForEach<PresenceInfo>(onlineAgents, pi => onlineAgentsUuidSet.Add(pi.UserID));
  230. groupMembers = groupMembers.Where(gmd => onlineAgentsUuidSet.Contains(gmd.AgentID.ToString())).ToList();
  231. // if (m_debugEnabled)
  232. // m_log.DebugFormat(
  233. // "[Groups.Messaging]: SendMessageToGroup called for group {0} with {1} visible members, {2} online",
  234. // groupID, groupMembersCount, groupMembers.Count());
  235. int requestStartTick = Environment.TickCount;
  236. im.imSessionID = groupID.Guid;
  237. im.fromGroup = true;
  238. IClientAPI thisClient = GetActiveClient(fromAgentID);
  239. if (thisClient != null)
  240. {
  241. im.RegionID = thisClient.Scene.RegionInfo.RegionID.Guid;
  242. }
  243. // Send to self first of all
  244. im.toAgentID = im.fromAgentID;
  245. im.fromGroup = true;
  246. ProcessMessageFromGroupSession(im);
  247. List<UUID> regions = new List<UUID>();
  248. List<UUID> clientsAlreadySent = new List<UUID>();
  249. // Then send to everybody else
  250. foreach (GroupMembersData member in groupMembers)
  251. {
  252. if (member.AgentID.Guid == im.fromAgentID)
  253. continue;
  254. if (clientsAlreadySent.Contains(member.AgentID))
  255. continue;
  256. clientsAlreadySent.Add(member.AgentID);
  257. if (sendCondition != null)
  258. {
  259. if (!sendCondition(member))
  260. {
  261. if (m_debugEnabled)
  262. m_log.DebugFormat(
  263. "[Groups.Messaging]: Not sending to {0} as they do not fulfill send condition",
  264. member.AgentID);
  265. continue;
  266. }
  267. }
  268. else if (hasAgentDroppedGroupChatSession(member.AgentID.ToString(), groupID))
  269. {
  270. // Don't deliver messages to people who have dropped this session
  271. if (m_debugEnabled)
  272. m_log.DebugFormat("[Groups.Messaging]: {0} has dropped session, not delivering to them", member.AgentID);
  273. continue;
  274. }
  275. im.toAgentID = member.AgentID.Guid;
  276. IClientAPI client = GetActiveClient(member.AgentID);
  277. if (client == null)
  278. {
  279. // If they're not local, forward across the grid
  280. // BUT do it only once per region, please! Sim would be even better!
  281. if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: Delivering to {0} via Grid", member.AgentID);
  282. bool reallySend = true;
  283. if (onlineAgents != null)
  284. {
  285. PresenceInfo presence = onlineAgents.First(p => p.UserID == member.AgentID.ToString());
  286. if (regions.Contains(presence.RegionID))
  287. reallySend = false;
  288. else
  289. regions.Add(presence.RegionID);
  290. }
  291. if (reallySend)
  292. {
  293. // We have to create a new IM structure because the transfer module
  294. // uses async send
  295. GridInstantMessage msg = new GridInstantMessage(im, true);
  296. m_msgTransferModule.SendInstantMessage(msg, delegate(bool success) { });
  297. }
  298. }
  299. else
  300. {
  301. // Deliver locally, directly
  302. if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: Passing to ProcessMessageFromGroupSession to deliver to {0} locally", client.Name);
  303. ProcessMessageFromGroupSession(im);
  304. }
  305. }
  306. if (m_debugEnabled)
  307. m_log.DebugFormat(
  308. "[Groups.Messaging]: SendMessageToGroup for group {0} with {1} visible members, {2} online took {3}ms",
  309. groupID, groupMembersCount, groupMembers.Count(), Environment.TickCount - requestStartTick);
  310. }
  311. #region SimGridEventHandlers
  312. void OnClientLogin(IClientAPI client)
  313. {
  314. if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: OnInstantMessage registered for {0}", client.Name);
  315. }
  316. private void OnNewClient(IClientAPI client)
  317. {
  318. if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: OnInstantMessage registered for {0}", client.Name);
  319. ResetAgentGroupChatSessions(client.AgentId.ToString());
  320. }
  321. void OnMakeRootAgent(ScenePresence sp)
  322. {
  323. sp.ControllingClient.OnInstantMessage += OnInstantMessage;
  324. }
  325. void OnMakeChildAgent(ScenePresence sp)
  326. {
  327. sp.ControllingClient.OnInstantMessage -= OnInstantMessage;
  328. }
  329. private void OnGridInstantMessage(GridInstantMessage msg)
  330. {
  331. // The instant message module will only deliver messages of dialog types:
  332. // MessageFromAgent, StartTyping, StopTyping, MessageFromObject
  333. //
  334. // Any other message type will not be delivered to a client by the
  335. // Instant Message Module
  336. UUID regionID = new UUID(msg.RegionID);
  337. if (m_debugEnabled)
  338. {
  339. m_log.DebugFormat("[Groups.Messaging]: {0} called, IM from region {1}",
  340. System.Reflection.MethodBase.GetCurrentMethod().Name, regionID);
  341. DebugGridInstantMessage(msg);
  342. }
  343. // Incoming message from a group
  344. if ((msg.fromGroup == true) && (msg.dialog == (byte)InstantMessageDialog.SessionSend))
  345. {
  346. // We have to redistribute the message across all members of the group who are here
  347. // on this sim
  348. UUID GroupID = new UUID(msg.imSessionID);
  349. Scene aScene = m_sceneList[0];
  350. GridRegion regionOfOrigin = aScene.GridService.GetRegionByUUID(aScene.RegionInfo.ScopeID, regionID);
  351. List<GroupMembersData> groupMembers = m_groupData.GetGroupMembers(UUID.Zero.ToString(), GroupID);
  352. //if (m_debugEnabled)
  353. // foreach (GroupMembersData m in groupMembers)
  354. // m_log.DebugFormat("[Groups.Messaging]: member {0}", m.AgentID);
  355. foreach (Scene s in m_sceneList)
  356. {
  357. s.ForEachScenePresence(sp =>
  358. {
  359. // If we got this via grid messaging, it's because the caller thinks
  360. // that the root agent is here. We should only send the IM to root agents.
  361. if (sp.IsChildAgent)
  362. return;
  363. GroupMembersData m = groupMembers.Find(gmd =>
  364. {
  365. return gmd.AgentID == sp.UUID;
  366. });
  367. if (m.AgentID == UUID.Zero)
  368. {
  369. if (m_debugEnabled)
  370. m_log.DebugFormat("[Groups.Messaging]: skipping agent {0} because he is not a member of the group", sp.UUID);
  371. return;
  372. }
  373. // Check if the user has an agent in the region where
  374. // the IM came from, and if so, skip it, because the IM
  375. // was already sent via that agent
  376. if (regionOfOrigin != null)
  377. {
  378. AgentCircuitData aCircuit = s.AuthenticateHandler.GetAgentCircuitData(sp.UUID);
  379. if (aCircuit != null)
  380. {
  381. if (aCircuit.ChildrenCapSeeds.Keys.Contains(regionOfOrigin.RegionHandle))
  382. {
  383. if (m_debugEnabled)
  384. m_log.DebugFormat("[Groups.Messaging]: skipping agent {0} because he has an agent in region of origin", sp.UUID);
  385. return;
  386. }
  387. else
  388. {
  389. if (m_debugEnabled)
  390. m_log.DebugFormat("[Groups.Messaging]: not skipping agent {0}", sp.UUID);
  391. }
  392. }
  393. }
  394. UUID AgentID = sp.UUID;
  395. msg.toAgentID = AgentID.Guid;
  396. if (!hasAgentDroppedGroupChatSession(AgentID.ToString(), GroupID))
  397. {
  398. if (!hasAgentBeenInvitedToGroupChatSession(AgentID.ToString(), GroupID))
  399. AddAgentToSession(AgentID, GroupID, msg);
  400. else
  401. {
  402. if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: Passing to ProcessMessageFromGroupSession to deliver to {0} locally", sp.Name);
  403. ProcessMessageFromGroupSession(msg);
  404. }
  405. }
  406. });
  407. }
  408. }
  409. }
  410. private void ProcessMessageFromGroupSession(GridInstantMessage msg)
  411. {
  412. if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: Session message from {0} going to agent {1}", msg.fromAgentName, msg.toAgentID);
  413. UUID AgentID = new UUID(msg.fromAgentID);
  414. UUID GroupID = new UUID(msg.imSessionID);
  415. UUID toAgentID = new UUID(msg.toAgentID);
  416. switch (msg.dialog)
  417. {
  418. case (byte)InstantMessageDialog.SessionAdd:
  419. AgentInvitedToGroupChatSession(AgentID.ToString(), GroupID);
  420. break;
  421. case (byte)InstantMessageDialog.SessionDrop:
  422. AgentDroppedFromGroupChatSession(AgentID.ToString(), GroupID);
  423. break;
  424. case (byte)InstantMessageDialog.SessionSend:
  425. // User hasn't dropped, so they're in the session,
  426. // maybe we should deliver it.
  427. IClientAPI client = GetActiveClient(new UUID(msg.toAgentID));
  428. if (client != null)
  429. {
  430. // Deliver locally, directly
  431. if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: Delivering to {0} locally", client.Name);
  432. if (!hasAgentDroppedGroupChatSession(toAgentID.ToString(), GroupID))
  433. {
  434. if (!hasAgentBeenInvitedToGroupChatSession(toAgentID.ToString(), GroupID))
  435. // This actually sends the message too, so no need to resend it
  436. // with client.SendInstantMessage
  437. AddAgentToSession(toAgentID, GroupID, msg);
  438. else
  439. client.SendInstantMessage(msg);
  440. }
  441. }
  442. else
  443. {
  444. m_log.WarnFormat("[Groups.Messaging]: Received a message over the grid for a client that isn't here: {0}", msg.toAgentID);
  445. }
  446. break;
  447. default:
  448. m_log.WarnFormat("[Groups.Messaging]: I don't know how to proccess a {0} message.", ((InstantMessageDialog)msg.dialog).ToString());
  449. break;
  450. }
  451. }
  452. private void AddAgentToSession(UUID AgentID, UUID GroupID, GridInstantMessage msg)
  453. {
  454. // Agent not in session and hasn't dropped from session
  455. // Add them to the session for now, and Invite them
  456. AgentInvitedToGroupChatSession(AgentID.ToString(), GroupID);
  457. IClientAPI activeClient = GetActiveClient(AgentID);
  458. if (activeClient != null)
  459. {
  460. GroupRecord groupInfo = m_groupData.GetGroupRecord(UUID.Zero.ToString(), GroupID, null);
  461. if (groupInfo != null)
  462. {
  463. if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: Sending chatterbox invite instant message");
  464. // Force? open the group session dialog???
  465. // and simultanously deliver the message, so we don't need to do a seperate client.SendInstantMessage(msg);
  466. IEventQueue eq = activeClient.Scene.RequestModuleInterface<IEventQueue>();
  467. eq.ChatterboxInvitation(
  468. GroupID
  469. , groupInfo.GroupName
  470. , new UUID(msg.fromAgentID)
  471. , msg.message
  472. , AgentID
  473. , msg.fromAgentName
  474. , msg.dialog
  475. , msg.timestamp
  476. , msg.offline == 1
  477. , (int)msg.ParentEstateID
  478. , msg.Position
  479. , 1
  480. , new UUID(msg.imSessionID)
  481. , msg.fromGroup
  482. , OpenMetaverse.Utils.StringToBytes(groupInfo.GroupName)
  483. );
  484. eq.ChatterBoxSessionAgentListUpdates(
  485. new UUID(GroupID)
  486. , AgentID
  487. , new UUID(msg.toAgentID)
  488. , false //canVoiceChat
  489. , false //isModerator
  490. , false //text mute
  491. );
  492. }
  493. }
  494. }
  495. #endregion
  496. #region ClientEvents
  497. private void OnInstantMessage(IClientAPI remoteClient, GridInstantMessage im)
  498. {
  499. if (m_debugEnabled)
  500. {
  501. m_log.DebugFormat("[Groups.Messaging]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
  502. DebugGridInstantMessage(im);
  503. }
  504. // Start group IM session
  505. if ((im.dialog == (byte)InstantMessageDialog.SessionGroupStart))
  506. {
  507. if (m_debugEnabled) m_log.InfoFormat("[Groups.Messaging]: imSessionID({0}) toAgentID({1})", im.imSessionID, im.toAgentID);
  508. UUID GroupID = new UUID(im.imSessionID);
  509. UUID AgentID = new UUID(im.fromAgentID);
  510. GroupRecord groupInfo = m_groupData.GetGroupRecord(UUID.Zero.ToString(), GroupID, null);
  511. if (groupInfo != null)
  512. {
  513. AgentInvitedToGroupChatSession(AgentID.ToString(), GroupID);
  514. ChatterBoxSessionStartReplyViaCaps(remoteClient, groupInfo.GroupName, GroupID);
  515. IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>();
  516. queue.ChatterBoxSessionAgentListUpdates(
  517. GroupID
  518. , AgentID
  519. , new UUID(im.toAgentID)
  520. , false //canVoiceChat
  521. , false //isModerator
  522. , false //text mute
  523. );
  524. }
  525. }
  526. // Send a message from locally connected client to a group
  527. if ((im.dialog == (byte)InstantMessageDialog.SessionSend))
  528. {
  529. UUID GroupID = new UUID(im.imSessionID);
  530. UUID AgentID = new UUID(im.fromAgentID);
  531. if (m_debugEnabled)
  532. m_log.DebugFormat("[Groups.Messaging]: Send message to session for group {0} with session ID {1}", GroupID, im.imSessionID.ToString());
  533. //If this agent is sending a message, then they want to be in the session
  534. AgentInvitedToGroupChatSession(AgentID.ToString(), GroupID);
  535. SendMessageToGroup(im, GroupID);
  536. }
  537. }
  538. #endregion
  539. void ChatterBoxSessionStartReplyViaCaps(IClientAPI remoteClient, string groupName, UUID groupID)
  540. {
  541. if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
  542. OSDMap moderatedMap = new OSDMap(4);
  543. moderatedMap.Add("voice", OSD.FromBoolean(false));
  544. OSDMap sessionMap = new OSDMap(4);
  545. sessionMap.Add("moderated_mode", moderatedMap);
  546. sessionMap.Add("session_name", OSD.FromString(groupName));
  547. sessionMap.Add("type", OSD.FromInteger(0));
  548. sessionMap.Add("voice_enabled", OSD.FromBoolean(false));
  549. OSDMap bodyMap = new OSDMap(4);
  550. bodyMap.Add("session_id", OSD.FromUUID(groupID));
  551. bodyMap.Add("temp_session_id", OSD.FromUUID(groupID));
  552. bodyMap.Add("success", OSD.FromBoolean(true));
  553. bodyMap.Add("session_info", sessionMap);
  554. IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>();
  555. if (queue != null)
  556. {
  557. queue.Enqueue(queue.BuildEvent("ChatterBoxSessionStartReply", bodyMap), remoteClient.AgentId);
  558. }
  559. }
  560. private void DebugGridInstantMessage(GridInstantMessage im)
  561. {
  562. // Don't log any normal IMs (privacy!)
  563. if (m_debugEnabled && im.dialog != (byte)InstantMessageDialog.MessageFromAgent)
  564. {
  565. m_log.WarnFormat("[Groups.Messaging]: IM: fromGroup({0})", im.fromGroup ? "True" : "False");
  566. m_log.WarnFormat("[Groups.Messaging]: IM: Dialog({0})", ((InstantMessageDialog)im.dialog).ToString());
  567. m_log.WarnFormat("[Groups.Messaging]: IM: fromAgentID({0})", im.fromAgentID.ToString());
  568. m_log.WarnFormat("[Groups.Messaging]: IM: fromAgentName({0})", im.fromAgentName.ToString());
  569. m_log.WarnFormat("[Groups.Messaging]: IM: imSessionID({0})", im.imSessionID.ToString());
  570. m_log.WarnFormat("[Groups.Messaging]: IM: message({0})", im.message.ToString());
  571. m_log.WarnFormat("[Groups.Messaging]: IM: offline({0})", im.offline.ToString());
  572. m_log.WarnFormat("[Groups.Messaging]: IM: toAgentID({0})", im.toAgentID.ToString());
  573. m_log.WarnFormat("[Groups.Messaging]: IM: binaryBucket({0})", OpenMetaverse.Utils.BytesToHexString(im.binaryBucket, "BinaryBucket"));
  574. }
  575. }
  576. #region Client Tools
  577. /// <summary>
  578. /// Try to find an active IClientAPI reference for agentID giving preference to root connections
  579. /// </summary>
  580. private IClientAPI GetActiveClient(UUID agentID)
  581. {
  582. if (m_debugEnabled) m_log.WarnFormat("[Groups.Messaging]: Looking for local client {0}", agentID);
  583. IClientAPI child = null;
  584. // Try root avatar first
  585. foreach (Scene scene in m_sceneList)
  586. {
  587. ScenePresence sp = scene.GetScenePresence(agentID);
  588. if (sp != null)
  589. {
  590. if (!sp.IsChildAgent)
  591. {
  592. if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: Found root agent for client : {0}", sp.ControllingClient.Name);
  593. return sp.ControllingClient;
  594. }
  595. else
  596. {
  597. if (m_debugEnabled) m_log.DebugFormat("[Groups.Messaging]: Found child agent for client : {0}", sp.ControllingClient.Name);
  598. child = sp.ControllingClient;
  599. }
  600. }
  601. }
  602. // If we didn't find a root, then just return whichever child we found, or null if none
  603. if (child == null)
  604. {
  605. if (m_debugEnabled) m_log.WarnFormat("[Groups.Messaging]: Could not find local client for agent : {0}", agentID);
  606. }
  607. else
  608. {
  609. if (m_debugEnabled) m_log.WarnFormat("[Groups.Messaging]: Returning child agent for client : {0}", child.Name);
  610. }
  611. return child;
  612. }
  613. #endregion
  614. #region GroupSessionTracking
  615. public void ResetAgentGroupChatSessions(string agentID)
  616. {
  617. foreach (List<string> agentList in m_groupsAgentsDroppedFromChatSession.Values)
  618. agentList.Remove(agentID);
  619. foreach (List<string> agentList in m_groupsAgentsInvitedToChatSession.Values)
  620. agentList.Remove(agentID);
  621. }
  622. public bool hasAgentBeenInvitedToGroupChatSession(string agentID, UUID groupID)
  623. {
  624. // If we're tracking this group, and we can find them in the tracking, then they've been invited
  625. return m_groupsAgentsInvitedToChatSession.ContainsKey(groupID)
  626. && m_groupsAgentsInvitedToChatSession[groupID].Contains(agentID);
  627. }
  628. public bool hasAgentDroppedGroupChatSession(string agentID, UUID groupID)
  629. {
  630. // If we're tracking drops for this group,
  631. // and we find them, well... then they've dropped
  632. return m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID)
  633. && m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID);
  634. }
  635. public void AgentDroppedFromGroupChatSession(string agentID, UUID groupID)
  636. {
  637. if (m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID))
  638. {
  639. // If not in dropped list, add
  640. if (!m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID))
  641. {
  642. m_groupsAgentsDroppedFromChatSession[groupID].Add(agentID);
  643. }
  644. }
  645. }
  646. public void AgentInvitedToGroupChatSession(string agentID, UUID groupID)
  647. {
  648. // Add Session Status if it doesn't exist for this session
  649. CreateGroupChatSessionTracking(groupID);
  650. // If nessesary, remove from dropped list
  651. if (m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID))
  652. {
  653. m_groupsAgentsDroppedFromChatSession[groupID].Remove(agentID);
  654. }
  655. // Add to invited
  656. if (!m_groupsAgentsInvitedToChatSession[groupID].Contains(agentID))
  657. m_groupsAgentsInvitedToChatSession[groupID].Add(agentID);
  658. }
  659. private void CreateGroupChatSessionTracking(UUID groupID)
  660. {
  661. if (!m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID))
  662. {
  663. m_groupsAgentsDroppedFromChatSession.Add(groupID, new List<string>());
  664. m_groupsAgentsInvitedToChatSession.Add(groupID, new List<string>());
  665. }
  666. }
  667. #endregion
  668. }
  669. }