Source

pyogp.lib.client / pyogp / lib / client / inventory.py

Full commit
   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

"""
Contributors can be viewed at:
http://svn.secondlife.com/svn/linden/projects/2008/pyogp/lib/base/trunk/CONTRIBUTORS.txt 

$LicenseInfo:firstyear=2008&license=apachev2$

Copyright 2009, Linden Research, Inc.

Licensed under the Apache License, Version 2.0.
You may obtain a copy of the License at:
    http://www.apache.org/licenses/LICENSE-2.0
or in 
    http://svn.secondlife.com/svn/linden/projects/2008/pyogp/lib/base/LICENSE.txt

$/LicenseInfo$
"""

# standard python libs
from logging import getLogger
import re, random

# related
import uuid
import struct

# pyogp
from pyogp.lib.base.datatypes import UUID
from pyogp.lib.client.exc import ResourceError, ResourceNotFound, DataParsingError
from pyogp.lib.client.datamanager import DataManager

# pyogp.message
from pyogp.lib.base.message.message import Message, Block

# pyogp utilities
from pyogp.lib.client.enums import ImprovedIMDialogue

# initialize logging
logger = getLogger('pyogp.lib.client.inventory')

# ToDo: handle library inventory properly. right now, it's treated as regular inv. store it in self.library_folders

class InventoryManager(DataManager):
    """ is an inventory container 

    Initialize the event queue client class
    >>> inventory = InventoryManager()

    Sample implementations: agent.py
    Tests: tests/test_inventory.py
    """

    def __init__(self, agent = None, settings = None):
        """ set up the inventory manager """
        super(InventoryManager, self).__init__(agent, settings)
        # For now, store the inventory contents in a list
        #     of folders with it's contents list containing it's inventory items
        # Ditto the library

        self.folders = []
        self.items = []
        self.library_folders = []

        # the root inventory and library root folder are special cases
        self.inventory_root = None
        self.library_root = None

        if self.settings.LOG_VERBOSE:
            logger.info("Initializing inventory storage")

    def enable_callbacks(self):
        """ enable monitors for certain inventory related packet events """

        onInventoryDescendents_received = self.agent.region.message_handler.register('InventoryDescendents')
        onInventoryDescendents_received.subscribe(self.onInventoryDescendents)

        onFetchInventoryReply_received = self.agent.region.message_handler.register('FetchInventoryReply')
        onFetchInventoryReply_received.subscribe(self.onFetchInventoryReply)

        onBulkUpdateInventory_received = self.agent.region.message_handler.register('BulkUpdateInventory')
        onBulkUpdateInventory_received.subscribe(self.onBulkUpdateInventory)

    def onInventoryDescendents(self, packet):

        raise NotImplemented("onInventoryDescendents")

    def onFetchInventoryReply(self, packet):

        raise NotImplemented("onFetchInventoryReply")

    def onBulkUpdateInventory(self, packet):
        """ handle the inventory data being delivered in the BullkUpdateInventory packet """

        for FolderData_block in packet['FolderData']:

            _FolderID = FolderData_block['FolderID']
            _ParentID = FolderData_block['ParentID']
            _Type = FolderData_block['Type']
            _Name = FolderData_block['Name']

            folder = InventoryFolder( _Name, _FolderID, _ParentID, None, _Type)

            self._store_inventory_folder(folder)

        for ItemData_block in packet['ItemData']:

            # what is CallbackID??? not doing anything with it.

            _ItemID = ItemData_block['ItemID']
            _FolderID = ItemData_block['FolderID']
            _CreatorID = ItemData_block['CreatorID']
            _OwnerID = ItemData_block['OwnerID']
            _GroupID = ItemData_block['GroupID']
            _BaseMask = ItemData_block['BaseMask']
            _OwnerMask = ItemData_block['OwnerMask']
            _GroupMask = ItemData_block['GroupMask']
            _EveryoneMask = ItemData_block['EveryoneMask']
            _NextOwnerMask = ItemData_block['NextOwnerMask']
            _GroupOwned = ItemData_block['GroupOwned']
            _AssetID = ItemData_block['AssetID']
            _Type = ItemData_block['Type']
            _InvType = ItemData_block['InvType']
            _Flags = ItemData_block['Flags']
            _SaleType = ItemData_block['SaleType']
            _SalePrice = ItemData_block['SalePrice']
            _Name = ItemData_block['Name']
            _Description = ItemData_block['Description']
            _CreationDate = ItemData_block['CreationDate']
            _CRC = ItemData_block['CRC']

            inventory_item = InventoryItem(_ItemID,
                                            _FolderID,
                                            _CreatorID,
                                            _OwnerID,
                                            _GroupID,
                                            _BaseMask,
                                            _OwnerMask,
                                            _GroupMask,
                                            _EveryoneMask,
                                            _NextOwnerMask,
                                            _GroupOwned,
                                            _AssetID,
                                            _Type,
                                            _InvType,
                                            _Flags,
                                            _SaleType,
                                            _SalePrice,
                                            _Name,
                                            _Description,
                                            _CreationDate,
                                            _CRC)

            self._store_inventory_item(inventory_item)

    def _parse_folders_from_login_response(self):
        """ the login response may contain inventory information, append data to our folders list """

        if self.settings.LOG_VERBOSE:
            logger.debug('Parsing the login response for inventory folders')

        if self.agent.login_response.has_key('inventory-skeleton'):
            [self._store_inventory_folder(folder, 'inventory') for folder in self.agent.login_response['inventory-skeleton']]

        if self.agent.login_response.has_key('inventory-skel-lib'):
            [self._store_inventory_folder(folder, 'library') for folder in self.agent.login_response['inventory-skel-lib']]

    def _store_inventory_item(self, inventory_item, destination = 'inventory'):
        """ inventory items comes from packets, or from caps """

        container = self.items
       # if destination == 'inventory':

       #     containter = self.items

       # elif destination == 'library':

       #     container = self.library_folders

       # else:

       #     logger.warning('Not storing folder data, as it\'s not bound for a valid destination.')
       #     return

        # replace an existing list member, else, append
        # for now, we are assuming the parent folder exists.
        # if it doesn't we'll know via traceback

        index = [container.index(item) for item in container if str(item.ItemID) == str(inventory_item.ItemID)]
        
        # did not find a folder for this item
        # this is probably a case we are not handling correctly
        if len(index) == 0:
            self.items.append(inventory_item)
