<commit_before>﻿#region usings
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Signum.Engine.Operations;
using Signum.Utilities;
using Signum.Entities;
using System.Web;
using Signum.Entities.Basics;
using System.Reflection;
using Signum.Entities.Files;
using Signum.Engine.Mailing;
using System.Web.UI;
using System.IO;
using Signum.Entities.Mailing;
using System.Web.Routing;
using Signum.Engine;
using Signum.Engine.Basics;
using Signum.Engine.DynamicQuery;
using Signum.Entities.DynamicQuery;
using Signum.Entities.UserQueries;
using Signum.Web.Operations;
using Signum.Web.UserQueries;
using System.Text.RegularExpressions;
#endregion

namespace Signum.Web.Mailing
{
    public static class MailingClient
    {
        public static string ViewPrefix = "~/Mailing/Views/{0}.cshtml";
        public static string Module = "Extensions/Signum.Web.Extensions/Mailing/Scripts/Mailing";
        public static string TabsRepeaterModule = "Extensions/Signum.Web.Extensions/Mailing/Scripts/Mailing";

        private static QueryTokenDN ParseQueryToken(string tokenString, string queryRuntimeInfoInput)
        {
            if (tokenString.IsNullOrEmpty())
                return null;

            var queryRuntimeInfo = RuntimeInfo.FromFormValue(queryRuntimeInfoInput);
            var queryName = QueryLogic.ToQueryName(((Lite<QueryDN>)queryRuntimeInfo.ToLite()).InDB(q => q.Key));
            QueryDescription qd = DynamicQueryManager.Current.QueryDescription(queryName);

            return new QueryTokenDN(QueryUtils.Parse(tokenString, qd, canAggregate: false));
        }

