FriendsModule.cs 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  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 OpenSim 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;
  29. using System.Collections.Generic;
  30. using System.Reflection;
  31. using OpenMetaverse;
  32. using log4net;
  33. using Nini.Config;
  34. using Nwc.XmlRpc;
  35. using OpenSim.Framework;
  36. using OpenSim.Framework.Communications.Cache;
  37. using OpenSim.Framework.Servers;
  38. using OpenSim.Region.Interfaces;
  39. using OpenSim.Region.Environment.Interfaces;
  40. using OpenSim.Region.Environment.Scenes;
  41. namespace OpenSim.Region.Environment.Modules.Avatar.Friends
  42. {
  43. /*
  44. This module handles adding/removing friends, and the the presence
  45. notification process for login/logoff of friends.
  46. The presence notification works as follows:
  47. - After the user initially connects to a region (so we now have a UDP
  48. connection to work with), this module fetches the friends of user
  49. (those are cached), their on-/offline status, and info about the
  50. region they are in from the MessageServer.
  51. - (*) It then informs the user about the on-/offline status of her friends.
  52. - It then informs all online friends currently on this region-server about
  53. user's new online status (this will save some network traffic, as local
  54. messages don't have to be transferred inter-region, and it will be all
  55. that has to be done in Standalone Mode).
  56. - For the rest of the online friends (those not on this region-server),
  57. this module uses the provided region-information to map users to
  58. regions, and sends one notification to every region containing the
  59. friends to inform on that server.
  60. - The region-server will handle that in the following way:
  61. - If it finds the friend, it informs her about the user being online.
  62. - If it doesn't find the friend (maybe she TPed away in the meantime),
  63. it stores that information.
  64. - After it processed all friends, it returns the list of friends it
  65. couldn't find.
  66. - If this list isn't empty, the FriendsModule re-requests information
  67. about those online friends that have been missed and starts at (*)
  68. again until all friends have been found, or until it tried 3 times
  69. (to prevent endless loops due to some uncaught error).
  70. NOTE: Online/Offline notifications don't need to be sent on region change.
  71. We implement two XMLRpc handlers here, handling all the inter-region things
  72. we have to handle:
  73. - On-/Offline-Notifications (bulk)
  74. - Terminate Friendship messages (single)
  75. */
  76. public class FriendsModule : IRegionModule, IFriendsModule
  77. {
  78. private class Transaction
  79. {
  80. public UUID agentID;
  81. public string agentName;
  82. public uint count;
  83. public Transaction(UUID agentID, string agentName)
  84. {
  85. this.agentID = agentID;
  86. this.agentName = agentName;
  87. this.count = 1;
  88. }
  89. }
  90. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  91. private Cache m_friendLists = new Cache(CacheFlags.AllowUpdate);
  92. private Dictionary<UUID, ulong> m_rootAgents = new Dictionary<UUID, ulong>();
  93. private Dictionary<UUID, UUID> m_pendingCallingcardRequests = new Dictionary<UUID,UUID>();
  94. private Scene m_initialScene; // saves a lookup if we don't have a specific scene
  95. private Dictionary<ulong, Scene> m_scenes = new Dictionary<ulong,Scene>();
  96. private IMessageTransferModule m_TransferModule = null;
  97. #region IRegionModule Members
  98. public void Initialise(Scene scene, IConfigSource config)
  99. {
  100. lock (m_scenes)
  101. {
  102. if (m_scenes.Count == 0)
  103. {
  104. scene.CommsManager.HttpServer.AddXmlRPCHandler("presence_update_bulk", processPresenceUpdateBulk);
  105. scene.CommsManager.HttpServer.AddXmlRPCHandler("terminate_friend", processTerminateFriend);
  106. m_friendLists.DefaultTTL = new TimeSpan(1, 0, 0); // store entries for one hour max
  107. m_initialScene = scene;
  108. }
  109. if (!m_scenes.ContainsKey(scene.RegionInfo.RegionHandle))
  110. m_scenes[scene.RegionInfo.RegionHandle] = scene;
  111. }
  112. scene.RegisterModuleInterface<IFriendsModule>(this);
  113. scene.EventManager.OnNewClient += OnNewClient;
  114. scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage;
  115. scene.EventManager.OnAvatarEnteringNewParcel += AvatarEnteringParcel;
  116. scene.EventManager.OnMakeChildAgent += MakeChildAgent;
  117. scene.EventManager.OnClientClosed += ClientClosed;
  118. }
  119. public void PostInitialise()
  120. {
  121. if (m_scenes.Count > 0)
  122. {
  123. m_TransferModule = m_initialScene.RequestModuleInterface<IMessageTransferModule>();
  124. }
  125. if (m_TransferModule == null)
  126. m_log.Error("[FRIENDS]: Unable to find a message transfer module, friendship offers will not work");
  127. }
  128. public void Close()
  129. {
  130. }
  131. public string Name
  132. {
  133. get { return "FriendsModule"; }
  134. }
  135. public bool IsSharedModule
  136. {
  137. get { return true; }
  138. }
  139. #endregion
  140. /// <summary>
  141. /// Receive presence information changes about clients in other regions.
  142. /// </summary>
  143. /// <param name="req"></param>
  144. /// <returns></returns>
  145. public XmlRpcResponse processPresenceUpdateBulk(XmlRpcRequest req)
  146. {
  147. Hashtable requestData = (Hashtable)req.Params[0];
  148. List<UUID> friendsNotHere = new List<UUID>();
  149. // this is called with the expectation that all the friends in the request are on this region-server.
  150. // But as some time passed since we checked (on the other region-server, via the MessagingServer),
  151. // some of the friends might have teleported away.
  152. // Actually, even now, between this line and the sending below, some people could TP away. So,
  153. // we'll have to lock the m_rootAgents list for the duration to prevent/delay that.
  154. lock (m_rootAgents)
  155. {
  156. List<ScenePresence> friendsHere = new List<ScenePresence>();
  157. try
  158. {
  159. UUID agentID = new UUID((string)requestData["agentID"]);
  160. bool agentOnline = (bool)requestData["agentOnline"];
  161. int count = (int)requestData["friendCount"];
  162. for (int i = 0; i < count; ++i)
  163. {
  164. UUID uuid;
  165. if (UUID.TryParse((string)requestData["friendID_" + i], out uuid))
  166. {
  167. if (m_rootAgents.ContainsKey(uuid)) friendsHere.Add(GetRootPresenceFromAgentID(uuid));
  168. else friendsNotHere.Add(uuid);
  169. }
  170. }
  171. // now send, as long as they are still here...
  172. UUID[] agentUUID = new UUID[] { agentID };
  173. if (agentOnline)
  174. {
  175. foreach (ScenePresence agent in friendsHere)
  176. {
  177. agent.ControllingClient.SendAgentOnline(agentUUID);
  178. }
  179. }
  180. else
  181. {
  182. foreach (ScenePresence agent in friendsHere)
  183. {
  184. agent.ControllingClient.SendAgentOffline(agentUUID);
  185. }
  186. }
  187. }
  188. catch(Exception e)
  189. {
  190. m_log.Warn("[FRIENDS]: Got exception while parsing presence_update_bulk request:", e);
  191. }
  192. }
  193. // no need to lock anymore; if TPs happen now, worst case is that we have an additional agent in this region,
  194. // which should be caught on the next iteration...
  195. Hashtable result = new Hashtable();
  196. int idx = 0;
  197. foreach (UUID uuid in friendsNotHere)
  198. {
  199. result["friendID_" + idx++] = uuid.ToString();
  200. }
  201. result["friendCount"] = idx;
  202. XmlRpcResponse response = new XmlRpcResponse();
  203. response.Value = result;
  204. return response;
  205. }
  206. public XmlRpcResponse processTerminateFriend(XmlRpcRequest req)
  207. {
  208. Hashtable requestData = (Hashtable)req.Params[0];
  209. bool success = false;
  210. UUID agentID;
  211. UUID friendID;
  212. if (requestData.ContainsKey("agentID") && UUID.TryParse((string)requestData["agentID"], out agentID) &&
  213. requestData.ContainsKey("friendID") && UUID.TryParse((string)requestData["friendID"], out friendID))
  214. {
  215. // try to find it and if it is there, prevent it to vanish before we sent the message
  216. lock (m_rootAgents)
  217. {
  218. if (m_rootAgents.ContainsKey(agentID))
  219. {
  220. m_log.DebugFormat("[FRIEND]: Sending terminate friend {0} to agent {1}", friendID, agentID);
  221. GetRootPresenceFromAgentID(agentID).ControllingClient.SendTerminateFriend(friendID);
  222. success = true;
  223. }
  224. }
  225. }
  226. // return whether we were successful
  227. Hashtable result = new Hashtable();
  228. result["success"] = success;
  229. XmlRpcResponse response = new XmlRpcResponse();
  230. response.Value = result;
  231. return response;
  232. }
  233. private void OnNewClient(IClientAPI client)
  234. {
  235. // All friends establishment protocol goes over instant message
  236. // There's no way to send a message from the sim
  237. // to a user to 'add a friend' without causing dialog box spam
  238. // Subscribe to instant messages
  239. client.OnInstantMessage += OnInstantMessage;
  240. // Friend list management
  241. client.OnApproveFriendRequest += OnApproveFriendRequest;
  242. client.OnDenyFriendRequest += OnDenyFriendRequest;
  243. client.OnTerminateFriendship += OnTerminateFriendship;
  244. // ... calling card handling...
  245. client.OnOfferCallingCard += OnOfferCallingCard;
  246. client.OnAcceptCallingCard += OnAcceptCallingCard;
  247. client.OnDeclineCallingCard += OnDeclineCallingCard;
  248. // we need this one exactly once per agent session (see comments in the handler below)
  249. client.OnEconomyDataRequest += OnEconomyDataRequest;
  250. // if it leaves, we want to know, too
  251. client.OnLogout += OnLogout;
  252. }
  253. private void ClientClosed(UUID AgentId)
  254. {
  255. // agent's client was closed. As we handle logout in OnLogout, this here has only to handle
  256. // TPing away (root agent is closed) or TPing/crossing in a region far enough away (client
  257. // agent is closed).
  258. // NOTE: In general, this doesn't mean that the agent logged out, just that it isn't around
  259. // in one of the regions here anymore.
  260. lock (m_rootAgents)
  261. {
  262. if (m_rootAgents.ContainsKey(AgentId))
  263. {
  264. m_rootAgents.Remove(AgentId);
  265. }
  266. }
  267. }
  268. private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, UUID regionID)
  269. {
  270. lock (m_rootAgents)
  271. {
  272. m_rootAgents[avatar.UUID] = avatar.RegionHandle;
  273. // Claim User! my user! Mine mine mine!
  274. }
  275. }
  276. private void MakeChildAgent(ScenePresence avatar)
  277. {
  278. lock (m_rootAgents)
  279. {
  280. if (m_rootAgents.ContainsKey(avatar.UUID))
  281. {
  282. // only delete if the region matches. As this is a shared module, the avatar could be
  283. // root agent in another region on this server.
  284. if (m_rootAgents[avatar.UUID] == avatar.RegionHandle)
  285. {
  286. m_rootAgents.Remove(avatar.UUID);
  287. // m_log.Debug("[FRIEND]: Removing " + avatar.Firstname + " " + avatar.Lastname + " as a root agent");
  288. }
  289. }
  290. }
  291. }
  292. private ScenePresence GetRootPresenceFromAgentID(UUID AgentID)
  293. {
  294. ScenePresence returnAgent = null;
  295. lock (m_scenes)
  296. {
  297. ScenePresence queryagent = null;
  298. foreach (Scene scene in m_scenes.Values)
  299. {
  300. queryagent = scene.GetScenePresence(AgentID);
  301. if (queryagent != null)
  302. {
  303. if (!queryagent.IsChildAgent)
  304. {
  305. returnAgent = queryagent;
  306. break;
  307. }
  308. }
  309. }
  310. }
  311. return returnAgent;
  312. }
  313. private ScenePresence GetAnyPresenceFromAgentID(UUID AgentID)
  314. {
  315. ScenePresence returnAgent = null;
  316. lock (m_scenes)
  317. {
  318. ScenePresence queryagent = null;
  319. foreach (Scene scene in m_scenes.Values)
  320. {
  321. queryagent = scene.GetScenePresence(AgentID);
  322. if (queryagent != null)
  323. {
  324. returnAgent = queryagent;
  325. break;
  326. }
  327. }
  328. }
  329. return returnAgent;
  330. }
  331. public void OfferFriendship(UUID fromUserId, IClientAPI toUserClient, string offerMessage)
  332. {
  333. CachedUserInfo userInfo = m_initialScene.CommsManager.UserProfileCacheService.GetUserDetails(fromUserId);
  334. if (userInfo != null)
  335. {
  336. GridInstantMessage msg = new GridInstantMessage(
  337. toUserClient.Scene, fromUserId, userInfo.UserProfile.Name, toUserClient.AgentId,
  338. (byte)InstantMessageDialog.FriendshipOffered, offerMessage, false, Vector3.Zero);
  339. FriendshipOffered(msg);
  340. }
  341. else
  342. {
  343. m_log.ErrorFormat("[FRIENDS]: No user found for id {0} in OfferFriendship()", fromUserId);
  344. }
  345. }
  346. #region FriendRequestHandling
  347. private void OnInstantMessage(IClientAPI client, GridInstantMessage im)
  348. {
  349. // Friend Requests go by Instant Message.. using the dialog param
  350. // https://wiki.secondlife.com/wiki/ImprovedInstantMessage
  351. if (im.dialog == (byte)InstantMessageDialog.FriendshipOffered) // 38
  352. {
  353. FriendshipOffered(im);
  354. }
  355. else if (im.dialog == (byte)InstantMessageDialog.FriendshipAccepted) // 39
  356. {
  357. FriendshipAccepted(client, im);
  358. }
  359. else if (im.dialog == (byte)InstantMessageDialog.FriendshipDeclined) // 40
  360. {
  361. FriendshipDeclined(client, im);
  362. }
  363. }
  364. /// <summary>
  365. /// Invoked when a user offers a friendship.
  366. /// </summary>
  367. /// May not currently be used - see OnApproveFriendRequest() instead
  368. /// <param name="im"></param>
  369. /// <param name="client"></param>
  370. private void FriendshipOffered(GridInstantMessage im)
  371. {
  372. // this is triggered by the initiating agent:
  373. // A local agent offers friendship to some possibly remote friend.
  374. // A IM is triggered, processed here and sent to the friend (possibly in a remote region).
  375. // some properties are misused here:
  376. // fromAgentName is the *destination* name (the friend we offer friendship to)
  377. ScenePresence initiator = GetAnyPresenceFromAgentID(new UUID(im.fromAgentID));
  378. im.fromAgentName = initiator != null ? initiator.Name : "(hippo)";
  379. m_log.DebugFormat("[FRIEND]: Offer(38) - From: {0}, FromName: {1} To: {2}, Session: {3}, Message: {4}, Offline {5}",
  380. im.fromAgentID, im.fromAgentName, im.toAgentID, im.imSessionID, im.message, im.offline);
  381. // 1.20 protocol sends an UUID in the message field, instead of the friendship offer text.
  382. // For interoperability, we have to clear that
  383. if (Util.isUUID(im.message)) im.message = "";
  384. // be sneeky and use the initiator-UUID as transactionID. This means we can be stateless.
  385. // we have to look up the agent name on friendship-approval, though.
  386. im.imSessionID = im.fromAgentID;
  387. if (m_TransferModule != null)
  388. {
  389. // Send it to whoever is the destination.
  390. // If new friend is local, it will send an IM to the viewer.
  391. // If new friend is remote, it will cause a OnGridInstantMessage on the remote server
  392. m_TransferModule.SendInstantMessage(im,
  393. delegate(bool success)
  394. {
  395. m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success);
  396. }
  397. );
  398. }
  399. }
  400. /// <summary>
  401. /// Invoked when a user accepts a friendship offer.
  402. /// </summary>
  403. /// <param name="im"></param>
  404. /// <param name="client"></param>
  405. private void FriendshipAccepted(IClientAPI client, GridInstantMessage im)
  406. {
  407. m_log.DebugFormat("[FRIEND]: 39 - from client {0}, agent {2} {3}, imsession {4} to {5}: {6} (dialog {7})",
  408. client.AgentId, im.fromAgentID, im.fromAgentName, im.imSessionID, im.toAgentID, im.message, im.dialog);
  409. }
  410. /// <summary>
  411. /// Invoked when a user declines a friendship offer.
  412. /// </summary>
  413. /// May not currently be used - see OnDenyFriendRequest() instead
  414. /// <param name="im"></param>
  415. /// <param name="client"></param>
  416. private void FriendshipDeclined(IClientAPI client, GridInstantMessage im)
  417. {
  418. UUID fromAgentID = new UUID(im.fromAgentID);
  419. UUID toAgentID = new UUID(im.toAgentID);
  420. // declining the friendship offer causes a type 40 IM being sent to the (possibly remote) initiator
  421. // toAgentID is initiator, fromAgentID declined friendship
  422. m_log.DebugFormat("[FRIEND]: 40 - from client {0}, agent {1} {2}, imsession {3} to {4}: {5} (dialog {6})",
  423. client != null ? client.AgentId.ToString() : "<null>",
  424. fromAgentID, im.fromAgentName, im.imSessionID, im.toAgentID, im.message, im.dialog);
  425. // Send the decline to whoever is the destination.
  426. GridInstantMessage msg = new GridInstantMessage(client.Scene, fromAgentID, client.Name, toAgentID,
  427. im.dialog, im.message, im.offline != 0, im.Position);
  428. // If new friend is local, it will send an IM to the viewer.
  429. // If new friend is remote, it will cause a OnGridInstantMessage on the remote server
  430. m_TransferModule.SendInstantMessage(msg,
  431. delegate(bool success) {
  432. m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success);
  433. }
  434. );
  435. }
  436. private void OnGridInstantMessage(GridInstantMessage msg)
  437. {
  438. // This event won't be raised unless we have that agent,
  439. // so we can depend on the above not trying to send
  440. // via grid again
  441. m_log.DebugFormat("[FRIEND]: Got GridIM from {0}, to {1}, imSession {2}, message {3}, dialog {4}",
  442. msg.fromAgentID, msg.toAgentID, msg.imSessionID, msg.message, msg.dialog);
  443. if (msg.dialog == (byte)InstantMessageDialog.FriendshipOffered ||
  444. msg.dialog == (byte)InstantMessageDialog.FriendshipAccepted ||
  445. msg.dialog == (byte)InstantMessageDialog.FriendshipDeclined)
  446. {
  447. // this should succeed as we *know* the root agent is here.
  448. m_TransferModule.SendInstantMessage(msg,
  449. delegate(bool success) {
  450. m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success);
  451. }
  452. );
  453. }
  454. if (msg.dialog == (byte)InstantMessageDialog.FriendshipAccepted)
  455. {
  456. // for accept friendship, we have to do a bit more
  457. ApproveFriendship(new UUID(msg.fromAgentID), new UUID(msg.toAgentID), msg.fromAgentName);
  458. }
  459. }
  460. private void ApproveFriendship(UUID fromAgentID, UUID toAgentID, string fromName)
  461. {
  462. m_log.DebugFormat("[FRIEND]: Approve friendship from {0} (ID: {1}) to {2}",
  463. fromAgentID, fromName, toAgentID);
  464. // a new friend was added in the initiator's and friend's data, so the cache entries are wrong now.
  465. lock (m_friendLists)
  466. {
  467. m_friendLists.Invalidate(fromAgentID);
  468. m_friendLists.Invalidate(toAgentID);
  469. }
  470. // now send presence update and add a calling card for the new friend
  471. ScenePresence initiator = GetAnyPresenceFromAgentID(toAgentID);
  472. if (initiator == null)
  473. {
  474. // quite wrong. Shouldn't happen.
  475. m_log.WarnFormat("[FRIEND]: Coudn't find initiator of friend request {0}", toAgentID);
  476. return;
  477. }
  478. m_log.DebugFormat("[FRIEND]: Tell {0} that {1} is online",
  479. initiator.Name, fromName);
  480. // tell initiator that friend is online
  481. initiator.ControllingClient.SendAgentOnline(new UUID[] { fromAgentID });
  482. // find the folder for the friend...
  483. InventoryFolderImpl folder =
  484. initiator.Scene.CommsManager.UserProfileCacheService.GetUserDetails(toAgentID).FindFolderForType((int)InventoryType.CallingCard);
  485. if (folder != null)
  486. {
  487. // ... and add the calling card
  488. CreateCallingCard(initiator.ControllingClient, fromAgentID, folder.ID, fromName);
  489. }
  490. }
  491. private void OnApproveFriendRequest(IClientAPI client, UUID agentID, UUID friendID, List<UUID> callingCardFolders)
  492. {
  493. m_log.DebugFormat("[FRIEND]: Got approve friendship from {0} {1}, agentID {2}, tid {3}",
  494. client.Name, client.AgentId, agentID, friendID);
  495. // store the new friend persistently for both avatars
  496. m_initialScene.StoreAddFriendship(friendID, agentID, (uint) FriendRights.CanSeeOnline);
  497. // The cache entries aren't valid anymore either, as we just added a friend to both sides.
  498. lock (m_friendLists)
  499. {
  500. m_friendLists.Invalidate(agentID);
  501. m_friendLists.Invalidate(friendID);
  502. }
  503. // if it's a local friend, we don't have to do the lookup
  504. ScenePresence friendPresence = GetAnyPresenceFromAgentID(friendID);
  505. if (friendPresence != null)
  506. {
  507. m_log.Debug("[FRIEND]: Local agent detected.");
  508. // create calling card
  509. CreateCallingCard(client, friendID, callingCardFolders[0], friendPresence.Name);
  510. // local message means OnGridInstantMessage won't be triggered, so do the work here.
  511. friendPresence.ControllingClient.SendInstantMessage(agentID, agentID.ToString(), friendID, client.Name,
  512. (byte)InstantMessageDialog.FriendshipAccepted,
  513. (uint)Util.UnixTimeSinceEpoch());
  514. ApproveFriendship(agentID, friendID, client.Name);
  515. }
  516. else
  517. {
  518. m_log.Debug("[FRIEND]: Remote agent detected.");
  519. // fetch the friend's name for the calling card.
  520. CachedUserInfo info = m_initialScene.CommsManager.UserProfileCacheService.GetUserDetails(friendID);
  521. // create calling card
  522. CreateCallingCard(client, friendID, callingCardFolders[0],
  523. info.UserProfile.FirstName + " " + info.UserProfile.SurName);
  524. // Compose (remote) response to friend.
  525. GridInstantMessage msg = new GridInstantMessage(client.Scene, agentID, client.Name, friendID,
  526. (byte)InstantMessageDialog.FriendshipAccepted,
  527. agentID.ToString(), false, Vector3.Zero);
  528. if (m_TransferModule != null)
  529. {
  530. m_TransferModule.SendInstantMessage(msg,
  531. delegate(bool success) {
  532. m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success);
  533. }
  534. );
  535. }
  536. }
  537. // tell client that new friend is online
  538. client.SendAgentOnline(new UUID[] { friendID });
  539. }
  540. private void OnDenyFriendRequest(IClientAPI client, UUID agentID, UUID friendID, List<UUID> callingCardFolders)
  541. {
  542. m_log.DebugFormat("[FRIEND]: Got deny friendship from {0} {1}, agentID {2}, tid {3}",
  543. client.Name, client.AgentId, agentID, friendID);
  544. // Compose response to other agent.
  545. GridInstantMessage msg = new GridInstantMessage(client.Scene, agentID, client.Name, friendID,
  546. (byte)InstantMessageDialog.FriendshipDeclined,
  547. agentID.ToString(), false, Vector3.Zero);
  548. // send decline to initiator
  549. if (m_TransferModule != null)
  550. {
  551. m_TransferModule.SendInstantMessage(msg,
  552. delegate(bool success) {
  553. m_log.DebugFormat("[FRIEND]: sending IM success = {0}", success);
  554. }
  555. );
  556. }
  557. }
  558. private void OnTerminateFriendship(IClientAPI client, UUID agentID, UUID exfriendID)
  559. {
  560. // client.AgentId == agentID!
  561. // this removes the friends from the stored friendlists. After the next login, they will be gone...
  562. m_initialScene.StoreRemoveFriendship(agentID, exfriendID);
  563. // ... now tell the two involved clients that they aren't friends anymore.
  564. // I don't know why we have to tell <agent>, as this was caused by her, but that's how it works in SL...
  565. client.SendTerminateFriend(exfriendID);
  566. // now send the friend, if online
  567. ScenePresence presence = GetAnyPresenceFromAgentID(exfriendID);
  568. if (presence != null)
  569. {
  570. m_log.DebugFormat("[FRIEND]: Sending terminate friend {0} to agent {1}", agentID, exfriendID);
  571. presence.ControllingClient.SendTerminateFriend(agentID);
  572. }
  573. else
  574. {
  575. // retry 3 times, in case the agent TPed from the last known region...
  576. for (int retry = 0; retry < 3; ++retry)
  577. {
  578. // wasn't sent, so ex-friend wasn't around on this region-server. Fetch info and try to send
  579. UserAgentData data = m_initialScene.CommsManager.UserService.GetAgentByUUID(exfriendID);
  580. if (null == data)
  581. break;
  582. if (!data.AgentOnline)
  583. {
  584. m_log.DebugFormat("[FRIEND]: {0} is offline, so not sending TerminateFriend", exfriendID);
  585. break; // if ex-friend isn't online, we don't need to send
  586. }
  587. m_log.DebugFormat("[FRIEND]: Sending remote terminate friend {0} to agent {1}@{2}",
  588. agentID, exfriendID, data.Handle);
  589. // try to send to foreign region, retry if it fails (friend TPed away, for example)
  590. if (m_initialScene.TriggerTerminateFriend(data.Handle, exfriendID, agentID)) break;
  591. }
  592. }
  593. // clean up cache: FriendList is wrong now...
  594. lock (m_friendLists)
  595. {
  596. m_friendLists.Invalidate(agentID);
  597. m_friendLists.Invalidate(exfriendID);
  598. }
  599. }
  600. #endregion
  601. #region CallingCards
  602. private void OnOfferCallingCard(IClientAPI client, UUID destID, UUID transactionID)
  603. {
  604. m_log.DebugFormat("[CALLING CARD]: got offer from {0} for {1}, transaction {2}",
  605. client.AgentId, destID, transactionID);
  606. // This might be slightly wrong. On a multi-region server, we might get the child-agent instead of the root-agent
  607. // (or the root instead of the child)
  608. ScenePresence destAgent = GetAnyPresenceFromAgentID(destID);
  609. if (destAgent == null)
  610. {
  611. client.SendAlertMessage("The person you have offered a card to can't be found anymore.");
  612. return;
  613. }
  614. lock (m_pendingCallingcardRequests)
  615. {
  616. m_pendingCallingcardRequests[transactionID] = client.AgentId;
  617. }
  618. // inform the destination agent about the offer
  619. destAgent.ControllingClient.SendOfferCallingCard(client.AgentId, transactionID);
  620. }
  621. private void CreateCallingCard(IClientAPI client, UUID creator, UUID folder, string name)
  622. {
  623. InventoryItemBase item = new InventoryItemBase();
  624. item.AssetID = UUID.Zero;
  625. item.AssetType = (int)AssetType.CallingCard;
  626. item.BasePermissions = (uint)PermissionMask.Copy;
  627. item.CreationDate = Util.UnixTimeSinceEpoch();
  628. item.Creator = creator;
  629. item.CurrentPermissions = item.BasePermissions;
  630. item.Description = "";
  631. item.EveryOnePermissions = (uint)PermissionMask.None;
  632. item.Flags = 0;
  633. item.Folder = folder;
  634. item.GroupID = UUID.Zero;
  635. item.GroupOwned = false;
  636. item.ID = UUID.Random();
  637. item.InvType = (int)InventoryType.CallingCard;
  638. item.Name = name;
  639. item.NextPermissions = item.EveryOnePermissions;
  640. item.Owner = client.AgentId;
  641. item.SalePrice = 10;
  642. item.SaleType = (byte)SaleType.Not;
  643. ((Scene)client.Scene).AddInventoryItem(client, item);
  644. }
  645. private void OnAcceptCallingCard(IClientAPI client, UUID transactionID, UUID folderID)
  646. {
  647. m_log.DebugFormat("[CALLING CARD]: User {0} ({1} {2}) accepted tid {3}, folder {4}",
  648. client.AgentId,
  649. client.FirstName, client.LastName,
  650. transactionID, folderID);
  651. UUID destID;
  652. lock (m_pendingCallingcardRequests)
  653. {
  654. if (!m_pendingCallingcardRequests.TryGetValue(transactionID, out destID))
  655. {
  656. m_log.WarnFormat("[CALLING CARD]: Got a AcceptCallingCard from {0} without an offer before.",
  657. client.Name);
  658. return;
  659. }
  660. // else found pending calling card request with that transaction.
  661. m_pendingCallingcardRequests.Remove(transactionID);
  662. }
  663. ScenePresence destAgent = GetAnyPresenceFromAgentID(destID);
  664. // inform sender of the card that destination declined the offer
  665. if (destAgent != null) destAgent.ControllingClient.SendAcceptCallingCard(transactionID);
  666. // put a calling card into the inventory of receiver
  667. CreateCallingCard(client, destID, folderID, destAgent.Name);
  668. }
  669. private void OnDeclineCallingCard(IClientAPI client, UUID transactionID)
  670. {
  671. m_log.DebugFormat("[CALLING CARD]: User {0} (ID:{1}) declined card, tid {2}",
  672. client.Name, client.AgentId, transactionID);
  673. UUID destID;
  674. lock (m_pendingCallingcardRequests)
  675. {
  676. if (!m_pendingCallingcardRequests.TryGetValue(transactionID, out destID))
  677. {
  678. m_log.WarnFormat("[CALLING CARD]: Got a AcceptCallingCard from {0} without an offer before.",
  679. client.Name);
  680. return;
  681. }
  682. // else found pending calling card request with that transaction.
  683. m_pendingCallingcardRequests.Remove(transactionID);
  684. }
  685. ScenePresence destAgent = GetAnyPresenceFromAgentID(destID);
  686. // inform sender of the card that destination declined the offer
  687. if (destAgent != null) destAgent.ControllingClient.SendDeclineCallingCard(transactionID);
  688. }
  689. /// <summary>
  690. /// Send presence information about a client to other clients in both this region and others.
  691. /// </summary>
  692. /// <param name="client"></param>
  693. /// <param name="friendList"></param>
  694. /// <param name="iAmOnline"></param>
  695. private void SendPresenceState(IClientAPI client, List<FriendListItem> friendList, bool iAmOnline)
  696. {
  697. //m_log.DebugFormat("[FRIEND]: {0} logged {1}; sending presence updates", client.Name, iAmOnline ? "in" : "out");
  698. if (friendList == null || friendList.Count == 0)
  699. {
  700. //m_log.DebugFormat("[FRIEND]: {0} doesn't have friends.", client.Name);
  701. return; // nothing we can do if she doesn't have friends...
  702. }
  703. // collect sets of friendIDs; to send to (online and offline), and to receive from
  704. // TODO: If we ever switch to .NET >= 3, replace those Lists with HashSets.
  705. // I can't believe that we have Dictionaries, but no Sets, considering Java introduced them years ago...
  706. List<UUID> friendIDsToSendTo = new List<UUID>();
  707. List<UUID> candidateFriendIDsToReceive = new List<UUID>();
  708. foreach (FriendListItem item in friendList)
  709. {
  710. if (((item.FriendListOwnerPerms | item.FriendPerms) & (uint)FriendRights.CanSeeOnline) != 0)
  711. {
  712. // friend is allowed to see my presence => add
  713. if ((item.FriendListOwnerPerms & (uint)FriendRights.CanSeeOnline) != 0)
  714. friendIDsToSendTo.Add(item.Friend);
  715. if ((item.FriendPerms & (uint)FriendRights.CanSeeOnline) != 0)
  716. candidateFriendIDsToReceive.Add(item.Friend);
  717. }
  718. }
  719. // we now have a list of "interesting" friends (which we have to find out on-/offline state for),
  720. // friends we want to send our online state to (if *they* are online, too), and
  721. // friends we want to receive online state for (currently unknown whether online or not)
  722. // as this processing might take some time and friends might TP away, we try up to three times to
  723. // reach them. Most of the time, we *will* reach them, and this loop won't loop
  724. int retry = 0;
  725. do
  726. {
  727. // build a list of friends to look up region-information and on-/offline-state for
  728. List<UUID> friendIDsToLookup = new List<UUID>(friendIDsToSendTo);
  729. foreach (UUID uuid in candidateFriendIDsToReceive)
  730. {
  731. if (!friendIDsToLookup.Contains(uuid)) friendIDsToLookup.Add(uuid);
  732. }
  733. m_log.DebugFormat(
  734. "[FRIEND]: {0} to lookup, {1} to send to, {2} candidates to receive from for agent {3}",
  735. friendIDsToLookup.Count, friendIDsToSendTo.Count, candidateFriendIDsToReceive.Count, client.Name);
  736. // we have to fetch FriendRegionInfos, as the (cached) FriendListItems don't
  737. // necessarily contain the correct online state...
  738. Dictionary<UUID, FriendRegionInfo> friendRegions = m_initialScene.GetFriendRegionInfos(friendIDsToLookup);
  739. m_log.DebugFormat(
  740. "[FRIEND]: Found {0} regionInfos for {1} friends of {2}",
  741. friendRegions.Count, friendIDsToLookup.Count, client.Name);
  742. // argument for SendAgentOn/Offline; we shouldn't generate that repeatedly within loops.
  743. UUID[] agentArr = new UUID[] { client.AgentId };
  744. // first, send to friend presence state to me, if I'm online...
  745. if (iAmOnline)
  746. {
  747. List<UUID> friendIDsToReceive = new List<UUID>();
  748. for (int i = candidateFriendIDsToReceive.Count - 1; i >= 0; --i)
  749. {
  750. UUID uuid = candidateFriendIDsToReceive[i];
  751. FriendRegionInfo info;
  752. if (friendRegions.TryGetValue(uuid, out info) && info != null && info.isOnline)
  753. {
  754. friendIDsToReceive.Add(uuid);
  755. }
  756. }
  757. m_log.DebugFormat(
  758. "[FRIEND]: Sending {0} online friends to {1}", friendIDsToReceive.Count, client.Name);
  759. if (friendIDsToReceive.Count > 0)
  760. client.SendAgentOnline(friendIDsToReceive.ToArray());
  761. // clear them for a possible second iteration; we don't have to repeat this
  762. candidateFriendIDsToReceive.Clear();
  763. }
  764. // now, send my presence state to my friends
  765. for (int i = friendIDsToSendTo.Count - 1; i >= 0; --i)
  766. {
  767. UUID uuid = friendIDsToSendTo[i];
  768. FriendRegionInfo info;
  769. if (friendRegions.TryGetValue(uuid, out info) && info != null && info.isOnline)
  770. {
  771. // any client is good enough, root or child...
  772. ScenePresence agent = GetAnyPresenceFromAgentID(uuid);
  773. if (agent != null)
  774. {
  775. m_log.DebugFormat("[FRIEND]: Found local agent {0}", agent.Name);
  776. // friend is online and on this server...
  777. if (iAmOnline) agent.ControllingClient.SendAgentOnline(agentArr);
  778. else agent.ControllingClient.SendAgentOffline(agentArr);
  779. // done, remove it
  780. friendIDsToSendTo.RemoveAt(i);
  781. }
  782. }
  783. else
  784. {
  785. m_log.DebugFormat("[FRIEND]: Friend {0} ({1}) is offline; not sending.", uuid, i);
  786. // friend is offline => no need to try sending
  787. friendIDsToSendTo.RemoveAt(i);
  788. }
  789. }
  790. m_log.DebugFormat("[FRIEND]: Have {0} friends to contact via inter-region comms.", friendIDsToSendTo.Count);
  791. // we now have all the friends left that are online (we think), but not on this region-server
  792. if (friendIDsToSendTo.Count > 0)
  793. {
  794. // sort them into regions
  795. Dictionary<ulong, List<UUID>> friendsInRegion = new Dictionary<ulong,List<UUID>>();
  796. foreach (UUID uuid in friendIDsToSendTo)
  797. {
  798. ulong handle = friendRegions[uuid].regionHandle; // this can't fail as we filtered above already
  799. List<UUID> friends;
  800. if (!friendsInRegion.TryGetValue(handle, out friends))
  801. {
  802. friends = new List<UUID>();
  803. friendsInRegion[handle] = friends;
  804. }
  805. friends.Add(uuid);
  806. }
  807. m_log.DebugFormat("[FRIEND]: Found {0} regions to send to.", friendRegions.Count);
  808. // clear uuids list and collect missed friends in it for the next retry
  809. friendIDsToSendTo.Clear();
  810. // send bulk updates to the region
  811. foreach (KeyValuePair<ulong, List<UUID>> pair in friendsInRegion)
  812. {
  813. m_log.DebugFormat("[FRIEND]: Inform {0} friends in region {1} that user {2} is {3}line",
  814. pair.Value.Count, pair.Key, client.Name, iAmOnline ? "on" : "off");
  815. friendIDsToSendTo.AddRange(m_initialScene.InformFriendsInOtherRegion(client.AgentId, pair.Key, pair.Value, iAmOnline));
  816. }
  817. }
  818. // now we have in friendIDsToSendTo only the agents left that TPed away while we tried to contact them.
  819. // In most cases, it will be empty, and it won't loop here. But sometimes, we have to work harder and try again...
  820. }
  821. while (++retry < 3 && friendIDsToSendTo.Count > 0);
  822. }
  823. private void OnEconomyDataRequest(UUID agentID)
  824. {
  825. // KLUDGE: This is the only way I found to get a message (only) after login was completed and the
  826. // client is connected enough to receive UDP packets).
  827. // This packet seems to be sent only once, just after connection was established to the first
  828. // region after login.
  829. // We use it here to trigger a presence update; the old update-on-login was never be heard by
  830. // the freshly logged in viewer, as it wasn't connected to the region at that time.
  831. // TODO: Feel free to replace this by a better solution if you find one.
  832. // get the agent. This should work every time, as we just got a packet from it
  833. //ScenePresence agent = GetRootPresenceFromAgentID(agentID);
  834. // KLUDGE 2: As this is sent quite early, the avatar isn't here as root agent yet. So, we have to cheat a bit
  835. ScenePresence agent = GetAnyPresenceFromAgentID(agentID);
  836. // just to be paranoid...
  837. if (agent == null)
  838. {
  839. m_log.ErrorFormat("[FRIEND]: Got a packet from agent {0} who can't be found anymore!?", agentID);
  840. return;
  841. }
  842. List<FriendListItem> fl;
  843. lock (m_friendLists)
  844. {
  845. fl = (List<FriendListItem>)m_friendLists.Get(agent.ControllingClient.AgentId,
  846. m_initialScene.GetFriendList);
  847. }
  848. // tell everyone that we are online
  849. SendPresenceState(agent.ControllingClient, fl, true);
  850. }
  851. private void OnLogout(IClientAPI remoteClient)
  852. {
  853. List<FriendListItem> fl;
  854. lock (m_friendLists)
  855. {
  856. fl = (List<FriendListItem>)m_friendLists.Get(remoteClient.AgentId,
  857. m_initialScene.GetFriendList);
  858. }
  859. // tell everyone that we are offline
  860. SendPresenceState(remoteClient, fl, false);
  861. }
  862. }
  863. #endregion
  864. }