#            if self.settings.LOG_VERBOSE:
#                logger.debug('Did not find parent folder %s for Inventory Item %s: %s' % (inventory_item.ItemID, inventory_item.FolderID, inventory_item.Name))
#            return
        else:
            self.items[index[0]] = inventory_item

        try:

            #inventory_index = [container[index].index(item) for item in container[index].inventory]
            #container[index[0]].inventory[inventory_index[0]] = inventory_item

            if self.settings.LOG_VERBOSE:
                logger.debug('Replacing a stored inventory item: %s' % (inventory_item.ItemID))

        except:

            container[index[0]].inventory.append(inventory_item)

            if self.settings.LOG_VERBOSE:
                logger.debug('Storing a new inventory item: %s ' % (inventory_item.ItemID))


    def search_inventory(self, folder_list = [], item_id = None, name = None,
                         match_list = []):
        """ search through all inventory folders for an id(uuid) or Name, and
        return a list of matching InventoryItems or InventoryFolders

        recursive search, based on folder_id. if no folder id is specified
        look through everything in self.folders

        This does not request inventory from the grid. It could, were we to go about enabling this...
        """ 

        def match():
            _match = lambda arg : False
            if item_id != None:
                def _match(arg):
                    if isinstance(arg, InventoryItem):
                        return str(arg.ItemID) == str(item_id)
                    else:
                        return str(arg.FolderID) == str(item_id)
            elif name != None:
                pattern = re.compile(name)
                def _match(arg):
                    if pattern.match(arg.Name):
                        return True
                    else:
                        return False
            return _match

        is_match = match()

        # search our inventory storage if we aren't told what to look in
        if folder_list == []:
            search_folders = self.folders
        else:
            search_folders = folder_list

        for item in search_folders:
            if is_match(item):
                match_list.append(item)
            if isinstance(item, InventoryFolder):
                matches = self.search_inventory_folder(folder_list,
                                                       item.FolderID,
                                                       _id=item_id,
                                                       name=name)
                match_list.extend(matches)
        return match_list

    def search_inventory_folder(self, folder_list, folder_id, _id = None, name = None):
        """ search an inventory folder for _id or name

        return a list of matches
        """ 

        match_list = []

        search_folder = [folder for folder in folder_list if str(folder.FolderID) == str(folder_id)][0]

        for item in search_folder.inventory:

            if _id != None:

                if isinstance(item, InventoryItem):
                    if str(item.ItemID) == str(_id):
                        match_list.append(item)
                elif isinstance(item, InventoryFolder):
                    if str(item.FolderID) == str(_id):
                        match_list.append(item)

            elif name != None:

                pattern = re.compile(name)

                if pattern.match(item.Name):
                    match_list.append(item)

        return match_list

    def _store_inventory_folder(self, folder_data, destination = 'inventory'):
        """ inventory folder data comes from either packets or login, or from caps. destination is either 'inventory' or 'library' """

        if destination == 'inventory':

            container = self.folders

        elif destination == 'library':

            container = self.library_folders

        else:

            logger.warning('Not storing folder data, as it\'s not bound for a valid destination.')
            return

        # if it's a dict, we are parsing login response data or a caps response
        # transform to an InventoryFolder() instance and store it if we havne't already stored it, otherwise, update the params
        if type(folder_data) == dict:

            if folder_data.has_key('category_id'):

                # this is from caps

                folder = InventoryFolder(folder_data['name'], folder_data['category_id'], folder_data['parent_id'], folder_data['version'], folder_data['type_default'], folder_data['agent_id'])

            else:

                # this is from login inv skeleton

                folder = InventoryFolder(folder_data['name'], folder_data['folder_id'], folder_data['parent_id'], folder_data['version'], folder_data['type_default'])
            folder_name = folder_data['name']
            parent_id = folder_data['parent_id']

        elif isinstance(folder_data, InventoryFolder):

            folder = folder_data
            folder_name = folder.Name
            parent_id = str(folder.ParentID)

        # see if we have already stored this folder
        index = [container.index(target_folder) for target_folder in container if str(folder.FolderID) == str(target_folder.FolderID)]

        # skip storing folders we already know about
        if len(index) == 1:

            # we may be receiving an update to the folder attributes, if so, save off the contents, swap in the new representation, then append the contents

            if self.settings.LOG_VERBOSE: logger.debug('Replacing a stored inventory folder: %s for agent \'%s\'' % (folder.FolderID, self.agent.agent_id))

            contents = container[index[0]].inventory

            cached_folder = container[index[0]] 

            if cached_folder.Descendents > -1: 
                folder.Descendents = cached_folder.Descendents 

            container[index[0]] = folder

            container[index[0]].inventory = contents

        else:

            if self.settings.LOG_VERBOSE: logger.debug("Storing inventory folder %s" % (folder.Name))

            if parent_id == '00000000-0000-0000-0000-000000000000' and folder_name == 'My Inventory':

                self.inventory_root = folder

            elif parent_id == '00000000-0000-0000-0000-000000000000' and folder_name == 'Library':

                self.library_root = folder

            container.append(folder)

    def display_folder_contents(self, folder_id = None):
        """ returns a list of the local representation of a folder's contents """

        if folder_id != None:

            return [member for member in self.folders if str(member.ParentID) == str(folder_id)]

        # the name case is not handled at this time
        '''
        elif name != None:

            folder_ids = [member.folder_id for member in self.contents if member.name == name]

            return [member for member in self.contents if member.name == name]
        '''

    def request_known_folder_contents(self, folder_id = None):
        """ send requests to the server for contents of all known folders """

        [self.inventory._request_folder_contents(folder.FolderID) for folder in self.inventory.folders if str(folder.ParentID) == str(self.inventory.inventory_root.FolderID)]

    def _request_folder_contents(self, folder_id = None, source = 'inventory'):
        """ send a request to the server for folder contents, wraps sendFetchInventoryDescendentsPacket """

        if source == 'inventory':

            self.sendFetchInventoryDescendentsRequest(folder_id = folder_id)

        elif source == 'library':

            self.sendFetchLibDescendentsRequest(folder_id = folder_id)

    def request_inventory_by_id(self, id_list = None):
        """ ask for inventory data by id via a list """

        if id_list != None:

            self.send_FetchInventory(self.agent.agent_id, self.agent.session_id, self.agent.agent_id, id_list)

    def send_FetchInventory(self, agent_id, session_id, owner_id, inventory_ids):
        """
        send a FetchInventory message to the host simulator 
        each of the ids in inventory_ids will be sent in it's own InventoryData block
        """

        packet = Message('FetchInventory',
                        Block('AgentData',
                                AgentID = agent_id,
                                SessionID = session_id),
                        *[Block('InventoryData',
                                OwnerID = owner_id,
                                ItemID = item_id) for item_id in inventory_ids])

        # enqueue the message
        self.region.enqueue_message(packet)

    def give_inventory(self, ItemID = None, agent_id = None):
        """ offers another agent the specified inventory item 

        searches the local inventory for the specified ItemID
        given a match, sends an ImprovedInventoryMessage packet to the specified AgentID
        """

        if not (ItemID or agent_id):
            logger.warning("ItemID and agent_id are required in InventoryManager().give_inventory()")
            return

        item_id = self.search_inventory(item_id = ItemID)

        if item_id == []:
            logger.warning("ItemID %s not found in inventory of %s" % (ItemID, self.agent.Name()))
            return
        elif len(item_id) > 1:
            logger.warning("Multiple matches in inventory for ItemID %s, using the first one in InventoryManager().give_inventory()" % (ItemID))

        inv_item = item_id[0]

        inv_item.give(self.agent, agent_id)

    def handle_inventory_offer(self, packet):
        """ parses and handles an incoming inventory offer """

        FromAgentID = packet['AgentData'][0]['AgentID']
        FromAgentName = packet['MessageBlock'][0]['FromAgentName']
        InventoryName = packet['MessageBlock'][0]['Message']
        ID = packet['MessageBlock'][0]['ID']
        _Message = packet['MessageBlock'][0]['Message']
        ToAgentID = packet['MessageBlock'][0]['ToAgentID']

        BinaryBucket = packet['MessageBlock'][0]['BinaryBucket']

        # parse the binary bucket
        AssetType = struct.unpack(">b", BinaryBucket[0:1])[0]
        ItemID =  UUID(BinaryBucket[1:17])

        if str(FromAgentID) == str(self.agent.agent_id):

            logger.info("%s offered inventory to %s" % (self.agent.Name(), ToAgentID))

        else:

            logger.info("%s received an inventory offer from %s for %s." % (self.agent.Name(), FromAgentName, InventoryName))

            if self.settings.LOG_VERBOSE:
                logger.debug("Inventory offer data. \n\tFromAgentID: %s \n\tFromAgentName: %s \n\tInventoryName: %s \n\tID: %s \n\tAssetType: %s \n\tItemID: %s \n\tMessage: %s" % (FromAgentID, FromAgentName, InventoryName, ID, AssetType, ItemID, Message))

        if self.agent.settings.ACCEPT_INVENTORY_OFFERS:

            accept = True

        else:

            accept = False

        self.confirm_inventory_offer(FromAgentID, FromAgentName, InventoryName, ID, AssetType, ItemID, accept)

    def confirm_inventory_offer(self, FromAgentID, FromAgentName, InventoryName, ID, AssetType, ItemID, accept):
        """ sends an ImprovedInstantMessage packet accepting or declining an inventory offer """

        if accept:
            accept_key = ImprovedIMDialogue.InventoryAccepted
            logger.info("Sending an inventory accepted message to %s for item %s(%s)" % (FromAgentName, InventoryName, ID))
        else:
            accept_key = ImprovedIMDialogue.InventoryDeclined
            logger.info("Sending an inventory declined message to %s for item %s(%s)" % (FromAgentName, InventoryName, ID))

        self.agent.send_ImprovedInstantMessage(self.agent.agent_id, self.agent.session_id, 0, FromAgentID, 0, UUID(), self.agent.Position, 0, accept_key, ID, 0, self.agent.Name(), '', '')

    def create_new_item(self, folder, name, desc, asset_type, inv_type,
                        wearable_type, next_owner_permission, callback=None):
        """
        Creates a new item in folder.
        """
        transaction_id = UUID()
        transaction_id.random()

        updateCreateInventoryHandler = self.agent.region.message_handler.register('UpdateCreateInventoryItem')

        def onUpdateCreateInventoryItem(packet):
            if str(transaction_id) != str(packet['AgentData'][0]['TransactionID']):
                inv_data = packet['InventoryData'][0]
                item = InventoryItem(inv_data['ItemID'],
                                     inv_data['FolderID'],
                                     inv_data['CreatorID'],
                                     inv_data['OwnerID'],
                                     inv_data['GroupID'],
                                     inv_data['BaseMask'],
                                     inv_data['OwnerMask'],
                                     inv_data['GroupMask'],
                                     inv_data['EveryoneMask'],
                                     inv_data['NextOwnerMask'],
                                     inv_data['GroupOwned'],
                                     inv_data['AssetID'],
                                     inv_data['Type'],
                                     inv_data['InvType'],
                                     inv_data['Flags'],
                                     inv_data['SaleType'],
                                     inv_data['SalePrice'],
                                     inv_data['Name'],
                                     inv_data['Description'],
                                     inv_data['CreationDate'],
                                     inv_data['CRC'])

                self._store_inventory_item(item)
                updateCreateInventoryHandler.unsubscribe(onUpdateCreateInventoryItem)
                if callback != None:
                    callback(item)

        updateCreateInventoryHandler.subscribe(onUpdateCreateInventoryItem) 

        self.send_CreateInventoryItem(self.agent.agent_id,
                                      self.agent.session_id,
                                      0,
                                      folder.FolderID,
                                      transaction_id,
                                      next_owner_permission,
                                      asset_type,
                                      inv_type,
                                      wearable_type,
                                      name,
                                      desc)

    def send_CreateInventoryItem(self, agent_id, session_id, callback_id,
                                 folder_id, transaction_id, next_owner_mask,
                                 type_, inv_type, wearable_type, name, desc):
        """ sends a CreateInventoryItem message """
        args = [Block('AgentData',
                      AgentID = agent_id,
                      SessionID = session_id)]
        args += [Block('InventoryBlock',
                       CallbackID = callback_id,
                       FolderID = folder_id,
                       TransactionID = transaction_id,
                       NextOwnerMask = next_owner_mask,
                       Type = type_,
                       InvType = inv_type,
                       WearableType = wearable_type,
                       Name = name,
                       Description = desc)]
        self.agent.region.enqueue_message(Message("CreateInventoryItem", *args))

    def remove_inventory_item(self, item, folder,
                              folder_list):
        folder.inventory.remove(item)
        self.send_RemoveInventoryItem(self.agent.agent_id,
                                      self.agent.session_id,
                                      item.ItemID)
    
    def send_RemoveInventoryItem(self, agent_id, session_id, item_id):
        """ sends a RemoveInventoryItem message """
        idx = 0
        for _item in self.items: 
            idx += 1
            if str(_item.ItemID) == str(item_id):
                del self.items[idx]
                break

        args = [Block('AgentData',
                      AgentID = agent_id,
                      SessionID = session_id)]
        args += [Block('InventoryData',
                       ItemID = item_id)]
        self.agent.region.enqueue_message(Message("RemoveInventoryItem", *args))
        
    def sendFetchInventoryDescendentsRequest(self, folder_id = None):
        """ send a request to the grid for folder contents """

        raise NotImplemented("sendFetchInventoryDescendentsRequest")

    def sendFetchInventoryRequest(self, folder_id = None):
        """ send a request to the grid for inventory items in folder """

        raise NotImplemented("sendFetchInventoryRequest")

    def sendFetchLibRequest(self, item_id = None):
        """ send a request to the grid for library items """

        raise NotImplemented("sendFetchLibRequest")

    def sendFetchLibDescendentsRequest(self, item_id = None):
        """ send a request to the grid for library folder contents """

        raise NotImplemented("sendFetchDescendentsRequest")

