Beispiel #1
0
        /// <summary>
        /// UPDATE
        /// </summary>
        /// 
        private void UpdateItem(ItemMetadata item, ItemChange change, SaveChangeContext context)
        {
            var data = (IFileDataRetriever)context.ChangeData;
            var attr = _metadataStore.GetItemInfo(item);
            var stream = data.FileData.IsDirectory ? null : data.FileStream;
            try
            {
                SyncedNodeAttributes updatedNode = null;
                //if pathes are different then consider renaming with unchanged content
                if (attr.Path != data.FileData.RelativePath)
                {
                    updatedNode = _nodeStore.MoveFile(attr.Path, data.FileData.RelativePath, attr.Id);
                    OnAppliedChange(ChangeType.Rename, data.FileData.RelativePath, attr.Path);
                }
                else
                {
                    updatedNode = _nodeStore.UpdateFile(attr.Path, data.FileData, stream, attr.Id);
                    OnAppliedChange(ChangeType.Update, data.FileData.RelativePath);
                }

                item.ChangeVersion = change.ChangeVersion;
                _metadataStore.SaveItemMetadata(item, updatedNode.Id, updatedNode.Path);
            }
            catch (MegaStoreConstraintException e)
            {
                ProcessConstraint(change, context, e, item, e.Node);
            }
            catch (MegaStoreException e)
            {
                ForgetItem(context, item, e);
            }
            catch (MegaApiException e)
            {
                context.RecordRecoverableErrorForItem(new RecoverableErrorData(e));
                OnDemandedResync();
            }
            catch (DirectoryNotFoundException e)
            {
                context.RecordRecoverableErrorForItem(new RecoverableErrorData(e));
                OnDemandedResync();
            }

            catch (COMException e)
            {
                OnDemandedResync();
                context.RecordRecoverableErrorForItem(new RecoverableErrorData(e));
            }
            finally
            {
                CloseStream(stream);
            }
        }
Beispiel #2
0
 private void SaveItemMetadata(ItemMetadata item)
 {
     _metadata.SaveItemMetadata(item);
 }
Beispiel #3
0
        /// <summary>
        /// CREATE
        /// </summary>
        private void CreateItem(ItemChange change, SaveChangeContext context, ItemMetadata itemToSaveChanges = null)
        {
            var data = (IFileDataRetriever)context.ChangeData;
            Stream stream = null;
            try
            {
                stream = data.FileData.IsDirectory ? null : data.FileStream;
                var createdNode = _nodeStore.InsertNode(data.FileData, data.FileData.RelativePath, stream);
                if (itemToSaveChanges == null)
                {
                    itemToSaveChanges = _metadataStore.CreateItemMetadata(change.ItemId, change.CreationVersion);
                }
                itemToSaveChanges.ChangeVersion = change.ChangeVersion;

                _metadataStore.SaveItemMetadata(itemToSaveChanges, createdNode.Id, createdNode.Path);
                OnAppliedChange(ChangeType.Create, data.FileData.RelativePath);
            }
            catch (MegaStoreConstraintException e)
            {
                ProcessConstraint(change, context, e, null, e.Node);
            }
            catch (MegaApiException e)
            {
                context.RecordRecoverableErrorForItem(new RecoverableErrorData(e));
            }
            catch (DirectoryNotFoundException e)
            {
                OnDemandedResync();
                context.RecordRecoverableErrorForItem(new RecoverableErrorData(e));
            }
            catch (COMException e)
            {
                OnDemandedResync();
                context.RecordRecoverableErrorForItem(new RecoverableErrorData(e));
            }
            finally
            {
                CloseStream(stream);
            }
        }
Beispiel #4
0
        private void ProcessConstraint(
            ItemChange change,
            SaveChangeContext context,
            MegaStoreConstraintException e,
            ItemMetadata item,
            MegaNodeHelper conflictingNode)
        {
            switch (e.ConstraintType)
            {
                case MegaStoreConstraintType.TargetExists:
                    ResolveConflict(item, change, context, conflictingNode);
                    break;

                case MegaStoreConstraintType.NoParent:
                    OnDemandedResync();
                    context.RecordConstraintConflictForItem(ConstraintConflictReason.NoParent);
                    break;
                // todo add no-free-space handling
                case MegaStoreConstraintType.ZeroSize:
                    context.RecordConstraintConflictForItem(ConstraintConflictReason.Other);
                    break;

                case MegaStoreConstraintType.NotEmpty:
                    OnDemandedResync();
                    context.RecordRecoverableErrorForItem(new RecoverableErrorData(e));
                    break;
            }
        }
 private void SaveItemMetadata(ItemMetadata item, UInt64 timeStamp)
 {
     item.SetCustomField(TIMESTAMP_COLUMNNAME, timeStamp);
     //   item.SetCustomField(ENTITY_COLUMNNAME, entityType);
     SaveItemMetadata(item);
 }
