private async Task ValidateUserClaims(Data.Resource entity, string userClaims) { if (entity.UserClaims == userClaims) { return; } if (String.IsNullOrEmpty(userClaims)) { entity.UserClaims = userClaims; return; } var resources = await _store.GetAll(); var identityScopes = resources .Where(r => r.Type == ResourceType.Identity && (r.Default || _profile.IsPrivileged || r.Managers.Any(m => m.SubjectId == _profile.Id))) .SelectMany(r => r.UserClaims.Split()) .Distinct(); var validClaims = new List <string>(); foreach (string name in userClaims.Split(" ", StringSplitOptions.RemoveEmptyEntries)) { if (identityScopes.Contains(name) && !validClaims.Contains(name)) { validClaims.Add(name); } } entity.UserClaims = string.Join(" ", validClaims); }
/// <summary> /// Get specific resource /// </summary> /// <param name="language">ar/en</param> /// <param name="module">module name</param> /// <param name="key">resource key</param> /// <param name="notTranslated">Informs whether the resource is translated or not</param> /// <returns>Returns the matching resource</returns> public static Data.Resource GetResource(string language, string module, string key, out bool notTranslated) { string value = key; Data.Resource resource = new Data.Resource() { Module = module, Language = language, Key = key }; try { ResourceValueItem item = Resources[module][language][key]; resource.Value = item.Value; resource.IsEditable = item.IsEditable; notTranslated = false; } catch { try { string complementaryLanguage = (language == "ar" ? "en" : "ar"); ResourceValueItem item = Resources[module][complementaryLanguage][key]; resource.Value = item.Value; resource.IsEditable = item.IsEditable; notTranslated = true; } catch { notTranslated = false; resource = null; } } return(resource); }
public static Render.ILayerSprite CreateSprite(Render.ISpriteFactory spriteFactory, int width, int height, Data.Resource resourceType, uint spriteIndex, byte displayLayer) { var offset = GetTextureAtlasOffset(resourceType, spriteIndex); return(spriteFactory.Create(width, height, offset.X, offset.Y, false, true, displayLayer) as Render.ILayerSprite); }
public override void ModifyResource(EngineRequest request, Data.Resource resource) { CheckInitialization(); Logger.Storage.Debug("Modifying resource '" + resource.ResourceId.ToString() + "'..."); EngineMethods.ModifyResource act = new EngineMethods.ModifyResource(request, resource); act.Execute(); }
public MarkResourceForCheckout(Data.Resource resource, string username, int sendTimeout, int receiveTimeout, int sendBufferSize, int receiveBufferSize) : base(sendTimeout, receiveTimeout, sendBufferSize, receiveBufferSize) { _resource = resource; _username = username; }
public UploadResource(IDatabase db, Data.Resource resource, int sendTimeout, int receiveTimeout, int sendBufferSize, int receiveBufferSize) : base(sendTimeout, receiveTimeout, sendBufferSize, receiveBufferSize) { _db = db; _resource = resource; }
internal DataResource(Data.Resource asset, Data.Type type, uint count, string name) { Asset = asset; Type = type; Count = count; Name = name; }
public virtual Sprite GetSprite(Data.Resource resource, uint index, Sprite.Color color) { if (index >= Data.GetResourceCount(resource)) { return(null); } Tuple <Sprite, Sprite> ms = GetSpriteParts(resource, index); Sprite mask = ms.Item1; Sprite image = ms.Item2; if (mask != null) { mask.FillMasked(color); if (image != null) { mask.Blend(image); } return(mask); } return(image); }
/// <summary> /// Adds a Resource to the Resources dictionnary /// </summary> public static void AddResource(Data.Resource resource) { Resources[resource.Module][resource.Language][resource.Key] = new ResourceValueItem() { Value = resource.Value, IsEditable = resource.IsEditable }; }
public HeadAllVersionsOfResource(IDatabase db, Data.Resource resource, Security.RequestingPartyType requestingPartyType, Security.Session session, int sendTimeout, int receiveTimeout, int sendBufferSize, int receiveBufferSize) : base(db, sendTimeout, receiveTimeout, sendBufferSize, receiveBufferSize) { _resource = resource; _requestingPartyType = requestingPartyType; _session = session; }
public override void TaskComplete(Tasks.Base sender, ICommandReply reply) { Type t = sender.GetType(); if (t == typeof(Tasks.DownloadResource)) { Tasks.DownloadResource task = (Tasks.DownloadResource)sender; _resource = task.Resource; _resourceRemainder = task.Remainder; RunTaskProcess(new Tasks.CheckResourcePermissions(_db, _resource, _requestingPartyType, _session, Security.Authorization.ResourcePermissionType.Checkout, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.CheckResourcePermissions)) { Tasks.CheckResourcePermissions task = (Tasks.CheckResourcePermissions)sender; if (!task.IsAuthorized) { TriggerOnAuthorizationDenied(task); return; } RunTaskProcess(new Tasks.MarkResourceForCheckout(_resource, _session.User.Username, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.MarkResourceForCheckout)) { List <Exception> errors; Tasks.MarkResourceForCheckout task = (Tasks.MarkResourceForCheckout)sender; Transitions.Resource txResource = new Transitions.Resource(); Model.Document doc = txResource.Transition(_resource, out errors); doc.CombineWith(_resourceRemainder); RunTaskProcess(new Tasks.UploadResource(_db, doc, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.UploadResource)) { Tasks.UploadResource task = (Tasks.UploadResource)sender; if (reply.IsError) { TriggerOnError(sender, reply.ToString(), null); return; } RunTaskProcess(new Tasks.DownloadVersion(_db, _id, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.DownloadVersion)) { Tasks.DownloadVersion task = (Tasks.DownloadVersion)sender; Version = task.Version; Remainder = task.Remainder; TriggerOnComplete(reply, new Tuple <Data.Version, JObject>(Version, Remainder)); } else { TriggerOnError(sender, reply.ToString(), null); } }
public override void TaskComplete(Tasks.Base sender, ICommandReply reply) { Type t = sender.GetType(); if (t == typeof(Tasks.DownloadResource)) { Tasks.DownloadResource task = (Tasks.DownloadResource)sender; _resource = task.Resource; _resourceRemainder = task.Remainder; RunTaskProcess(new Tasks.CheckResourcePermissions(_db, _resource, _requestingPartyType, _session, Security.Authorization.ResourcePermissionType.Checkout, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.CheckResourcePermissions)) { Tasks.CheckResourcePermissions task = (Tasks.CheckResourcePermissions)sender; if (!task.IsAuthorized) { TriggerOnAuthorizationDenied(task); return; } RunTaskProcess(new Tasks.MarkResourceForCheckout(_resource, _session.User.Username, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.MarkResourceForCheckout)) { List<Exception> errors; Tasks.MarkResourceForCheckout task = (Tasks.MarkResourceForCheckout)sender; Transitions.Resource txResource = new Transitions.Resource(); Model.Document doc = txResource.Transition(_resource, out errors); doc.CombineWith(_resourceRemainder); RunTaskProcess(new Tasks.UploadResource(_db, doc, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.UploadResource)) { Tasks.UploadResource task = (Tasks.UploadResource)sender; if(reply.IsError) { TriggerOnError(sender, reply.ToString(), null); return; } RunTaskProcess(new Tasks.DownloadVersion(_db, _id, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.DownloadVersion)) { Tasks.DownloadVersion task = (Tasks.DownloadVersion)sender; Version = task.Version; Remainder = task.Remainder; TriggerOnComplete(reply, new Tuple<Data.Version, JObject>(Version, Remainder)); } else { TriggerOnError(sender, reply.ToString(), null); } }
public uint GetGuiTypeOffset(Data.Resource type) { if (!guiResourceOffsets.ContainsKey(type)) { throw new ExceptionFreeserf(ErrorSystemType.Textures, "The given resource type is not part of the gui."); } return(guiResourceOffsets[type]); }
public CheckResourcePermissions(IDatabase db, Data.Resource resource, Security.RequestingPartyType requestingPartyType, Security.Session session, Security.Authorization.ResourcePermissionType requiredPermissions, int sendTimeout, int receiveTimeout, int sendBufferSize, int receiveBufferSize) : base(sendTimeout, receiveTimeout, sendBufferSize, receiveBufferSize) { _db = db; _resource = resource; _rpt = requestingPartyType; _session = session; _requiredPermissions = requiredPermissions; }
private void UpdateManagers(Data.Resource entity, IEnumerable <ResourceManager> managers) { foreach (var manager in managers.Where(s => s.Deleted)) { var target = entity.Managers.SingleOrDefault(s => s.Id == manager.Id); if (target != null) { entity.Managers.Remove(target); } } }
private void UpdateSecrets(Data.Resource entity, IEnumerable <ApiSecret> secrets) { foreach (var secret in secrets.Where(s => s.Deleted)) { var target = entity.Secrets.SingleOrDefault(s => s.Id == secret.Id); if (target != null) { entity.Secrets.Remove(target); } } }
public int Create(Models.Resource resource) { var target = new Data.Resource { ResourceName = resource.ResourceName, Comments = resource.Comments, ResourceTypeID = resource.ResourceType.ResourceTypeID, }; var result = _entities.Resources.Add(target); _entities.SaveChanges(); return(result.ResourceID); }
public int Create(Models.Resource resource) { var target = new Data.Resource { ResourceName = resource.ResourceName, Comments = resource.Comments, ResourceTypeID = resource.ResourceType.ResourceTypeID, }; var result = _entities.Resources.Add(target); _entities.SaveChanges(); return result.ResourceID; }
void AddGuiElements(Data.Resource resourceType, uint num, ref uint index, DataSource data, Sprite.Color color) { guiResourceOffsets.Add(resourceType, index); for (uint i = 0; i < num; ++i) { var sprite = data.GetSprite(resourceType, i, color); if (sprite != null) { AddSprite(Layer.Gui, index, sprite); } ++index; } }
public static Position GetTextureAtlasOffset(Data.Resource resourceType, uint spriteIndex) { var layer = Freeserf.Layer.Gui; if (resourceType == Data.Resource.MapObject) { layer = Freeserf.Layer.GuiBuildings; } else if (resourceType == Data.Resource.UIText) { layer = Freeserf.Layer.GuiFont; } var textureAtlasManager = Render.TextureAtlasManager.Instance; var textureAtlas = textureAtlasManager.GetOrCreate(layer); var offset = (resourceType == Data.Resource.MapObject) ? 0 : textureAtlasManager.GetGuiTypeOffset(resourceType); return(textureAtlas.GetOffset(offset + spriteIndex)); }
public List <Exception> AddMetadata(Data.Resource resource, Model.Document doc) { if (resource.Metadata == null) { return(null); } List <Exception> errors = null; Dictionary <string, object> .Enumerator en = resource.Metadata.GetEnumerator(); while (en.MoveNext()) { if ((errors = AddMetadata(en.Current.Key, en.Current.Value, doc)) != null) { return(errors); } } return(null); }
public override Sprite GetSprite(Data.Resource resource, uint index, Sprite.Color color) { switch (GraphicDataUsage) { case DataUsage.ForceAmiga: if (!amigaGraphicsOk) { throw new ExceptionFreeserf(ErrorSystemType.Data, "Amiga graphic data not available."); } return(amiga.GetSprite(resource, index, color)); case DataUsage.ForceDos: if (!dosOk) { throw new ExceptionFreeserf(ErrorSystemType.Data, "DOS graphic data not available."); } return(dos.GetSprite(resource, index, color)); case DataUsage.PreferAmiga: if (amigaGraphicsOk) { return(amiga.GetSprite(resource, index, color)); } else { return(dos.GetSprite(resource, index, color)); } case DataUsage.PreferDos: default: if (dosOk) { return(dos.GetSprite(resource, index, color)); } else { return(amiga.GetSprite(resource, index, color)); } } }
public SpriteInfo GetSpriteInfo(Data.Resource resource, uint index) { if (spriteInfoCache.ContainsKey(resource) && spriteInfoCache[resource] != null && spriteInfoCache[resource].ContainsKey(index)) { return(spriteInfoCache[resource][index]); } var sprite = GetSprite(resource, index, Sprite.Color.Transparent); SpriteInfo spriteInfo = null; if (sprite != null) { spriteInfo = new SpriteInfo() { Width = (int)sprite.Width, Height = (int)sprite.Height, OffsetX = sprite.OffsetX, OffsetY = sprite.OffsetY, DeltaX = sprite.DeltaX, DeltaY = sprite.DeltaY }; } if (!spriteInfoCache.ContainsKey(resource)) { spriteInfoCache.Add(resource, new Dictionary <uint, SpriteInfo>() { { index, spriteInfo } }); } else { spriteInfoCache[resource].Add(index, spriteInfo); } return(spriteInfo); }
public override void TaskComplete(Tasks.Base sender, ICommandReply reply) { Type t = sender.GetType(); // 1) Download // 2) Check Perms // 3) Upload Resource (no need to update versions, etc as we just want to change resource) if (t == typeof(Tasks.DownloadResource)) { Tasks.DownloadResource task = (Tasks.DownloadResource)sender; _storedResource = task.Resource; _storedRemainder = task.Remainder; RunTaskProcess(new Tasks.CheckResourcePermissions(_db, _storedResource, _requestingPartyType, _session, Security.Authorization.ResourcePermissionType.Modify, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.CheckResourcePermissions)) { Tasks.CheckResourcePermissions task = (Tasks.CheckResourcePermissions)sender; if (!task.IsAuthorized) { TriggerOnAuthorizationDenied(task); return; } RunTaskProcess(new Tasks.UploadResource(_db, _resource, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.UploadResource)) { TriggerOnComplete(reply, _resource); } else { TriggerOnError(sender, reply.ToString(), null); } }
private void ValidateScopes(Data.Resource entity, string scopes, string previousName) { if (entity.Scopes == scopes && entity.Name == previousName) { return; } if (String.IsNullOrEmpty(scopes)) { entity.Scopes = entity.Name; } var scopeNames = scopes.Split(" ", StringSplitOptions.RemoveEmptyEntries) .Select(s => { if (entity.Name != previousName) // find and replace first occurance of previousName { var i = s.IndexOf(previousName); string name = i < 0 ? s : s.Substring(0, i) + entity.Name + s.Substring(i + previousName.Length); return(name == entity.Name || name.StartsWith($"{entity.Name}-") ? name : $"{entity.Name}-{name}"); } if (s == entity.Name || (s.StartsWith($"{entity.Name}-"))) { return(s); } return($"{entity.Name}-{s}"); }) .Distinct() .ToList(); if (!scopeNames.Contains(entity.Name)) { scopeNames.Add(entity.Name); } entity.Scopes = string.Join(" ", scopeNames); }
public override void Process() { Resource = _resource; Resource.UpdateCheckout(DateTime.Now, _username); TriggerOnComplete(null); }
public abstract Tuple <Sprite, Sprite> GetSpriteParts(Data.Resource resource, uint index);
public override void TaskComplete(Tasks.Base sender, ICommandReply reply) { Type t = sender.GetType(); if (t == typeof(Tasks.DownloadResource)) { Tasks.DownloadResource task = (Tasks.DownloadResource)sender; _resource = task.Resource; _resourceRemainder = task.Remainder; RunTaskProcess(new Tasks.CheckResourcePermissions(_db, _resource, _requestingPartyType, _session, Security.Authorization.ResourcePermissionType.Modify, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.CheckResourcePermissions)) { Tasks.CheckResourcePermissions task = (Tasks.CheckResourcePermissions)sender; if (!task.IsAuthorized) { TriggerOnAuthorizationDenied(task); return; } RunTaskProcess(new Tasks.MarkResourceForCheckout(_resource, _session.User.Username, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.MarkResourceForCheckout)) { Tasks.MarkResourceForCheckout task = (Tasks.MarkResourceForCheckout)sender; _resource = task.Resource; List <Exception> errors; List <Model.Document> docs = new List <Model.Document>(); Transitions.Version txVersion = new Transitions.Version(); Transitions.Resource txResource = new Transitions.Resource(); docs.Add(txResource.Transition(_resource, out errors)); if (errors != null) { TriggerOnError(null, errors[0].Message, errors[0]); return; } docs[0].CombineWith(_resourceRemainder); docs.Add(txVersion.Transition(_version, out errors)); if (errors != null) { TriggerOnError(null, errors[0].Message, errors[0]); return; } RunTaskProcess(new Tasks.MakeBulkDocument(docs, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.MakeBulkDocument)) { Tasks.MakeBulkDocument task = (Tasks.MakeBulkDocument)sender; RunTaskProcess(new Tasks.UploadBulkDocuments(_db, task.BulkDocument, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.UploadBulkDocuments)) { Tasks.UploadBulkDocuments task = (Tasks.UploadBulkDocuments)sender; Commands.PostBulkDocumentsReply.Entry entry = task.FindEntryById(_version.VersionId.ToString()); if (entry == null) { TriggerOnError(task, "Failed to locate " + _version.VersionId.ToString() + " in the " + "bulk document post results.", null); return; } // This is needed so that couchdb can apply the content to the correct revision. _version.UpdateRevision(entry.Rev); // If no content -> return if (_version.Content == null) { Resource = _resource; Version = _version; TriggerOnComplete(reply, new Tuple <Data.Resource, Data.Version>(_resource, _version)); return; } // Upload Data.Content from Data.Version RunTaskProcess(new Tasks.UploadContent(_db, _version, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.UploadContent)) { Resource = _resource; Version = _version; TriggerOnComplete(reply, new Tuple <Data.Resource, Data.Version>(_resource, _version)); } else { TriggerOnError(sender, reply.ToString(), null); } }
public static Uri Build(IDatabase db, Data.Resource resource) { return(Build(db, resource.ResourceId)); }
public override void TaskComplete(Tasks.Base sender, ICommandReply reply) { /* We encounter a bit of an issue here. Upon doing some research it is easily resolved * by couchdb. Lets examine. * * Issue: We update the resource to the server, connection is lost, we try to delete the * versions newer than the target version of the rollback. This fails. We now have * zombie versions that will block future recreation of those versions as the IDs will * be the same. * * Solution: "Updating existing documents requires setting the _rev member to the * revision being updated. To delete a document set the _deleted member to true." * http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API. * * Example: * { * "docs": [ * {"_id": "0", "_rev": "1-62657917", "_deleted": true}, * {"_id": "1", "_rev": "1-2089673485", "integer": 2, "string": "2"}, * {"_id": "2", "_rev": "1-2063452834", "integer": 3, "string": "3"} * ] * } * * Implementation: So, we already have bulk document post support. We simply need to * load the bulkdocument with the resource and the _id and _rev for each version we want * to remove. We will also want to set the _deleted to true. */ // 1) Download Resource // 2) Check for VersionControl permission // 3) Modify Resource (VersionIds, CurrentVersionId) // 4) Make bulk document // 5) Upload bulk document Type t = sender.GetType(); if (t == typeof(Tasks.DownloadResource)) { Tasks.DownloadResource task = (Tasks.DownloadResource)sender; _resource = task.Resource; _remainder = task.Remainder; RunTaskProcess(new Tasks.CheckResourcePermissions(_db, _resource, _requestingPartyType, _session, Security.Authorization.ResourcePermissionType.VersionControl, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.CheckResourcePermissions)) { Data.VersionId oldCurrentVersionId; Tasks.CheckResourcePermissions task = (Tasks.CheckResourcePermissions)sender; if (!task.IsAuthorized) { TriggerOnAuthorizationDenied(task); return; } // If version number < rollback -> error // Versions: 0,1,2 / rollback: 2 -> 0th version if (_resource.CurrentVersionId.VersionNumber < _rollbackDepth) { TriggerOnError(null, "Rollback depth out of range.", null); return; } else if (_rollbackDepth <= 0) { TriggerOnError(null, "Rollback depth must be a positive value.", null); return; } oldCurrentVersionId = _resource.CurrentVersionId; _versionsToDelete = new Dictionary<Data.VersionId, Data.Version>(); long targetVersionNumber = _resource.CurrentVersionId.VersionNumber - _rollbackDepth; for(int i=0; i<_resource.VersionIds.Count; i++) { if (_resource.VersionIds[i].VersionNumber > targetVersionNumber) { Data.VersionId vid = new Data.VersionId(_resource.ResourceId, i); _versionsToDelete.Add(vid, new Data.Version(vid)); } } // Removes the versions more recent than the rollback point _resource.VersionIds.RemoveRange(_resource.VersionIds.Count - _rollbackDepth, _rollbackDepth); _resource.UpdateCurrentVersionBasedOnVersionsList(); Dictionary<Data.VersionId, Data.Version>.Enumerator en = _versionsToDelete.GetEnumerator(); // Dispatch all our heads to get the revisions // *note* do not combine these loops - we want the full list before starting while (en.MoveNext()) { RunTaskProcess(new Tasks.HeadVersion(_db, en.Current.Key, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } } else if (t == typeof(Tasks.HeadVersion)) { Tasks.HeadVersion task = (Tasks.HeadVersion)sender; if (!_versionsToDelete.ContainsKey(task.VersionId)) { TriggerOnError(task, "The id '" + task.VersionId.ToString() + "' could not be found.", new KeyNotFoundException()); return; } lock (_versionsToDelete) { _receivedCount++; _versionsToDelete[task.VersionId].UpdateRevision(task.Revision); if (_versionsToDelete.Count == _receivedCount) { // Inside here we have a collection "docs" that contains the new resource // which has the new "current" version and has all the more recent // versions removed. We also have inside "docs" deletion markers for all // the more recent versions. List<Exception> errors; List<Model.Document> docs = new List<Model.Document>(); Transitions.Resource txResource = new Transitions.Resource(); Model.Document doc = txResource.Transition(_resource, out errors); if (errors != null) { TriggerOnError(null, errors[0].Message, errors[0]); return; } doc.CombineWith(_remainder); docs.Add(doc); Dictionary<Data.VersionId, Data.Version>.Enumerator en = _versionsToDelete.GetEnumerator(); // Dispatch all our heads to get the revisions // *note* do not combine these loops - we want the full list before starting while (en.MoveNext()) { Transitions.Version txVersion = new Transitions.Version(); Model.Document doc2 = txVersion.Transition(en.Current.Value, out errors); if (errors != null) { TriggerOnError(null, errors[0].Message, errors[0]); return; } doc2.Add("_deleted", true); docs.Add(doc2); } RunTaskProcess(new Tasks.MakeBulkDocument(docs, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } } } else if (t == typeof(Tasks.MakeBulkDocument)) { Tasks.MakeBulkDocument task = (Tasks.MakeBulkDocument)sender; RunTaskProcess(new Tasks.UploadBulkDocuments(_db, task.BulkDocument, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.UploadBulkDocuments)) { Tasks.UploadBulkDocuments task = (Tasks.UploadBulkDocuments)sender; TriggerOnComplete(reply, task.Results); } else { TriggerOnError(sender, reply.ToString(), null); } }
/// <summary> /// Edit specific resource /// </summary> /// <param name="resource">The modified resource</param> public static void EditResource(Data.Resource resource) { Resources[resource.Module][resource.Language][resource.Key].Value = resource.Value; }
public override void TaskComplete(Tasks.Base sender, ICommandReply reply) { Type t = sender.GetType(); if (t == typeof(Tasks.DownloadGlobalPermissions)) { Tasks.DownloadGlobalPermissions task = (Tasks.DownloadGlobalPermissions)sender; _gur = task.GlobalUsageRights; RunTaskProcess(new Tasks.CheckGlobalPermissions(_db, _gur, _requestingPartyType, _session, Security.Authorization.GlobalPermissionType.CreateResource, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.CheckGlobalPermissions)) { Tasks.CheckGlobalPermissions task = (Tasks.CheckGlobalPermissions)sender; if (!task.IsAuthorized) { TriggerOnAuthorizationDenied(task); return; } RunTaskProcess(new Tasks.DownloadResourceUsageRightsTemplate(_db, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.DownloadResourceUsageRightsTemplate)) { string username = _session.User.Username; DateTime creation = DateTime.Now; List<Exception> errors; List<Model.Document> docs = new List<Model.Document>(); Tasks.DownloadResourceUsageRightsTemplate task = (Tasks.DownloadResourceUsageRightsTemplate)sender; // Create the Resource and Version objects List<Data.VersionId> versions = new List<Data.VersionId>(); Data.ResourceId resourceId = Data.ResourceId.Create(); _version = new Data.Version(new Data.VersionId(resourceId), _args.VersionArgs.Metadata, _args.VersionArgs.Content) { Md5 = _args.VersionArgs.Md5, Extension = _args.VersionArgs.Extension, Created = creation, Creator = username, Modified = creation, Modifier = username }; versions.Add(_version.VersionId); _resource = new Data.Resource(resourceId, null, versions, _version.VersionId, _args.Metadata, task.Value.UsageRights) { Tags = _args.Tags, Created = creation, Creator = username, Modified = creation, Modifier = username, CheckedOutAt = creation, CheckedOutTo = username, LastCommit = creation, LastCommitter = username, Title = _args.Title }; // Transition to json objects Transitions.Resource txResource = new Transitions.Resource(); docs.Add(txResource.Transition(_resource, out errors)); if (errors != null) { TriggerOnError(null, errors[0].Message, errors[0]); return; } Transitions.Version txVersion = new Transitions.Version(); docs.Add(txVersion.Transition(_version, out errors)); if (errors != null) { TriggerOnError(null, errors[0].Message, errors[0]); return; } RunTaskProcess(new Tasks.MakeBulkDocument(docs, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.MakeBulkDocument)) { Tasks.MakeBulkDocument task = (Tasks.MakeBulkDocument)sender; RunTaskProcess(new Tasks.UploadBulkDocuments(_db, task.BulkDocument, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.UploadBulkDocuments)) { Tasks.UploadBulkDocuments task = (Tasks.UploadBulkDocuments)sender; Commands.PostBulkDocumentsReply.Entry entry = task.FindEntryById(_version.VersionId.ToString()); if (entry == null) { TriggerOnError(task, "Failed to locate " + _version.VersionId.ToString() + " in the " + "bulk document post results.", null); return; } // This is needed so that couchdb can apply the content to the correct revision. _version.UpdateRevision(entry.Rev); // Upload Data.Content from Data.Version RunTaskProcess(new Tasks.UploadContent(_db, _version, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.UploadContent)) { TriggerOnComplete(reply, new Tuple<Data.Resource, Data.Version>(_resource, _version)); } else { TriggerOnError(sender, reply.ToString(), null); } }
public Data.Resource Transition(Model.Document document, out JObject remainder) { Data.Resource resource; Data.ResourceId id; string rev = null; Data.VersionId currentVersionId; List<Data.VersionId> versionIds = null; List<Security.UsageRight> usageRights = null; Security.UsageRight usageRight = null; JObject jobj = null; JProperty prop = null; IEnumerator<JToken> en; string verifyString; JArray jarray = new JArray(); if (!VerifyDocumentIntegrity(document, out verifyString)) { Logger.Storage.Error("The document is not properly formatted. It is missing the property '" + verifyString + "'."); throw new FormattingException("The argument document does not have the necessary property '" + verifyString + "'."); } // I ran into a problem here where I was removing the properties from the document and what was left was the remainder. // However, this causes an issue when using the transition to make a resource for permissions checking as the // object returned to implementing software is the document. Thus, the implementing software only received those properties // not removed... which obviously excludes the most important properties. To remedy this issue, I created a constructor for // Model.Document(Document). This constructor will format the argument document to a string and then create a JObject from // that string. C# will deep copy the string (not byref) so as to guarantee an independent object. remainder = new Model.Document(document); try { id = new Data.ResourceId(document.Id); if (document["_rev"] != null) { rev = document.Rev; remainder.Remove("_rev"); } remainder.Remove("_id"); remainder.Remove("$type"); currentVersionId = new Data.VersionId(document["$currentversionid"].Value<string>()); remainder.Remove("$currentversionid"); versionIds = new List<Data.VersionId>(); jarray = (JArray)document["$versionids"]; for (int i = 0; i < jarray.Count; i++) versionIds.Add(new Data.VersionId(jarray[i].Value<string>())); remainder.Remove("$versionids"); usageRights = new List<Security.UsageRight>(); jarray = (JArray)document["$usagerights"]; for (int i = 0; i < jarray.Count; i++) { jobj = (JObject)jarray[i]; en = jobj.Children().GetEnumerator(); while (en.MoveNext()) { prop = (JProperty)en.Current; // Json.Net is giving me some weird errors here when I try to call prop.value<int>(); // I cannot figure out why so this code is a temporary work-around, it needs figured out. string a = prop.ToString(); a = a.Substring(a.LastIndexOf("\"") + 1); // we know the value is an int, so we can look for the last " a = a.Replace(":", "").Trim(); usageRight = new Security.UsageRight(prop.Name, (Security.Authorization.ResourcePermissionType)int.Parse(a)); usageRights.Add(usageRight); } } remainder.Remove("$usagerights"); resource = new Data.Resource(id, rev, versionIds, currentVersionId, new Data.Metadata(), usageRights); // Tags resource.Tags = new List<string>(); jarray = (JArray)document["$tags"]; for (int i = 0; i < jarray.Count; i++) resource.Tags.Add(jarray[i].Value<string>()); remainder.Remove("$tags"); resource.Created = document["$created"].Value<DateTime>(); resource.Creator = document["$creator"].Value<string>(); resource.Modified = document["$modified"].Value<DateTime>(); resource.Modifier = document["$modifier"].Value<string>(); resource.CheckedOutAt = document["$checkedoutat"].Value<DateTime>(); resource.CheckedOutTo = document["$checkedoutto"].Value<string>(); resource.LastCommit = document["$lastcommit"].Value<DateTime>(); resource.LastCommitter = document["$lastcommitter"].Value<string>(); resource.Title = document["$title"].Value<string>(); remainder.Remove("$created"); remainder.Remove("$creator"); remainder.Remove("$modified"); remainder.Remove("$modifier"); remainder.Remove("$checkedoutat"); remainder.Remove("$checkedoutto"); remainder.Remove("$lastcommit"); remainder.Remove("$lastcommitter"); remainder.Remove("$title"); } catch (Exception e) { Logger.Storage.Error("An exception occurred while attempting to parse the document.", e); throw; } return resource; }
public override void TaskComplete(Tasks.Base sender, ICommandReply reply) { Type t = sender.GetType(); if (t == typeof(Tasks.DownloadResource)) { Tasks.DownloadResource task = (Tasks.DownloadResource)sender; _resource = task.Resource; _remainder = task.Remainder; RunTaskProcess(new Tasks.CheckResourcePermissions(_db, _resource, _requestingPartyType, _session, Security.Authorization.ResourcePermissionType.Delete, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.CheckResourcePermissions)) { Tasks.CheckResourcePermissions task = (Tasks.CheckResourcePermissions)sender; if (!task.IsAuthorized) { TriggerOnAuthorizationDenied(task); return; } // First, we load up revisions for (int i = 0; i < _resource.VersionIds.Count; i++) { _versions.Add(_resource.VersionIds[i], new Data.Version(_resource.VersionIds[i])); } // Now our _revisions holds indexes for all version ids // Dispatch all our heads to get the revisions // *note* do not combine these loops - we want the full dictionary before starting for (int i = 0; i < _resource.VersionIds.Count; i++) { RunTaskProcess(new Tasks.HeadVersion(_db, _resource.VersionIds[i], _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } } else if (t == typeof(Tasks.HeadVersion)) { Tasks.HeadVersion task = (Tasks.HeadVersion)sender; if (!_versions.ContainsKey(task.VersionId)) { TriggerOnError(task, "The id '" + task.VersionId.ToString() + "' could not be found.", new KeyNotFoundException()); return; } lock (_versions) { _receivedCount++; _versions[task.VersionId].UpdateRevision(task.Revision); if (_versions.Count == _receivedCount) { List<Exception> errors; List<Model.Document> docs = new List<Model.Document>(); Transitions.Resource txResource = new Transitions.Resource(); Model.Document doc = txResource.Transition(_resource, out errors); if (errors != null) { TriggerOnError(null, errors[0].Message, errors[0]); return; } // Pointless, we are deleting it //doc.CombineWith(_remainder); doc.Add("_deleted", true); docs.Add(doc); Dictionary<Data.VersionId, Data.Version>.Enumerator en = _versions.GetEnumerator(); while (en.MoveNext()) { Transitions.Version txVersion = new Transitions.Version(); Model.Document doc2 = txVersion.Transition(en.Current.Value, out errors); if (errors != null) { TriggerOnError(null, errors[0].Message, errors[0]); return; } doc2.Add("_deleted", true); docs.Add(doc2); } RunTaskProcess(new Tasks.MakeBulkDocument(docs, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else { TriggerOnProgress(task, Networking.Protocols.Tcp.DirectionType.Download, -1, -1, ((decimal)((decimal)_receivedCount / (decimal)_versions.Count))); } } } else if (t == typeof(Tasks.MakeBulkDocument)) { Tasks.MakeBulkDocument task = (Tasks.MakeBulkDocument)sender; RunTaskProcess(new Tasks.UploadBulkDocuments(_db, task.BulkDocument, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.UploadBulkDocuments)) { Tasks.UploadBulkDocuments task = (Tasks.UploadBulkDocuments)sender; TriggerOnComplete(reply, task.Results); } else { TriggerOnError(sender, reply.ToString(), null); } }
public override void TaskComplete(Tasks.Base sender, ICommandReply reply) { Type t = sender.GetType(); if (t == typeof(Tasks.DownloadResource)) { Tasks.DownloadResource task = (Tasks.DownloadResource)sender; _resource = task.Resource; _remainder = task.Remainder; RunTaskProcess(new Tasks.CheckResourcePermissions(_db, _resource, _requestingPartyType, _session, Security.Authorization.ResourcePermissionType.Delete, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.CheckResourcePermissions)) { Tasks.CheckResourcePermissions task = (Tasks.CheckResourcePermissions)sender; if (!task.IsAuthorized) { TriggerOnAuthorizationDenied(task); return; } // First, we load up revisions for (int i = 0; i < _resource.VersionIds.Count; i++) { _versions.Add(_resource.VersionIds[i], new Data.Version(_resource.VersionIds[i])); } // Now our _revisions holds indexes for all version ids // Dispatch all our heads to get the revisions // *note* do not combine these loops - we want the full dictionary before starting for (int i = 0; i < _resource.VersionIds.Count; i++) { RunTaskProcess(new Tasks.HeadVersion(_db, _resource.VersionIds[i], _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } } else if (t == typeof(Tasks.HeadVersion)) { Tasks.HeadVersion task = (Tasks.HeadVersion)sender; if (!_versions.ContainsKey(task.VersionId)) { TriggerOnError(task, "The id '" + task.VersionId.ToString() + "' could not be found.", new KeyNotFoundException()); return; } lock (_versions) { _receivedCount++; _versions[task.VersionId].UpdateRevision(task.Revision); if (_versions.Count == _receivedCount) { List <Exception> errors; List <Model.Document> docs = new List <Model.Document>(); Transitions.Resource txResource = new Transitions.Resource(); Model.Document doc = txResource.Transition(_resource, out errors); if (errors != null) { TriggerOnError(null, errors[0].Message, errors[0]); return; } // Pointless, we are deleting it //doc.CombineWith(_remainder); doc.Add("_deleted", true); docs.Add(doc); Dictionary <Data.VersionId, Data.Version> .Enumerator en = _versions.GetEnumerator(); while (en.MoveNext()) { Transitions.Version txVersion = new Transitions.Version(); Model.Document doc2 = txVersion.Transition(en.Current.Value, out errors); if (errors != null) { TriggerOnError(null, errors[0].Message, errors[0]); return; } doc2.Add("_deleted", true); docs.Add(doc2); } RunTaskProcess(new Tasks.MakeBulkDocument(docs, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else { TriggerOnProgress(task, Networking.Protocols.Tcp.DirectionType.Download, -1, -1, ((decimal)((decimal)_receivedCount / (decimal)_versions.Count))); } } } else if (t == typeof(Tasks.MakeBulkDocument)) { Tasks.MakeBulkDocument task = (Tasks.MakeBulkDocument)sender; RunTaskProcess(new Tasks.UploadBulkDocuments(_db, task.BulkDocument, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.UploadBulkDocuments)) { Tasks.UploadBulkDocuments task = (Tasks.UploadBulkDocuments)sender; TriggerOnComplete(reply, task.Results); } else { TriggerOnError(sender, reply.ToString(), null); } }
// Create sprite object public override Tuple <Sprite, Sprite> GetSpriteParts(Data.Resource resource, uint index) { if (index >= Data.GetResourceCount(resource)) { return(Tuple.Create <Sprite, Sprite>(null, null)); } Resource dosRes = DosResources[(int)resource]; ColorDos[] palette = GetDosPalette(dosRes.DosPalette); Buffer data; if (palette == null) { return(Tuple.Create <Sprite, Sprite>(null, null)); } if (resource == Data.Resource.SerfTorso) { data = GetObject(dosRes.Index + index); if (data == null) { return(Tuple.Create <Sprite, Sprite>(null, null)); } Sprite torso = new SpriteDosTransparent(data, palette, 64); data = GetObject(dosRes.Index + index); if (data == null) { return(Tuple.Create <Sprite, Sprite>(null, null)); } Sprite torso2 = new SpriteDosTransparent(data, palette, 72); MaskImage maskImage = SeparateSprites(torso, torso2); data = GetObject(DATA_SERF_ARMS + index); Sprite arms = new SpriteDosTransparent(data, palette); torso.Stick(arms, 0, 0); return(maskImage); } else if (resource == Data.Resource.MapObject) { if ((index >= 128) && (index <= 143)) { // Flag sprites uint flagFrame = (index - 128) % 4; data = GetObject(dosRes.Index + 128 + flagFrame); if (data == null) { return(Tuple.Create <Sprite, Sprite>(null, null)); } Sprite s1 = new SpriteDosTransparent(data, palette); data = GetObject(dosRes.Index + 128 + 4 + flagFrame); if (data == null) { return(Tuple.Create <Sprite, Sprite>(null, null)); } Sprite s2 = new SpriteDosTransparent(data, palette); return(SeparateSprites(s1, s2)); } } else if (resource == Data.Resource.Font || resource == Data.Resource.FontShadow) { data = GetObject(dosRes.Index + index); if (data == null) { return(Tuple.Create <Sprite, Sprite>(null, null)); } return(Tuple.Create <Sprite, Sprite>(new SpriteDosTransparent(data, palette), null)); } data = GetObject(dosRes.Index + index); if (data == null) { return(Tuple.Create <Sprite, Sprite>(null, null)); } Sprite sprite; switch (dosRes.SpriteType) { case SpriteType.Solid: { sprite = new SpriteDosSolid(data, palette); break; } case SpriteType.Transparent: { sprite = new SpriteDosTransparent(data, palette); break; } case SpriteType.Overlay: { sprite = new SpriteDosOverlay(data, palette, 0x80); break; } case SpriteType.Mask: { sprite = new SpriteDosMask(data); break; } default: return(Tuple.Create <Sprite, Sprite>(null, null)); } return(Tuple.Create <Sprite, Sprite>(null, sprite)); }
public override void TaskComplete(Tasks.Base sender, ICommandReply reply) { Type t = sender.GetType(); if (t == typeof(Tasks.DownloadResource)) { Tasks.DownloadResource task = (Tasks.DownloadResource)sender; _resource = task.Resource; _resourceRemainder = task.Remainder; RunTaskProcess(new Tasks.CheckResourcePermissions(_db, _resource, _requestingPartyType, _session, Security.Authorization.ResourcePermissionType.Modify, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.CheckResourcePermissions)) { Tasks.CheckResourcePermissions task = (Tasks.CheckResourcePermissions)sender; if (!task.IsAuthorized) { TriggerOnAuthorizationDenied(task); return; } RunTaskProcess(new Tasks.MarkResourceForCheckout(_resource, _session.User.Username, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.MarkResourceForCheckout)) { Tasks.MarkResourceForCheckout task = (Tasks.MarkResourceForCheckout)sender; _resource = task.Resource; List<Exception> errors; List<Model.Document> docs = new List<Model.Document>(); Transitions.Version txVersion = new Transitions.Version(); Transitions.Resource txResource = new Transitions.Resource(); docs.Add(txResource.Transition(_resource, out errors)); if (errors != null) { TriggerOnError(null, errors[0].Message, errors[0]); return; } docs[0].CombineWith(_resourceRemainder); docs.Add(txVersion.Transition(_version, out errors)); if (errors != null) { TriggerOnError(null, errors[0].Message, errors[0]); return; } RunTaskProcess(new Tasks.MakeBulkDocument(docs, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.MakeBulkDocument)) { Tasks.MakeBulkDocument task = (Tasks.MakeBulkDocument)sender; RunTaskProcess(new Tasks.UploadBulkDocuments(_db, task.BulkDocument, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.UploadBulkDocuments)) { Tasks.UploadBulkDocuments task = (Tasks.UploadBulkDocuments)sender; Commands.PostBulkDocumentsReply.Entry entry = task.FindEntryById(_version.VersionId.ToString()); if (entry == null) { TriggerOnError(task, "Failed to locate " + _version.VersionId.ToString() + " in the " + "bulk document post results.", null); return; } // This is needed so that couchdb can apply the content to the correct revision. _version.UpdateRevision(entry.Rev); // If no content -> return if (_version.Content == null) { Resource = _resource; Version = _version; TriggerOnComplete(reply, new Tuple<Data.Resource, Data.Version>(_resource, _version)); return; } // Upload Data.Content from Data.Version RunTaskProcess(new Tasks.UploadContent(_db, _version, _sendTimeout, _receiveTimeout, _sendBufferSize, _receiveBufferSize)); } else if (t == typeof(Tasks.UploadContent)) { Resource = _resource; Version = _version; TriggerOnComplete(reply, new Tuple<Data.Resource, Data.Version>(_resource, _version)); } else { TriggerOnError(sender, reply.ToString(), null); } }
public ModifyResource(EngineRequest request, Data.Resource resource) : base(request) { _resource = resource; }