aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region/CoreModules/Avatar/UserProfiles/UserProfileModule.cs
blob: 1ee2a7bb84506b2dfdf1446833122df6938d957b (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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
/*
 * 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.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Xml;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
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;

namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
{
    [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "UserProfilesModule")]
    public class UserProfileModule : IProfileModule, INonSharedRegionModule
    {
        /// <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.
        Dictionary<UUID, UUID> m_classifiedCache = new Dictionary<UUID, UUID>();
        Dictionary<UUID, int> m_classifiedInterest = new Dictionary<UUID, int>();

        private JsonRpcRequestManager rpc = new JsonRpcRequestManager();

        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;
        }


        #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 (ProfileServerUri == "")
            {
                Enabled = false;
                return;
            }
                
            m_log.Debug("[PROFILES]: 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;
            Scene.RegisterModuleInterface<IProfileModule>(this);
            Scene.EventManager.OnNewClient += OnNewClient;
            Scene.EventManager.OnMakeRootAgent += HandleOnMakeRootAgent;

            UserManagementModule = Scene.RequestModuleInterface<IUserManagement>();
        }

        void HandleOnMakeRootAgent (ScenePresence obj)
        {
            if(obj.PresenceType == PresenceType.Npc)
                return;

            Util.FireAndForget(delegate
            {
                GetImageAssets(((IScenePresence)obj).UUID);
            });
        }

        /// <summary>
        /// Removes the region.
        /// </summary>
        /// <param name='scene'>
        /// Scene.
        /// </param>
        public void RemoveRegion(Scene scene)
        {
            if(!Enabled)
                return;
        }

        /// <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;
        }

        /// <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()
        {
        }

        /// <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;
        }
        #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;

            UUID targetID;
            UUID.TryParse(args[0], out targetID);

            // Can't handle NPC yet...
            ScenePresence p = FindPresence(targetID);

            if (null != p)
            {
                if (p.PresenceType == PresenceType.Npc)
                    return;
            }

            string serverURI = string.Empty;
            GetUserProfileServerURI(targetID, out serverURI);
            UUID creatorId = UUID.Zero;
            Dictionary<UUID, string> classifieds = new Dictionary<UUID, string>();

            OSDMap parameters= new OSDMap();
            UUID.TryParse(args[0], out creatorId);
            parameters.Add("creatorId", OSD.FromUUID(creatorId));
            OSD Params = (OSD)parameters;
            if(!rpc.JsonRpcRequest(ref Params, "avatarclassifiedsrequest", serverURI, UUID.Random().ToString()))
            {
                remoteClient.SendAvatarClassifiedReply(new UUID(args[0]), classifieds);
                return;
            }

            parameters = (OSDMap)Params;

            OSDArray list = (OSDArray)parameters["result"];


            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,creatorId);
                        m_classifiedInterest.Add(cid, 0);
                    }

                    m_classifiedInterest[cid]++;
                }
            }

            remoteClient.SendAvatarClassifiedReply(new UUID(args[0]), 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);
                    }
                }
            }
            
            string serverURI = string.Empty;
            GetUserProfileServerURI(target, out serverURI);

            object Ad = (object)ad;
            if(!rpc.JsonRpcRequest(ref Ad, "classifieds_info_query", serverURI, UUID.Random().ToString()))
            {
                remoteClient.SendAgentAlertMessage(
                        "Error getting classified info", false);
                return;
            }
            ad = (UserClassifiedAdd) Ad;

            if(ad.CreatorId == UUID.Zero)
                return;

            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)
        {
            UserClassifiedAdd ad = new UserClassifiedAdd();

            Scene s = (Scene) remoteClient.Scene;
            Vector3 pos = remoteClient.SceneAgent.AbsolutePosition;
            ILandObject land = s.LandChannel.GetLandObject(pos.X, pos.Y);
            ScenePresence p = FindPresence(remoteClient.AgentId);
            
            string serverURI = string.Empty;
            GetUserProfileServerURI(remoteClient.AgentId, out serverURI);

            if (land == null)
            {
                ad.ParcelName = string.Empty;
            }
            else
            {
                ad.ParcelName = 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;

            OSD.SerializeMembers(Ad);

            if(!rpc.JsonRpcRequest(ref Ad, "classified_update", serverURI, UUID.Random().ToString()))
            {
                remoteClient.SendAgentAlertMessage(
                        "Error updating classified", false);
            }
        }

        /// <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;
            GetUserProfileServerURI(remoteClient.AgentId, out serverURI);

            UUID classifiedId;
            OSDMap parameters= new OSDMap();
            UUID.TryParse(queryClassifiedID.ToString(), out classifiedId);
            parameters.Add("classifiedId", OSD.FromUUID(classifiedId));
            OSD Params = (OSD)parameters;
            if(!rpc.JsonRpcRequest(ref Params, "classified_delete", serverURI, UUID.Random().ToString()))
            {
                remoteClient.SendAgentAlertMessage(
                        "Error classified delete", false);
            }

            parameters = (OSDMap)Params;
        }
        #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;
            UUID.TryParse(args[0], out targetId);

            // Can't handle NPC yet...
            ScenePresence p = FindPresence(targetId);

            if (null != p)
            {
                if (p.PresenceType == PresenceType.Npc)
                    return;
            }

            string serverURI = string.Empty;
            GetUserProfileServerURI(targetId, out serverURI);
            
            Dictionary<UUID, string> picks = new Dictionary<UUID, string>();

            OSDMap parameters= new OSDMap();
            parameters.Add("creatorId", OSD.FromUUID(targetId));
            OSD Params = (OSD)parameters;
            if(!rpc.JsonRpcRequest(ref Params, "avatarpicksrequest", serverURI, UUID.Random().ToString()))
            {
                remoteClient.SendAvatarPicksReply(new UUID(args[0]), picks);
                return;
            }

            parameters = (OSDMap)Params;

            OSDArray list = (OSDArray)parameters["result"];

            foreach(OSD map in list)
            {
                OSDMap m = (OSDMap)map;
                UUID cid = m["pickuuid"].AsUUID();
                string name = m["name"].AsString();
                
                m_log.DebugFormat("[PROFILES]: PicksRequest {0}", name);

                picks[cid] = name;
            }
            remoteClient.SendAvatarPicksReply(new UUID(args[0]), 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;

            UUID targetID;
            UUID.TryParse(args[0], out targetID);
            string serverURI = string.Empty;
            GetUserProfileServerURI(targetID, out serverURI);
            IClientAPI remoteClient = (IClientAPI)sender;

            UserProfilePick pick = new UserProfilePick();
            UUID.TryParse(args[0], out pick.CreatorId);
            UUID.TryParse(args[1], out pick.PickId);

                
            object Pick = (object)pick;
            if(!rpc.JsonRpcRequest(ref Pick, "pickinforequest", serverURI, UUID.Random().ToString()))
            {
                remoteClient.SendAgentAlertMessage(
                        "Error selecting pick", false);
            }
            pick = (UserProfilePick) Pick;
             
            Vector3 globalPos;
            Vector3.TryParse(pick.GlobalPos,out globalPos);

            m_log.DebugFormat("[PROFILES]: PickInfoRequest: {0} : {1}", pick.Name.ToString(), pick.SnapshotId.ToString());

            remoteClient.SendPickInfoReply(pick.PickId,pick.CreatorId,pick.TopPick,pick.ParcelId,pick.Name,
                                           pick.Desc,pick.SnapshotId,pick.User,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);
            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 landOwnerName = string.Empty;
            ILandObject land = p.Scene.LandChannel.GetLandObject(avaPos.X, avaPos.Y);

            if (land != null)
            {
                if (land.LandData.IsGroupOwned)
                {
                    IGroupsModule groupMod = p.Scene.RequestModuleInterface<IGroupsModule>();
                    UUID groupId = land.LandData.GroupID;
                    GroupRecord groupRecord = groupMod.GetGroupRecord(groupId);
                    landOwnerName = groupRecord.GroupName;
                }
                else
                {
                    IUserAccountService accounts = p.Scene.RequestModuleInterface<IUserAccountService>();
                    UserAccount user = accounts.GetUserAccount(p.Scene.RegionInfo.ScopeID, land.LandData.OwnerID);
                    landOwnerName = user.Name;
                }
            }
            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 = p.currentParcelUUID;
            pick.SnapshotId = snapshotID;
            pick.User = landOwnerName;
            pick.SimName = remoteClient.Scene.RegionInfo.RegionName;
            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);
            }

            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);

            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);
            }
        }
        #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;

            IClientAPI remoteClient = (IClientAPI)sender;
            string serverURI = string.Empty;
            GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
            note.UserId = remoteClient.AgentId;
            UUID.TryParse(args[0], out note.TargetId);

            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)
        {
            UserProfileNotes note = new UserProfileNotes();

            note.UserId = remoteClient.AgentId;
            note.TargetId = queryTargetID;
            note.Notes = queryNotes;

            string serverURI = string.Empty;
            GetUserProfileServerURI(remoteClient.AgentId, out serverURI);

            object Note = note;
            if(!rpc.JsonRpcRequest(ref Note, "avatar_notes_update", serverURI, UUID.Random().ToString()))
            {
                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);

            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);


            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)
        {
            UserProfileProperties prop = new UserProfileProperties();

            prop.UserId = remoteClient.AgentId;
            prop.WantToMask = (int)wantmask;
            prop.WantToText = wanttext;
            prop.SkillsMask = (int)skillsmask;
            prop.SkillsText = skillstext;
            prop.Language = languages;

            string serverURI = string.Empty;
            GetUserProfileServerURI(remoteClient.AgentId, out serverURI);

            object Param = prop;
            if(!rpc.JsonRpcRequest(ref Param, "avatar_interests_update", serverURI, UUID.Random().ToString()))
            {
                remoteClient.SendAgentAlertMessage(
                        "Error updating interests", false);
            }
        }

        public void RequestAvatarProperties(IClientAPI remoteClient, UUID avatarID)
        {
            if (String.IsNullOrEmpty(avatarID.ToString()) || String.IsNullOrEmpty(remoteClient.AgentId.ToString()))
            {
                // Looking for a reason that some viewers are sending null Id's
                m_log.DebugFormat("[PROFILES]: This should not happen remoteClient.AgentId {0} - avatarID {1}", remoteClient.AgentId, avatarID);
                return;
            }

            // Can't handle NPC yet...
            ScenePresence p = FindPresence(avatarID);

            if (null != p)
            {
                if (p.PresenceType == PresenceType.Npc)
                    return;
            }

            string serverURI = string.Empty;
            bool foreign = GetUserProfileServerURI(avatarID, out serverURI);

            UserAccount account = null;
            Dictionary<string,object> userInfo;

            if (!foreign)
            {
                account = Scene.UserAccountService.GetUserAccount(Scene.RegionInfo.ScopeID, avatarID);
            }
            else
            {
                userInfo = new Dictionary<string, object>();
            }

            Byte[] charterMember = new Byte[1];
            string born = String.Empty;
            uint flags = 0x00;

            if (null != account)
            {
                if (account.UserTitle == "")
                {
                    charterMember[0] = (Byte)((account.UserFlags & 0xf00) >> 8);
                }
                else
                {
                    charterMember = Utils.StringToBytes(account.UserTitle);
                }

                born = Util.ToDateTime(account.Created).ToString(
                                  "M/d/yyyy", CultureInfo.InvariantCulture);
                flags = (uint)(account.UserFlags & 0xff);
            }
            else
            {
                if (GetUserAccountData(avatarID, out userInfo) == true)
                {
                    if ((string)userInfo["user_title"] == "")
                    {
                        charterMember[0] = (Byte)(((Byte)userInfo["user_flags"] & 0xf00) >> 8);
                    }
                    else
                    {
                        charterMember = Utils.StringToBytes((string)userInfo["user_title"]);
                    }

                    int val_born = (int)userInfo["user_created"];
                    born = Util.ToDateTime(val_born).ToString(
                                  "M/d/yyyy", CultureInfo.InvariantCulture);

                    // picky, picky
                    int val_flags = (int)userInfo["user_flags"];
                    flags = (uint)(val_flags & 0xff);
                }
            }

            UserProfileProperties props = new UserProfileProperties();
            string result = string.Empty;

            props.UserId = avatarID;

            if (!GetProfileData(ref props, foreign, out result))
            {
                m_log.DebugFormat("Error getting profile for {0}: {1}", avatarID, result);
                return;
            }

            remoteClient.SendAvatarProperties(props.UserId, props.AboutText, born, charterMember , props.FirstLifeText, flags,
                                              props.FirstLifeImageId, props.ImageId, props.WebUrl, props.PartnerId);


            remoteClient.SendAvatarInterestsReply(props.UserId, (uint)props.WantToMask, props.WantToText, (uint)props.SkillsMask,
                                                  props.SkillsText, props.Language);
        }

        /// <summary>
        /// Updates the avatar properties.
        /// </summary>
        /// <param name='remoteClient'>
        /// Remote client.
        /// </param>
        /// <param name='newProfile'>
        /// New profile.
        /// </param>
        public void AvatarPropertiesUpdate(IClientAPI remoteClient, UserProfileData newProfile)
        {
            if (remoteClient.AgentId == newProfile.ID)
            {
                UserProfileProperties prop = new UserProfileProperties();

                prop.UserId = remoteClient.AgentId;
                prop.WebUrl = newProfile.ProfileUrl;
                prop.ImageId = newProfile.Image;
                prop.AboutText = newProfile.AboutText;
                prop.FirstLifeImageId = newProfile.FirstLifeImage;
                prop.FirstLifeText = newProfile.FirstLifeAboutText;

                string serverURI = string.Empty;
                GetUserProfileServerURI(remoteClient.AgentId, out serverURI);

                object Prop = prop;

                if(!rpc.JsonRpcRequest(ref Prop, "avatar_properties_update", serverURI, UUID.Random().ToString()))
                {
                    remoteClient.SendAgentAlertMessage(
                            "Error updating properties", false);
                }

                RequestAvatarProperties(remoteClient, newProfile.ID);
            }
        }

        /// <summary>
        /// Gets the profile data.
        /// </summary>
        /// <returns>
        /// The profile data.
        /// </returns>
        bool GetProfileData(ref UserProfileProperties properties, bool foreign, out string message)
        {
            // Can't handle NPC yet...
            ScenePresence p = FindPresence(properties.UserId);

            if (null != p)
            {
                if (p.PresenceType == PresenceType.Npc)
                {
                    message = "Id points to NPC";
                    return false;
                }
            }

            string serverURI = string.Empty;
            GetUserProfileServerURI(properties.UserId, out serverURI);

            // This is checking a friend on the home grid
            // Not HG friend
            if (String.IsNullOrEmpty(serverURI))
            {
                message = "No Presence - foreign friend";
                return false;
            }

            object Prop = (object)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("Request using the OpenProfile API to {0} failed", 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 to {0} failed", serverURI);
                    return false;
                }
                // else, continue below
            }
            
            properties = (UserProfileProperties)Prop;

            message = "Success";
            return true;
        }
        #endregion Avatar Properties

        #region Utils
        bool GetImageAssets(UUID avatarId)
        {
            string profileServerURI = string.Empty;
            string assetServerURI = string.Empty;

            bool foreign = GetUserProfileServerURI(avatarId, out profileServerURI);

            if(!foreign)
                return true;

            assetServerURI = UserManagementModule.GetUserServerURL(avatarId, "AssetServerURI");

            if(string.IsNullOrEmpty(profileServerURI) || string.IsNullOrEmpty(assetServerURI))
                return false;

            OSDMap parameters= new OSDMap();
            parameters.Add("avatarId", OSD.FromUUID(avatarId));
            OSD Params = (OSD)parameters;
            if(!rpc.JsonRpcRequest(ref Params, "image_assets_request", profileServerURI, UUID.Random().ToString()))
            {
                return false;
            }
            
            parameters = (OSDMap)Params;
            
            OSDArray list = (OSDArray)parameters["result"];
            
            foreach(OSD asset in list)
            {
                OSDString assetId = (OSDString)asset;

                Scene.AssetService.Get(string.Format("{0}/{1}",assetServerURI, assetId.AsString()));
            }
            return true;
        }

        /// <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 Dictionary<string, object> userInfo)
        {
            Dictionary<string,object> info = new Dictionary<string, object>();

            if (UserManagementModule.IsLocalGridUser(userID))
            {
                // Is local
                IUserAccountService uas = Scene.UserAccountService;
                UserAccount account = uas.GetUserAccount(Scene.RegionInfo.ScopeID, userID);

                info["user_flags"] = account.UserFlags;
                info["user_created"] = account.Created;

                if (!String.IsNullOrEmpty(account.UserTitle))
                    info["user_title"] = account.UserTitle;
                else
                    info["user_title"] = "";

                userInfo = info;

                return false;
            }
            else
            {
                // Is Foreign
                string home_url = UserManagementModule.GetUserServerURL(userID, "HomeURI");

                if (String.IsNullOrEmpty(home_url))
                {
                    info["user_flags"] = 0;
                    info["user_created"] = 0;
                    info["user_title"] = "Unavailable";

                    userInfo = info;
                    return true;
                }

                UserAgentServiceConnector uConn = new UserAgentServiceConnector(home_url);

                Dictionary<string, object> account;
                try
                {
                    account = uConn.GetUserInfo(userID);
                }
                catch (Exception e)
                {
                    m_log.Debug("[PROFILES]: GetUserInfo call failed ", e);
                    account = new Dictionary<string, object>();
                }

                if (account.Count > 0)
                {
                    if (account.ContainsKey("user_flags"))
                        info["user_flags"] = account["user_flags"];
                    else
                        info["user_flags"] = "";

                    if (account.ContainsKey("user_created"))
                        info["user_created"] = account["user_created"];
                    else
                        info["user_created"] = "";

                    info["user_title"] = "HG Visitor";
                }
                else
                {
                   info["user_flags"] = 0;
                   info["user_created"] = 0;
                   info["user_title"] = "HG Visitor";
                }
                userInfo = info;
                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)
        {
            bool local;
            local = UserManagementModule.IsLocalGridUser(userID);

            if (!local)
            {
                serverURI = UserManagementModule.GetUserServerURL(userID, "ProfileServerURI");
                // Is Foreign
                return true;
            }
            else
            {
                serverURI = ProfileServerUri;
                // Is local
                return 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;
        }
        #endregion Util
    }
}