        public static void Start(bool newsletter, bool pop3Config)
        {
            if (Navigator.Manager.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                Navigator.RegisterArea(typeof(MailingClient));
                Navigator.AddSettings(new List<EntitySettings>
                {
                    new EmbeddedEntitySettings<EmailAttachmentDN>{ PartialViewName = e => ViewPrefix.Formato("EmailAttachment")},
                    new EntitySettings<EmailPackageDN>{ PartialViewName = e => ViewPrefix.Formato("EmailPackage")},
                    
                    new EntitySettings<EmailMessageDN>{ PartialViewName = e => ViewPrefix.Formato("EmailMessage")},
                    
                    new EmbeddedEntitySettings<EmailAddressDN>{ PartialViewName = e => ViewPrefix.Formato("EmailAddress")},
                    new EmbeddedEntitySettings<EmailRecipientDN>{ PartialViewName = e => ViewPrefix.Formato("EmailRecipient")},
                    
                    new EmbeddedEntitySettings<EmailConfigurationDN> { PartialViewName = e => ViewPrefix.Formato("EmailConfiguration")},
                    new EntitySettings<SystemEmailDN>{ },
                    
                    new EntitySettings<EmailMasterTemplateDN> { PartialViewName = e => ViewPrefix.Formato("EmailMasterTemplate") },
                    new EmbeddedEntitySettings<EmailMasterTemplateMessageDN>
                    {
                        PartialViewName = e => ViewPrefix.Formato("EmailMasterTemplateMessage"),
                        MappingDefault = new EntityMapping<EmailMasterTemplateMessageDN>(true)
                            .SetProperty(emtm => emtm.MasterTemplate, ctx => 
                            {
                                return (EmailMasterTemplateDN)ctx.Parent.Parent.Parent.Parent.UntypedValue;
                            })
                    },
                    
                    new EntitySettings<EmailTemplateDN>
                    { 
                        PartialViewName = e => ViewPrefix.Formato("EmailTemplate"),
                    },
                    new EmbeddedEntitySettings<EmailTemplateMessageDN>() 
                    { 
                        PartialViewName = e => ViewPrefix.Formato("EmailTemplateMessage"),
                        MappingDefault = new EntityMapping<EmailTemplateMessageDN>(true)
                            .SetProperty(etm => etm.Template, ctx =>
                            {
                                return (EmailTemplateDN)ctx.Parent.Parent.Parent.Parent.UntypedValue;
                            })
                    },

                    new EmbeddedEntitySettings<EmailTemplateContactDN>() 
                    { 
                        PartialViewName = e => ViewPrefix.Formato("EmailTemplateContact"),
                        MappingDefault = new EntityMapping<EmailTemplateContactDN>(true)
                            .SetProperty(ec => ec.Token, ctx =>
                            {
                                string tokenStr = UserQueriesHelper.GetTokenString(ctx);
                                return ParseQueryToken(tokenStr, ctx.Parent.Parent.Parent.Inputs[TypeContextUtilities.Compose("Query", EntityBaseKeys.RuntimeInfo)]);
                            }),
                    },

                    new EmbeddedEntitySettings<EmailTemplateRecipientDN>() 
                    { 
                        PartialViewName = e => ViewPrefix.Formato("EmailTemplateRecipient"),
                        MappingDefault = new EntityMapping<EmailTemplateRecipientDN>(true)
                            .SetProperty(ec => ec.Token, ctx =>
                            {
                                string tokenStr = UserQueriesHelper.GetTokenString(ctx);

                                return ParseQueryToken(tokenStr, ctx.Parent.Parent.Parent.Parent.Inputs[TypeContextUtilities.Compose("Query", EntityBaseKeys.RuntimeInfo)]);
                            })
                    },

                    new EntitySettings<SmtpConfigurationDN> { PartialViewName = e => ViewPrefix.Formato("SmtpConfiguration") },
                    new EmbeddedEntitySettings<ClientCertificationFileDN> { PartialViewName = e => ViewPrefix.Formato("ClientCertificationFile")},
                });

                OperationClient.AddSettings(new List<OperationSettings>
                {
                    new EntityOperationSettings(EmailMessageOperation.CreateMailFromTemplate)
                    {
                        Group = EntityOperationGroup.None,
                        OnClick = ctx => new JsOperationFunction(Module, "createMailFromTemplate",
                            new FindOptions(((EmailTemplateDN)ctx.Entity).Query.ToQueryName()).ToJS(ctx.Prefix, "New"), 
                            ctx.Url.Action((MailingController mc)=>mc.CreateMailFromTemplateAndEntity()))
                    }
                });

                if (newsletter)
                {
                    Navigator.AddSettings(new List<EntitySettings>
                    {
                        new EntitySettings<NewsletterDN> { PartialViewName = e => ViewPrefix.Formato("Newsletter") },
                        new EntitySettings<NewsletterDeliveryDN> { PartialViewName = e => ViewPrefix.Formato("NewsletterDelivery") },
                    });

                    OperationClient.AddSettings(new List<OperationSettings>
                    {
                        new EntityOperationSettings(NewsletterOperation.RemoveRecipients)
                        {
                            OnClick = ctx =>new JsOperationFunction(Module, "removeRecipients",
                                new FindOptions(typeof(NewsletterDeliveryDN), "Newsletter", ctx.Entity).ToJS(ctx.Prefix, "New"),
                                ctx.Url.Action((MailingController mc)=>mc.RemoveRecipientsExecute()))
                        }
                    });
                }


                //require("SF_Lines", "MyModule", function(Lines, MyModule) { MyModule.MyMethod(Lines.CreateEntityLine($("#myLine")), args..); });
                //onClick="require("SF_Operations", function(Operations) { Operations.execute({....}); })"
                //onClick="require("MyModule", function() { MyModule({....}, args...); })"


                if (pop3Config)
                    Navigator.AddSettings(new List<EntitySettings>
                {
                    new EntitySettings<Pop3ConfigurationDN> { PartialViewName = e => ViewPrefix.Formato("Pop3Configuration") },
                    new EntitySettings<Pop3ReceptionDN> { PartialViewName = e => ViewPrefix.Formato("Pop3Reception") },
                });


                TasksGetWebMailBody += WebMailProcessor.ReplaceUntrusted;
                TasksGetWebMailBody += WebMailProcessor.CidToFilePath;

                TasksSetWebMailBody += WebMailProcessor.AssertNoUntrusted;
                TasksSetWebMailBody += WebMailProcessor.FilePathToCid;

                Navigator.EntitySettings<EmailMessageDN>().MappingMain.AsEntityMapping()
                    .RemoveProperty(a => a.Body)
                    .SetProperty(a => a.Body, ctx =>
                    {
                        var email = ((EmailMessageDN)ctx.Parent.UntypedValue);

                        return SetWebMailBody(ctx.Value, new WebMailOptions<commit_msg>MailingClient<commit_after>﻿#region usings
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Signum.Engine.Operations;
using Signum.Utilities;
using Signum.Entities;
using System.Web;
using Signum.Entities.Basics;
using System.Reflection;
using Signum.Entities.Files;
using Signum.Engine.Mailing;
using System.Web.UI;
using System.IO;
using Signum.Entities.Mailing;
using System.Web.Routing;
using Signum.Engine;
using Signum.Engine.Basics;
using Signum.Engine.DynamicQuery;
using Signum.Entities.DynamicQuery;
using Signum.Entities.UserQueries;
using Signum.Web.Operations;
using Signum.Web.UserQueries;
using System.Text.RegularExpressions;
#endregion

namespace Signum.Web.Mailing
{
    public static class MailingClient
    {
        public static string ViewPrefix = "~/Mailing/Views/{0}.cshtml";
        public static string Module = "Extensions/Signum.Web.Extensions/Mailing/Scripts/Mailing";
        public static string TabsRepeaterModule = "Extensions/Signum.Web.Extensions/Mailing/Scripts/Mailing";

        private static QueryTokenDN ParseQueryToken(string tokenString, string queryRuntimeInfoInput)
        {
            if (tokenString.IsNullOrEmpty())
                return null;

            var queryRuntimeInfo = RuntimeInfo.FromFormValue(queryRuntimeInfoInput);
            var queryName = QueryLogic.ToQueryName(((Lite<QueryDN>)queryRuntimeInfo.ToLite()).InDB(q => q.Key));
            QueryDescription qd = DynamicQueryManager.Current.QueryDescription(queryName);

            return new QueryTokenDN(QueryUtils.Parse(tokenString, qd, canAggregate: false));
        }

        public static void Start(bool newsletter, bool pop3Config)
        {
            if (Navigator.Manager.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                Navigator.RegisterArea(typeof(MailingClient));
                Navigator.AddSettings(new List<EntitySettings>
                {
                    new EmbeddedEntitySettings<EmailAttachmentDN>{ PartialViewName = e => ViewPrefix.Formato("EmailAttachment")},
                    new EntitySettings<EmailPackageDN>{ PartialViewName = e => ViewPrefix.Formato("EmailPackage")},
                    
                    new EntitySettings<EmailMessageDN>{ PartialViewName = e => ViewPrefix.Formato("EmailMessage")},
                    
                    new EmbeddedEntitySettings<EmailAddressDN>{ PartialViewName = e => ViewPrefix.Formato("EmailAddress")},
                    new EmbeddedEntitySettings<EmailRecipientDN>{ PartialViewName = e => ViewPrefix.Formato("EmailRecipient")},
                    
                    new EmbeddedEntitySettings<EmailConfigurationDN> { PartialViewName = e => ViewPrefix.Formato("EmailConfiguration")},
                    new EntitySettings<SystemEmailDN>{ },
                    
                    new EntitySettings<EmailMasterTemplateDN> { PartialViewName = e => ViewPrefix.Formato("EmailMasterTemplate") },
                    new EmbeddedEntitySettings<EmailMasterTemplateMessageDN>
                    {
                        PartialViewName = e => ViewPrefix.Formato("EmailMasterTemplateMessage"),
                        MappingDefault = new EntityMapping<EmailMasterTemplateMessageDN>(true)
                            .SetProperty(emtm => emtm.MasterTemplate, ctx => 
                            {
                                return (EmailMasterTemplateDN)ctx.Parent.Parent.Parent.Parent.UntypedValue;
                            })
                    },
                    
                    new EntitySettings<EmailTemplateDN>
                    { 
                        PartialViewName = e => ViewPrefix.Formato("EmailTemplate"),
                    },
                    new EmbeddedEntitySettings<EmailTemplateMessageDN>() 
                    { 
                        PartialViewName = e => ViewPrefix.Formato("EmailTemplateMessage"),
                        MappingDefault = new EntityMapping<EmailTemplateMessageDN>(true)
                            .SetProperty(etm => etm.Template, ctx =>
                            {
                                return (EmailTemplateDN)ctx.Parent.Parent.Parent.Parent.UntypedValue;
                            })
                    },

                    new EmbeddedEntitySettings<EmailTemplateContactDN>() 
                    { 
                        PartialViewName = e => ViewPrefix.Formato("EmailTemplateContact"),
                        MappingDefault = new EntityMapping<EmailTemplateContactDN>(true)
                            .SetProperty(ec => ec.Token, ctx =>
                            {
                                string tokenStr = UserQueriesHelper.GetTokenString(ctx);
                                return ParseQueryToken(tokenStr, ctx.Parent.Parent.Parent.Inputs[TypeContextUtilities.Compose("Query", EntityBaseKeys.RuntimeInfo)]);
                            }),
                    },

                    new EmbeddedEntitySettings<EmailTemplateRecipientDN>() 
                    { 
                        PartialViewName = e => ViewPrefix.Formato("EmailTemplateRecipient"),
                        MappingDefault = new EntityMapping<EmailTemplateRecipientDN>(true)
                            .SetProperty(ec => ec.Token, ctx =>
                            {
                                string tokenStr = UserQueriesHelper.GetTokenString(ctx);

                                return ParseQueryToken(tokenStr, ctx.Parent.Parent.Parent.Parent.Inputs[TypeContextUtilities.Compose("Query", EntityBaseKeys.RuntimeInfo)]);
                            })
                    },

                    new EntitySettings<SmtpConfigurationDN> { PartialViewName = e => ViewPrefix.Formato("SmtpConfiguration") },
                    new EmbeddedEntitySettings<ClientCertificationFileDN> { PartialViewName = e => ViewPrefix.Formato("ClientCertificationFile")},
                });

                OperationClient.AddSettings(new List<OperationSettings>
                {
                    new EntityOperationSettings(EmailMessageOperation.CreateMailFromTemplate)
                    {
                        Group = EntityOperationGroup.None,
                        OnClick = ctx => new JsOperationFunction(Module, "createMailFromTemplate",
                            new FindOptions(((EmailTemplateDN)ctx.Entity).Query.ToQueryName()).ToJS(ctx.Prefix, "New"), 
                            ctx.Url.Action((MailingController mc)=>mc.CreateMailFromTemplateAndEntity()))
                    }
                });

                if (newsletter)
                {
                    Navigator.AddSettings(new List<EntitySettings>
                    {
                        new EntitySettings<NewsletterDN> { PartialViewName = e => ViewPrefix.Formato("Newsletter") },
                        new EntitySettings<NewsletterDeliveryDN> { PartialViewName = e => ViewPrefix.Formato("NewsletterDelivery") },
                    });

                    OperationClient.AddSettings(new List<OperationSettings>
                    {
                        new EntityOperationSettings(NewsletterOperation.RemoveRecipients)
                        {
                            OnClick = ctx =>new JsOperationFunction(Module, "removeRecipients",
                                new FindOptions(typeof(NewsletterDeliveryDN), "Newsletter", ctx.Entity).ToJS(ctx.Prefix, "New"),
                                ctx.Url.Action((MailingController mc)=>mc.RemoveRecipientsExecute()))
                        }
                    });
                }

                if (pop3Config)
                    Navigator.AddSettings(new List<EntitySettings>
                {
                    new EntitySettings<Pop3ConfigurationDN> { PartialViewName = e => ViewPrefix.Formato("Pop3Configuration") },
                    new EntitySettings<Pop3ReceptionDN> { PartialViewName = e => ViewPrefix.Formato("Pop3Reception") },
                });


                TasksGetWebMailBody += WebMailProcessor.ReplaceUntrusted;
                TasksGetWebMailBody += WebMailProcessor.CidToFilePath;

                TasksSetWebMailBody += WebMailProcessor.AssertNoUntrusted;
                TasksSetWebMailBody += WebMailProcessor.FilePathToCid;

                Navigator.EntitySettings<EmailMessageDN>().MappingMain.AsEntityMapping()
                    .RemoveProperty(a => a.Body)
                    .SetProperty(a => a.Body, ctx =>
                    {
                        var email = ((EmailMessageDN)ctx.Parent.UntypedValue);

                        return SetWebMailBody(ctx.Value, new WebMailOptions
{'fraction_non_alphanumeric': 0.08820205672957396, 'fraction_numerical': 0.0007910498361396768, 'mean_word_length': 1.8214570380997928, 'pattern_counts': {'":': 0, '<': 63, '<?xml version=': 0, '>': 131, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5992246', 'n_tokens_mistral': 4214, 'n_tokens_neox': 3975, 'n_words': 628}