Beispiel #6
0
        private void BackupFile(ItemMetadata item, string path, ItemChange change, SaveChangeContext context)
        {
            var t = _nodeStore.BackupFile(path);
            var newItem = _metadataStore.CreateItemMetadata();
            _metadataStore.SaveItemMetadata(newItem, t.Node.Id, t.Path);

            if (item == null)
            {
                CreateItem(change, context);
            }
            else
            {
                UpdateItem(item, change, context);
            }
        }
Beispiel #7
0
 private void UploadBack(ItemMetadata item, ItemChange change, SaveChangeContext context)
 {
     //TODO this still re-downloads the file just uploaded
     item.ResurrectDeletedItem();
     CreateItem(change, context, item);
 }
Beispiel #8
0
 internal SyncedNodeAttributes GetItemInfo(ItemMetadata item)
 {
     if (item == null) { return null; }
     return new SyncedNodeAttributes
     {
         Path = item.GetStringField(PATH_COLUMNNAME),
         Id = item.GetStringField(ID_COLUMNNAME)
     };
 }
    private static void HandleRandomHair(GameSession session, PacketReader packet)
    {
        int  shopId     = packet.ReadInt();
        bool useVoucher = packet.ReadBool();

        BeautyMetadata    beautyShop  = BeautyMetadataStorage.GetShopById(shopId);
        List <BeautyItem> beautyItems = BeautyMetadataStorage.GetGenderItems(beautyShop.ShopId, session.Player.Gender);

        if (!HandleShopPay(session, beautyShop, useVoucher))
        {
            return;
        }

        // Grab random hair
        Random     random     = RandomProvider.Get();
        int        indexHair  = random.Next(beautyItems.Count);
        BeautyItem chosenHair = beautyItems[indexHair];

        //Grab a preset hair and length of hair
        ItemMetadata beautyItemData = ItemMetadataStorage.GetMetadata(chosenHair.ItemId);
        int          indexPreset    = random.Next(beautyItemData.HairPresets.Count);
        HairPresets  chosenPreset   = beautyItemData.HairPresets[indexPreset];

        //Grab random front hair length
        double chosenFrontLength = random.NextDouble() *
                                   (beautyItemData.HairPresets[indexPreset].MaxScale - beautyItemData.HairPresets[indexPreset].MinScale) + beautyItemData.HairPresets[indexPreset].MinScale;

        //Grab random back hair length
        double chosenBackLength = random.NextDouble() *
                                  (beautyItemData.HairPresets[indexPreset].MaxScale - beautyItemData.HairPresets[indexPreset].MinScale) + beautyItemData.HairPresets[indexPreset].MinScale;

        // Grab random preset color
        ColorPaletteMetadata palette = ColorPaletteMetadataStorage.GetMetadata(2); // pick from palette 2. Seems like it's the correct palette for basic hair colors

        int        indexColor = random.Next(palette.DefaultColors.Count);
        MixedColor color      = palette.DefaultColors[indexColor];

        Item newHair = new(chosenHair.ItemId)
        {
            Color              = EquipColor.Argb(color, indexColor, palette.PaletteId),
            HairData           = new((float)chosenBackLength, (float)chosenFrontLength, chosenPreset.BackPositionCoord, chosenPreset.BackPositionRotation, chosenPreset.FrontPositionCoord, chosenPreset.FrontPositionRotation),
            IsTemplate         = false,
            IsEquipped         = true,
            OwnerCharacterId   = session.Player.CharacterId,
            OwnerCharacterName = session.Player.Name
        };
        Dictionary <ItemSlot, Item> cosmetics = session.Player.Inventory.Cosmetics;

        //Remove old hair
        if (cosmetics.Remove(ItemSlot.HR, out Item previousHair))
        {
            previousHair.Slot = -1;
            session.Player.HairInventory.RandomHair = previousHair; // store the previous hair
            DatabaseManager.Items.Delete(previousHair.Uid);
            session.FieldManager.BroadcastPacket(EquipmentPacket.UnequipItem(session.Player.FieldPlayer, previousHair));
        }

        cosmetics[ItemSlot.HR] = newHair;

        session.FieldManager.BroadcastPacket(EquipmentPacket.EquipItem(session.Player.FieldPlayer, newHair, ItemSlot.HR));
        session.Send(BeautyPacket.RandomHairOption(previousHair, newHair));
    }
