SimianPresenceServiceConnector.cs 18 KB

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