SimianPresenceServiceConnector.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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.Collections.Specialized;
  30. using System.Net;
  31. using System.Reflection;
  32. using log4net;
  33. using Mono.Addins;
  34. using Nini.Config;
  35. using OpenSim.Framework;
  36. using OpenSim.Framework.Servers.HttpServer;
  37. using OpenSim.Region.Framework.Interfaces;
  38. using OpenSim.Region.Framework.Scenes;
  39. using OpenSim.Services.Interfaces;
  40. using OpenSim.Server.Base;
  41. using OpenMetaverse;
  42. using OpenMetaverse.StructuredData;
  43. using PresenceInfo = OpenSim.Services.Interfaces.PresenceInfo;
  44. namespace OpenSim.Services.Connectors.SimianGrid
  45. {
  46. /// <summary>
  47. /// Connects avatar presence information (for tracking current location and
  48. /// message routing) to the SimianGrid backend
  49. /// </summary>
  50. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")]
  51. public class SimianPresenceServiceConnector : IPresenceService, IGridUserService, ISharedRegionModule
  52. {
  53. private static readonly ILog m_log =
  54. LogManager.GetLogger(
  55. MethodBase.GetCurrentMethod().DeclaringType);
  56. private string m_serverUrl = String.Empty;
  57. private SimianActivityDetector m_activityDetector;
  58. #region ISharedRegionModule
  59. public Type ReplaceableInterface { get { return null; } }
  60. public void RegionLoaded(Scene scene) { }
  61. public void PostInitialise() { }
  62. public void Close() { }
  63. public SimianPresenceServiceConnector() { m_activityDetector = new SimianActivityDetector(this); }
  64. public string Name { get { return "SimianPresenceServiceConnector"; } }
  65. public void AddRegion(Scene scene)
  66. {
  67. if (!String.IsNullOrEmpty(m_serverUrl))
  68. {
  69. scene.RegisterModuleInterface<IPresenceService>(this);
  70. scene.RegisterModuleInterface<IGridUserService>(this);
  71. m_activityDetector.AddRegion(scene);
  72. LogoutRegionAgents(scene.RegionInfo.RegionID);
  73. }
  74. }
  75. public void RemoveRegion(Scene scene)
  76. {
  77. if (!String.IsNullOrEmpty(m_serverUrl))
  78. {
  79. scene.UnregisterModuleInterface<IPresenceService>(this);
  80. scene.UnregisterModuleInterface<IGridUserService>(this);
  81. m_activityDetector.RemoveRegion(scene);
  82. LogoutRegionAgents(scene.RegionInfo.RegionID);
  83. }
  84. }
  85. #endregion ISharedRegionModule
  86. public SimianPresenceServiceConnector(IConfigSource source)
  87. {
  88. Initialise(source);
  89. }
  90. public void Initialise(IConfigSource source)
  91. {
  92. if (Simian.IsSimianEnabled(source, "PresenceServices", this.Name))
  93. {
  94. IConfig gridConfig = source.Configs["PresenceService"];
  95. if (gridConfig == null)
  96. {
  97. m_log.Error("[SIMIAN PRESENCE CONNECTOR]: PresenceService missing from OpenSim.ini");
  98. throw new Exception("Presence connector init error");
  99. }
  100. string serviceUrl = gridConfig.GetString("PresenceServerURI");
  101. if (String.IsNullOrEmpty(serviceUrl))
  102. {
  103. m_log.Error("[SIMIAN PRESENCE CONNECTOR]: No PresenceServerURI in section PresenceService");
  104. throw new Exception("Presence connector init error");
  105. }
  106. m_serverUrl = serviceUrl;
  107. }
  108. }
  109. #region IPresenceService
  110. public bool LoginAgent(string userID, UUID sessionID, UUID secureSessionID)
  111. {
  112. m_log.ErrorFormat("[SIMIAN PRESENCE CONNECTOR]: Login requested, UserID={0}, SessionID={1}, SecureSessionID={2}",
  113. userID, sessionID, secureSessionID);
  114. NameValueCollection requestArgs = new NameValueCollection
  115. {
  116. { "RequestMethod", "AddSession" },
  117. { "UserID", userID.ToString() }
  118. };
  119. if (sessionID != UUID.Zero)
  120. {
  121. requestArgs["SessionID"] = sessionID.ToString();
  122. requestArgs["SecureSessionID"] = secureSessionID.ToString();
  123. }
  124. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  125. bool success = response["Success"].AsBoolean();
  126. if (!success)
  127. m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to login agent " + userID + ": " + response["Message"].AsString());
  128. return success;
  129. }
  130. public bool LogoutAgent(UUID sessionID)
  131. {
  132. m_log.InfoFormat("[SIMIAN PRESENCE CONNECTOR]: Logout requested for agent with sessionID " + sessionID);
  133. NameValueCollection requestArgs = new NameValueCollection
  134. {
  135. { "RequestMethod", "RemoveSession" },
  136. { "SessionID", sessionID.ToString() }
  137. };
  138. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  139. bool success = response["Success"].AsBoolean();
  140. if (!success)
  141. m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to logout agent with sessionID " + sessionID + ": " + response["Message"].AsString());
  142. return success;
  143. }
  144. public bool LogoutRegionAgents(UUID regionID)
  145. {
  146. m_log.InfoFormat("[SIMIAN PRESENCE CONNECTOR]: Logout requested for all agents in region " + regionID);
  147. NameValueCollection requestArgs = new NameValueCollection
  148. {
  149. { "RequestMethod", "RemoveSessions" },
  150. { "SceneID", regionID.ToString() }
  151. };
  152. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  153. bool success = response["Success"].AsBoolean();
  154. if (!success)
  155. m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to logout agents from region " + regionID + ": " + response["Message"].AsString());
  156. return success;
  157. }
  158. public bool ReportAgent(UUID sessionID, UUID regionID)
  159. {
  160. // Not needed for SimianGrid
  161. return true;
  162. }
  163. public PresenceInfo GetAgent(UUID sessionID)
  164. {
  165. m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting session data for agent with sessionID " + sessionID);
  166. NameValueCollection requestArgs = new NameValueCollection
  167. {
  168. { "RequestMethod", "GetSession" },
  169. { "SessionID", sessionID.ToString() }
  170. };
  171. OSDMap sessionResponse = WebUtil.PostToService(m_serverUrl, requestArgs);
  172. if (sessionResponse["Success"].AsBoolean())
  173. {
  174. UUID userID = sessionResponse["UserID"].AsUUID();
  175. m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting user data for " + userID);
  176. requestArgs = new NameValueCollection
  177. {
  178. { "RequestMethod", "GetUser" },
  179. { "UserID", userID.ToString() }
  180. };
  181. OSDMap userResponse = WebUtil.PostToService(m_serverUrl, requestArgs);
  182. if (userResponse["Success"].AsBoolean())
  183. return ResponseToPresenceInfo(sessionResponse, userResponse);
  184. else
  185. m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve user data for " + userID + ": " + userResponse["Message"].AsString());
  186. }
  187. else
  188. {
  189. m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve session " + sessionID + ": " + sessionResponse["Message"].AsString());
  190. }
  191. return null;
  192. }
  193. public PresenceInfo[] GetAgents(string[] userIDs)
  194. {
  195. List<PresenceInfo> presences = new List<PresenceInfo>(userIDs.Length);
  196. for (int i = 0; i < userIDs.Length; i++)
  197. {
  198. UUID userID;
  199. if (UUID.TryParse(userIDs[i], out userID) && userID != UUID.Zero)
  200. presences.AddRange(GetSessions(userID));
  201. }
  202. return presences.ToArray();
  203. }
  204. #endregion IPresenceService
  205. #region IGridUserService
  206. public GridUserInfo LoggedIn(string userID)
  207. {
  208. // Never implemented at the sim
  209. return null;
  210. }
  211. public bool LoggedOut(string userID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt)
  212. {
  213. // Save our last position as user data
  214. NameValueCollection requestArgs = new NameValueCollection
  215. {
  216. { "RequestMethod", "AddUserData" },
  217. { "UserID", userID.ToString() },
  218. { "LastLocation", SerializeLocation(regionID, lastPosition, lastLookAt) }
  219. };
  220. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  221. bool success = response["Success"].AsBoolean();
  222. if (!success)
  223. m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to set last location for " + userID + ": " + response["Message"].AsString());
  224. return success;
  225. }
  226. public bool SetHome(string userID, UUID regionID, Vector3 position, Vector3 lookAt)
  227. {
  228. m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Setting home location for user " + userID);
  229. NameValueCollection requestArgs = new NameValueCollection
  230. {
  231. { "RequestMethod", "AddUserData" },
  232. { "UserID", userID.ToString() },
  233. { "HomeLocation", SerializeLocation(regionID, position, lookAt) }
  234. };
  235. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  236. bool success = response["Success"].AsBoolean();
  237. if (!success)
  238. m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to set home location for " + userID + ": " + response["Message"].AsString());
  239. return success;
  240. }
  241. public bool SetLastPosition(string userID, UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt)
  242. {
  243. return UpdateSession(sessionID, regionID, lastPosition, lastLookAt);
  244. }
  245. public GridUserInfo GetGridUserInfo(string user)
  246. {
  247. m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting session data for agent " + user);
  248. UUID userID = new UUID(user);
  249. m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting user data for " + userID);
  250. NameValueCollection requestArgs = new NameValueCollection
  251. {
  252. { "RequestMethod", "GetUser" },
  253. { "UserID", userID.ToString() }
  254. };
  255. OSDMap userResponse = WebUtil.PostToService(m_serverUrl, requestArgs);
  256. if (userResponse["Success"].AsBoolean())
  257. return ResponseToGridUserInfo(userResponse);
  258. else
  259. m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve user data for " + userID + ": " + userResponse["Message"].AsString());
  260. return null;
  261. }
  262. #endregion
  263. #region Helpers
  264. private OSDMap GetUserData(UUID userID)
  265. {
  266. m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting user data for " + userID);
  267. NameValueCollection requestArgs = new NameValueCollection
  268. {
  269. { "RequestMethod", "GetUser" },
  270. { "UserID", userID.ToString() }
  271. };
  272. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  273. if (response["Success"].AsBoolean() && response["User"] is OSDMap)
  274. return response;
  275. else
  276. m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve user data for " + userID + ": " + response["Message"].AsString());
  277. return null;
  278. }
  279. private OSDMap GetSessionData(UUID sessionID)
  280. {
  281. m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting session data for session " + sessionID);
  282. NameValueCollection requestArgs = new NameValueCollection
  283. {
  284. { "RequestMethod", "GetSession" },
  285. { "SessionID", sessionID.ToString() }
  286. };
  287. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  288. if (response["Success"].AsBoolean())
  289. return response;
  290. else
  291. m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve session data for session " + sessionID);
  292. return null;
  293. }
  294. private List<PresenceInfo> GetSessions(UUID userID)
  295. {
  296. List<PresenceInfo> presences = new List<PresenceInfo>(1);
  297. OSDMap userResponse = GetUserData(userID);
  298. if (userResponse != null)
  299. {
  300. m_log.DebugFormat("[SIMIAN PRESENCE CONNECTOR]: Requesting sessions for " + userID);
  301. NameValueCollection requestArgs = new NameValueCollection
  302. {
  303. { "RequestMethod", "GetSession" },
  304. { "UserID", userID.ToString() }
  305. };
  306. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  307. if (response["Success"].AsBoolean())
  308. {
  309. PresenceInfo presence = ResponseToPresenceInfo(response, userResponse);
  310. if (presence != null)
  311. presences.Add(presence);
  312. }
  313. else
  314. {
  315. m_log.Debug("[SIMIAN PRESENCE CONNECTOR]: No session returned for " + userID + ": " + response["Message"].AsString());
  316. }
  317. }
  318. return presences;
  319. }
  320. private bool UpdateSession(UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt)
  321. {
  322. // Save our current location as session data
  323. NameValueCollection requestArgs = new NameValueCollection
  324. {
  325. { "RequestMethod", "UpdateSession" },
  326. { "SessionID", sessionID.ToString() },
  327. { "SceneID", regionID.ToString() },
  328. { "ScenePosition", lastPosition.ToString() },
  329. { "SceneLookAt", lastLookAt.ToString() }
  330. };
  331. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  332. bool success = response["Success"].AsBoolean();
  333. if (!success)
  334. m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to update agent session " + sessionID + ": " + response["Message"].AsString());
  335. return success;
  336. }
  337. ///// <summary>
  338. ///// Fetch the last known avatar location with GetSession and persist it
  339. ///// as user data with AddUserData
  340. ///// </summary>
  341. //private bool SetLastLocation(UUID sessionID)
  342. //{
  343. // NameValueCollection requestArgs = new NameValueCollection
  344. // {
  345. // { "RequestMethod", "GetSession" },
  346. // { "SessionID", sessionID.ToString() }
  347. // };
  348. // OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  349. // bool success = response["Success"].AsBoolean();
  350. // if (success)
  351. // {
  352. // UUID userID = response["UserID"].AsUUID();
  353. // UUID sceneID = response["SceneID"].AsUUID();
  354. // Vector3 position = response["ScenePosition"].AsVector3();
  355. // Vector3 lookAt = response["SceneLookAt"].AsVector3();
  356. // return SetLastLocation(userID, sceneID, position, lookAt);
  357. // }
  358. // else
  359. // {
  360. // m_log.Warn("[SIMIAN PRESENCE CONNECTOR]: Failed to retrieve presence information for session " + sessionID +
  361. // " while saving last location: " + response["Message"].AsString());
  362. // }
  363. // return success;
  364. //}
  365. private PresenceInfo ResponseToPresenceInfo(OSDMap sessionResponse, OSDMap userResponse)
  366. {
  367. if (sessionResponse == null)
  368. return null;
  369. PresenceInfo info = new PresenceInfo();
  370. info.UserID = sessionResponse["UserID"].AsUUID().ToString();
  371. info.RegionID = sessionResponse["SceneID"].AsUUID();
  372. return info;
  373. }
  374. private GridUserInfo ResponseToGridUserInfo(OSDMap userResponse)
  375. {
  376. if (userResponse != null && userResponse["User"] is OSDMap)
  377. {
  378. GridUserInfo info = new GridUserInfo();
  379. info.Online = true;
  380. info.UserID = userResponse["UserID"].AsUUID().ToString();
  381. info.LastRegionID = userResponse["SceneID"].AsUUID();
  382. info.LastPosition = userResponse["ScenePosition"].AsVector3();
  383. info.LastLookAt = userResponse["SceneLookAt"].AsVector3();
  384. OSDMap user = (OSDMap)userResponse["User"];
  385. info.Login = user["LastLoginDate"].AsDate();
  386. info.Logout = user["LastLogoutDate"].AsDate();
  387. DeserializeLocation(user["HomeLocation"].AsString(), out info.HomeRegionID, out info.HomePosition, out info.HomeLookAt);
  388. return info;
  389. }
  390. return null;
  391. }
  392. private string SerializeLocation(UUID regionID, Vector3 position, Vector3 lookAt)
  393. {
  394. return "{" + String.Format("\"SceneID\":\"{0}\",\"Position\":\"{1}\",\"LookAt\":\"{2}\"", regionID, position, lookAt) + "}";
  395. }
  396. private bool DeserializeLocation(string location, out UUID regionID, out Vector3 position, out Vector3 lookAt)
  397. {
  398. OSDMap map = null;
  399. try { map = OSDParser.DeserializeJson(location) as OSDMap; }
  400. catch { }
  401. if (map != null)
  402. {
  403. regionID = map["SceneID"].AsUUID();
  404. if (Vector3.TryParse(map["Position"].AsString(), out position) &&
  405. Vector3.TryParse(map["LookAt"].AsString(), out lookAt))
  406. {
  407. return true;
  408. }
  409. }
  410. regionID = UUID.Zero;
  411. position = Vector3.Zero;
  412. lookAt = Vector3.Zero;
  413. return false;
  414. }
  415. #endregion Helpers
  416. }
  417. }