FriendsModule.cs 49 KB

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