Last active
April 12, 2023 10:37
-
-
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/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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