GroupsMessagingModule.cs 33 KB

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