public IActionResult GetPartFromTypeAndRole( [FromRoute] string database, [FromRoute] string id, [FromRoute] string type, [FromRoute] string role) { ICadmusRepository repository = _repositoryProvider.CreateRepository(database); IPart part = repository.GetItemParts(new[] { id }, type == "any" ? null : type, role == "default" ? null : role) .FirstOrDefault(); if (part == null) { return(NotFound()); } string json = repository.GetPartContent(part.Id); if (json == null) { return(new NotFoundResult()); } json = AdjustPartJson(json); object result = JsonConvert.DeserializeObject(json); return(Ok(result)); }
public ActionResult <Dictionary <string, ThesaurusModel> > GetThesauri( [FromRoute] string database, [FromRoute] string ids, [FromQuery] bool purgeIds) { ICadmusRepository repository = _repositoryProvider.CreateRepository(database); Dictionary <string, ThesaurusModel> dct = new Dictionary <string, ThesaurusModel>(); foreach (string id in (ids ?? "") .Split(',', StringSplitOptions.RemoveEmptyEntries) .Distinct()) { Thesaurus thesaurus = repository.GetThesaurus(id); if (thesaurus == null) { continue; } dct[purgeIds ? PurgeThesaurusId(id) : id] = new ThesaurusModel { Id = thesaurus.Id, Language = thesaurus.GetLanguage(), Entries = thesaurus.GetEntries().ToArray() }; } return(Ok(dct)); }
public IActionResult GetSetIds([FromRoute] string database) { ICadmusRepository repository = _repositoryProvider.CreateRepository(database); return(Ok(repository.GetThesaurusIds())); }
public ActionResult <FacetDefinition[]> Get(string database) { ICadmusRepository repository = _repositoryProvider.CreateRepository(database); return(Ok(repository.GetFacetDefinitions().ToArray())); }
public IActionResult GetLayerPartBreakChance( [FromRoute] string database, [FromRoute] string id) { ICadmusRepository repository = _repositoryProvider.CreateRepository(database); string intervalOption = _configuration.GetSection("Editing") ["BaseToLayerToleranceSeconds"]; int interval; if (!string.IsNullOrEmpty(intervalOption) && int.TryParse(intervalOption, out int n)) { interval = n; } else { interval = 60; } int chance = repository.GetLayerPartBreakChance(id, interval); return(Ok(new { Chance = chance })); }
public async Task <IActionResult> DeletePart( [FromRoute] string database, [FromRoute] string id) { _logger.Information("User {UserName} deleting part {PartId} from {IP}", User.Identity.Name, id, HttpContext.Connection.RemoteIpAddress); ICadmusRepository repository = _repositoryProvider.CreateRepository(database); // operators can delete only parts created by themselves ApplicationUser user = await _userManager.GetUserAsync(User); if (await IsUserInRole(user, "operator", new HashSet <string>(new string[] { "admin", "editor" })) && repository.GetPartCreatorId(id) != user.UserName) { return(Unauthorized()); } repository.DeletePart(id, User.Identity.Name); return(Ok()); }
public IActionResult GetThesaurus( [FromRoute] string database, [FromRoute] string id, [FromQuery] bool emptyIfNotFound) { ICadmusRepository repository = _repositoryProvider.CreateRepository(database); Thesaurus thesaurus = repository.GetThesaurus(id); if (thesaurus == null) { return(emptyIfNotFound ? Ok(new ThesaurusModel { Id = id, Language = "en", Entries = Array.Empty <ThesaurusEntry>() }) : (IActionResult)NotFound()); } ThesaurusModel model = new ThesaurusModel { Id = thesaurus.Id, Language = thesaurus.GetLanguage(), Entries = thesaurus.GetEntries().ToArray() }; return(Ok(model)); }
public ActionResult <DataPage <ItemInfo> > GetItems( [FromRoute] string database, [FromQuery] ItemFilterModel filter) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } ICadmusRepository repository = _repositoryProvider.CreateRepository(database); DataPage <ItemInfo> page = repository.GetItems(new ItemFilter { PageNumber = filter.PageNumber, PageSize = filter.PageSize, Title = filter.Title, Description = filter.Description, FacetId = filter.FacetId, GroupId = filter.GroupId, Flags = filter.Flags, MinModified = filter.MinModified, MaxModified = filter.MaxModified, UserId = filter.UserId }); return(Ok(page)); }
/// <summary> /// Builds the whole index by indexing all the items in the specified /// repository. /// </summary> /// <param name="repository">The repository.</param> /// <param name="filter">The optional item filter; paging information /// will be overwritten.</param> /// <param name="cancel">The cancellation token.</param> /// <param name="progress">The optional progress reporter.</param> public void Build( ICadmusRepository repository, ItemFilter filter, CancellationToken cancel, IProgress <ProgressReport> progress = null) { if (filter == null) { filter = new ItemFilter(); } filter.PageNumber = 1; filter.PageSize = 100; // first page DataPage <ItemInfo> page = repository.GetItems(filter); if (page.Total == 0) { return; } ProgressReport report = progress != null ? new ProgressReport() : null; do { // index all the items in page foreach (ItemInfo info in page.Items) { IItem item = repository.GetItem(info.Id); if (item == null) { continue; } _writer.Write(item); } // handle cancel and progress if (cancel.IsCancellationRequested) { break; } if (progress != null) { report.Count += page.Items.Count; report.Percent = report.Count * 100 / page.Total; progress.Report(report); } // next page if (++filter.PageNumber > page.PageCount) { break; } page = repository.GetItems(filter); } while (page.Items.Count != 0); }
public void DeleteThesaurus( [FromRoute] string database, [FromRoute] string id) { ICadmusRepository repository = _repositoryProvider.CreateRepository(database); repository.DeleteThesaurus(id); }
/// <summary> /// Initializes a new instance of the <see cref="PartImporter"/> class. /// </summary> /// <param name="repository">The repository.</param> /// <exception cref="ArgumentNullException">repository</exception> public PartImporter(ICadmusRepository repository) { _options = new JsonDocumentOptions { AllowTrailingCommas = true }; _repository = repository ?? throw new ArgumentNullException(nameof(repository)); }
public ActionResult <LayerHint> GetLayerPartHints( [FromRoute] string database, [FromRoute] string id) { ICadmusRepository repository = _repositoryProvider.CreateRepository(database); return(Ok(repository.GetLayerPartHints(id))); }
public IActionResult GetItemLayerInfo( [FromRoute] string database, [FromRoute] string id, [FromQuery] bool absent) { ICadmusRepository repository = _repositoryProvider.CreateRepository(database); IList <LayerPartInfo> parts = repository.GetItemLayerInfo(id, absent); return(Ok(parts)); }
private Tuple <string, string> AddRawPart(string database, string raw) { ICadmusRepository repository = _repositoryProvider.CreateRepository(database); JObject doc = JObject.Parse(raw); // add the ID if new part JValue id = (JValue)doc["id"]; string partId; bool isNew = id == null || !_guidRegex.IsMatch(id.Value <string>()); if (isNew) { partId = Guid.NewGuid().ToString("N"); if (id != null) { doc.Property("id").Remove(); } doc.AddFirst(new JProperty("id", partId)); } else { partId = id.Value <string>(); } // set the creator ID if not specified JValue creatorId = (JValue)doc["creatorId"]; if (string.IsNullOrEmpty(creatorId?.ToString())) { if (creatorId != null) { doc.Property("creatorId").Remove(); } doc.Add(new JProperty("creatorId", User.Identity.Name)); } // override the user ID doc.Property("userId")?.Remove(); doc.Add(new JProperty("userId", User.Identity.Name ?? "")); // add the part _logger.Information("User {UserName} saving part {PartId} from {IP}", User.Identity.Name, partId, HttpContext.Connection.RemoteIpAddress); string json = doc.ToString(Formatting.None); repository.AddPartFromContent(json); return(Tuple.Create(partId, json)); }
public ActionResult <PartDefinition[]> GetFacetParts(string database, [FromRoute] string id, [FromQuery] bool noRoles = false) { ICadmusRepository repository = _repositoryProvider.CreateRepository(database); FacetDefinition facet = repository.GetFacetDefinition(id); PartDefinition[] result = CollectFacetParts(facet, noRoles); return(Ok(result)); }
public void Delete([FromRoute] string database, [FromRoute] string id) { _logger.Information("User {UserName} deleting item {ItemId} from {IP}", User.Identity.Name, id, HttpContext.Connection.RemoteIpAddress); ICadmusRepository repository = _repositoryProvider.CreateRepository(database); repository.DeleteItem(id, User.Identity.Name); }
public IActionResult AddItem( [FromRoute] string database, [FromBody] ItemBindingModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } Item item = new Item { Title = model.Title, Description = model.Description, FacetId = model.FacetId, SortKey = model.SortKey, Flags = model.Flags, // override the user ID UserId = User.Identity.Name, }; // set the creator ID if not specified if (string.IsNullOrEmpty(item.CreatorId)) { item.CreatorId = User.Identity.Name; } // set the item's ID if specified, else go with the default // newly generated one if (!string.IsNullOrEmpty(model.Id) && _guidRegex.IsMatch(model.Id)) { item.Id = model.Id; } _logger.Information("User {UserName} saving item {ItemId} from {IP}", User.Identity.Name, item.Id, HttpContext.Connection.RemoteIpAddress); ICadmusRepository repository = _repositoryProvider.CreateRepository(database); repository.AddItem(item); return(CreatedAtRoute("GetItem", new { database, id = item.Id, parts = false }, item)); }
public async Task Run() { Console.WriteLine("EXPORT APPARATUS INTO TEI FILES\n"); Console.ResetColor(); Console.WriteLine( $"Database: {_database}\n" + $"Output dir: {_outputDir}\n" + $"Comments: {_comments}\n" + $"Dry: {_dry}\n" + $"Group IDs: {string.Join(", ", _groupIds)}"); ILoggerFactory loggerFactory = new LoggerFactory(); loggerFactory.AddSerilog(Log.Logger); Log.Logger.Information("EXPORT APPARATUS INTO TEI FILES"); ICadmusRepository repository = _repositoryProvider.CreateRepository(_database); ApparatusExporter exporter = new ApparatusExporter(repository) { Logger = loggerFactory.CreateLogger("export"), IncludeComments = _comments, IsDryModeEnabled = _dry }; foreach (string id in _groupIds) { exporter.SelectedGroupIds.Add(id); } if (!Directory.Exists(_outputDir)) { Directory.CreateDirectory(_outputDir); } using (var bar = new ProgressBar(100, "Exporting...", new ProgressBarOptions { ProgressCharacter = '.', ProgressBarOnBottom = true, DisplayTimeInRealTime = false })) { await exporter.ExportAsync(_outputDir, new Progress <ProgressReport>( r => bar.Tick(r.Percent, r.Message))); } }
public IActionResult SetPartThesaurusScope( [FromRoute] string database, [FromBody] PartThesaurusScopeBindingModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } ICadmusRepository repository = _repositoryProvider.CreateRepository(database); repository.SetPartThesaurusScope(model.Ids, model.Scope); return(Ok()); }
public IActionResult SetItemGroupId( [FromRoute] string database, [FromBody] ItemGroupIdBindingModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } ICadmusRepository repository = _repositoryProvider.CreateRepository(database); repository.SetItemGroupId(model.Ids, model.GroupId); return(Ok()); }
public ActionResult <PartDefinition> GetFacet( string database, [FromRoute] string id) { ICadmusRepository repository = _repositoryProvider.CreateRepository(database); FacetDefinition facet = repository.GetFacetDefinition(id); if (facet == null) { return(NotFound()); } return(Ok(facet)); }
public ActionResult <IItem> GetItem( [FromRoute] string database, [FromRoute] string id, [FromQuery] bool parts) { ICadmusRepository repository = _repositoryProvider.CreateRepository(database); IItem item = repository.GetItem(id, parts); if (item == null) { return(new NotFoundResult()); } return(Ok(item)); }
public IActionResult GetTextLayerPartTypeId(string database) { ICadmusRepository repository = _repositoryProvider.CreateRepository(database); foreach (FacetDefinition facet in repository.GetFacetDefinitions()) { PartDefinition partDef = facet.PartDefinitions .Find(d => d.RoleId?.StartsWith( PartBase.FR_PREFIX, StringComparison.Ordinal) == true); if (partDef != null) { return(Ok(new { partDef.TypeId })); } } return(Ok(new { TypeId = (string)null })); }
public IActionResult ApplyLayerPartPatches( [FromRoute] string database, [FromRoute] string id, [FromBody] string[] patches) { ICadmusRepository repository = _repositoryProvider.CreateRepository(database); string json = repository.ApplyLayerPartPatches( id, User.Identity.Name, patches); return(CreatedAtRoute("GetPart", new { database, id }, json)); }
public IActionResult GetPart( [FromRoute] string database, [FromRoute] string id) { ICadmusRepository repository = _repositoryProvider.CreateRepository(database); string json = repository.GetPartContent(id); if (json == null) { return(new NotFoundResult()); } json = AdjustPartJson(json); object part = JsonConvert.DeserializeObject(json); return(Ok(part)); }
public IActionResult GetBaseText( [FromRoute] string database, [FromRoute] string itemId) { ICadmusRepository repository = _repositoryProvider.CreateRepository(database); IHasText partWithText = repository.GetItemParts( new[] { itemId }, null, PartBase.BASE_TEXT_ROLE_ID) .FirstOrDefault() as IHasText; return(Ok(new { Part = partWithText, Text = partWithText?.GetText() })); }
/// <summary> /// Builds the sort key from the specified item. /// </summary> /// <param name="item">The item.</param> /// <param name="repository">The repository.</param> /// <returns>Sort key.</returns> /// <exception cref="ArgumentNullException">item</exception> public string BuildKey(IItem item, ICadmusRepository repository) { if (item == null) { throw new ArgumentNullException(nameof(item)); } if (_ud == null) { _ud = new UniData(); } StringBuilder sb = new StringBuilder(); foreach (char c in item.Title ?? "") { if (char.IsWhiteSpace(c)) { if (sb.Length > 0 && (sb[sb.Length - 1] != ' ')) { sb.Append(' '); } } else { if (char.IsDigit(c) || c == '\'') { sb.Append(c); continue; } if (char.IsLetter(c)) { char seg = _ud.GetSegment(char.ToLowerInvariant(c), true); if (seg != '\0') { sb.Append(seg); } } } } return(sb.ToString().TrimEnd()); }
public IActionResult GetPartPins( [FromRoute] string database, [FromRoute] string id) { ICadmusRepository repository = _repositoryProvider.CreateRepository(database); string json = repository.GetPartContent(id); if (json == null) { return(new NotFoundResult()); } // remove ISODate(...) function (this seems to be a Mongo artifact) json = Regex.Replace(json, @"ISODate\(([^)]+)\)", "$1"); // Pascal-case properties json = _camelPropRegex.Replace(json, m => $"\"{m.Groups[1].Value.ToUpperInvariant()}{m.Groups[2].Value}\":"); Match typeMatch = Regex.Match(json, "\"TypeId\":\\s*\"([^\"]+)\""); if (!typeMatch.Success) { return(NotFound()); } Match roleMatch = Regex.Match(json, "\"RoleId\":\\s*\"([^\"]+)\""); string role = roleMatch.Success ? roleMatch.Groups[1].Value : null; IPartTypeProvider provider = _repositoryProvider.GetPartTypeProvider(); Type t = provider.Get(typeMatch.Groups[1].Value); IPart part = (IPart)JsonConvert.DeserializeObject(json, t); var result = (from p in part.GetDataPins() select new { p.Name, p.Value }).ToList(); return(Ok(result)); }
/// <summary> /// Initializes a new instance of the <see cref="ApparatusExporter"/> class. /// </summary> /// <param name="repository">The repository.</param> /// <exception cref="ArgumentNullException">repository</exception> public ApparatusExporter(ICadmusRepository repository) : base(repository) { SelectedGroupIds = new HashSet <string>(); _layerPartTypeId = new TiledTextLayerPart <ApparatusLayerFragment>().TypeId; TagAttribute?attr = typeof(ApparatusLayerFragment).GetTypeInfo() .GetCustomAttribute <TagAttribute>(); string frTag = attr != null ? attr.Tag : GetType().FullName !; // apparatus fragment IDs for plain apparatus and margin apparatus _apparatusFrIds = new string[] { frTag, $"{frTag}:margin" }; _noteRenderer = new NoteElementRenderer(); _locMapper = new LocationToIdMapper(); // for parsing normValue (=ident + # + @n` N times) _identRegex = new Regex(@"(?<i>[^#]+)(?:\#(?<n>[^`]+)`?)?"); }
public ActionResult <PartDefinition> GetFacetFromItemId( string database, [FromRoute] string id) { ICadmusRepository repository = _repositoryProvider.CreateRepository(database); IItem item = repository.GetItem(id, false); if (item?.FacetId == null) { return(NotFound()); } FacetDefinition facet = repository.GetFacetDefinition(item.FacetId); if (facet == null) { return(NotFound()); } return(Ok(facet)); }