class AIS(InventoryManager):
    """ AIS specific inventory manager """

    def __init__(self, agent, capabilities, settings = None):

        super(AIS, self).__init__(agent, settings)

        self.capabilities = capabilities

    def sendFetchInventoryRequest(self, item_ids = []):
        """ send a request to the grid for inventory item attributes """

        if len(item_ids) == 0:
            logger.warning("sendFetchInventoryRequest requires > 0 item_ids, 0 passed in")
            return
        elif type(item_ids) != list:
            logger.warning("sendFetchInventoryRequest requires a list of item_ids, %s passed in" % (type(item_ids)))
            return            

        cap = self.capabilities['FetchInventory']

        post_body = {'items': [{'item_id': str(item_id)} for item_id in item_ids]}

        custom_headers = {'Accept' : 'application/llsd+xml'}

        try:
            result = cap.POST(post_body, custom_headers)
        except ResourceError, error:
            logger.error(error)
            return
        except ResourceNotFound, error:
            logger.error("404 calling: %s" % (error))
            return

        for item in response['folders']:

            self._store_caps_items(item, folder_id)

    def sendFetchLibRequest(self, folder_id, item_ids = []):
        """ send a request to the grid for library item attributes """

        if len(item_ids) == 0:
            logger.warning("sendFetchLibRequest requires > 0 item_ids, 0 passed in")
            return
        elif type(item_ids) != list:
            logger.warning("sendFetchLibRequest a list of item_ids, %s passed in" % (type(item_ids)))
            return            

        cap = self.capabilities['FetchLib']

        post_body = {'items': [{'item_id': str(item_id)} for item_id in item_ids]}

        custom_headers = {'Accept' : 'application/llsd+xml'}

        try:
            result = cap.POST(post_body, custom_headers)
        except ResourceError, error:
            logger.error(error)
            return
        except ResourceNotFound, error:
            logger.error("404 calling: %s" % (error))
            return

        for item in response['folders']:

            self._store_caps_items(item, folder_id, 'library')

    def sendFetchInventoryDescendentsRequest(self, folder_id):
        """ send a request to the server for inventory folder contents """

        cap = self.capabilities['WebFetchInventoryDescendents']

        post_body = {'folders': [{'folder_id': str(folder_id), 'owner_id': str(self.agent.agent_id)}]}

        custom_headers = {'Accept' : 'application/llsd+xml'}

        try:
            response = cap.POST(post_body, custom_headers)
        except ResourceError, error:
            logger.error(error)
            return
        except ResourceNotFound, error:
            logger.error("404 calling: %s" % (error))
            return

        '''
        Response shape

        {'folders':[ {'category': CATEGORY_SHAPE,
                'categories': [CATEGORY_SHAPE,],
                'items': [ITEM_SHAPE,] }]}
        '''

        for member in response['folders']:

            if member.has_key('category'):
                self._store_inventory_folder(member['category'])

            if member.has_key('categories'):
                [self._store_inventory_folder(folder_info) for folder_info in member['categories']]

            # pass a tuple of (item_info, category_id)
            if member.has_key('items'):
                self._store_caps_items(member['items'], member['category']['category_id'])

    def _store_caps_items(self, items, folder_id, destination = 'inventory'):
        """ transform an AIS caps response's inventory items and folder_id to InventoryItems and store it """

        for item in items:
            inventory_item = InventoryItem(item['item_id'], folder_id, item['permissions']['creator_id'], item['permissions']['owner_id'], item['permissions']['group_id'], item['permissions']['base_mask'], item['permissions']['owner_mask'], item['permissions']['group_mask'], item['permissions']['everyone_mask'], item['permissions']['next_owner_mask'], None, item['asset_id'], item['type'], item['inv_type'], item['flags'], item['sale_info']['sale_type'], item['sale_info']['sale_price'], item['name'], item['desc'], item['created_at'], None, item['permissions']['last_owner_id'])

            self._store_inventory_item(inventory_item, destination)

    def sendFetchLibDescendentsRequest(self, folder_id):
        """ send a request to the server for folder contents """

        cap = self.capabilities['FetchLibDescendents']

        post_body = {'folders': [{'folder_id': str(folder_id), 'owner_id': self.settings.ALEXANDRIA_LINDEN}]}

        custom_headers = {'Accept' : 'application/llsd+xml'}

        try:
            response = cap.POST(post_body, custom_headers)
        except ResourceError, error:
            logger.error(error)
            return
        except ResourceNotFound, error:
            logger.error("404 calling: %s" % (error))
            return

        '''
        Response shape

        {'folders':[ {'category': CATEGORY_SHAPE,
                 'categories': [CATEGORY_SHAPE,],
                 'items': [ITEM_SHAPE,] }]}
        '''

        for member in response['folders']:

            if member.has_key('category'):
                self._store_inventory_folder(member['category'], 'library')

            if member.has_key('categories'):
                [self._store_inventory_folder(folder_info, 'library') for folder_info in member['categories']]

            if member.has_key('items'):
                self._store_caps_items(member['items'], member['category']['category_id'], 'library')


