Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Form & Email attachments #12218

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
<ProjectReference Include="..\..\OrchardCore\OrchardCore.Admin.Abstractions\OrchardCore.Admin.Abstractions.csproj" />
<ProjectReference Include="..\..\OrchardCore\OrchardCore.DisplayManagement\OrchardCore.DisplayManagement.csproj" />
<ProjectReference Include="..\..\OrchardCore\OrchardCore.Email.Core\OrchardCore.Email.Core.csproj" />
<ProjectReference Include="..\..\OrchardCore\OrchardCore.FileStorage.FileSystem\OrchardCore.FileStorage.FileSystem.csproj" />
<ProjectReference Include="..\..\OrchardCore\OrchardCore.Media.Abstractions\OrchardCore.Media.Abstractions.csproj" />
<ProjectReference Include="..\..\OrchardCore\OrchardCore.Navigation.Core\OrchardCore.Navigation.Core.csproj" />
<ProjectReference Include="..\..\OrchardCore\OrchardCore.Module.Targets\OrchardCore.Module.Targets.csproj" />
<ProjectReference Include="..\..\OrchardCore\OrchardCore.ResourceManagement\OrchardCore.ResourceManagement.csproj" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,22 @@
<span class="hint">@T["The subject of the email message. With Liquid support."]</span>
</div>

<div class="mb-3">
<div class="form-check">
<input type="checkbox" class="form-check-input" asp-for="IncludeStoredAttachments" />
<label class="form-check-label" asp-for="IncludeStoredAttachments">@T["Include attachments from Save Form Attachments Task."]</label>
<span class="hint dashed">@T["If checked, attachments are included into email. They are also stored in predefined folder."]</span>
</div>
</div>

<div class="mb-3">
<div class="form-check">
<input type="checkbox" class="form-check-input" asp-for="RemoveStoredAttachments" />
<label class="form-check-label" asp-for="RemoveStoredAttachments">@T["Remove attachments from Save Form Attachments Task after sending email."]</label>
<span class="hint dashed">@T["If checked, attachments are removed from file storage after email is sent."]</span>
</div>
</div>

<div class="mb-3">
<div class="form-check">
<input type="checkbox" class="form-check-input" asp-for="IsBodyHtml" />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using OrchardCore.Environment.Shell;
using OrchardCore.FileStorage;
using OrchardCore.FileStorage.FileSystem;
using OrchardCore.Media;
using OrchardCore.Workflows.Abstractions.Models;
using OrchardCore.Workflows.Activities;
using OrchardCore.Workflows.Models;
Expand All @@ -16,17 +22,26 @@ public class EmailTask : TaskActivity
private readonly IWorkflowExpressionEvaluator _expressionEvaluator;
private readonly IStringLocalizer S;
private readonly HtmlEncoder _htmlEncoder;
private readonly IFileStore _fileStore;
private readonly IOptions<ShellOptions> _shellOptions;
readonly ShellSettings _shellSettings;

public EmailTask(
ISmtpService smtpService,
IWorkflowExpressionEvaluator expressionEvaluator,
IStringLocalizer<EmailTask> localizer,
IMediaFileStore mediaFileStore,
IOptions<ShellOptions> shellOptions,
ShellSettings shellSettings,
HtmlEncoder htmlEncoder
)
{
_smtpService = smtpService;
_expressionEvaluator = expressionEvaluator;
S = localizer;
_fileStore = mediaFileStore;
_shellOptions = shellOptions;
_shellSettings = shellSettings;
_htmlEncoder = htmlEncoder;
}

Expand Down Expand Up @@ -101,6 +116,18 @@ public bool IsBodyText
set => SetProperty(value);
}

public bool IncludeStoredAttachments
{
get => GetProperty(() => true);
set => SetProperty(value);
}

public bool RemoveStoredAttachments
{
get => GetProperty(() => true);
set => SetProperty(value);
}

