public async Task <ActionResult <MediaLinkModel> > Post([FromForm] CreateMediaLinkViewModel model) { MediaLinkModel exists = await _context.MediaLinks.FirstOrDefaultAsync(x => x.Name == model.Name); MediaGroupModel group = await _context.MediaGroups.FirstOrDefaultAsync(x => x.Id == model.Group); if (exists != null) { return(BadRequest($"An image with name {model.Name} already exists.")); } using (MemoryStream thumbnail = CreateThumbnail(model.File)) using (MemoryStream memoryStream = new MemoryStream()) { model.File.CopyTo(memoryStream); try { await PutImageAsync(memoryStream, $"{group.NormalizedName}/{model.Name}"); await PutImageAsync(thumbnail, $"{Constants.ThumbnailGroup}/{group.NormalizedName}/{model.Name}"); } catch (Exception ex) { return(BadRequest(ex.Message)); } } MediaLinkModel image = new MediaLinkModel() { Name = model.Name, Group = group, Url = $"https://{_config["aws:bucket"]}.s3.amazonaws.com/{group.NormalizedName}/{model.Name}", Thumbnail = $"https://{_config["aws:bucket"]}.s3.amazonaws.com/{Constants.ThumbnailGroup}/{group.NormalizedName}/{model.Name}" }; try { await _context.MediaLinks.AddAsync(image); await _context.SaveChangesAsync(); return(Ok(image)); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
public async Task <ActionResult <MediaLinkModel> > Delete(Guid id) { MediaLinkModel model = await _context.MediaLinks.Include(x => x.Group).FirstOrDefaultAsync(x => x.Id == id); if (model == null) { return(NotFound($"Image with Id {id} not found.")); } string modelKey = $"{model.Group.NormalizedName}/{model.Name}"; string thumbnailKey = $"{Constants.ThumbnailGroup}/{modelKey}"; DeleteObjectsRequest request = new DeleteObjectsRequest { BucketName = _config["aws:bucket"], Objects = new List <KeyVersion>() { new KeyVersion() { Key = modelKey }, new KeyVersion() { Key = thumbnailKey } } }; try { await _s3Client.DeleteObjectsAsync(request); _context.MediaLinks.Remove(model); await _context.SaveChangesAsync(); return(Ok(model)); } catch (Exception ex) { return(BadRequest(ex.Message)); } }