class UDP_Inventory(InventoryManager):

    def __init__(self, agent, settings = None):

        super(UDP_Inventory, self).__init__(agent, settings)

    def sendFetchInventoryRequest(self, folder_id = None):
        """ send a request to the grid for folder attributes """

        raise NotImplemented("sendFetchInventoryRequest")

    def sendFetchLibRequest(self, item_id = None):
        """ send a request to the grid for library items """

        raise NotImplemented("sendFetchInventoryRequest")

    def sendFetchInventoryDescendentsRequest(self, folder_id = None):
        """ send a request to the grid for folder contents """

        packet = Message('FetchInventoryDescendents',
                        Block('AgentData',
                                AgentID = self.agent.agent_id,          # MVT_LLUUID
                                SessionID = self.agent.session_id),     # MVT_LLUUID
                        Block('InventoryData',
                                FolderID = UUID(str(folder_id)),        # MVT_LLUUID
                                OwnerID = self.agent.agent_id,          # MVT_LLUUID
                                SortOrder = 0,                          # MVT_S32, 0 = name, 1 = time
                                FetchFolders = True,                    # MVT_BOOL
                                FetchItems = True))                     # MVT_BOOL

        self.agent.region.enqueue_message(packet)

    def sendFetchLibDescendentsRequest(self, folder_id = None):
        """ send a request to the grid for library items """

        raise NotImplemented("sendFetchLibDescendentsRequest")

    def onFetchInventoryReply(self, packet):

        _agent_id = packet['AgentData'][0]['AgentID']

        for InventoryData_block in packet['InventoryData']:

            _ItemID = InventoryData_block['ItemID']
            _FolderID = InventoryData_block['FolderID']
            _CreatorID = InventoryData_block['CreatorID']
            _OwnerID = InventoryData_block['OwnerID']
            _GroupID = InventoryData_block['GroupID']
            _BaseMask = InventoryData_block['BaseMask']
            _OwnerMask = InventoryData_block['OwnerMask']
            _GroupMask = InventoryData_block['GroupMask']
            _EveryoneMask = InventoryData_block['EveryoneMask']
            _NextOwnerMask = InventoryData_block['NextOwnerMask']
            _GroupOwned = InventoryData_block['GroupOwned']
            _AssetID = InventoryData_block['AssetID']
            _Type = InventoryData_block['Type']
            _InvType = InventoryData_block['InvType']
            _Flags = InventoryData_block['Flags']
            _SaleType = InventoryData_block['SaleType']
            _SalePrice = InventoryData_block['SalePrice']
            _Name = InventoryData_block['Name']
            _Description = InventoryData_block['Description']
            _CreationDate = InventoryData_block['CreationDate']
            _CRC = InventoryData_block['CRC']

            inventory_item = InventoryItem(_ItemID, _FolderID, _CreatorID, _OwnerID, _GroupID, _BaseMask, _OwnerMask, _GroupMask, _EveryoneMask, _NextOwnerMask, _GroupOwned, _AssetID, _Type, _InvType, _Flags, _SaleType, _SalePrice, _Name, _Description, _CreationDate, _CRC)

            self._store_inventory_item(inventory_item)

    def onInventoryDescendents(self, packet):

        for folder in self.folders:
            if str(folder.FolderID) == str(packet['AgentData'][0]['FolderID']):
                folder.Descendents = packet['AgentData'][0]['Descendents']
                break

        if packet['AgentData'][0]['Descendents'] > 0:

            _agent_id = packet['AgentData'][0]['AgentID']
            _folder_id = packet['AgentData'][0]['FolderID']
            _owner_id = packet['AgentData'][0]['OwnerID']
            _version = packet['AgentData'][0]['Version']
            _descendents = packet['AgentData'][0]['Descendents']
            # _descendents is not dealt with in any way here


            if str(packet['ItemData'][0]['ItemID']) != str(UUID()):

                for ItemData_block in packet['ItemData']:

                    _ItemID = ItemData_block['ItemID']
                    _FolderID = ItemData_block['FolderID']
                    _CreatorID = ItemData_block['CreatorID']
                    _OwnerID = ItemData_block['OwnerID']
                    _GroupID = ItemData_block['GroupID']
                    _BaseMask = ItemData_block['BaseMask']
                    _OwnerMask = ItemData_block['OwnerMask']
                    _GroupMask = ItemData_block['GroupMask']
                    _EveryoneMask = ItemData_block['EveryoneMask']
                    _NextOwnerMask = ItemData_block['NextOwnerMask']
                    _GroupOwned = ItemData_block['GroupOwned']
                    _AssetID = ItemData_block['AssetID']
                    _Type = ItemData_block['Type']
                    _InvType = ItemData_block['InvType']
                    _Flags = ItemData_block['Flags']
                    _SaleType = ItemData_block['SaleType']
                    _SalePrice = ItemData_block['SalePrice']
                    _Name = ItemData_block['Name']
                    _Description = ItemData_block['Description']
                    _CreationDate = ItemData_block['CreationDate']
                    _CRC = ItemData_block['CRC']

                    inventory_item = InventoryItem(_ItemID, _FolderID, _CreatorID, _OwnerID, _GroupID, _BaseMask, _OwnerMask, _GroupMask, _EveryoneMask, _NextOwnerMask, _GroupOwned, _AssetID, _Type, _InvType, _Flags, _SaleType, _SalePrice, _Name, _Description, _CreationDate, _CRC)

                    self._store_inventory_item(inventory_item)

            if str(packet['FolderData'][0]['FolderID']) != str(UUID()):

                for FolderData_block in packet['FolderData']:

                    _FolderID = FolderData_block['FolderID']
                    _ParentID = FolderData_block['ParentID']
                    _Type = FolderData_block['Type']
                    _Name = FolderData_block['Name']

                    folder = InventoryFolder( _Name, _FolderID, _ParentID, None, _Type, _agent_id)

                    self._store_inventory_folder(folder)

