Skip to content
Snippets Groups Projects
Select Git revision
  • master
1 result

503.nfa

Blame
  • Code owners
    Assign users and groups as approvers for specific file changes. Learn more.
    NotificationBusController.cs 5.75 KiB
    using Coscine.Configuration;
    using Coscine.Database.DataModel;
    using Coscine.Database.Models;
    using Coscine.NotificationChannelBase;
    using Coscine.NotificationConfiguration;
    using Microsoft.AspNetCore.Mvc;
    using Newtonsoft.Json.Linq;
    using Stubble.Core.Builders;
    using Stubble.Core.Loaders;
    using System;
    using System.Collections.Generic;
    using System.Reflection;
    using System.Threading.Tasks;
    
    namespace Coscine.Api.NotificationBus.Controllers
    {
        public class NotificationBusController : Controller
        {
    
            private readonly UserModel _userModel;
    
            private readonly ProjectModel _projectModel;
    
            private readonly LanguageModel _languageModel;
    
            private readonly IConfiguration _configuration;
    
            private readonly Coscine.NotificationConfiguration.NotificationConfiguration _notificationConfiguration;
    
    
            public NotificationBusController()
            {
                _userModel = new UserModel();
                _projectModel = new ProjectModel();
                _languageModel = new LanguageModel();
                _configuration = Program.Configuration;
                _notificationConfiguration = new Coscine.NotificationConfiguration.NotificationConfiguration();
            }
    
            [HttpPost("[controller]/send")]
            public IActionResult Send([FromBody] NotificationParameterObject notificationParameterObject)
            {
                SendNotifications(notificationParameterObject).Wait();
                return Ok();
            }
    
            [HttpPost("[controller]/sendAsync")]
            public async Task<IActionResult> SendAsync([FromBody] NotificationParameterObject notificationParameterObject)
            {
                await SendNotifications(notificationParameterObject);
                return Ok();
            }
    
            private async Task SendNotifications(NotificationParameterObject notificationParameterObject)
            {
                Project project = GetProject(notificationParameterObject.ProjectId);
                var action = notificationParameterObject.Action;
                ActionObject actionObject = _notificationConfiguration.GetAction(action);
                List<string> channelList = _notificationConfiguration.GetAllChannelsForAction(action);
    
                string basePath = _configuration.GetStringAndWait("coscine/local/notifications/channels/folder");
    
                // for every available channel
                foreach (string channelName in channelList)
                {
                    ChannelObject channelInfo = _notificationConfiguration.GetChannel(channelName);
                    string pathToDll = basePath + channelInfo.Path;
    
                    var mergeSettings = new JsonMergeSettings
                    {
                        MergeArrayHandling = MergeArrayHandling.Union
                    };
    
                    if(notificationParameterObject.Args != null)
                    {
                        notificationParameterObject.Args.Merge(channelInfo.Args, mergeSettings);
                    }
                    else
                    {
                        notificationParameterObject.Args = channelInfo.Args;
                    }
    
                    // for every available user
                    foreach (User user in notificationParameterObject.Users)
                    {
                        JObject messageData = FillTemplate(channelName, actionObject, notificationParameterObject.Args, user, project);
    
                        INotificationChannel notificationChannel = null;
    
                        var DLL = Assembly.LoadFile(pathToDll);
                        foreach (Type type in DLL.GetExportedTypes())
                        {
                            if (typeof(INotificationChannel).IsAssignableFrom(type))
                            {
                                notificationChannel = (INotificationChannel)Activator.CreateInstance(type);
                            }
                        }
    
                        await notificationChannel.SendAsync(Program.Configuration, new Message(messageData, notificationParameterObject.Args, user, project));
                    }
                }
                return;
            }
    
            private JObject FillTemplate(string channelName, ActionObject action, JObject requestArgs, User user, Project project)
            {
                string language = "en";
                if (user.LanguageId != null)
                {
                    language = _languageModel.GetById(new Guid(user.LanguageId.ToString())).Abbreviation;
                }
                var template = (JObject)(action.Template[channelName][language]);
    
                var stubble = new StubbleBuilder()
                  .Configure(settings =>
                  {
                      settings.SetPartialTemplateLoader(new DictionaryLoader(_notificationConfiguration.GetPartialsForChannel(channelName, language)));
                  }).Build();
    
                var dict = new Dictionary<string, object>();
                if (requestArgs["placeholder"] != null)
                {
                    dict = ((JObject)(requestArgs["placeholder"])).ToObject<Dictionary<string, object>>();
                }            
                dict.Add("_targetUserName", user.DisplayName);
                dict.Add("_projectName", project.DisplayName);
    
                foreach (JProperty property in template.Properties())
                {
                    template[property.Name] = stubble.Render(template[property.Name].ToString(), dict);
                }
    
                return template;
            }
    
            private List<User> GetUsers(List<string> userIds)
            {
                var users = new List<User>();
                foreach (var userId in userIds)
                {
                    users.Add(_userModel.GetById(new Guid(userId.ToString())));
                }
                return users;
            }
    
            private Project GetProject(string projectId)
            {
                Project project = null;
                if (projectId != null)
                {
                    project = _projectModel.GetById(new Guid(projectId));
                }
                return project;
            }
        }
    }