Beispiel #10
0
 public void SaveItemMetadata(ItemMetadata item, string id, string path)
 {
     item.SetCustomField(ID_COLUMNNAME, id);
     item.SetCustomField(PATH_COLUMNNAME, path);
     SaveItemMetadata(item);
 }
Beispiel #11
0
 public void SaveItemMetadata(ItemMetadata item)
 {
     _metadata.SaveItemMetadata(item);
 }
Beispiel #12
0
 protected ProviderItem(ItemMetadata createdFolder)
 {
     this.Identifier       = createdFolder.Identifier;
     this.ParentIdentifier = createdFolder.ParentIdentifier;
     this.Filename         = createdFolder.Name;
 }
        public void SaveItemChange(SaveChangeAction saveChangeAction, ItemChange change, SaveChangeContext context)
        {
            try
            {
                UInt64          timeStamp = 0;
                ItemMetadata    item      = null;
                ISyncDataObject data      = null;
                switch (saveChangeAction)
                {
                case SaveChangeAction.Create:
                    //Do duplicate detection here
                    item = _metadata.FindItemMetadataById(change.ItemId);
                    if (null != item)
                    {
                        throw new SyncException("SaveItemChange must not have Create action for existing items.");
                    }
                    item = _metadata.CreateItemMetadata(change.ItemId, change.CreationVersion);
                    item.ChangeVersion = change.ChangeVersion;
                    data = (ISyncDataObject)context.ChangeData;
                    //We are using the same id for both the local and global item id.

                    var version = _syncContext.CreateItem(data, change.ItemId.GetGuidId(), CompanyId, StoreId);
                    if (version != null)
                    {
                        timeStamp = BitConverter.ToUInt64(version, 0);
                        SaveItemMetadata(item, timeStamp);
                    }
                    break;

                case SaveChangeAction.UpdateVersionAndData:
                case SaveChangeAction.UpdateVersionOnly:
                    item = _metadata.FindItemMetadataById(change.ItemId);
                    if (null == item)
                    {
                        throw new SyncException("Item Not Found in Store!?");
                    }

                    item.ChangeVersion = change.ChangeVersion;
                    if (saveChangeAction == SaveChangeAction.UpdateVersionOnly)
                    {
                        SaveItemMetadata(item);
                    }
                    else      //Also update the data and the timestamp.
                    {
                        data      = (ISyncDataObject)context.ChangeData;
                        timeStamp = BitConverter.ToUInt64(_syncContext.UpdateItem(item.GlobalId.GetGuidId(), data, CompanyId, StoreId), 0);
                        SaveItemMetadata(item, timeStamp);
                    }
                    break;

                case SaveChangeAction.DeleteAndStoreTombstone:
                    item = _metadata.FindItemMetadataById(change.ItemId);
                    if (null == item)
                    {
                        // item = _metadata.CreateItemMetadata(change.ItemId, change.CreationVersion);
                        return;
                    }

                    if (change.ChangeKind == ChangeKind.Deleted)
                    {
                        item.MarkAsDeleted(change.ChangeVersion);
                    }
                    else
                    {
                        // This should never happen in Sync Framework V1.0
                        throw new SyncException("Invalid ChangeType");
                    }

                    item.ChangeVersion = change.ChangeVersion;
                    SaveItemMetadata(item, timeStamp);      // set timestamp to 0 for tombstones
                    _syncContext.DeleteItem(item.GlobalId.GetGuidId(), CompanyId, StoreId);
                    break;

                //Merge the changes! (Take the data from the local item + the remote item),noting to update the tick count to propagate the resolution!
                case SaveChangeAction.UpdateVersionAndMergeData:
                    item = _metadata.FindItemMetadataById(change.ItemId);

                    if (null == item)
                    {
                        throw new SyncException("Item Not Found in Store!?");
                    }
                    if (item.IsDeleted != true)
                    {
                        //Note - you must update the change version to propagate the resolution!
                        item.ChangeVersion = new SyncVersion(0, _metadata.GetNextTickCount());
                        //Combine the conflicting data...
                        ISyncDataObject mergedData = _syncContext.Merge(_syncContext.GetItem(item.GlobalId.GetGuidId(), CompanyId, StoreId), (ISyncDataObject)context.ChangeData, CompanyId, StoreId);
                        timeStamp = BitConverter.ToUInt64(_syncContext.UpdateItem(item.GlobalId.GetGuidId(), mergedData, CompanyId, StoreId), 0);
                        SaveItemMetadata(item, timeStamp);
                    }
                    break;

                case SaveChangeAction.DeleteAndRemoveTombstone:
                    item = _metadata.FindItemMetadataById(change.ItemId);
                    if (item != null)
                    {
                        List <SyncId> ids = new List <SyncId>();
                        ids.Add(item.GlobalId);
                        _metadata.RemoveItemMetadata(ids);
                    }
                    _syncContext.DeleteItem(change.ItemId.GetGuidId(), CompanyId, StoreId);
                    break;
                }
            }
            catch (SyncException ex)
            {
                ILog logger = LogManager.GetLogger(Assembly.GetExecutingAssembly().GetName().Name);
                logger.Error(ex.Message, ex);
                //do Log
            }
            catch (DbEntityValidationException ex)
            {
                ILog logger = LogManager.GetLogger(Assembly.GetExecutingAssembly().GetName().Name);
                logger.Error(ex.Message, ex);
                //do Log
            }
            catch (Exception ex)
            {
                ILog logger = LogManager.GetLogger(Assembly.GetExecutingAssembly().GetName().Name);
                logger.Error(ex.Message, ex);
                //do Log
            }
        }
 private void SaveItemMetadata(ItemMetadata item)
 {
     _metadata.SaveItemMetadata(item);
 }