class InventoryFolder(object):
    """ represents an Inventory folder 

    Sample implementations: inventory.py
    Tests: tests/test_inventory.py
    """

    def __init__(self, Name = None, FolderID = None, ParentID = None, Version = None, Type = None, AgentID = UUID(), Descendents = -1):
        """ initialize the inventory folder """

        self.type = 'InventoryFolder'

        self.Name = Name
        self.FolderID = UUID(str(FolderID))
        self.ParentID = UUID(str(ParentID))
        self.Version = Version
        self.Type = Type
        self.Descendents = Descendents
        self.AgentID = UUID(str(AgentID))

        self.inventory = []

    def purge_descendents(self, agent):
        """ removes inventory from this folder, by unlinking the inventory from this parent folder """

        self.send_PurgeInventoryDescendents(agent.agent_id, agent.session_id, self.FolderID)

    def send_PurgeInventoryDescendents(self, agent, agent_id, session_id, folder_id):
        """ send a PurgeInventoryDescendents message to the host simulator """

        packet = Message('PurgeInventoryDescendents',
                        Block('AgentData',
                                AgentID = agent_id,
                                SessionID = session_id),
                        Block('InventoryData',
                                FolderID = folder_id))

        agent.region.enqueue_message(packet)

    def move(self, agent, parent_id, restamp = False):
        """ reparents this inventory folder """

        self.send_MoveInventoryFolder(agent, agent.agent_id, agent.session_id, restamp, self.FolderID, UUID(str(parent_id)))

    def send_MoveInventoryFolder(self, agent, agent_id, session_id, restamp, folder_id, parent_id):
        """ sends a MoveInventoryFolder message to the host simulator """

        # ToDo: the InventoryData block may the variable, if moved to a more
        # generic location (not nested under Inventory folder),
        # make it such that multiple blocks can be sent
        # use *[Block('InventoryData',FolderID = folder_id) for folder_id in folder_ids]

        packet = Message('MoveInventoryFolder',
                        Block('AgentData',
                            AgentID = agent_id,
                            SessionID = session_id,
                            Stamp = restamp),
                        Block('InventoryData',
                            FolderID = folder_id,
                            ParentID = parent_id))

        agent.region.enqueue_message(packet)

    def remove(self, agent):
        """ removes this inventory folder """

        self.send_RemoveInventoryFolder(agent, agent.agent_id, agent.session_id, False, self.FolderID)

    def send_RemoveInventoryFolder(self, agent, agent_id, session_id, restamp, folder_id):
        """ sends a RemoveInventoryFolder message to the host simulator """

        # ToDo: the InventoryData block may the variable, if moved to a more
        # generic location (not nested under Inventory folder),
        # make it such that multiple blocks can be sent
        # use *[Block('InventoryData',FolderID = folder_id) for folder_id in folder_ids]

        packet = Message('RemoveInventoryFolder',
                        Block('AgentData',
                                AgentID = agent_id,
                                SessionID = session_id,
                                Stamp = restamp),
                        Block('InventoryData',
                                FolderID = folder_id))

        agent.region.enqueue_message(packet)