public override IEnumerable<Outcome> GetPossibleOutcomes(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
{
return Outcomes(S["Done"], S["Failed"]);
Expand All @@ -117,6 +144,7 @@ public override async Task<ActivityExecutionResult> ExecuteAsync(WorkflowExecuti
var subject = await _expressionEvaluator.EvaluateAsync(Subject, workflowContext, null);
var body = await _expressionEvaluator.EvaluateAsync(Body, workflowContext, _htmlEncoder);
var bodyText = await _expressionEvaluator.EvaluateAsync(BodyText, workflowContext, null);
IFileStore fileStore = null;

var message = new MailMessage
{
Expand All @@ -131,15 +159,18 @@ public override async Task<ActivityExecutionResult> ExecuteAsync(WorkflowExecuti
Body = body?.Trim(),
BodyText = bodyText?.Trim(),
IsBodyHtml = IsBodyHtml,
IsBodyText = IsBodyText
IsBodyText = IsBodyText,
};

if (!String.IsNullOrWhiteSpace(sender))
{
message.Sender = sender.Trim();
}

fileStore = await AddMailAttachments(workflowContext, fileStore, message);
var result = await _smtpService.SendAsync(message);
await DeleteStoredAttachments(workflowContext, fileStore, result, message);

workflowContext.LastResult = result;

if (!result.Succeeded)
Expand All @@ -149,5 +180,46 @@ public override async Task<ActivityExecutionResult> ExecuteAsync(WorkflowExecuti

return Outcomes("Done");
}

private async Task DeleteStoredAttachments(WorkflowExecutionContext workflowContext, IFileStore fileStore, SmtpResult result, MailMessage message)
{
if (RemoveStoredAttachments && result.Succeeded && fileStore != null && workflowContext.Properties.ContainsKey("FormAttachments"))
{
// close open file streams
message.Attachments.ForEach(p => p.Stream.Dispose());

foreach (var filePath in (List<string>)workflowContext.Properties["FormAttachments"])
{
var success = await fileStore?.TryDeleteFileAsync(filePath);
}
}
}

private async Task<IFileStore> AddMailAttachments(WorkflowExecutionContext workflowContext, IFileStore fileStore, MailMessage message)
{
if (IncludeStoredAttachments
&& workflowContext.Properties.ContainsKey("FormAttachmentsUseMediaFileStore")
&& workflowContext.Properties.ContainsKey("FormAttachments"))
{
bool useMediaFileStore = (bool)workflowContext.Properties["FormAttachmentsUseMediaFileStore"];
fileStore = useMediaFileStore ? _fileStore : CreateDefaultFileStore();
foreach (var filePath in (List<string>)workflowContext.Properties["FormAttachments"])
{
var fileInfo = await fileStore.GetFileInfoAsync(filePath);
var fileStream = await fileStore.GetFileStreamAsync(fileInfo);
message.Attachments.Add(new MailMessageAttachment() { Filename = fileInfo.Name, Stream = fileStream });
}
}

return fileStore;
}

private IFileStore CreateDefaultFileStore()
{
var shell = _shellOptions.Value;
var innerPath = PathExtensions.Combine(shell.ShellsContainerName, _shellSettings.Name);
var directory = PathExtensions.Combine(shell.ShellsApplicationDataPath, innerPath);
return new FileSystemStore(directory);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ protected override void EditActivity(EmailTask activity, EmailTaskViewModel mode
model.IsBodyText = activity.IsBodyText;
model.BccExpression = activity.Bcc.Expression;
model.CcExpression = activity.Cc.Expression;
model.IncludeStoredAttachments = activity.IncludeStoredAttachments;
model.RemoveStoredAttachments = activity.RemoveStoredAttachments;
}

protected override void UpdateActivity(EmailTaskViewModel model, EmailTask activity)
Expand All @@ -35,6 +37,8 @@ protected override void UpdateActivity(EmailTaskViewModel model, EmailTask activ
activity.IsBodyText = model.IsBodyText;
activity.Bcc = new WorkflowExpression<string>(model.BccExpression);
activity.Cc = new WorkflowExpression<string>(model.CcExpression);
activity.IncludeStoredAttachments = model.IncludeStoredAttachments;
activity.RemoveStoredAttachments = model.RemoveStoredAttachments;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,7 @@ public class EmailTaskViewModel
public bool IsBodyHtml { get; set; }

public bool IsBodyText { get; set; }
public bool IncludeStoredAttachments { get; set; }
public bool RemoveStoredAttachments { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using OrchardCore.Environment.Shell;
using OrchardCore.FileStorage;
using OrchardCore.FileStorage.FileSystem;
using OrchardCore.Media;
using OrchardCore.Workflows.Abstractions.Models;
using OrchardCore.Workflows.Models;
using OrchardCore.Workflows.Services;

namespace OrchardCore.Workflows.Activities
{
public class SaveFormAttachmentsTask : TaskActivity
{
readonly IOptions<ShellOptions> _shellOptions;
protected readonly IStringLocalizer S;
readonly ShellSettings _shellSettings;
private readonly IFileStore _fileStore;
private readonly IHttpContextAccessor _http;
private readonly IWorkflowExpressionEvaluator _expressionEvaluator;

public SaveFormAttachmentsTask(
IWorkflowExpressionEvaluator expressionEvaluator,
IStringLocalizer<SaveFormAttachmentsTask> localizer,
IOptions<ShellOptions> shellOptions,
ShellSettings shellSettings,
IMediaFileStore mediaFileStore,
IHttpContextAccessor httpContextAccessor)
{
_shellOptions = shellOptions;
_shellSettings = shellSettings;
_fileStore = mediaFileStore;
_http = httpContextAccessor;
S = localizer;
_expressionEvaluator = expressionEvaluator;
}

public override string Name => nameof(SaveFormAttachmentsTask);

public override LocalizedString DisplayText => S["Save Form Attachments Task"];

public override LocalizedString Category => S["Media"];

public override IEnumerable<Outcome> GetPossibleOutcomes(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
{
return Outcomes(S["Done"]);
}

public override bool CanExecute(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
{
return _http.HttpContext?.Request?.Form != null;
}

public override async Task<ActivityExecutionResult> ExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
{
// use either configured mediaFileStore or create new FileSystemStore --> TODO: mediaFileStore does not resolve permissions, everything is in public folders and can be accessible.
// to put files in different folder, we would need either to register some private MediaFileStore, or allow to specify folder outside base path (?)
var fileStore = UseMediaFileStore ? _fileStore : CreateDefaultFileStore();
var filePaths = new List<string>();
foreach (var file in _http.HttpContext.Request.Form.Files)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How does that work in the context that the form is not set to enctype="multipart/form-data"???

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Skrypt

It does not work without that - does not break but does nothing. I put it in description of task so everyone sees that it needs multipart formdata

{
var filePath = fileStore.Combine(Folder, $"{workflowContext.WorkflowId}-{file.FileName}");
filePaths.Add(await fileStore.CreateFileFromStreamAsync(filePath, file.OpenReadStream()));
}

workflowContext.Properties["FormAttachments"] = filePaths;
workflowContext.Properties["FormAttachmentsUseMediaFileStore"] = UseMediaFileStore;
return Outcomes("Done");
}

public string Folder
{
get => GetProperty<string>(() => string.Empty);
set => SetProperty(value);
}

public bool UseMediaFileStore
{
get => GetProperty<bool>();
set => SetProperty(value);
}

private IFileStore CreateDefaultFileStore()
{
var shell = _shellOptions.Value;
var innerPath = PathExtensions.Combine(shell.ShellsContainerName, _shellSettings.Name);
var directory = PathExtensions.Combine(shell.ShellsApplicationDataPath, innerPath);

// do not include Folder in FileSystemStore path, it is included in file path.
var destPath = PathExtensions.Combine(directory, Folder);
Directory.CreateDirectory(destPath);
return new FileSystemStore(directory);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using OrchardCore.Workflows.Activities;
using OrchardCore.Workflows.Display;
using OrchardCore.Workflows.Models;
using OrchardCore.Workflows.ViewModels;

namespace OrchardCore.Workflows.Drivers
{
public class SaveFormAttachmentsTaskDisplayDriver : ActivityDisplayDriver<SaveFormAttachmentsTask, SaveFormAttachmentsTaskViewModel>
{
protected override void EditActivity(SaveFormAttachmentsTask activity, SaveFormAttachmentsTaskViewModel model)
{
model.Folder = activity.Folder;
model.UseMediaFileStore = activity.UseMediaFileStore;
}

protected override void UpdateActivity(SaveFormAttachmentsTaskViewModel model, SaveFormAttachmentsTask activity)
{
activity.Folder = model.Folder;
activity.UseMediaFileStore = model.UseMediaFileStore;
}
}
}
8 changes: 8 additions & 0 deletions src/OrchardCore.Modules/OrchardCore.Workflows/Manifest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,11 @@
Dependencies = new[] { "OrchardCore.Workflows" },
Category = "Workflows"
)]

[assembly: Feature(
Id = "OrchardCore.Workflows.SaveFormAttachments",
Name = "Save Form Attachments Activities",
Description = "Provides Save Form Attachments activity.",
Dependencies = new[] { "OrchardCore.Workflows", "OrchardCore.Media", "OrchardCore.FileStorage" },
Category = "Workflows"
)]
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
<ProjectReference Include="..\..\OrchardCore\OrchardCore.Deployment.Abstractions\OrchardCore.Deployment.Abstractions.csproj" />
<ProjectReference Include="..\..\OrchardCore\OrchardCore.DisplayManagement.Liquid\OrchardCore.DisplayManagement.Liquid.csproj" />
<ProjectReference Include="..\..\OrchardCore\OrchardCore.DisplayManagement\OrchardCore.DisplayManagement.csproj" />
<ProjectReference Include="..\..\OrchardCore\OrchardCore.FileStorage.FileSystem\OrchardCore.FileStorage.FileSystem.csproj" />
<ProjectReference Include="..\..\OrchardCore\OrchardCore.Media.Abstractions\OrchardCore.Media.Abstractions.csproj" />
<ProjectReference Include="..\..\OrchardCore\OrchardCore.Navigation.Core\OrchardCore.Navigation.Core.csproj" />
<ProjectReference Include="..\..\OrchardCore\OrchardCore.Liquid.Abstractions\OrchardCore.Liquid.Abstractions.csproj" />
<ProjectReference Include="..\..\OrchardCore\OrchardCore.Localization.Abstractions\OrchardCore.Localization.Abstractions.csproj" />
Expand Down
9 changes: 9 additions & 0 deletions src/OrchardCore.Modules/OrchardCore.Workflows/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -143,4 +143,13 @@ public override void ConfigureServices(IServiceCollection services)
services.AddActivity<CommitTransactionTask, CommitTransactionTaskDisplayDriver>();
}
}

[Feature("OrchardCore.Workflows.SaveFormAttachments")]
public class SaveFormAttachmentsStartup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddActivity<SaveFormAttachmentsTask, SaveFormAttachmentsTaskDisplayDriver>();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System.ComponentModel.DataAnnotations;

namespace OrchardCore.Workflows.ViewModels
{
public class SaveFormAttachmentsTaskViewModel
{
[Required]
public string Folder { get; set; }

[Required]
public bool UseMediaFileStore { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
@model OrchardCore.Workflows.ViewModels.ActivityViewModel<SaveFormAttachmentsTask>


<header>
<h4><i class="fa fa-floppy-o"></i>@Model.Activity.GetTitleOrDefault(() => T["Save form attachments"])</h4>
</header>


@Model.Activity.Folder
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
@model OrchardCore.Workflows.ViewModels.SaveFormAttachmentsTaskViewModel

<div class="form-group" asp-validation-class-for="Folder">
<label asp-for="Folder">@T["Folder name"]</label>
<input type="text" asp-for="Folder" class="form-control code" />
<span asp-validation-for="Folder"></span>
<span class="hint">@T["The folder name. In case of not using media file storage, folder is created under tenant folder."]</span>
</div>

<div class="mb-3">
<input type="checkbox" asp-for="UseMediaFileStore" />
<label asp-for="UseMediaFileStore">@T["Use Media File Store"]</label>
<span class="hint">@T["If checked, configured media file storage is used. Beware, currently not secured, so your files would be visible."]</span>
</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<h4 class="card-title"><i class="fa fa-floppy-o"></i>@T["Save form attachments"]</h4>
<p>@T["Stores attachments from POST request into file system or predefined media file storage. Request has to be of multipart/form-data enctype. Attachments can be consumed by Send Email Task."]</p>
Loading