Beispiel #15
0
 /// <summary>
 /// DELETE
 /// </summary>
 private void DeleteItem(ItemMetadata item, ItemChange change, SaveChangeContext context, bool removeTombstone = false)
 {
     try
     {
         var attr = _metadataStore.GetItemInfo(item);
         _nodeStore.DeleteFile(attr.Path, attr.Id);
         OnAppliedChange(ChangeType.Delete, null, attr.Path);
         if (removeTombstone)
         {
             _metadataStore.Metadata.RemoveItemMetadata(new List<SyncId> { item.GlobalId });
         }
         else
         {
             item.MarkAsDeleted(change.ChangeVersion);
             _metadataStore.SaveItemMetadata(item);
         }
     }
     catch (MegaStoreConstraintException e)
     {
         ProcessConstraint(change, context, e, item, null);
     }
     // never mind, the item isn't found anyway
     catch (MegaStoreException)
     {
         if (removeTombstone)
         {
             _metadataStore.Metadata.RemoveItemMetadata(new List<SyncId> { item.GlobalId });
         }
         else
         {
             item.MarkAsDeleted(change.ChangeVersion);
             _metadataStore.SaveItemMetadata(item);
         }
     }
     catch (MegaApiException e)
     {
         context.RecordRecoverableErrorForItem(new RecoverableErrorData(e));
         OnDemandedResync();
     }
 }
Beispiel #16
0
 public ItemMetadataWrapper(ItemMetadata meta)
 {
     _meta = meta;
 }
Beispiel #17
0
 /// <summary>
 /// CONFLICT
 /// </summary>
 private void ResolveConflict(ItemMetadata item, ItemChange change, SaveChangeContext context, MegaNodeHelper conflictingNode)
 {
     var data = (IFileDataRetriever)context.ChangeData;
     // item does not exist in metadata (can happen when create+create)
     if (item == null) 
     {
         if (conflictingNode == null) 
         {
             context.RecordRecoverableErrorForItem(new RecoverableErrorData(new Exception()));
         }
         if (FilesAreEqual(data, conflictingNode))
         {
             DoNothing(item, change, context, false, conflictingNode);
         }
         else
         {
             BackupFile(item, conflictingNode.Path, change, context);
         }
         return;
     }
     var attr = _metadataStore.GetItemInfo(item);
     try
     {
         if (change.ChangeKind == ChangeKind.Deleted)
         {
             // local delete + remote delete
             if (item.IsDeleted)
             {
                 DoNothing(item, change, context, true);
             }
             // local delete + remote update
             else
             {
                 DownloadBack(item, change);
             }
         }
         else
         {
             // local update + remote delete
             if (item.IsDeleted)
             {
                 UploadBack(item, change, context);
             }
             // update + update
             else
             {
                 if (FilesAreEqual(data, _nodeStore.FindNodeById(attr.Id)))
                 {
                     DoNothing(item, change, context);
                 }
                 else
                 {
                     BackupFile(item, attr.Path, change, context);
                 }
             }
         }
     }
     catch (MegaApiException e)
     {
         context.RecordRecoverableErrorForItem(new RecoverableErrorData(e));
     }
 }
Beispiel #18
0
 public override void SaveItemMetadata(ItemMetadata item)
 {
     ItemMetadataAdaptor entityItemMetaData =  ItemMetadataAdaptor.CreateInstance(item);
     entityItemMetaData.Save();
 }
