-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathNotificationController.cs
91 lines (76 loc) · 3.25 KB
/
NotificationController.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
* Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license.
* See LICENSE in the source repository root for complete license information.
*/
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using MicrosoftGraph_Security_API_Sample.Models;
using MicrosoftGraph_Security_API_Sample.SignalR;
using MicrosoftGraph_Security_API_Sample.Helpers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Security.Claims;
namespace MicrosoftGraph_Security_API_Sample.Controllers
{
using MicrosoftGraph_Security_API_Sample.SignalR;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
public class NotificationController : Controller
{
public ActionResult LoadView()
{
ViewBag.CurrentUserId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier")?.Value;
return View("Notification");
}
/// <summary>
/// Listener for the notifications
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<ActionResult> Listen()
{
// Validate the new subscription by sending the token back to Microsoft Graph.
// This response is required for each subscription.
if (Request.QueryString["validationToken"] != null)
{
var token = Request.QueryString["validationToken"];
return Content(token, "plain/text");
}
// Parse the received notifications.
else
{
try
{
string documentContents;
using (var inputStream = Request.InputStream)
{
using (StreamReader readStream = new StreamReader(inputStream, Encoding.UTF8))
{
documentContents = readStream.ReadToEnd();
}
var notifications = JsonConvert.DeserializeObject<NotificationCollection>(documentContents);
Notification notifcation = notifications.Value.FirstOrDefault();
notifcation.EntityId = notifcation.ResourceData.Id;
List<NotificationViewModel> messages = new List<NotificationViewModel>();
NotificationViewModel messageViewModel = new NotificationViewModel(notifcation, notifcation.SubscriptionId);
messages.Add(messageViewModel);
NotificationService notificationService = new NotificationService();
notificationService.SendNotificationToClient(messages);
}
}
catch (Exception)
{
// TODO: Handle the exception.
// Still return a 202 so the service doesn't resend the notification.
}
return new HttpStatusCodeResult(202);
}
}
}
}