-
Notifications
You must be signed in to change notification settings - Fork 711
/
HomeController.cs
222 lines (195 loc) · 8.89 KB
/
HomeController.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
// <copyright file="HomeController.cs" company="Microsoft">
// Copyright (c) Microsoft. All Rights Reserved.
// </copyright>
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Graph;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using ActivityFeedBroadcast.Helpers;
using ActivityFeedBroadcast.Model;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using System.Text;
using TabActivityFeed.Helpers;
namespace ActivityFeedBroadcast.Controllers
{
public class HomeController : Controller
{
private readonly IConfiguration _configuration;
private readonly IHttpClientFactory _httpClientFactory;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly ConcurrentDictionary<string, List<BroadcastInfo>> _taskList;
const int recipientPartitionSize = 85;
const int partitionCount = 5;
public HomeController(
IConfiguration configuration,
IHttpClientFactory httpClientFactory,
IHttpContextAccessor httpContextAccessor,
ConcurrentDictionary<string, List<BroadcastInfo>> taskList)
{
_configuration = configuration;
_httpClientFactory = httpClientFactory;
_httpContextAccessor = httpContextAccessor;
_taskList = taskList;
}
// Get broadcast page.
[Route("broadcast")]
public ActionResult Broadcast()
{
return View("Index");
}
// Get broadcast message Id.
[HttpGet]
[Route("MessageDetails")]
public ActionResult GetRequestByID(string taskId)
{
var currentTaskList = new List<BroadcastInfo>();
_taskList.TryGetValue("taskList", out currentTaskList);
if (currentTaskList == null)
{
ViewBag.Message = "No record found";
}
else
{
var request = currentTaskList.FirstOrDefault(p => p.taskId.ToString() == taskId);
ViewBag.TaskDetails = request;
}
return View("Message");
}
// Send notification to organisation.
[HttpPost]
[Route("SendNotificationToOrganisation")]
public async Task<ActionResult> SendNotificationToOrganisation(BroadcastInfo taskInfo)
{
try
{
var currentTaskList = new List<BroadcastInfo>();
List<BroadcastInfo> taskList = new List<BroadcastInfo>();
_taskList.TryGetValue("taskList", out currentTaskList);
taskInfo.taskId = Guid.NewGuid();
if (currentTaskList == null)
{
taskList.Add(taskInfo);
_taskList.AddOrUpdate("taskList", taskList, (key, newValue) => taskList);
ViewBag.TaskList = taskList;
}
else
{
currentTaskList.Add(taskInfo);
_taskList.AddOrUpdate("taskList", currentTaskList, (key, newValue) => currentTaskList);
ViewBag.TaskList = currentTaskList;
}
// Graph client for user.
var graphClient = SimpleGraphClient.GetGraphClient(taskInfo.access_token);
// Graph client for app.
var graphClientApp = SimpleGraphClient.GetGraphClientforApp(_configuration["AzureAd:MicrosoftAppId"], _configuration["AzureAd:MicrosoftAppPassword"], _configuration["AzureAd:TenantId"]);
var usersList = await graphClient.Users
.Request()
.GetAsync();
var installedAppsForCurrentUser = await graphClient.Users[taskInfo.userId].Teamwork.InstalledApps
.Request()
.Expand("teamsAppDefinition")
.GetAsync();
// Get app id using app display name.
var appId = installedAppsForCurrentUser.Where(id => id.TeamsAppDefinition.DisplayName == _configuration["AppName"]).Select(x => x.TeamsAppDefinition.TeamsAppId);
var count = usersList.Count;
var counter = 0;
var recipientsList = new List<Dictionary<string, string>>();
await UtilityHelper.ForEachAsync(usersList, partitionCount, async users => {
try
{
var installedApp = await graphClient.Users[users.Id].Teamwork.InstalledApps
.Request()
.Expand("teamsApp")
.GetAsync();
var response = new HttpResponseMessage();
var installationId = installedApp.Where(id => id.TeamsApp.DisplayName == _configuration["AppName"]).Select(x => x.TeamsApp.Id);
if (installationId.ToList().Count == 0)
{
var userScopeTeamsAppInstallation = new UserScopeTeamsAppInstallation
{
AdditionalData = new Dictionary<string, object>()
{
{"teamsApp@odata.bind", "https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/"+appId.ToList()[0]}
}
};
await graphClient.Users[users.Id].Teamwork.InstalledApps
.Request()
.AddAsync(userScopeTeamsAppInstallation);
}
counter++;
recipientsList.Add(new Dictionary<string, string>
{
{"@odata.type", "microsoft.graph.aadUserNotificationRecipient"},
{"userId", users.Id}
});
}
catch (Exception ex)
{
Console.WriteLine("Installation failed for " + users.DisplayName);
}
});
var url = "https://teams.microsoft.com/l/entity/" + appId.ToList()[0] + "/broadcast?context={\"subEntityId\":\"" + taskInfo.taskId + "\"}";
var client = new HttpClient();
var recipientsChunks = UtilityHelper.SplitIntoChunks(recipientsList, recipientPartitionSize);
foreach (var recipientList in recipientsChunks)
{
var postData = new
{
topic = new TeamworkActivityTopic()
{
Source = TeamworkActivityTopicSource.Text,
Value = $"{taskInfo.title}",
WebUrl = url
},
activityType = "approvalRequired",
previewText = new ItemBody
{
Content = $"Message By:"
},
templateParameters = new List<Microsoft.Graph.KeyValuePair>()
{
new Microsoft.Graph.KeyValuePair
{
Name = "approvalTaskId",
Value = taskInfo.title
}
},
recipients = recipientList
};
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", taskInfo.access_token);
var data = new StringContent(JsonConvert.SerializeObject(postData), Encoding.UTF8, "application/json");
// Sending acitivity feed notification in bulk
await client.PostAsync($"https://graph.microsoft.com/beta/teamwork/sendActivityNotificationToRecipients", data);
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return View("Index");
}
// Get user access token.
[Authorize]
[HttpGet("/GetUserAccessToken")]
public async Task<ActionResult<string>> GetUserAccessToken()
{
try
{
var accessToken = await AuthHelper.GetAccessTokenOnBehalfUserAsync(_configuration, _httpClientFactory, _httpContextAccessor);
return accessToken;
}
catch (Exception)
{
return null;
}
}
}
}