Beispiel #19
0
 private void DownloadBack(ItemMetadata item, ItemChange change)
 {
     item.ChangeVersion = new SyncVersion(change.ChangeVersion.ReplicaKey, GetNextTickCount());
     _metadataStore.SaveItemMetadata(item);
 }
 private void SaveItemMetadata(ItemMetadata item, ulong timeStamp)
 {
     item.SetCustomField(TIMESTAMP_COLUMNNAME, timeStamp);
     SaveItemMetadata(item);
 }
Beispiel #21
0
 private void DoNothing(
     ItemMetadata item, 
     ItemChange change,
     SaveChangeContext context,
     bool deleted = false,
     MegaNodeHelper existingNode = null)
 {
     // creating
     if (item == null)
     {
         if (existingNode == null)
         {
             context.RecordRecoverableErrorForItem(new RecoverableErrorData(new Exception()));
         }
         item = _metadataStore.Metadata.CreateItemMetadata(change.ItemId, change.CreationVersion);
         item.ChangeVersion = change.ChangeVersion;
         _metadataStore.SaveItemMetadata(item, existingNode.Node.Id, existingNode.Path);
         return;
     }
     if (deleted)
     {
         item.MarkAsDeleted(change.ChangeVersion);
     }
     item.ChangeVersion = change.ChangeVersion;
     _metadataStore.SaveItemMetadata(item);
 }
Beispiel #22
0
 private void SaveItemMetadata(ItemMetadata item, ulong timeStamp)
 {
     item.SetCustomField(TIMESTAMP_COLUMNNAME, timeStamp);
     SaveItemMetadata(item);
 }
Beispiel #23
0
 // the node is suddenly out, remove it from database 
 // (it was a concurrency delete attempt - we should restore the existing version)
 private void ForgetItem(SaveChangeContext context, ItemMetadata item, Exception e)
 {
     _metadataStore.Metadata.RemoveItemMetadata(new List<SyncId> { item.GlobalId });
     OnDemandedResync();
     context.RecordRecoverableErrorForItem(new RecoverableErrorData(e));
 }
        //Update the metadata store with changes that have occured on the data store since the last time it was updated.
        public void UpdateMetadataStoreWithLocalChanges()
        {
            SyncVersion newVersion = new SyncVersion(0, _metadata.GetNextTickCount());

            _metadata.DeleteDetector.MarkAllItemsUnreported();

            var entities = _syncContext.GetSyncObjects(CompanyId, StoreId);

            foreach (ISyncDataObject entity in entities)
            {
                try
                {
                    ISyncDataObject data = entity;
                    ItemMetadata    item = null;

                    //Look up an item's metadata by its ID...
                    item = _metadata.FindItemMetadataById(new SyncId(entity.SyncItemId));
                    if (null == item)
                    {
                        //New item, must have been created since that last time the metadata was updated.
                        //Create the item metadata required for sync (giving it a SyncID and a version, defined to be a DWORD and a ULONGLONG
                        //For creates, simply provide the relative replica ID (0) and the tick count for the provider (ever increasing)
                        item = _metadata.CreateItemMetadata(new SyncId(entity.SyncItemId), newVersion);
                        item.ChangeVersion = newVersion;
                        SaveItemMetadata(item, BitConverter.ToUInt64(data.SyncItemVersion, 0));
                        //var package = data as SyncDataPackage;
                        //if (package != null)
                        //{
                        //    item.SetCustomField(PACKAGECOUNT, (UInt32)package.Items.Count);
                        //}
                    }
                    else
                    {
                        //var package = data as SyncDataPackage;
                        //var packageCount = item.GetUInt32Field(PACKAGECOUNT);
                        if (BitConverter.ToUInt64(data.SyncItemVersion, 0) != item.GetUInt64Field(TIMESTAMP_COLUMNNAME)) // the item has changed since the last sync operation.
                        {
                            //Changed Item, this item has changed since the last time the metadata was updated.
                            //Assign a new version by simply stating "who" modified this item (0 = local/me) and "when" (tick count for the store)
                            item.ChangeVersion = newVersion;
                            SaveItemMetadata(item, BitConverter.ToUInt64(data.SyncItemVersion, 0));
                        }
                        else
                        {
                            //Unchanged item, nothing has changes so just mark it as live so that the metadata knows it has not been deleted.
                            _metadata.DeleteDetector.ReportLiveItemById(new SyncId(entity.SyncItemId));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }


            //Now go back through the items that are no longer in the store and mark them as deleted in the metadata.
            //This sets the item as a tombstone.
            foreach (ItemMetadata item in _metadata.DeleteDetector.FindUnreportedItems())
            {
                item.MarkAsDeleted(newVersion);
                SaveItemMetadata(item, 0); // set timestamp to null for tombstones
            }
        }