class InventoryItem(object):
    """ represents an Inventory item 

    Sample implementations: inventory.py
    Tests: tests/test_inventory.py
    """

    def __init__(self,
                 ItemID = None,
                 FolderID = None,
                 CreatorID = None,
                 OwnerID = None,
                 GroupID = None,
                 BaseMask = None,
                 OwnerMask = None,
                 GroupMask = None,
                 EveryoneMask = None,
                 NextOwnerMask = 0,
                 GroupOwned = None,
                 AssetID = None,
                 Type = None,
                 InvType = None,
                 Flags = None,
                 SaleType = None,
                 SalePrice = None,
                 Name = None,
                 Description = None,
                 CreationDate = None,
                 CRC = None,
                 LastOwnerID = UUID()):
        """ initialize the inventory item """

        self.type = 'InventoryItem'

        self.ItemID = UUID(str(ItemID))            # LLUUID
        self.FolderID = UUID(str(FolderID))        # LLUUID
        self.CreatorID = UUID(str(CreatorID))      # LLUUID
        self.OwnerID = UUID(str(OwnerID))          # LLUUID
        self.GroupID = UUID(str(GroupID))          # LLUUID
        self.BaseMask = BaseMask                        # U32
        self.OwnerMask = OwnerMask                      # U32
        self.GroupMask = GroupMask                      # U32
        self.EveryoneMask = EveryoneMask                # U32
        self.NextOwnerMask = NextOwnerMask
        self.GroupOwned = GroupOwned                    # Bool
        self.AssetID = UUID(str(AssetID))          # LLUUID
        self.Type = Type                                # S8
        self.InvType = InvType                          # S8
        self.Flags = Flags                              # U32
        self.SaleType = SaleType                        # U8
        self.SalePrice = SalePrice                      # S32
        self.Name = Name                                # Variable 1
        self.Description = Description                  # Variable 1
        self.CreationDate = CreationDate                # S32
        self.CRC = CRC                                  # U32
        self.LastOwnerID = UUID(str(LastOwnerID))

    def rez_object(self, agent, relative_position = (1, 0, 0)):

        # self.agent.Position holds where we are. we need to add this Vector3 to the incoming tuple (vector to a vector)
        location_to_rez_x = agent.Position.X + relative_position[0]
        location_to_rez_y = agent.Position.Y  + relative_position[1]
        location_to_rez_z = agent.Position.Z + relative_position[2]

        location_to_rez = (location_to_rez_x, location_to_rez_y, location_to_rez_z)

        sendRezObject(agent, self, location_to_rez, location_to_rez)

    def update(self, agent, name = None, value = None):
        """ allow arbitraty update to any data in the inventory item 

        accepts a dictionary of key:value pairs which will update the stored inventory items
        and then send an UpdateInventoryItem packet
        """

        if self.__dict__.has_key(name):
            self.__dict__[name] = value
            sendUpdateInventoryItem(agent, [self])
        else:
            raise DataParsingError('Inventory item attribute update failes, no field named \'%s\'' % (name))

    def give(self, agent, to_agent_id):
        """ sends the target agent an inventory offer of this """

        # prep variables and send the message
        _AgentID = agent.agent_id
        _SessionID = agent.session_id
        _FromGroup = False
        _ToAgentID = to_agent_id
        _ParentEstateID = 0
        _RegionID = agent.region.RegionID
        _Position = agent.Position
        _Offline = 0
        _Dialog = ImprovedIMDialogue.InventoryOffered
        _ID = uuid.uuid4()
        _Timestamp = 0
        _FromAgentName = agent.Name()
        _Message = self.Name
        _BinaryBucket = struct.pack(">b", self.Type) + self.ItemID.get_bytes() # binary of asset type and id

        logger.info("Sending inventory offer of %s from %s to %s" % (self.Name, agent.agent_id, to_agent_id))

        agent.send_ImprovedInstantMessage(_AgentID, _SessionID, _FromGroup, _ToAgentID, _ParentEstateID, _RegionID, _Position, _Offline, _Dialog, _ID, _Timestamp, _FromAgentName, _Message, _BinaryBucket)

