Skip to content

Instantly share code, notes, and snippets.

@LucGosso
Last active April 12, 2023 10:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LucGosso/6908dca85bc8156b95bf95c71938243c to your computer and use it in GitHub Desktop.
Save LucGosso/6908dca85bc8156b95bf95c71938243c to your computer and use it in GitHub Desktop.
Send message to INotification API in Optimizely Content Cloud https://optimizely.blog/2023/04/send-notification-to-optimizely-user-from-external-system/
using EPiServer;
using EPiServer.Cms.UI.AspNetIdentity;
using EPiServer.Core;
using EPiServer.Logging;
using EPiServer.Notification;
using EPiServer.ServiceLocation;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Epicweb.Optimizely.Blog.Features.Notifications
{
[ApiController]
[Route("api/notify")]
public class WebhooksNotificationsApiController : Controller
{
private readonly ILogger _log = LogManager.GetLogger();
private readonly INotifier _notifier;
private readonly IContentLoader _contentLoader;
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
public WebhooksNotificationsApiController(INotifier notifier, IContentLoader contentLoader, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
{
_notifier = notifier;
_contentLoader = contentLoader;
_userManager = userManager;
_roleManager = roleManager;
}
public class JsonModel {
public string message { get; set; }
public string title { get; set; }
public int contentReference { get; set; }
public string roleName { get; set; }
public string userName { get; set; }
}
[HttpPost("message")]
public async Task<IActionResult> GeneralWebhook([FromBody] JsonModel model, string secret = null)
{
if (secret != "ChangeThisORReplaceWithSomethingSecure-d34249beae5663213ee3d9")
{
return BadRequest("Secret no good");
}
if (model.contentReference < 1)
return BadRequest("ContentReference less then 0");
try
{
var reference = new ContentReference(model.contentReference);
if (!_contentLoader.TryGet(reference, out IContent content))
{
_log.Error($"Cound not found {model.contentReference}");
return NotFound();
}
var editasseturl = EPiServer.Editor.PageEditing.GetEditUrl(reference);
var message = $"{model.message}: <a href={editasseturl} style=\"color:#0000FF;text-decoration:underline;\">{content.Name}</a>";
await NotifyEditor(model.title, message, model.userName, model.roleName);
return Ok("success");
}
catch (Exception e)
{
_log.Error("Cound not deliver expire message: " + model.contentReference, e);
return new JsonResult(e.Message)
{
StatusCode = StatusCodes.Status500InternalServerError
};
}
}
private async Task NotifyEditor(string subject, string content, string userName = null, string roleName = null, string type = "WebHook API Integration")
{
//type => WebHook API Integration
//content => <updatemessage><![CDATA[Example message with link: <a href={0} style="color:#0000FF;text-decoration:underline;">{1}</a>]]></updatemessage>
IEnumerable<INotificationUser> notificationReceivers = await GetUsers(userName, roleName);
var message = new NotificationMessage
{
ChannelName = "EpicwebMessaging",
TypeName = type,
Sender = new NotificationUser("WebHook API Integration"), //This user needs to exists "WebHook API Integration"
Recipients = notificationReceivers,
Subject = subject,
Content = content
};
_notifier.PostNotificationAsync(message).Wait();
}
/// <summary>
/// if no username, get roles
/// </summary>
/// <param name="userName"></param>
/// <param name="role"></param>
/// <returns></returns>
private async Task<IEnumerable<INotificationUser>> GetUsers(string userName = null, string roleName = "WebEditors")
{
if (string.IsNullOrEmpty(userName))
{
var role = await _roleManager.FindByNameAsync(roleName);
if (role == null)
{
// Role doesn't exist
throw new ContentNotFoundException(roleName);
}
var usersInRole = await _userManager.GetUsersInRoleAsync(roleName);
return (from sUser in usersInRole
select new NotificationUser(sUser.UserName))
.Cast<INotificationUser>().ToList();
}
else
{
return new List<NotificationUser>() { new NotificationUser(userName) };
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment