1
0

SimianProfiles.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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 OpenMetaverse;
  35. using OpenMetaverse.StructuredData;
  36. using OpenSim.Framework;
  37. using OpenSim.Framework.Client;
  38. using OpenSim.Region.Framework.Interfaces;
  39. using OpenSim.Region.Framework.Scenes;
  40. using OpenSim.Services.Interfaces;
  41. namespace OpenSim.Services.Connectors.SimianGrid
  42. {
  43. /// <summary>
  44. /// Avatar profile flags
  45. /// </summary>
  46. [Flags]
  47. public enum ProfileFlags : uint
  48. {
  49. AllowPublish = 1,
  50. MaturePublish = 2,
  51. Identified = 4,
  52. Transacted = 8,
  53. Online = 16
  54. }
  55. /// <summary>
  56. /// Connects avatar profile and classified queries to the SimianGrid
  57. /// backend
  58. /// </summary>
  59. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")]
  60. public class SimianProfiles : INonSharedRegionModule
  61. {
  62. private static readonly ILog m_log =
  63. LogManager.GetLogger(
  64. MethodBase.GetCurrentMethod().DeclaringType);
  65. private string m_serverUrl = String.Empty;
  66. #region INonSharedRegionModule
  67. public Type ReplaceableInterface { get { return null; } }
  68. public void RegionLoaded(Scene scene) { }
  69. public void Close() { }
  70. public SimianProfiles() { }
  71. public string Name { get { return "SimianProfiles"; } }
  72. public void AddRegion(Scene scene) { if (!String.IsNullOrEmpty(m_serverUrl)) { CheckEstateManager(scene); scene.EventManager.OnClientConnect += ClientConnectHandler; } }
  73. public void RemoveRegion(Scene scene) { if (!String.IsNullOrEmpty(m_serverUrl)) { scene.EventManager.OnClientConnect -= ClientConnectHandler; } }
  74. #endregion INonSharedRegionModule
  75. public SimianProfiles(IConfigSource source)
  76. {
  77. Initialise(source);
  78. }
  79. public void Initialise(IConfigSource source)
  80. {
  81. if (Simian.IsSimianEnabled(source, "UserAccountServices", "SimianUserAccountServiceConnector"))
  82. {
  83. IConfig gridConfig = source.Configs["UserAccountService"];
  84. if (gridConfig == null)
  85. {
  86. m_log.Error("[SIMIAN PROFILES]: UserAccountService missing from OpenSim.ini");
  87. throw new Exception("Profiles init error");
  88. }
  89. string serviceUrl = gridConfig.GetString("UserAccountServerURI");
  90. if (String.IsNullOrEmpty(serviceUrl))
  91. {
  92. m_log.Error("[SIMIAN PROFILES]: No UserAccountServerURI in section UserAccountService");
  93. throw new Exception("Profiles init error");
  94. }
  95. if (!serviceUrl.EndsWith("/"))
  96. serviceUrl = serviceUrl + '/';
  97. m_serverUrl = serviceUrl;
  98. IConfig profilesConfig = source.Configs["Profiles"];
  99. if (profilesConfig == null)
  100. {
  101. // Do not run this module by default.
  102. return;
  103. }
  104. else
  105. {
  106. // if profiles aren't enabled, we're not needed.
  107. // if we're not specified as the connector to use, then we're not wanted
  108. if (profilesConfig.GetString("Module", String.Empty) != Name)
  109. {
  110. return;
  111. }
  112. m_log.InfoFormat("[SIMIAN ACCOUNT CONNECTOR]: Initializing {0}", this.Name);
  113. }
  114. }
  115. }
  116. private void ClientConnectHandler(IClientCore clientCore)
  117. {
  118. if (clientCore is IClientAPI)
  119. {
  120. IClientAPI client = (IClientAPI)clientCore;
  121. // Classifieds
  122. client.AddGenericPacketHandler("avatarclassifiedsrequest", AvatarClassifiedsRequestHandler);
  123. client.OnClassifiedInfoRequest += ClassifiedInfoRequestHandler;
  124. client.OnClassifiedInfoUpdate += ClassifiedInfoUpdateHandler;
  125. client.OnClassifiedDelete += ClassifiedDeleteHandler;
  126. // Picks
  127. client.AddGenericPacketHandler("avatarpicksrequest", HandleAvatarPicksRequest);
  128. client.AddGenericPacketHandler("pickinforequest", HandlePickInfoRequest);
  129. client.OnPickInfoUpdate += PickInfoUpdateHandler;
  130. client.OnPickDelete += PickDeleteHandler;
  131. // Notes
  132. client.AddGenericPacketHandler("avatarnotesrequest", HandleAvatarNotesRequest);
  133. client.OnAvatarNotesUpdate += AvatarNotesUpdateHandler;
  134. // Profiles
  135. client.OnRequestAvatarProperties += RequestAvatarPropertiesHandler;
  136. client.OnUpdateAvatarProperties += UpdateAvatarPropertiesHandler;
  137. client.OnAvatarInterestUpdate += AvatarInterestUpdateHandler;
  138. client.OnUserInfoRequest += UserInfoRequestHandler;
  139. client.OnUpdateUserInfo += UpdateUserInfoHandler;
  140. }
  141. }
  142. #region Classifieds
  143. private void AvatarClassifiedsRequestHandler(Object sender, string method, List<String> args)
  144. {
  145. if (!(sender is IClientAPI))
  146. return;
  147. IClientAPI client = (IClientAPI)sender;
  148. UUID targetAvatarID;
  149. if (args.Count < 1 || !UUID.TryParse(args[0], out targetAvatarID))
  150. {
  151. m_log.Error("[SIMIAN PROFILES]: Unrecognized arguments for " + method);
  152. return;
  153. }
  154. // FIXME: Query the generic key/value store for classifieds
  155. client.SendAvatarClassifiedReply(targetAvatarID, new Dictionary<UUID, string>(0));
  156. }
  157. private void ClassifiedInfoRequestHandler(UUID classifiedID, IClientAPI client)
  158. {
  159. // FIXME: Fetch this info
  160. client.SendClassifiedInfoReply(classifiedID, UUID.Zero, 0, Utils.DateTimeToUnixTime(DateTime.UtcNow + TimeSpan.FromDays(1)),
  161. 0, String.Empty, String.Empty, UUID.Zero, 0, UUID.Zero, String.Empty, Vector3.Zero, String.Empty, 0, 0);
  162. }
  163. private void ClassifiedInfoUpdateHandler(UUID classifiedID, uint category, string name, string description,
  164. UUID parcelID, uint parentEstate, UUID snapshotID, Vector3 globalPos, byte classifiedFlags, int price,
  165. IClientAPI client)
  166. {
  167. // FIXME: Save this info
  168. }
  169. private void ClassifiedDeleteHandler(UUID classifiedID, IClientAPI client)
  170. {
  171. // FIXME: Delete the specified classified ad
  172. }
  173. #endregion Classifieds
  174. #region Picks
  175. private void HandleAvatarPicksRequest(Object sender, string method, List<String> args)
  176. {
  177. if (!(sender is IClientAPI))
  178. return;
  179. IClientAPI client = (IClientAPI)sender;
  180. UUID targetAvatarID;
  181. if (args.Count < 1 || !UUID.TryParse(args[0], out targetAvatarID))
  182. {
  183. m_log.Error("[SIMIAN PROFILES]: Unrecognized arguments for " + method);
  184. return;
  185. }
  186. // FIXME: Fetch these
  187. client.SendAvatarPicksReply(targetAvatarID, new Dictionary<UUID, string>(0));
  188. }
  189. private void HandlePickInfoRequest(Object sender, string method, List<String> args)
  190. {
  191. if (!(sender is IClientAPI))
  192. return;
  193. IClientAPI client = (IClientAPI)sender;
  194. UUID avatarID;
  195. UUID pickID;
  196. if (args.Count < 2 || !UUID.TryParse(args[0], out avatarID) || !UUID.TryParse(args[1], out pickID))
  197. {
  198. m_log.Error("[SIMIAN PROFILES]: Unrecognized arguments for " + method);
  199. return;
  200. }
  201. // FIXME: Fetch this
  202. client.SendPickInfoReply(pickID, avatarID, false, UUID.Zero, String.Empty, String.Empty, UUID.Zero, String.Empty,
  203. String.Empty, String.Empty, Vector3.Zero, 0, false);
  204. }
  205. private void PickInfoUpdateHandler(IClientAPI client, UUID pickID, UUID creatorID, bool topPick, string name,
  206. string desc, UUID snapshotID, int sortOrder, bool enabled)
  207. {
  208. // FIXME: Save this
  209. }
  210. private void PickDeleteHandler(IClientAPI client, UUID pickID)
  211. {
  212. // FIXME: Delete
  213. }
  214. #endregion Picks
  215. #region Notes
  216. private void HandleAvatarNotesRequest(Object sender, string method, List<String> args)
  217. {
  218. if (!(sender is IClientAPI))
  219. return;
  220. IClientAPI client = (IClientAPI)sender;
  221. UUID targetAvatarID;
  222. if (args.Count < 1 || !UUID.TryParse(args[0], out targetAvatarID))
  223. {
  224. m_log.Error("[SIMIAN PROFILES]: Unrecognized arguments for " + method);
  225. return;
  226. }
  227. // FIXME: Fetch this
  228. client.SendAvatarNotesReply(targetAvatarID, String.Empty);
  229. }
  230. private void AvatarNotesUpdateHandler(IClientAPI client, UUID targetID, string notes)
  231. {
  232. // FIXME: Save this
  233. }
  234. #endregion Notes
  235. #region Profiles
  236. private void RequestAvatarPropertiesHandler(IClientAPI client, UUID avatarID)
  237. {
  238. OSDMap user = FetchUserData(avatarID);
  239. ProfileFlags flags = ProfileFlags.AllowPublish | ProfileFlags.MaturePublish;
  240. if (user != null)
  241. {
  242. OSDMap about = null;
  243. if (user.ContainsKey("LLAbout"))
  244. {
  245. try { about = OSDParser.DeserializeJson(user["LLAbout"].AsString()) as OSDMap; }
  246. catch { }
  247. }
  248. if (about == null)
  249. about = new OSDMap(0);
  250. // Check if this user is a grid operator
  251. byte[] charterMember;
  252. if (user["AccessLevel"].AsInteger() >= 200)
  253. charterMember = Utils.StringToBytes("Operator");
  254. else
  255. charterMember = Utils.EmptyBytes;
  256. // Check if the user is online
  257. if (client.Scene is Scene)
  258. {
  259. OpenSim.Services.Interfaces.PresenceInfo[] presences = ((Scene)client.Scene).PresenceService.GetAgents(new string[] { avatarID.ToString() });
  260. if (presences != null && presences.Length > 0)
  261. flags |= ProfileFlags.Online;
  262. }
  263. // Check if the user is identified
  264. if (user["Identified"].AsBoolean())
  265. flags |= ProfileFlags.Identified;
  266. client.SendAvatarProperties(avatarID, about["About"].AsString(), user["CreationDate"].AsDate().ToString("M/d/yyyy",
  267. System.Globalization.CultureInfo.InvariantCulture), charterMember, about["FLAbout"].AsString(), (uint)flags,
  268. about["FLImage"].AsUUID(), about["Image"].AsUUID(), about["URL"].AsString(), user["Partner"].AsUUID());
  269. OSDMap interests = null;
  270. if (user.ContainsKey("LLInterests"))
  271. {
  272. try
  273. {
  274. interests = OSDParser.DeserializeJson(user["LLInterests"].AsString()) as OSDMap;
  275. client.SendAvatarInterestsReply(avatarID, interests["WantMask"].AsUInteger(), interests["WantText"].AsString(), interests["SkillsMask"].AsUInteger(), interests["SkillsText"].AsString(), interests["languages"].AsString());
  276. }
  277. catch { }
  278. }
  279. if (about == null)
  280. about = new OSDMap(0);
  281. }
  282. else
  283. {
  284. m_log.Warn("[SIMIAN PROFILES]: Failed to fetch profile information for " + client.Name + ", returning default values");
  285. client.SendAvatarProperties(avatarID, String.Empty, "1/1/1970", Utils.EmptyBytes,
  286. String.Empty, (uint)flags, UUID.Zero, UUID.Zero, String.Empty, UUID.Zero);
  287. }
  288. }
  289. private void UpdateAvatarPropertiesHandler(IClientAPI client, UserProfileData profileData)
  290. {
  291. OSDMap map = new OSDMap
  292. {
  293. { "About", OSD.FromString(profileData.AboutText) },
  294. { "Image", OSD.FromUUID(profileData.Image) },
  295. { "FLAbout", OSD.FromString(profileData.FirstLifeAboutText) },
  296. { "FLImage", OSD.FromUUID(profileData.FirstLifeImage) },
  297. { "URL", OSD.FromString(profileData.ProfileUrl) }
  298. };
  299. AddUserData(client.AgentId, "LLAbout", map);
  300. }
  301. private void AvatarInterestUpdateHandler(IClientAPI client, uint wantmask, string wanttext, uint skillsmask,
  302. string skillstext, string languages)
  303. {
  304. OSDMap map = new OSDMap
  305. {
  306. { "WantMask", OSD.FromInteger(wantmask) },
  307. { "WantText", OSD.FromString(wanttext) },
  308. { "SkillsMask", OSD.FromInteger(skillsmask) },
  309. { "SkillsText", OSD.FromString(skillstext) },
  310. { "Languages", OSD.FromString(languages) }
  311. };
  312. AddUserData(client.AgentId, "LLInterests", map);
  313. }
  314. private void UserInfoRequestHandler(IClientAPI client)
  315. {
  316. m_log.Error("[SIMIAN PROFILES]: UserInfoRequestHandler");
  317. // Fetch this user's e-mail address
  318. NameValueCollection requestArgs = new NameValueCollection
  319. {
  320. { "RequestMethod", "GetUser" },
  321. { "UserID", client.AgentId.ToString() }
  322. };
  323. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  324. string email = response["Email"].AsString();
  325. if (!response["Success"].AsBoolean())
  326. m_log.Warn("[SIMIAN PROFILES]: GetUser failed during a user info request for " + client.Name);
  327. client.SendUserInfoReply(false, true, email);
  328. }
  329. private void UpdateUserInfoHandler(bool imViaEmail, bool visible, IClientAPI client)
  330. {
  331. m_log.Info("[SIMIAN PROFILES]: Ignoring user info update from " + client.Name);
  332. }
  333. #endregion Profiles
  334. /// <summary>
  335. /// Sanity checks regions for a valid estate owner at startup
  336. /// </summary>
  337. private void CheckEstateManager(Scene scene)
  338. {
  339. EstateSettings estate = scene.RegionInfo.EstateSettings;
  340. if (estate.EstateOwner == UUID.Zero)
  341. {
  342. // Attempt to lookup the grid admin
  343. UserAccount admin = scene.UserAccountService.GetUserAccount(scene.RegionInfo.ScopeID, UUID.Zero);
  344. if (admin != null)
  345. {
  346. m_log.InfoFormat("[SIMIAN PROFILES]: Setting estate {0} (ID: {1}) owner to {2}", estate.EstateName,
  347. estate.EstateID, admin.Name);
  348. estate.EstateOwner = admin.PrincipalID;
  349. estate.Save();
  350. }
  351. else
  352. {
  353. m_log.WarnFormat("[SIMIAN PROFILES]: Estate {0} (ID: {1}) does not have an owner", estate.EstateName, estate.EstateID);
  354. }
  355. }
  356. }
  357. private bool AddUserData(UUID userID, string key, OSDMap value)
  358. {
  359. NameValueCollection requestArgs = new NameValueCollection
  360. {
  361. { "RequestMethod", "AddUserData" },
  362. { "UserID", userID.ToString() },
  363. { key, OSDParser.SerializeJsonString(value) }
  364. };
  365. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  366. bool success = response["Success"].AsBoolean();
  367. if (!success)
  368. m_log.WarnFormat("[SIMIAN PROFILES]: Failed to add user data with key {0} for {1}: {2}", key, userID, response["Message"].AsString());
  369. return success;
  370. }
  371. private OSDMap FetchUserData(UUID userID)
  372. {
  373. NameValueCollection requestArgs = new NameValueCollection
  374. {
  375. { "RequestMethod", "GetUser" },
  376. { "UserID", userID.ToString() }
  377. };
  378. OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
  379. if (response["Success"].AsBoolean() && response["User"] is OSDMap)
  380. {
  381. return (OSDMap)response["User"];
  382. }
  383. else
  384. {
  385. m_log.Error("[SIMIAN PROFILES]: Failed to fetch user data for " + userID + ": " + response["Message"].AsString());
  386. }
  387. return null;
  388. }
  389. }
  390. }