123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977 |
- /*
- * Copyright (c) Contributors, http://opensimulator.org/
- * See CONTRIBUTORS.TXT for a full list of copyright holders.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * Neither the name of the OpenSimulator Project nor the
- * names of its contributors may be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
- using System;
- using System.IO;
- using System.Text;
- using System.Collections;
- using System.Collections.Generic;
- using System.Collections.Concurrent;
- using System.Globalization;
- using System.Linq;
- using System.Net;
- using System.Reflection;
- using System.Threading;
- using System.Xml;
- using OpenMetaverse;
- using OpenMetaverse.StructuredData;
- using log4net;
- using Nini.Config;
- using OpenSim.Framework;
- using OpenSim.Region.Framework.Interfaces;
- using OpenSim.Region.Framework.Scenes;
- using OpenSim.Services.Interfaces;
- using Mono.Addins;
- using OpenSim.Services.Connectors.Hypergrid;
- using OpenSim.Framework.Servers.HttpServer;
- using OpenSim.Services.UserProfilesService;
- using GridRegion = OpenSim.Services.Interfaces.GridRegion;
- using Microsoft.CSharp;
- namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
- {
- [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "UserProfilesModule")]
- public class UserProfileModule : IProfileModule, INonSharedRegionModule
- {
- const double PROFILECACHEEXPIRE = 300;
- /// <summary>
- /// Logging
- /// </summary>
- static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
- // The pair of Dictionaries are used to handle the switching of classified ads
- // by maintaining a cache of classified id to creator id mappings and an interest
- // count. The entries are removed when the interest count reaches 0.
- readonly Dictionary<UUID, UUID> m_classifiedCache = new Dictionary<UUID, UUID>();
- readonly Dictionary<UUID, int> m_classifiedInterest = new Dictionary<UUID, int>();
- readonly ExpiringCacheOS<UUID, UserProfileCacheEntry> m_profilesCache = new ExpiringCacheOS<UUID, UserProfileCacheEntry>(60000);
- IAssetCache m_assetCache;
- IGroupsModule m_groupsModule = null;
- private JsonRpcRequestManager rpc = new JsonRpcRequestManager();
- private bool m_allowUserProfileWebURLs = true;
- struct AsyncPropsRequest
- {
- public IClientAPI client;
- public ScenePresence presence;
- public UUID agent;
- public int reqtype;
- }
- private ConcurrentStack<AsyncPropsRequest> m_asyncRequests = new ConcurrentStack<AsyncPropsRequest>();
- private object m_asyncRequestsLock = new object();
- private bool m_asyncRequestsRunning = false;
- private void ProcessRequests()
- {
- lock(m_asyncRequestsLock)
- {
- while (m_asyncRequests.TryPop(out AsyncPropsRequest req))
- {
- try
- {
- IClientAPI client = req.client;
- if(!client.IsActive)
- continue;
- if(req.reqtype == 0)
- {
- UUID avatarID = req.agent;
- ScenePresence p = req.presence;
- string serverURI = string.Empty;
- bool ok = true;
- bool foreign = GetUserProfileServerURI(avatarID, out serverURI);
- if(serverURI.Length == 0)
- ok = false;
- Byte[] membershipType = new Byte[1];
- string born = string.Empty;
- uint flags = 0x00;
- if (ok && GetUserAccountData(avatarID, out UserAccount acc))
- {
- int val_flags = acc.UserFlags;
- flags = (uint)(val_flags & 0xff);
- if (acc.UserTitle.Length == 0)
- membershipType[0] = (byte)((val_flags & 0x0f00) >> 8);
- else
- membershipType = Utils.StringToBytes(acc.UserTitle);
- int val_born = acc.Created;
- if (val_born != 0)
- born = Util.ToDateTime(val_born).ToString("M/d/yyyy", CultureInfo.InvariantCulture);
- // picky, picky
- }
- else
- ok = false;
- UserProfileProperties props = new UserProfileProperties();
- props.UserId = avatarID;
- if(ok)
- {
- string result = string.Empty;
- if (!GetProfileData(ref props, foreign, serverURI, out result))
- ok = false;
- }
- if (!ok)
- props.AboutText = "Profile not available at this time. User may still be unknown to this grid";
- if (!m_allowUserProfileWebURLs)
- props.WebUrl = "";
- GroupMembershipData[] agentGroups = null;
- if(ok && m_groupsModule != null)
- agentGroups = m_groupsModule.GetMembershipData(avatarID);
- HashSet<IClientAPI> clients;
- lock (m_profilesCache)
- {
- if (!m_profilesCache.TryGetValue(props.UserId, out UserProfileCacheEntry uce) || uce == null)
- uce = new UserProfileCacheEntry();
- uce.props = props;
- uce.born = born;
- uce.membershipType = membershipType;
- uce.flags = flags;
- clients = uce.ClientsWaitingProps;
- uce.ClientsWaitingProps = null;
- uce.avatarGroups = agentGroups;
- m_profilesCache.AddOrUpdate(props.UserId, uce, PROFILECACHEEXPIRE);
- }
- if (IsFriendOnline(req.client.AgentId, req.agent))
- flags |= (uint)ProfileFlags.Online;
- else
- flags &= (uint)~ProfileFlags.Online;
- if (clients == null)
- {
- client.SendAvatarProperties(props.UserId, props.AboutText, born, membershipType, props.FirstLifeText, flags,
- props.FirstLifeImageId, props.ImageId, props.WebUrl, props.PartnerId);
- client.SendAvatarInterestsReply(props.UserId, (uint)props.WantToMask, props.WantToText,
- (uint)props.SkillsMask, props.SkillsText, props.Language);
- if (agentGroups != null)
- client.SendAvatarGroupsReply(avatarID, agentGroups);
- }
- else
- {
- if (!clients.Contains(client) && client.IsActive)
- {
- client.SendAvatarProperties(props.UserId, props.AboutText, born, membershipType, props.FirstLifeText, flags,
- props.FirstLifeImageId, props.ImageId, props.WebUrl, props.PartnerId);
- client.SendAvatarInterestsReply(props.UserId, (uint)props.WantToMask, props.WantToText,
- (uint)props.SkillsMask, props.SkillsText, props.Language);
- if (agentGroups != null)
- client.SendAvatarGroupsReply(avatarID, agentGroups);
- }
- foreach (IClientAPI cli in clients)
- {
- if (!cli.IsActive)
- continue;
- cli.SendAvatarProperties(props.UserId, props.AboutText, born, membershipType, props.FirstLifeText, flags,
- props.FirstLifeImageId, props.ImageId, props.WebUrl, props.PartnerId);
- cli.SendAvatarInterestsReply(props.UserId, (uint)props.WantToMask, props.WantToText,
- (uint)props.SkillsMask, props.SkillsText, props.Language);
- if (agentGroups != null)
- cli.SendAvatarGroupsReply(avatarID, agentGroups);
- }
- }
- }
- }
- catch (Exception e)
- {
- m_log.ErrorFormat("[UserProfileModule]: Process fail {0} : {1}", e.Message, e.StackTrace);
- }
- }
- m_asyncRequestsRunning = false;
- }
- }
- public Scene Scene
- {
- get; private set;
- }
- /// <summary>
- /// Gets or sets the ConfigSource.
- /// </summary>
- /// <value>
- /// The configuration
- /// </value>
- public IConfigSource Config
- {
- get;
- set;
- }
- /// <summary>
- /// Gets or sets the URI to the profile server.
- /// </summary>
- /// <value>
- /// The profile server URI.
- /// </value>
- public string ProfileServerUri
- {
- get;
- set;
- }
- IProfileModule ProfileModule
- {
- get; set;
- }
- IUserManagement UserManagementModule
- {
- get; set;
- }
- /// <summary>
- /// Gets or sets a value indicating whether this
- /// <see cref="OpenSim.Region.Coremodules.UserProfiles.UserProfileModule"/> is enabled.
- /// </summary>
- /// <value>
- /// <c>true</c> if enabled; otherwise, <c>false</c>.
- /// </value>
- public bool Enabled
- {
- get;
- set;
- }
- private GridInfo m_thisGridInfo;
- #region IRegionModuleBase implementation
- /// <summary>
- /// This is called to initialize the region module. For shared modules, this is called exactly once, after
- /// creating the single (shared) instance. For non-shared modules, this is called once on each instance, after
- /// the instace for the region has been created.
- /// </summary>
- /// <param name='source'>
- /// Source.
- /// </param>
- public void Initialise(IConfigSource source)
- {
- Config = source;
- ReplaceableInterface = typeof(IProfileModule);
- IConfig profileConfig = Config.Configs["UserProfiles"];
- if (profileConfig == null)
- {
- //m_log.Debug("[PROFILES]: UserProfiles disabled, no configuration");
- Enabled = false;
- return;
- }
- // If we find ProfileURL then we configure for FULL support
- // else we setup for BASIC support
- ProfileServerUri = profileConfig.GetString("ProfileServiceURL", "");
- if (string.IsNullOrEmpty(ProfileServerUri))
- {
- Enabled = false;
- return;
- }
- OSHTTPURI tmp = new OSHTTPURI(ProfileServerUri, true);
- if (!tmp.IsResolvedHost)
- {
- m_log.ErrorFormat("[UserProfileModule: {0}", tmp.IsValidHost ? "Could not resolve ProfileServiceURL" : "ProfileServiceURL is a invalid host");
- throw new Exception("UserProfileModule init error");
- }
- ProfileServerUri = tmp.URI;
- m_allowUserProfileWebURLs = profileConfig.GetBoolean("AllowUserProfileWebURLs", m_allowUserProfileWebURLs);
- m_log.Debug("[UserProfileModule]: Full Profiles Enabled");
- ReplaceableInterface = null;
- Enabled = true;
- }
- /// <summary>
- /// Adds the region.
- /// </summary>
- /// <param name='scene'>
- /// Scene.
- /// </param>
- public void AddRegion(Scene scene)
- {
- if(!Enabled)
- return;
- Scene = scene;
- if(m_thisGridInfo == null)
- m_thisGridInfo = scene.SceneGridInfo;
- Scene.RegisterModuleInterface<IProfileModule>(this);
- Scene.EventManager.OnNewClient += OnNewClient;
- Scene.EventManager.OnClientClosed += OnClientClosed;
- UserManagementModule = Scene.RequestModuleInterface<IUserManagement>();
- }
- /// <summary>
- /// Removes the region.
- /// </summary>
- /// <param name='scene'>
- /// Scene.
- /// </param>
- public void RemoveRegion(Scene scene)
- {
- if(!Enabled)
- return;
- m_profilesCache.Clear();
- m_classifiedCache.Clear();
- m_classifiedInterest.Clear();
- }
- /// <summary>
- /// This will be called once for every scene loaded. In a shared module this will be multiple times in one
- /// instance, while a nonshared module instance will only be called once. This method is called after AddRegion
- /// has been called in all modules for that scene, providing an opportunity to request another module's
- /// interface, or hook an event from another module.
- /// </summary>
- /// <param name='scene'>
- /// Scene.
- /// </param>
- public void RegionLoaded(Scene scene)
- {
- if(!Enabled)
- return;
- m_assetCache = Scene.RequestModuleInterface<IAssetCache>();
- m_groupsModule = Scene.RequestModuleInterface<IGroupsModule>();
- }
- /// <summary>
- /// If this returns non-null, it is the type of an interface that this module intends to register. This will
- /// cause the loader to defer loading of this module until all other modules have been loaded. If no other
- /// module has registered the interface by then, this module will be activated, else it will remain inactive,
- /// letting the other module take over. This should return non-null ONLY in modules that are intended to be
- /// easily replaceable, e.g. stub implementations that the developer expects to be replaced by third party
- /// provided modules.
- /// </summary>
- /// <value>
- /// The replaceable interface.
- /// </value>
- public Type ReplaceableInterface
- {
- get; private set;
- }
- /// <summary>
- /// Called as the instance is closed.
- /// </summary>
- public void Close()
- {
- m_thisGridInfo = null;
- }
- /// <value>
- /// The name of the module
- /// </value>
- /// <summary>
- /// Gets the module name.
- /// </summary>
- public string Name
- {
- get { return "UserProfileModule"; }
- }
- #endregion IRegionModuleBase implementation
- #region Region Event Handlers
- /// <summary>
- /// Raises the new client event.
- /// </summary>
- /// <param name='client'>
- /// Client.
- /// </param>
- void OnNewClient(IClientAPI client)
- {
- //Profile
- client.OnRequestAvatarProperties += RequestAvatarProperties;
- client.OnUpdateAvatarProperties += AvatarPropertiesUpdate;
- client.OnAvatarInterestUpdate += AvatarInterestsUpdate;
- // Classifieds
- client.AddGenericPacketHandler("avatarclassifiedsrequest", ClassifiedsRequest);
- client.OnClassifiedInfoUpdate += ClassifiedInfoUpdate;
- client.OnClassifiedInfoRequest += ClassifiedInfoRequest;
- client.OnClassifiedDelete += ClassifiedDelete;
- // Picks
- client.AddGenericPacketHandler("avatarpicksrequest", PicksRequest);
- client.AddGenericPacketHandler("pickinforequest", PickInfoRequest);
- client.OnPickInfoUpdate += PickInfoUpdate;
- client.OnPickDelete += PickDelete;
- // Notes
- client.AddGenericPacketHandler("avatarnotesrequest", NotesRequest);
- client.OnAvatarNotesUpdate += NotesUpdate;
- // Preferences
- client.OnUserInfoRequest += UserPreferencesRequest;
- client.OnUpdateUserInfo += UpdateUserPreferences;
- }
- void OnClientClosed(UUID AgentId, Scene scene)
- {
- ScenePresence sp = scene.GetScenePresence(AgentId);
- IClientAPI client = sp.ControllingClient;
- if (client == null)
- return;
- //Profile
- client.OnRequestAvatarProperties -= RequestAvatarProperties;
- client.OnUpdateAvatarProperties -= AvatarPropertiesUpdate;
- client.OnAvatarInterestUpdate -= AvatarInterestsUpdate;
- // Classifieds
- // client.r GenericPacketHandler("avatarclassifiedsrequest", ClassifiedsRequest);
- client.OnClassifiedInfoUpdate -= ClassifiedInfoUpdate;
- client.OnClassifiedInfoRequest -= ClassifiedInfoRequest;
- client.OnClassifiedDelete -= ClassifiedDelete;
- // Picks
- // client.AddGenericPacketHandler("avatarpicksrequest", PicksRequest);
- // client.AddGenericPacketHandler("pickinforequest", PickInfoRequest);
- client.OnPickInfoUpdate -= PickInfoUpdate;
- client.OnPickDelete -= PickDelete;
- // Notes
- // client.AddGenericPacketHandler("avatarnotesrequest", NotesRequest);
- client.OnAvatarNotesUpdate -= NotesUpdate;
- // Preferences
- client.OnUserInfoRequest -= UserPreferencesRequest;
- client.OnUpdateUserInfo -= UpdateUserPreferences;
- }
- #endregion Region Event Handlers
- #region Classified
- ///
- /// <summary>
- /// Handles the avatar classifieds request.
- /// </summary>
- /// <param name='sender'>
- /// Sender.
- /// </param>
- /// <param name='method'>
- /// Method.
- /// </param>
- /// <param name='args'>
- /// Arguments.
- /// </param>
- public void ClassifiedsRequest(Object sender, string method, List<String> args)
- {
- if (!(sender is IClientAPI))
- return;
- IClientAPI remoteClient = (IClientAPI)sender;
- Dictionary<UUID, string> classifieds = new Dictionary<UUID, string>();
- UUID targetID;
- if(!UUID.TryParse(args[0], out targetID) || targetID.IsZero())
- return;
- if (targetID == Constants.m_MrOpenSimID)
- {
- remoteClient.SendAvatarClassifiedReply(targetID, classifieds);
- return;
- }
- ScenePresence p = FindPresence(targetID);
- if (p != null && p.IsNPC)
- {
- remoteClient.SendAvatarClassifiedReply(targetID, classifieds);
- return;
- }
- lock(m_profilesCache)
- {
- if(m_profilesCache.TryGetValue(targetID, out UserProfileCacheEntry uce) && uce != null)
- {
- if(uce.classifiedsLists != null)
- {
- foreach(KeyValuePair<UUID,string> kvp in uce.classifiedsLists)
- {
- UUID kvpkey = kvp.Key;
- classifieds[kvpkey] = kvp.Value;
- lock (m_classifiedCache)
- {
- if (!m_classifiedCache.ContainsKey(kvpkey))
- {
- m_classifiedCache.Add(kvpkey,targetID);
- m_classifiedInterest.Add(kvpkey, 0);
- }
- m_classifiedInterest[kvpkey]++;
- }
- }
- remoteClient.SendAvatarClassifiedReply(targetID, uce.classifiedsLists);
- return;
- }
- }
- }
- string serverURI = string.Empty;
- GetUserProfileServerURI(targetID, out serverURI);
- if(string.IsNullOrWhiteSpace(serverURI))
- {
- remoteClient.SendAvatarClassifiedReply(targetID, classifieds);
- return;
- }
- OSDMap parameters= new OSDMap() {{"creatorId", OSD.FromUUID(targetID) }};
- OSD osdtmp = parameters;
- if(!rpc.JsonRpcRequest(ref osdtmp, "avatarclassifiedsrequest", serverURI, UUID.Random().ToString()))
- {
- remoteClient.SendAvatarClassifiedReply(targetID, classifieds);
- return;
- }
- parameters = (OSDMap)osdtmp;
- if(!parameters.TryGetValue("result", out osdtmp) || !(osdtmp is OSDArray))
- {
- remoteClient.SendAvatarClassifiedReply(targetID, classifieds);
- return;
- }
- OSDArray list = (OSDArray)osdtmp;
- foreach(OSD map in list)
- {
- OSDMap m = (OSDMap)map;
- UUID cid = m["classifieduuid"].AsUUID();
- string name = m["name"].AsString();
- classifieds[cid] = name;
- lock (m_classifiedCache)
- {
- if (!m_classifiedCache.ContainsKey(cid))
- {
- m_classifiedCache.Add(cid,targetID);
- m_classifiedInterest.Add(cid, 0);
- }
- m_classifiedInterest[cid]++;
- }
- }
- lock(m_profilesCache)
- {
- if(!m_profilesCache.TryGetValue(targetID, out UserProfileCacheEntry uce) || uce == null)
- uce = new UserProfileCacheEntry();
- uce.classifiedsLists = classifieds;
- m_profilesCache.AddOrUpdate(targetID, uce, PROFILECACHEEXPIRE);
- }
- remoteClient.SendAvatarClassifiedReply(targetID, classifieds);
- }
- public void ClassifiedInfoRequest(UUID queryClassifiedID, IClientAPI remoteClient)
- {
- UUID target = remoteClient.AgentId;
- UserClassifiedAdd ad = new UserClassifiedAdd();
- ad.ClassifiedId = queryClassifiedID;
- lock (m_classifiedCache)
- {
- if (m_classifiedCache.ContainsKey(queryClassifiedID))
- {
- target = m_classifiedCache[queryClassifiedID];
- m_classifiedInterest[queryClassifiedID] --;
- if (m_classifiedInterest[queryClassifiedID] == 0)
- {
- m_classifiedInterest.Remove(queryClassifiedID);
- m_classifiedCache.Remove(queryClassifiedID);
- }
- }
- }
- UserProfileCacheEntry uce = null;
- lock(m_profilesCache)
- {
- if(m_profilesCache.TryGetValue(target, out uce) && uce != null)
- {
- if(uce.classifieds != null && uce.classifieds.ContainsKey(queryClassifiedID))
- {
- ad = uce.classifieds[queryClassifiedID];
- Vector3 gPos = new Vector3();
- Vector3.TryParse(ad.GlobalPos, out gPos);
- remoteClient.SendClassifiedInfoReply(ad.ClassifiedId, ad.CreatorId, (uint)ad.CreationDate,
- (uint)ad.ExpirationDate, (uint)ad.Category, ad.Name, ad.Description,
- ad.ParcelId, (uint)ad.ParentEstate, ad.SnapshotId, ad.SimName,
- gPos, ad.ParcelName, ad.Flags, ad.Price);
- return;
- }
- }
- }
- string serverURI = string.Empty;
- bool foreign = GetUserProfileServerURI(target, out serverURI);
- if(string.IsNullOrWhiteSpace(serverURI))
- {
- return;
- }
- object Adobject = ad;
- if(!rpc.JsonRpcRequest(ref Adobject, "classifieds_info_query", serverURI, UUID.Random().ToString()))
- {
- remoteClient.SendAgentAlertMessage(
- "Error getting classified info", false);
- return;
- }
- ad = (UserClassifiedAdd) Adobject;
- if(ad.CreatorId.IsZero())
- return;
- if(foreign)
- cacheForeignImage(target, ad.SnapshotId);
- lock(m_profilesCache)
- {
- if(!m_profilesCache.TryGetValue(target, out uce) || uce == null)
- uce = new UserProfileCacheEntry();
- if(uce.classifieds == null)
- uce.classifieds = new Dictionary<UUID, UserClassifiedAdd>();
- uce.classifieds[ad.ClassifiedId] = ad;
- m_profilesCache.AddOrUpdate(target, uce, PROFILECACHEEXPIRE);
- }
- Vector3 globalPos = new Vector3();
- Vector3.TryParse(ad.GlobalPos, out globalPos);
- remoteClient.SendClassifiedInfoReply(ad.ClassifiedId, ad.CreatorId, (uint)ad.CreationDate, (uint)ad.ExpirationDate,
- (uint)ad.Category, ad.Name, ad.Description, ad.ParcelId, (uint)ad.ParentEstate,
- ad.SnapshotId, ad.SimName, globalPos, ad.ParcelName, ad.Flags, ad.Price);
- }
- /// <summary>
- /// Classifieds info update.
- /// </summary>
- /// <param name='queryclassifiedID'>
- /// Queryclassified I.
- /// </param>
- /// <param name='queryCategory'>
- /// Query category.
- /// </param>
- /// <param name='queryName'>
- /// Query name.
- /// </param>
- /// <param name='queryDescription'>
- /// Query description.
- /// </param>
- /// <param name='queryParcelID'>
- /// Query parcel I.
- /// </param>
- /// <param name='queryParentEstate'>
- /// Query parent estate.
- /// </param>
- /// <param name='querySnapshotID'>
- /// Query snapshot I.
- /// </param>
- /// <param name='queryGlobalPos'>
- /// Query global position.
- /// </param>
- /// <param name='queryclassifiedFlags'>
- /// Queryclassified flags.
- /// </param>
- /// <param name='queryclassifiedPrice'>
- /// Queryclassified price.
- /// </param>
- /// <param name='remoteClient'>
- /// Remote client.
- /// </param>
- public void ClassifiedInfoUpdate(UUID queryclassifiedID, uint queryCategory, string queryName, string queryDescription, UUID queryParcelID,
- uint queryParentEstate, UUID querySnapshotID, Vector3 queryGlobalPos, byte queryclassifiedFlags,
- int queryclassifiedPrice, IClientAPI remoteClient)
- {
- Scene s = (Scene)remoteClient.Scene;
- Vector3 pos = remoteClient.SceneAgent.AbsolutePosition;
- ILandObject land = s.LandChannel.GetLandObject(pos.X, pos.Y);
- UUID creatorId = remoteClient.AgentId;
- ScenePresence p = FindPresence(creatorId);
- UserProfileCacheEntry uce = null;
- lock(m_profilesCache)
- m_profilesCache.TryGetValue(remoteClient.AgentId, out uce);
- string serverURI = string.Empty;
- bool foreign = GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
- if(string.IsNullOrWhiteSpace(serverURI))
- {
- return;
- }
- if(foreign)
- {
- remoteClient.SendAgentAlertMessage("Please change classifieds on your home grid", true);
- if(uce != null && uce.classifiedsLists != null)
- remoteClient.SendAvatarClassifiedReply(remoteClient.AgentId, uce.classifiedsLists);
- return;
- }
- OSDMap parameters = new OSDMap {{"creatorId", OSD.FromUUID(creatorId)}};
- OSD osdtmp = parameters;
- if (!rpc.JsonRpcRequest(ref osdtmp, "avatarclassifiedsrequest", serverURI, UUID.Random().ToString()))
- {
- remoteClient.SendAgentAlertMessage("Error fetching classifieds", false);
- return;
- }
- parameters = (OSDMap)osdtmp;
- OSDArray list = (OSDArray)parameters["result"];
- bool exists = list.Cast<OSDMap>().Where(map => map.ContainsKey("classifieduuid"))
- .Any(map => map["classifieduuid"].AsUUID().Equals(queryclassifiedID));
- IMoneyModule money = null;
- if (!exists)
- {
- money = s.RequestModuleInterface<IMoneyModule>();
- if (money != null)
- {
- if (!money.AmountCovered(remoteClient.AgentId, queryclassifiedPrice))
- {
- remoteClient.SendAgentAlertMessage("You do not have enough money to create this classified.", false);
- if(uce != null && uce.classifiedsLists != null)
- remoteClient.SendAvatarClassifiedReply(remoteClient.AgentId, uce.classifiedsLists);
- return;
- }
- }
- }
- UserClassifiedAdd ad = new UserClassifiedAdd();
- ad.ParcelName = land == null ? string.Empty : land.LandData.Name;
- ad.CreatorId = remoteClient.AgentId;
- ad.ClassifiedId = queryclassifiedID;
- ad.Category = Convert.ToInt32(queryCategory);
- ad.Name = queryName;
- ad.Description = queryDescription;
- ad.ParentEstate = Convert.ToInt32(queryParentEstate);
- ad.SnapshotId = querySnapshotID;
- ad.SimName = remoteClient.Scene.RegionInfo.RegionName;
- ad.GlobalPos = queryGlobalPos.ToString ();
- ad.Flags = queryclassifiedFlags;
- ad.Price = queryclassifiedPrice;
- ad.ParcelId = p.currentParcelUUID;
- object Ad = ad;
- if(!rpc.JsonRpcRequest(ref Ad, "classified_update", serverURI, UUID.Random().ToString()))
- {
- remoteClient.SendAgentAlertMessage("Error updating classified", false);
- if(uce != null && uce.classifiedsLists != null)
- remoteClient.SendAvatarClassifiedReply(remoteClient.AgentId, uce.classifiedsLists);
- return;
- }
- // only charge if it worked
- if (money != null)
- money.ApplyCharge(remoteClient.AgentId, queryclassifiedPrice, MoneyTransactionType.ClassifiedCharge);
- // just flush cache for now
- lock(m_profilesCache)
- {
- if(m_profilesCache.TryGetValue(remoteClient.AgentId, out uce) && uce != null)
- {
- uce.classifieds = null;
- uce.classifiedsLists = null;
- }
- }
- }
- /// <summary>
- /// Classifieds delete.
- /// </summary>
- /// <param name='queryClassifiedID'>
- /// Query classified I.
- /// </param>
- /// <param name='remoteClient'>
- /// Remote client.
- /// </param>
- public void ClassifiedDelete(UUID queryClassifiedID, IClientAPI remoteClient)
- {
- string serverURI = string.Empty;
- bool foreign = GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
- if(string.IsNullOrWhiteSpace(serverURI))
- return;
- if(foreign)
- {
- remoteClient.SendAgentAlertMessage("Please change classifieds on your home grid", true);
- return;
- }
- UUID classifiedId;
- if(!UUID.TryParse(queryClassifiedID.ToString(), out classifiedId))
- return;
- OSD Params = new OSDMap() {{ "classifiedId", OSD.FromUUID(classifiedId) }};
- if(!rpc.JsonRpcRequest(ref Params, "classified_delete", serverURI, UUID.Random().ToString()))
- {
- remoteClient.SendAgentAlertMessage(
- "Error deleting classified", false);
- return;
- }
- // flush cache
- UserProfileCacheEntry uce = null;
- lock(m_profilesCache)
- {
- if(m_profilesCache.TryGetValue(remoteClient.AgentId, out uce) && uce != null)
- {
- uce.classifieds = null;
- uce.classifiedsLists = null;
- }
- }
- }
- #endregion Classified
- #region Picks
- /// <summary>
- /// Handles the avatar picks request.
- /// </summary>
- /// <param name='sender'>
- /// Sender.
- /// </param>
- /// <param name='method'>
- /// Method.
- /// </param>
- /// <param name='args'>
- /// Arguments.
- /// </param>
- public void PicksRequest(Object sender, string method, List<String> args)
- {
- if (!(sender is IClientAPI))
- return;
- IClientAPI remoteClient = (IClientAPI)sender;
- UUID targetId;
- if(!UUID.TryParse(args[0], out targetId))
- return;
- Dictionary<UUID, string> picks = new Dictionary<UUID, string>();
- if (targetId == Constants.m_MrOpenSimID)
- {
- remoteClient.SendAvatarPicksReply(targetId, picks);
- return;
- }
- ScenePresence p = FindPresence(targetId);
- if (p != null && p.IsNPC)
- {
- remoteClient.SendAvatarPicksReply(targetId, picks);
- return;
- }
- UserProfileCacheEntry uce = null;
- lock(m_profilesCache)
- {
- if(m_profilesCache.TryGetValue(targetId, out uce) && uce != null)
- {
- if(uce != null && uce.picksList != null)
- {
- remoteClient.SendAvatarPicksReply(targetId, uce.picksList);
- return;
- }
- }
- }
- string serverURI = string.Empty;
- GetUserProfileServerURI(targetId, out serverURI);
- if(string.IsNullOrWhiteSpace(serverURI))
- {
- remoteClient.SendAvatarPicksReply(targetId, picks);
- return;
- }
- OSDMap parameters= new OSDMap() {{"creatorId", OSD.FromUUID(targetId)}};
- OSD osdtmp = parameters;
- if(!rpc.JsonRpcRequest(ref osdtmp, "avatarpicksrequest", serverURI, UUID.Random().ToString()))
- {
- remoteClient.SendAvatarPicksReply(targetId, picks);
- return;
- }
- parameters = (OSDMap)osdtmp;
- if(!parameters.TryGetValue("result", out osdtmp) || !(osdtmp is OSDArray))
- {
- remoteClient.SendAvatarPicksReply(targetId, picks);
- return;
- }
- OSDArray list = (OSDArray)osdtmp;
- foreach(OSD map in list)
- {
- OSDMap m = (OSDMap)map;
- UUID cid = m["pickuuid"].AsUUID();
- string name = m["name"].AsString();
- picks[cid] = name;
- }
- lock(m_profilesCache)
- {
- if(!m_profilesCache.TryGetValue(targetId, out uce) || uce == null)
- uce = new UserProfileCacheEntry();
- uce.picksList = picks;
- m_profilesCache.AddOrUpdate(targetId, uce, PROFILECACHEEXPIRE);
- }
- remoteClient.SendAvatarPicksReply(targetId, picks);
- }
- /// <summary>
- /// Handles the pick info request.
- /// </summary>
- /// <param name='sender'>
- /// Sender.
- /// </param>
- /// <param name='method'>
- /// Method.
- /// </param>
- /// <param name='args'>
- /// Arguments.
- /// </param>
- public void PickInfoRequest(Object sender, string method, List<String> args)
- {
- if (!(sender is IClientAPI))
- return;
- UserProfilePick pick = new UserProfilePick ();
- UUID targetID;
- if(!UUID.TryParse(args [0], out targetID))
- return;
- pick.CreatorId = targetID;
- if(!UUID.TryParse (args [1], out pick.PickId))
- return;
- IClientAPI remoteClient = (IClientAPI)sender;
- UserProfileCacheEntry uce = null;
- lock(m_profilesCache)
- {
- if(m_profilesCache.TryGetValue(targetID, out uce) && uce != null)
- {
- if(uce != null && uce.picks != null && uce.picks.ContainsKey(pick.PickId))
- {
- pick = uce.picks[pick.PickId];
- Vector3 gPos = new Vector3(Vector3.Zero);
- Vector3.TryParse(pick.GlobalPos, out gPos);
- remoteClient.SendPickInfoReply(pick.PickId,pick.CreatorId,pick.TopPick,pick.ParcelId,pick.Name,
- pick.Desc,pick.SnapshotId,pick.ParcelName,pick.OriginalName,pick.SimName,
- gPos,pick.SortOrder,pick.Enabled);
- return;
- }
- }
- }
- string serverURI = string.Empty;
- bool foreign = GetUserProfileServerURI (targetID, out serverURI);
- if(string.IsNullOrWhiteSpace(serverURI))
- {
- return;
- }
- object Pick = (object)pick;
- if (!rpc.JsonRpcRequest (ref Pick, "pickinforequest", serverURI, UUID.Random ().ToString ())) {
- remoteClient.SendAgentAlertMessage ("Error selecting pick", false);
- return;
- }
- pick = (UserProfilePick)Pick;
- if(foreign)
- cacheForeignImage(targetID, pick.SnapshotId);
- Vector3 globalPos = new Vector3(Vector3.Zero);
- Vector3.TryParse(pick.GlobalPos, out globalPos);
- if (m_thisGridInfo.IsLocalGrid(pick.Gatekeeper, true) == 0)
- {
- // Setup the illusion
- string region = string.Format("{0} {1}",pick.Gatekeeper,pick.SimName);
- GridRegion target = Scene.GridService.GetRegionByName(Scene.RegionInfo.ScopeID, region);
- if(target == null)
- {
- // This is a unreachable region
- }
- else
- {
- // we have a proxy on map
- ulong oriHandle;
- uint oriX;
- uint oriY;
- if(Util.ParseFakeParcelID(pick.ParcelId, out oriHandle, out oriX, out oriY))
- {
- pick.ParcelId = Util.BuildFakeParcelID(target.RegionHandle, oriX, oriY);
- globalPos.X = target.RegionLocX + oriX;
- globalPos.Y = target.RegionLocY + oriY;
- pick.GlobalPos = globalPos.ToString();
- }
- else
- {
- // this is a fail on large regions
- uint gtmp = (uint)globalPos.X >> 8;
- globalPos.X -= (gtmp << 8);
- gtmp = (uint)globalPos.Y >> 8;
- globalPos.Y -= (gtmp << 8);
- pick.ParcelId = Util.BuildFakeParcelID(target.RegionHandle, (uint)globalPos.X, (uint)globalPos.Y);
- globalPos.X += target.RegionLocX;
- globalPos.Y += target.RegionLocY;
- pick.GlobalPos = globalPos.ToString();
- }
- }
- }
- //m_log.DebugFormat("[PROFILES]: PickInfoRequest: {0} : {1}", pick.Name.ToString(), pick.SnapshotId.ToString());
- lock(m_profilesCache)
- {
- if(!m_profilesCache.TryGetValue(targetID, out uce) || uce == null)
- uce = new UserProfileCacheEntry();
- if(uce.picks == null)
- uce.picks = new Dictionary<UUID, UserProfilePick>();
- uce.picks[pick.PickId] = pick;
- m_profilesCache.AddOrUpdate(targetID, uce, PROFILECACHEEXPIRE);
- }
- // Pull the rabbit out of the hat
- remoteClient.SendPickInfoReply(pick.PickId,pick.CreatorId,pick.TopPick,pick.ParcelId,pick.Name,
- pick.Desc,pick.SnapshotId,pick.ParcelName,pick.OriginalName,pick.SimName,
- globalPos,pick.SortOrder,pick.Enabled);
- }
- /// <summary>
- /// Updates the userpicks
- /// </summary>
- /// <param name='remoteClient'>
- /// Remote client.
- /// </param>
- /// <param name='pickID'>
- /// Pick I.
- /// </param>
- /// <param name='creatorID'>
- /// the creator of the pick
- /// </param>
- /// <param name='topPick'>
- /// Top pick.
- /// </param>
- /// <param name='name'>
- /// Name.
- /// </param>
- /// <param name='desc'>
- /// Desc.
- /// </param>
- /// <param name='snapshotID'>
- /// Snapshot I.
- /// </param>
- /// <param name='sortOrder'>
- /// Sort order.
- /// </param>
- /// <param name='enabled'>
- /// Enabled.
- /// </param>
- public void PickInfoUpdate(IClientAPI remoteClient, UUID pickID, UUID creatorID, bool topPick, string name, string desc, UUID snapshotID, int sortOrder, bool enabled)
- {
- //m_log.DebugFormat("[PROFILES]: Start PickInfoUpdate Name: {0} PickId: {1} SnapshotId: {2}", name, pickID.ToString(), snapshotID.ToString());
- UserProfilePick pick = new UserProfilePick();
- string serverURI = string.Empty;
- GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
- if(string.IsNullOrWhiteSpace(serverURI))
- {
- return;
- }
- ScenePresence p = FindPresence(remoteClient.AgentId);
- Vector3 avaPos = p.AbsolutePosition;
- // Getting the global position for the Avatar
- Vector3 posGlobal = new Vector3(remoteClient.Scene.RegionInfo.WorldLocX + avaPos.X,
- remoteClient.Scene.RegionInfo.WorldLocY + avaPos.Y,
- avaPos.Z);
- string landParcelName = "My Parcel";
- // UUID landParcelID = p.currentParcelUUID;
- // to locate parcels we use a fake id that encodes the region handle
- // since we do not have a global locator
- // this fails on HG
- UUID landParcelID = Util.BuildFakeParcelID(remoteClient.Scene.RegionInfo.RegionHandle, (uint)avaPos.X, (uint)avaPos.Y);
- ILandObject land = p.Scene.LandChannel.GetLandObject(avaPos.X, avaPos.Y);
- if (land != null)
- {
- // If land found, use parcel uuid from here because the value from SP will be blank if the avatar hasnt moved
- landParcelName = land.LandData.Name;
- // landParcelID = land.LandData.GlobalID;
- }
- else
- {
- m_log.WarnFormat(
- "[PROFILES]: PickInfoUpdate found no parcel info at {0},{1} in {2}",
- avaPos.X, avaPos.Y, p.Scene.Name);
- }
- pick.PickId = pickID;
- pick.CreatorId = creatorID;
- pick.TopPick = topPick;
- pick.Name = name;
- pick.Desc = desc;
- pick.ParcelId = landParcelID;
- pick.SnapshotId = snapshotID;
- pick.ParcelName = landParcelName;
- pick.SimName = remoteClient.Scene.RegionInfo.RegionName;
- pick.Gatekeeper = m_thisGridInfo.GateKeeperURLNoEndSlash;
- pick.GlobalPos = posGlobal.ToString();
- pick.SortOrder = sortOrder;
- pick.Enabled = enabled;
- object Pick = (object)pick;
- if(!rpc.JsonRpcRequest(ref Pick, "picks_update", serverURI, UUID.Random().ToString()))
- {
- remoteClient.SendAgentAlertMessage(
- "Error updating pick", false);
- return;
- }
- UserProfileCacheEntry uce = null;
- lock(m_profilesCache)
- {
- if(!m_profilesCache.TryGetValue(remoteClient.AgentId, out uce) || uce == null)
- uce = new UserProfileCacheEntry();
- if(uce.picks == null)
- uce.picks = new Dictionary<UUID, UserProfilePick>();
- if(uce.picksList == null)
- uce.picksList = new Dictionary<UUID, string>();
- uce.picks[pick.PickId] = pick;
- uce.picksList[pick.PickId] = pick.Name;
- m_profilesCache.AddOrUpdate(remoteClient.AgentId, uce, PROFILECACHEEXPIRE);
- }
- remoteClient.SendAvatarPicksReply(remoteClient.AgentId, uce.picksList);
- remoteClient.SendPickInfoReply(pick.PickId,pick.CreatorId,pick.TopPick,pick.ParcelId,pick.Name,
- pick.Desc,pick.SnapshotId,pick.ParcelName,pick.OriginalName,pick.SimName,
- posGlobal,pick.SortOrder,pick.Enabled);
- //m_log.DebugFormat("[PROFILES]: Finish PickInfoUpdate {0} {1}", pick.Name, pick.PickId.ToString());
- }
- /// <summary>
- /// Delete a Pick
- /// </summary>
- /// <param name='remoteClient'>
- /// Remote client.
- /// </param>
- /// <param name='queryPickID'>
- /// Query pick I.
- /// </param>
- public void PickDelete(IClientAPI remoteClient, UUID queryPickID)
- {
- string serverURI = string.Empty;
- GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
- if(string.IsNullOrWhiteSpace(serverURI))
- {
- return;
- }
- OSDMap parameters= new OSDMap();
- parameters.Add("pickId", OSD.FromUUID(queryPickID));
- OSD Params = (OSD)parameters;
- if(!rpc.JsonRpcRequest(ref Params, "picks_delete", serverURI, UUID.Random().ToString()))
- {
- remoteClient.SendAgentAlertMessage(
- "Error picks delete", false);
- return;
- }
- UserProfileCacheEntry uce = null;
- lock(m_profilesCache)
- {
- if(m_profilesCache.TryGetValue(remoteClient.AgentId, out uce) && uce != null)
- {
- if(uce.picks != null && uce.picks.ContainsKey(queryPickID))
- uce.picks.Remove(queryPickID);
- if(uce.picksList != null && uce.picksList.ContainsKey(queryPickID))
- uce.picksList.Remove(queryPickID);
- m_profilesCache.AddOrUpdate(remoteClient.AgentId, uce, PROFILECACHEEXPIRE);
- }
- }
- if(uce != null && uce.picksList != null)
- remoteClient.SendAvatarPicksReply(remoteClient.AgentId, uce.picksList);
- else
- remoteClient.SendAvatarPicksReply(remoteClient.AgentId, new Dictionary<UUID, string>());
- }
- #endregion Picks
- #region Notes
- /// <summary>
- /// Handles the avatar notes request.
- /// </summary>
- /// <param name='sender'>
- /// Sender.
- /// </param>
- /// <param name='method'>
- /// Method.
- /// </param>
- /// <param name='args'>
- /// Arguments.
- /// </param>
- public void NotesRequest(Object sender, string method, List<String> args)
- {
- UserProfileNotes note = new UserProfileNotes();
- if (!(sender is IClientAPI))
- return;
- if(!UUID.TryParse(args[0], out note.TargetId))
- return;
- IClientAPI remoteClient = (IClientAPI)sender;
- note.UserId = remoteClient.AgentId;
- string serverURI = string.Empty;
- GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
- if(string.IsNullOrWhiteSpace(serverURI))
- {
- remoteClient.SendAvatarNotesReply(note.TargetId, note.Notes);
- return;
- }
- object Note = (object)note;
- if(!rpc.JsonRpcRequest(ref Note, "avatarnotesrequest", serverURI, UUID.Random().ToString()))
- {
- remoteClient.SendAvatarNotesReply(note.TargetId, note.Notes);
- return;
- }
- note = (UserProfileNotes) Note;
- remoteClient.SendAvatarNotesReply(note.TargetId, note.Notes);
- }
- /// <summary>
- /// Avatars the notes update.
- /// </summary>
- /// <param name='remoteClient'>
- /// Remote client.
- /// </param>
- /// <param name='queryTargetID'>
- /// Query target I.
- /// </param>
- /// <param name='queryNotes'>
- /// Query notes.
- /// </param>
- public void NotesUpdate(IClientAPI remoteClient, UUID queryTargetID, string queryNotes)
- {
- if (queryTargetID == Constants.m_MrOpenSimID)
- return;
- ScenePresence p = FindPresence(queryTargetID);
- if (p != null && p.IsNPC)
- {
- remoteClient.SendAgentAlertMessage(
- "Notes for NPCs not available", false);
- return;
- }
- UserProfileNotes note = new UserProfileNotes();
- note.UserId = remoteClient.AgentId;
- note.TargetId = queryTargetID;
- note.Notes = queryNotes;
- string serverURI = string.Empty;
- GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
- if(string.IsNullOrWhiteSpace(serverURI))
- return;
- object Note = note;
- if(!rpc.JsonRpcRequest(ref Note, "avatar_notes_update", serverURI, UUID.Random().ToString()))
- {
- remoteClient.SendAgentAlertMessage(
- "Error updating note", false);
- return;
- }
- }
- #endregion Notes
- #region User Preferences
- /// <summary>
- /// Updates the user preferences.
- /// </summary>
- /// <param name='imViaEmail'>
- /// Im via email.
- /// </param>
- /// <param name='visible'>
- /// Visible.
- /// </param>
- /// <param name='remoteClient'>
- /// Remote client.
- /// </param>
- public void UpdateUserPreferences(bool imViaEmail, bool visible, IClientAPI remoteClient)
- {
- UserPreferences pref = new UserPreferences();
- pref.UserId = remoteClient.AgentId;
- pref.IMViaEmail = imViaEmail;
- pref.Visible = visible;
- string serverURI = string.Empty;
- bool foreign = GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
- if(string.IsNullOrWhiteSpace(serverURI))
- return;
- object Pref = pref;
- if(!rpc.JsonRpcRequest(ref Pref, "user_preferences_update", serverURI, UUID.Random().ToString()))
- {
- m_log.InfoFormat("[PROFILES]: UserPreferences update error");
- remoteClient.SendAgentAlertMessage("Error updating preferences", false);
- return;
- }
- }
- /// <summary>
- /// Users the preferences request.
- /// </summary>
- /// <param name='remoteClient'>
- /// Remote client.
- /// </param>
- public void UserPreferencesRequest(IClientAPI remoteClient)
- {
- UserPreferences pref = new UserPreferences();
- pref.UserId = remoteClient.AgentId;
- string serverURI = string.Empty;
- bool foreign = GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
- if(string.IsNullOrWhiteSpace(serverURI))
- return;
- object Pref = (object)pref;
- if(!rpc.JsonRpcRequest(ref Pref, "user_preferences_request", serverURI, UUID.Random().ToString()))
- {
- // m_log.InfoFormat("[PROFILES]: UserPreferences request error");
- // remoteClient.SendAgentAlertMessage("Error requesting preferences", false);
- return;
- }
- pref = (UserPreferences) Pref;
- remoteClient.SendUserInfoReply(pref.IMViaEmail, pref.Visible, pref.EMail);
- }
- #endregion User Preferences
- #region Avatar Properties
- /// <summary>
- /// Update the avatars interests .
- /// </summary>
- /// <param name='remoteClient'>
- /// Remote client.
- /// </param>
- /// <param name='wantmask'>
- /// Wantmask.
- /// </param>
- /// <param name='wanttext'>
- /// Wanttext.
- /// </param>
- /// <param name='skillsmask'>
- /// Skillsmask.
- /// </param>
- /// <param name='skillstext'>
- /// Skillstext.
- /// </param>
- /// <param name='languages'>
- /// Languages.
- /// </param>
- public void AvatarInterestsUpdate(IClientAPI remoteClient, uint wantmask, string wanttext, uint skillsmask, string skillstext, string languages)
- {
- GetUserProfileServerURI(remoteClient.AgentId, out string serverURI);
- if (string.IsNullOrWhiteSpace(serverURI))
- return;
- object Param = new UserProfileProperties()
- {
- UserId = remoteClient.AgentId,
- WantToMask = (int)wantmask,
- WantToText = wanttext,
- SkillsMask = (int)skillsmask,
- SkillsText = skillstext,
- Language = languages
- };
- if(!rpc.JsonRpcRequest(ref Param, "avatar_interests_update", serverURI, UUID.Random().ToString()))
- {
- remoteClient.SendAgentAlertMessage(
- "Error updating interests", false);
- return;
- }
- // flush cache
- lock(m_profilesCache)
- {
- if(m_profilesCache.TryGetValue(remoteClient.AgentId, out UserProfileCacheEntry uce) && uce != null)
- {
- uce.props = null;
- uce.ClientsWaitingProps = null;
- }
- }
- RequestAvatarProperties(remoteClient, remoteClient.AgentId);
- }
- public void RequestAvatarProperties(IClientAPI remoteClient, UUID avatarID)
- {
- if (avatarID.IsZero())
- {
- // Looking for a reason that some viewers are sending null Id's
- m_log.Debug("[PROFILES]: got request of null ID");
- return;
- }
- if (avatarID.Equals(Constants.m_MrOpenSimID))
- {
- remoteClient.SendAvatarProperties(avatarID, "Creator of OpenSimulator shared assets library", Constants.m_MrOpenSimBorn.ToString(),
- Utils.StringToBytes("System agent"), "MrOpenSim has no life", 0x10,
- UUID.Zero, UUID.Zero, "", UUID.Zero);
- remoteClient.SendAvatarInterestsReply(avatarID, 0, "",
- 0, "Getting into trouble", "Droidspeak");
- return;
- }
- ScenePresence p = FindPresence(avatarID);
- if (p != null && p.IsNPC)
- {
- remoteClient.SendAvatarProperties(avatarID, ((INPC)(p.ControllingClient)).profileAbout, ((INPC)(p.ControllingClient)).Born,
- Utils.StringToBytes("Non Player Character (NPC)"), "NPCs have no life", 0x10,
- UUID.Zero, ((INPC)(p.ControllingClient)).profileImage, "", UUID.Zero);
- remoteClient.SendAvatarInterestsReply(avatarID, 0, "",
- 0, "Getting into trouble", "Droidspeak");
- return;
- }
- UserProfileProperties props;
- lock(m_profilesCache)
- {
- if(m_profilesCache.TryGetValue(avatarID, out UserProfileCacheEntry uce) && uce != null)
- {
- if(uce.props != null)
- {
- props = uce.props;
- uint cflags = uce.flags;
- if (IsFriendOnline(remoteClient.AgentId, avatarID))
- cflags = (uint)ProfileFlags.Online;
- else
- cflags &= (uint)~ProfileFlags.Online;
- remoteClient.SendAvatarProperties(props.UserId, props.AboutText,
- uce.born, uce.membershipType , props.FirstLifeText, cflags,
- props.FirstLifeImageId, props.ImageId, props.WebUrl, props.PartnerId);
- remoteClient.SendAvatarInterestsReply(props.UserId, (uint)props.WantToMask,
- props.WantToText, (uint)props.SkillsMask,
- props.SkillsText, props.Language);
- if(uce.avatarGroups != null)
- remoteClient.SendAvatarGroupsReply(avatarID, uce.avatarGroups);
- return;
- }
- else
- {
- if(uce.ClientsWaitingProps == null)
- uce.ClientsWaitingProps = new HashSet<IClientAPI>();
- else if(uce.ClientsWaitingProps.Contains(remoteClient))
- return;
- uce.ClientsWaitingProps.Add(remoteClient);
- }
- }
- else
- {
- uce = new UserProfileCacheEntry();
- uce.ClientsWaitingProps = new HashSet<IClientAPI>();
- uce.ClientsWaitingProps.Add(remoteClient);
- m_profilesCache.AddOrUpdate(avatarID, uce, PROFILECACHEEXPIRE);
- }
- }
- AsyncPropsRequest req = new AsyncPropsRequest();
- req.client = remoteClient;
- req.presence = p;
- req.agent = avatarID;
- req.reqtype = 0;
- m_asyncRequests.Push(req);
- if (Monitor.TryEnter(m_asyncRequestsLock))
- {
- if (!m_asyncRequestsRunning)
- {
- m_asyncRequestsRunning = true;
- Util.FireAndForget(x => ProcessRequests());
- }
- Monitor.Exit(m_asyncRequestsLock);
- }
- }
- /// <summary>
- /// Updates the avatar properties.
- /// </summary>
- /// <param name='remoteClient'>
- /// Remote client.
- /// </param>
- /// <param name='newProfile'>
- /// New profile.
- /// </param>
- public void AvatarPropertiesUpdate(IClientAPI remoteClient, UserProfileProperties newProfile)
- {
- GetUserProfileServerURI(remoteClient.AgentId, out string serverURI);
- if (string.IsNullOrWhiteSpace(serverURI))
- return;
- if (!m_allowUserProfileWebURLs)
- newProfile.WebUrl = string.Empty;
- object Prop = newProfile;
- if(!rpc.JsonRpcRequest(ref Prop, "avatar_properties_update", serverURI, UUID.Random().ToString()))
- {
- remoteClient.SendAgentAlertMessage("Error updating properties", false);
- return;
- }
- // flush cache
- lock(m_profilesCache)
- {
- if(m_profilesCache.TryGetValue(remoteClient.AgentId, out UserProfileCacheEntry uce) && uce != null)
- {
- uce.props = null;
- uce.ClientsWaitingProps = null;
- }
- }
- RequestAvatarProperties(remoteClient, remoteClient.AgentId);
- }
- /// <summary>
- /// Gets the profile data.
- /// </summary>
- /// <returns>
- /// The profile data.
- /// </returns>
- bool GetProfileData(ref UserProfileProperties properties, bool foreign, string serverURI, out string message)
- {
- if (String.IsNullOrEmpty(serverURI))
- {
- message = "User profile service unknown at this time";
- return false;
- }
- object Prop = properties;
- if (!rpc.JsonRpcRequest(ref Prop, "avatar_properties_request", serverURI, UUID.Random().ToString()))
- {
- // If it's a foreign user then try again using OpenProfile, in case that's what the grid is using
- bool secondChanceSuccess = false;
- if (foreign)
- {
- try
- {
- OpenProfileClient client = new OpenProfileClient(serverURI);
- if (client.RequestAvatarPropertiesUsingOpenProfile(ref properties))
- secondChanceSuccess = true;
- }
- catch (Exception e)
- {
- m_log.Debug(
- string.Format(
- "[PROFILES]: Request using the OpenProfile API for user {0} to {1} failed",
- properties.UserId, serverURI),
- e);
- // Allow the return 'message' to say "JsonRpcRequest" and not "OpenProfile", because
- // the most likely reason that OpenProfile failed is that the remote server
- // doesn't support OpenProfile, and that's not very interesting.
- }
- }
- if (!secondChanceSuccess)
- {
- message = string.Format("JsonRpcRequest for user {0} to {1} failed", properties.UserId, serverURI);
- m_log.DebugFormat("[PROFILES]: {0}", message);
- return false;
- }
- }
- properties = (UserProfileProperties)Prop;
- if(foreign)
- {
- cacheForeignImage(properties.UserId, properties.ImageId);
- cacheForeignImage(properties.UserId, properties.FirstLifeImageId);
- }
- message = "Success";
- return true;
- }
- #endregion Avatar Properties
- #region Utils
- /// <summary>
- /// Gets the user account data.
- /// </summary>
- /// <returns>
- /// The user profile data.
- /// </returns>
- /// <param name='userID'>
- /// If set to <c>true</c> user I.
- /// </param>
- /// <param name='userInfo'>
- /// If set to <c>true</c> user info.
- /// </param>
- bool GetUserAccountData(UUID userID, out UserAccount account)
- {
- account = null;
- if (UserManagementModule.IsLocalGridUser(userID))
- {
- // Is local
- IUserAccountService uas = Scene.UserAccountService;
- account = uas.GetUserAccount(Scene.RegionInfo.ScopeID, userID);
- return account != null;
- }
- else
- {
- // Is Foreign
- string home_url = UserManagementModule.GetUserServerURL(userID, "HomeURI", out bool recentFailedWeb);
- if (recentFailedWeb || String.IsNullOrEmpty(home_url))
- return false;
- UserAgentServiceConnector uConn = new UserAgentServiceConnector(home_url);
- Dictionary<string, object> info;
- try
- {
- info = uConn.GetUserInfo(userID);
- }
- catch (Exception e)
- {
- m_log.Debug("[PROFILES]: GetUserInfo call failed ", e);
- UserManagementModule.UserWebFailed(userID);
- return false;
- }
- if (info.Count == 0)
- return false;
- account = new UserAccount();
- if (info.ContainsKey("user_flags"))
- account.UserFlags = (int)info["user_flags"];
- if (info.ContainsKey("user_created"))
- account.Created = (int)info["user_created"];
- account.UserTitle = "HG Visitor";
- return true;
- }
- }
- /// <summary>
- /// Gets the user profile server UR.
- /// </summary>
- /// <returns>
- /// The user profile server UR.
- /// </returns>
- /// <param name='userID'>
- /// If set to <c>true</c> user I.
- /// </param>
- /// <param name='serverURI'>
- /// If set to <c>true</c> server UR.
- /// </param>
- bool GetUserProfileServerURI(UUID userID, out string serverURI)
- {
- if (!UserManagementModule.IsLocalGridUser(userID))
- {
- serverURI = UserManagementModule.GetUserServerURL(userID, "ProfileServerURI", out bool failed);
- if(failed)
- serverURI = string.Empty;
- // Is Foreign
- return true;
- }
- else
- {
- serverURI = ProfileServerUri;
- // Is local
- return false;
- }
- }
- void cacheForeignImage(UUID agent, UUID imageID)
- {
- if(imageID.IsZero())
- return;
- string assetServerURI = UserManagementModule.GetUserServerURL(agent, "AssetServerURI");
- if(string.IsNullOrWhiteSpace(assetServerURI))
- return;
- Scene.AssetService.Get(imageID.ToString(), assetServerURI, false);
- }
- /// <summary>
- /// Finds the presence.
- /// </summary>
- /// <returns>
- /// The presence.
- /// </returns>
- /// <param name='clientID'>
- /// Client I.
- /// </param>
- ScenePresence FindPresence(UUID clientID)
- {
- ScenePresence p;
- p = Scene.GetScenePresence(clientID);
- if (p != null && !p.IsChildAgent)
- return p;
- return null;
- }
- public virtual bool IsFriendOnline(UUID client, UUID agent)
- {
- // if on same region force online
- ScenePresence p = Scene.GetScenePresence(agent);
- if (p != null && !p.IsDeleted)
- return true;
- IFriendsModule friendsModule = Scene.RequestModuleInterface<IFriendsModule>();
- if (friendsModule != null)
- {
- int friendPerms = friendsModule.GetRightsGrantedByFriend(client, agent);
- if((friendPerms & (int) FriendRights.CanSeeOnline) != 0)
- {
- Services.Interfaces.PresenceInfo[] pi = Scene.PresenceService?.GetAgents(new string[] { agent.ToString() });
- return pi != null && pi.Length > 0;
- }
- }
- return false;
- }
- #endregion Util
- #region Web Util
- /// <summary>
- /// Sends json-rpc request with a serializable type.
- /// </summary>
- /// <returns>
- /// OSD Map.
- /// </returns>
- /// <param name='parameters'>
- /// Serializable type .
- /// </param>
- /// <param name='method'>
- /// Json-rpc method to call.
- /// </param>
- /// <param name='uri'>
- /// URI of json-rpc service.
- /// </param>
- /// <param name='jsonId'>
- /// Id for our call.
- /// </param>
- bool JsonRpcRequest(ref object parameters, string method, string uri, string jsonId)
- {
- if (jsonId == null)
- throw new ArgumentNullException ("jsonId");
- if (uri == null)
- throw new ArgumentNullException ("uri");
- if (method == null)
- throw new ArgumentNullException ("method");
- if (parameters == null)
- throw new ArgumentNullException ("parameters");
- // Prep our payload
- OSDMap json = new OSDMap();
- json.Add("jsonrpc", OSD.FromString("2.0"));
- json.Add("id", OSD.FromString(jsonId));
- json.Add("method", OSD.FromString(method));
- json.Add("params", OSD.SerializeMembers(parameters));
- string jsonRequestData = OSDParser.SerializeJsonString(json);
- byte[] content = Encoding.UTF8.GetBytes(jsonRequestData);
- HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
- webRequest.ContentType = "application/json-rpc";
- webRequest.Method = "POST";
- WebResponse webResponse = null;
- try
- {
- using(Stream dataStream = webRequest.GetRequestStream())
- dataStream.Write(content,0,content.Length);
- webResponse = webRequest.GetResponse();
- }
- catch (WebException e)
- {
- Console.WriteLine("Web Error" + e.Message);
- Console.WriteLine ("Please check input");
- return false;
- }
- OSDMap mret = new OSDMap();
- using (Stream rstream = webResponse.GetResponseStream())
- {
- try
- {
- mret = (OSDMap)OSDParser.DeserializeJson(rstream);
- }
- catch (Exception e)
- {
- m_log.DebugFormat("[PROFILES]: JsonRpcRequest Error {0} - remote user with legacy profiles?", e.Message);
- if (webResponse != null)
- webResponse.Close();
- return false;
- }
- }
- if (webResponse != null)
- webResponse.Close();
- if (mret.ContainsKey("error"))
- return false;
- // get params...
- OSD.DeserializeMembers(ref parameters, (OSDMap) mret["result"]);
- return true;
- }
- /// <summary>
- /// Sends json-rpc request with OSD parameter.
- /// </summary>
- /// <returns>
- /// The rpc request.
- /// </returns>
- /// <param name='data'>
- /// data - incoming as parameters, outgong as result/error
- /// </param>
- /// <param name='method'>
- /// Json-rpc method to call.
- /// </param>
- /// <param name='uri'>
- /// URI of json-rpc service.
- /// </param>
- /// <param name='jsonId'>
- /// If set to <c>true</c> json identifier.
- /// </param>
- bool JsonRpcRequest(ref OSD data, string method, string uri, string jsonId)
- {
- OSDMap map = new OSDMap();
- map["jsonrpc"] = "2.0";
- if(string.IsNullOrEmpty(jsonId))
- map["id"] = UUID.Random().ToString();
- else
- map["id"] = jsonId;
- map["method"] = method;
- map["params"] = data;
- string jsonRequestData = OSDParser.SerializeJsonString(map);
- byte[] content = Encoding.UTF8.GetBytes(jsonRequestData);
- HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
- webRequest.ContentType = "application/json-rpc";
- webRequest.Method = "POST";
- WebResponse webResponse = null;
- try
- {
- using(Stream dataStream = webRequest.GetRequestStream())
- dataStream.Write(content,0,content.Length);
- webResponse = webRequest.GetResponse();
- }
- catch (WebException e)
- {
- Console.WriteLine("Web Error" + e.Message);
- Console.WriteLine ("Please check input");
- return false;
- }
- OSDMap response = new OSDMap();
- using (Stream rstream = webResponse.GetResponseStream())
- {
- try
- {
- response = (OSDMap)OSDParser.DeserializeJson(rstream);
- }
- catch (Exception e)
- {
- m_log.DebugFormat("[PROFILES]: JsonRpcRequest Error {0} - remote user with legacy profiles?", e.Message);
- if (webResponse != null)
- webResponse.Close();
- return false;
- }
- }
- if (webResponse != null)
- webResponse.Close();
- if(response.ContainsKey("error"))
- {
- data = response["error"];
- return false;
- }
- data = response;
- return true;
- }
- #endregion Web Util
- }
- }
|