public async Task <Unit> Handle(DeleteAttachmentCommand request, CancellationToken cancellationToken) { var attachment = await fileDb.ByIdAsync(request.Id); if (null == attachment) { throw new AttachmentNotFoundException(request.Id); } foreach (var subAttachment in attachment.SubAttachments) { await DeleteFile(subAttachment.RealFilename()); } await DeleteFile(attachment.RealFilename()); await fileDb.DeleteAsync(request.Id, cancellationToken); await fileDb.CommitAsync(cancellationToken); return(Unit.Value); }
public async Task <Unit> Handle(CreateAttachmentCommand request, CancellationToken cancellationToken) { try { var stream = new MemoryStream(); request.AttachmentStream.Position = 0; await request.AttachmentStream.CopyToAsync(stream, cancellationToken); var attachment = new Attachment { Id = request.Id, Filename = request.Filename !.Trim(), MimeType = request.MimeType.Trim(), Size = AttachmentSize.MEDIA_SIZE_ORIG, FileSize = stream.Length, }; var filename = attachment.RealFilename(); await SaveFileAsync(stream, filename); stream.Position = 0; await fileDb.AddAsync(attachment, cancellationToken); if ((request.MimeType?.Trim().StartsWith("image") ?? false) && !request.MimeType.Trim().StartsWith("image/svg")) { try { foreach (var settingEntry in sizeSettings.Settings) { stream.Position = 0; using var img = new MagickImage(stream); var size = new MagickGeometry(Math.Min(settingEntry.MaxWidth, img.Width), Math.Min(settingEntry.MaxHeight, img.Height)); switch (Path.GetExtension(request.Filename)) { case ".jpg": img.Format = MagickFormat.Pjpeg; img.Interlace = Interlace.Jpeg; break; case ".png": img.Interlace = Interlace.Png; break; } img.Resize(size); img.Quality = settingEntry.Quality; var resizedStream = new MemoryStream(); await img.WriteAsync(resizedStream); var fileSize = resizedStream.Length; var resizedAttachment = new Attachment() { Id = Guid.NewGuid(), OriginalAttachmentId = request.Id, Filename = request.Filename?.Trim(), MimeType = request.MimeType?.Trim(), FileSize = fileSize, Size = settingEntry.Size, }; await SaveFileAsync(resizedStream, resizedAttachment.RealFilename()); await fileDb.AddAsync(resizedAttachment, cancellationToken); } } catch (Exception e) { logger.LogInformation($"Could not create smaller sizes for image, {e.Message}"); } } await fileDb.CommitAsync(cancellationToken); } catch { foreach (var storedFile in storedFiles) { try { File.Delete(storedFile); } catch { // ignored } } throw; } return(Unit.Value); }