# ~~~~~~~~~~~~~~~
# Packet Wrappers
# ~~~~~~~~~~~~~~~

def sendUpdateInventoryItem(agent, inventory_items = [], ):
    """ sends an UpdateInventoryItem packet to a region 

    this function expects an InventoryItem instance already with updated data
    """

    packet = Message('UpdateInventoryItem',
                    Block('AgentData',
                            AgentID = agent.agent_id,
                            SessionID = agent.session_id,
                            TransactionID = UUID()),
                    *[Block('InventoryData',
                            ItemID = item.ItemID,
                            FolderID = item.FolderID,
                            CallbackID = random.randint (0, pow (2, 32)-1),
                            CreatorID = item.CreatorID,
                            OwnerID = item.OwnerID,
                            GroupID = item.GroupID,
                            BaseMask = item.BaseMask,
                            OwnerMask = item.OwnerMask,
                            GroupMask = item.GroupMask,
                            EveryoneMask = item.EveryoneMask,
                            NextOwnerMask = item.NextOwnerMask,
                            GroupOwned = item.GroupOwned,
                            TransactionID = UUID(),
                            Type = item.Type,
                            InvType = item.InvType,
                            Flags = item.Flags,
                            SaleType = item.SaleType,
                            SalePrice = item.SalePrice,
                            Name = item.Name,
                            Description = item.Description,
                            CreationDate = item.CreationDate,
                            CRC = item.CRC) for item in inventory_items])

    agent.region.enqueue_message(packet)

