aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Services/Connectors/SimianGrid/SimianProfiles.cs
blob: 32f17ae1053ae9a7de53117d1fb124cdcde1d1af (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
/*
 * 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.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Client;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;

namespace OpenSim.Services.Connectors.SimianGrid
{
    /// <summary>
    /// Avatar profile flags
    /// </summary>
    [Flags]
    public enum ProfileFlags : uint
    {
        AllowPublish = 1,
        MaturePublish = 2,
        Identified = 4,
        Transacted = 8,
        Online = 16
    }

    /// <summary>
    /// Connects avatar profile and classified queries to the SimianGrid
    /// backend
    /// </summary>
    [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")]
    public class SimianProfiles
    {
        private static readonly ILog m_log =
                LogManager.GetLogger(
                MethodBase.GetCurrentMethod().DeclaringType);

        private string m_serverUrl = String.Empty;

        #region INonSharedRegionModule

        public Type ReplaceableInterface { get { return null; } }
        public void RegionLoaded(Scene scene) { }
        public void Close() { }

        public SimianProfiles() { }
        public string Name { get { return "SimianProfiles"; } }
        public void AddRegion(Scene scene) { CheckEstateManager(scene); scene.EventManager.OnClientConnect += ClientConnectHandler; }
        public void RemoveRegion(Scene scene) { scene.EventManager.OnClientConnect -= ClientConnectHandler; }

        #endregion INonSharedRegionModule

        public SimianProfiles(IConfigSource source)
        {
            Initialise(source);
        }

        public void Initialise(IConfigSource source)
        {
            IConfig gridConfig = source.Configs["UserAccountService"];
            if (gridConfig == null)
            {
                m_log.Error("[PROFILES]: UserAccountService missing from OpenSim.ini");
                throw new Exception("Profiles init error");
            }

            string serviceUrl = gridConfig.GetString("UserAccountServerURI");
            if (String.IsNullOrEmpty(serviceUrl))
            {
                m_log.Error("[PROFILES]: No UserAccountServerURI in section UserAccountService");
                throw new Exception("Profiles init error");
            }

            if (!serviceUrl.EndsWith("/"))
                serviceUrl = serviceUrl + '/';

            m_serverUrl = serviceUrl;
        }

        private void ClientConnectHandler(IClientCore clientCore)
        {
            if (clientCore is IClientAPI)
            {
                IClientAPI client = (IClientAPI)clientCore;

                // Classifieds
                client.AddGenericPacketHandler("avatarclassifiedsrequest", AvatarClassifiedsRequestHandler);
                client.OnClassifiedInfoRequest += ClassifiedInfoRequestHandler;
                client.OnClassifiedInfoUpdate += ClassifiedInfoUpdateHandler;
                client.OnClassifiedDelete += ClassifiedDeleteHandler;

                // Picks
                client.AddGenericPacketHandler("avatarpicksrequest", HandleAvatarPicksRequest);
                client.AddGenericPacketHandler("pickinforequest", HandlePickInfoRequest);
                client.OnPickInfoUpdate += PickInfoUpdateHandler;
                client.OnPickDelete += PickDeleteHandler;

                // Notes
                client.AddGenericPacketHandler("avatarnotesrequest", HandleAvatarNotesRequest);
                client.OnAvatarNotesUpdate += AvatarNotesUpdateHandler;

                // Profiles
                client.OnRequestAvatarProperties += RequestAvatarPropertiesHandler;
                client.OnUpdateAvatarProperties += UpdateAvatarPropertiesHandler;
                client.OnAvatarInterestUpdate += AvatarInterestUpdateHandler;
                client.OnUserInfoRequest += UserInfoRequestHandler;
                client.OnUpdateUserInfo += UpdateUserInfoHandler;
            }
        }

        #region Classifieds

        private void AvatarClassifiedsRequestHandler(Object sender, string method, List<String> args)
        {
            if (!(sender is IClientAPI))
                return;
            IClientAPI client = (IClientAPI)sender;

            UUID targetAvatarID;
            if (args.Count < 1 || !UUID.TryParse(args[0], out targetAvatarID))
            {
                m_log.Error("[PROFILES]: Unrecognized arguments for " + method);
                return;
            }

            // FIXME: Query the generic key/value store for classifieds
            client.SendAvatarClassifiedReply(targetAvatarID, new Dictionary<UUID, string>(0));
        }

        private void ClassifiedInfoRequestHandler(UUID classifiedID, IClientAPI client)
        {
            // FIXME: Fetch this info
            client.SendClassifiedInfoReply(classifiedID, UUID.Zero, 0, Utils.DateTimeToUnixTime(DateTime.UtcNow + TimeSpan.FromDays(1)),
                0, String.Empty, String.Empty, UUID.Zero, 0, UUID.Zero, String.Empty, Vector3.Zero, String.Empty, 0, 0);
        }

        private void ClassifiedInfoUpdateHandler(UUID classifiedID, uint category, string name, string description,
            UUID parcelID, uint parentEstate, UUID snapshotID, Vector3 globalPos, byte classifiedFlags, int price,
            IClientAPI client)
        {
            // FIXME: Save this info
        }

        private void ClassifiedDeleteHandler(UUID classifiedID, IClientAPI client)
        {
            // FIXME: Delete the specified classified ad
        }

        #endregion Classifieds

        #region Picks

        private void HandleAvatarPicksRequest(Object sender, string method, List<String> args)
        {
            if (!(sender is IClientAPI))
                return;
            IClientAPI client = (IClientAPI)sender;

            UUID targetAvatarID;
            if (args.Count < 1 || !UUID.TryParse(args[0], out targetAvatarID))
            {
                m_log.Error("[PROFILES]: Unrecognized arguments for " + method);
                return;
            }

            // FIXME: Fetch these
            client.SendAvatarPicksReply(targetAvatarID, new Dictionary<UUID, string>(0));
        }

        private void HandlePickInfoRequest(Object sender, string method, List<String> args)
        {
            if (!(sender is IClientAPI))
                return;
            IClientAPI client = (IClientAPI)sender;

            UUID avatarID;
            UUID pickID;
            if (args.Count < 2 || !UUID.TryParse(args[0], out avatarID) || !UUID.TryParse(args[1], out pickID))
            {
                m_log.Error("[PROFILES]: Unrecognized arguments for " + method);
                return;
            }

            // FIXME: Fetch this
            client.SendPickInfoReply(pickID, avatarID, false, UUID.Zero, String.Empty, String.Empty, UUID.Zero, String.Empty,
                String.Empty, String.Empty, Vector3.Zero, 0, false);
        }

        private void PickInfoUpdateHandler(IClientAPI client, UUID pickID, UUID creatorID, bool topPick, string name,
            string desc, UUID snapshotID, int sortOrder, bool enabled)
        {
            // FIXME: Save this
        }

        private void PickDeleteHandler(IClientAPI client, UUID pickID)
        {
            // FIXME: Delete
        }

        #endregion Picks

        #region Notes

        private void HandleAvatarNotesRequest(Object sender, string method, List<String> args)
        {
            if (!(sender is IClientAPI))
                return;
            IClientAPI client = (IClientAPI)sender;

            UUID targetAvatarID;
            if (args.Count < 1 || !UUID.TryParse(args[0], out targetAvatarID))
            {
                m_log.Error("[PROFILES]: Unrecognized arguments for " + method);
                return;
            }

            // FIXME: Fetch this
            client.SendAvatarNotesReply(targetAvatarID, String.Empty);
        }

        private void AvatarNotesUpdateHandler(IClientAPI client, UUID targetID, string notes)
        {
            // FIXME: Save this
        }

        #endregion Notes

        #region Profiles

        private void RequestAvatarPropertiesHandler(IClientAPI client, UUID avatarID)
        {
            OSDMap user = FetchUserData(avatarID);

            ProfileFlags flags = ProfileFlags.AllowPublish | ProfileFlags.MaturePublish;

            if (user != null)
            {
                OSDMap about = null;
                if (user.ContainsKey("LLAbout"))
                {
                    try { about = OSDParser.DeserializeJson(user["LLAbout"].AsString()) as OSDMap; }
                    catch { }
                }

                if (about == null)
                    about = new OSDMap(0);

                // Check if this user is a grid operator
                byte[] charterMember;
                if (user["AccessLevel"].AsInteger() >= 200)
                    charterMember = Utils.StringToBytes("Operator");
                else
                    charterMember = Utils.EmptyBytes;

                // Check if the user is online
                if (client.Scene is Scene)
                {
                    OpenSim.Services.Interfaces.PresenceInfo[] presences = ((Scene)client.Scene).PresenceService.GetAgents(new string[] { avatarID.ToString() });
                    if (presences != null && presences.Length > 0)
                        flags |= ProfileFlags.Online;
                }

                // Check if the user is identified
                if (user["Identified"].AsBoolean())
                    flags |= ProfileFlags.Identified;

                client.SendAvatarProperties(avatarID, about["About"].AsString(), user["CreationDate"].AsDate().ToString("M/d/yyyy",
                    System.Globalization.CultureInfo.InvariantCulture), charterMember, about["FLAbout"].AsString(), (uint)flags,
                    about["FLImage"].AsUUID(), about["Image"].AsUUID(), about["URL"].AsString(), user["Partner"].AsUUID());

            }
            else
            {
                m_log.Warn("[PROFILES]: Failed to fetch profile information for " + client.Name + ", returning default values");
                client.SendAvatarProperties(avatarID, String.Empty, "1/1/1970", Utils.EmptyBytes,
                    String.Empty, (uint)flags, UUID.Zero, UUID.Zero, String.Empty, UUID.Zero);
            }
        }

        private void UpdateAvatarPropertiesHandler(IClientAPI client, UserProfileData profileData)
        {
            OSDMap map = new OSDMap
            {
                { "About", OSD.FromString(profileData.AboutText) },
                { "Image", OSD.FromUUID(profileData.Image) },
                { "FLAbout", OSD.FromString(profileData.FirstLifeAboutText) },
                { "FLImage", OSD.FromUUID(profileData.FirstLifeImage) },
                { "URL", OSD.FromString(profileData.ProfileUrl) }
            };

            AddUserData(client.AgentId, "LLAbout", map);
        }

        private void AvatarInterestUpdateHandler(IClientAPI client, uint wantmask, string wanttext, uint skillsmask,
            string skillstext, string languages)
        {
            OSDMap map = new OSDMap
            {
                { "WantMask", OSD.FromInteger(wantmask) },
                { "WantText", OSD.FromString(wanttext) },
                { "SkillsMask", OSD.FromInteger(skillsmask) },
                { "SkillsText", OSD.FromString(skillstext) },
                { "Languages", OSD.FromString(languages) }
            };

            AddUserData(client.AgentId, "LLInterests", map);
        }

        private void UserInfoRequestHandler(IClientAPI client)
        {
            m_log.Error("[PROFILES]: UserInfoRequestHandler");

            // Fetch this user's e-mail address
            NameValueCollection requestArgs = new NameValueCollection
            {
                { "RequestMethod", "GetUser" },
                { "UserID", client.AgentId.ToString() }
            };

            OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
            string email = response["Email"].AsString();

            if (!response["Success"].AsBoolean())
                m_log.Warn("[PROFILES]: GetUser failed during a user info request for " + client.Name);

            client.SendUserInfoReply(false, true, email);
        }

        private void UpdateUserInfoHandler(bool imViaEmail, bool visible, IClientAPI client)
        {
            m_log.Info("[PROFILES]: Ignoring user info update from " + client.Name);
        }

        #endregion Profiles

        /// <summary>
        /// Sanity checks regions for a valid estate owner at startup
        /// </summary>
        private void CheckEstateManager(Scene scene)
        {
            EstateSettings estate = scene.RegionInfo.EstateSettings;

            if (estate.EstateOwner == UUID.Zero)
            {
                // Attempt to lookup the grid admin
                UserAccount admin = scene.UserAccountService.GetUserAccount(scene.RegionInfo.ScopeID, UUID.Zero);
                if (admin != null)
                {
                    m_log.InfoFormat("[PROFILES]: Setting estate {0} (ID: {1}) owner to {2}", estate.EstateName,
                        estate.EstateID, admin.Name);

                    estate.EstateOwner = admin.PrincipalID;
                    estate.Save();
                }
                else
                {
                    m_log.WarnFormat("[PROFILES]: Estate {0} (ID: {1}) does not have an owner", estate.EstateName, estate.EstateID);
                }
            }
        }

        private bool AddUserData(UUID userID, string key, OSDMap value)
        {
            NameValueCollection requestArgs = new NameValueCollection
            {
                { "RequestMethod", "AddUserData" },
                { "UserID", userID.ToString() },
                { key, OSDParser.SerializeJsonString(value) }
            };

            OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
            bool success = response["Success"].AsBoolean();

            if (!success)
                m_log.WarnFormat("[PROFILES]: Failed to add user data with key {0} for {1}: {2}", key, userID, response["Message"].AsString());

            return success;
        }

        private OSDMap FetchUserData(UUID userID)
        {
            NameValueCollection requestArgs = new NameValueCollection
            {
                { "RequestMethod", "GetUser" },
                { "UserID", userID.ToString() }
            };

            OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
            if (response["Success"].AsBoolean() && response["User"] is OSDMap)
            {
                return (OSDMap)response["User"];
            }
            else
            {
                m_log.Error("[PROFILES]: Failed to fetch user data for " + userID + ": " + response["Message"].AsString());
            }

            return null;
        }
    }
}