def sendRezObject(agent, inventory_item, RayStart, RayEnd, FromTaskID = UUID(), BypassRaycast = 1,  RayTargetID = UUID(), RayEndIsIntersection = False, RezSelected = False, RemoveItem = False, ItemFlags = 0, GroupMask = 0, EveryoneMask = 0, NextOwnerMask = 0):
    """ sends a RezObject packet to a region """

    packet = Message('RezObject',
                    Block('AgentData',
                          AgentID = agent.agent_id,
                          SessionID = agent.session_id,
                          GroupID = agent.ActiveGroupID),
                    Block('RezData',
                          FromTaskID = UUID(str(FromTaskID)),
                          BypassRaycast = BypassRaycast,
                          RayStart = RayStart,
                          RayEnd = RayEnd,
                          RayTargetID = UUID(str(RayTargetID)),
                          RayEndIsIntersection = RayEndIsIntersection,
                          RezSelected = RezSelected,
                          RemoveItem = RemoveItem,
                          ItemFlags = ItemFlags,
                          GroupMask = GroupMask,
                          EveryoneMask = EveryoneMask,
                          NextOwnerMask = NextOwnerMask),
                    Block('InventoryData',
                          ItemID = inventory_item.ItemID,
                          FolderID = inventory_item.FolderID,
                          CreatorID = inventory_item.CreatorID,
                          OwnerID = inventory_item.OwnerID,
                          GroupID = inventory_item.GroupID,
                          BaseMask = inventory_item.BaseMask,
                          OwnerMask = inventory_item.OwnerMask,
                          GroupMask = inventory_item.GroupMask,
                          EveryoneMask = inventory_item.EveryoneMask,
                          GroupOwned = inventory_item.GroupOwned,
                          TransactionID = UUID(),
                          Type = inventory_item.Type,
                          InvType = inventory_item.InvType,
                          Flags = inventory_item.Flags,
                          SaleType = inventory_item.SaleType,
                          SalePrice = inventory_item.SalePrice,
                          Name = inventory_item.Name,
                          Description = inventory_item.Description,
                          CreationDate = inventory_item.CreationDate,
                          CRC = inventory_item.CRC,
                          NextOwnerMask = inventory_item.NextOwnerMask))

    agent.region.enqueue_message(packet)