/
HomeController.cs
257 lines (222 loc) · 9.7 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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Graph;
using Microsoft.Identity.Client;
using Newtonsoft.Json;
using RSCWithGraphAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace RSCWithGraphAPI.Controllers
{
public class HomeController : Controller
{
private readonly IConfiguration _configuration;
public string appId;
public HomeController(IConfiguration configuration)
{
_configuration = configuration;
}
/// <summary>
/// RSC Setup
/// </summary>
[Route("Demo")]
public async Task<ActionResult> Demo(string tenantId, string groupId)
{
GraphServiceClient graphClient = await GetAuthenticatedClient(tenantId);
var viewModel = new DemoViewModel()
{
Channels = await GetChannelsList(graphClient, tenantId, groupId),
Permissions = await GetPermissionGrants(graphClient, tenantId, groupId)
};
return View(viewModel);
}
/// <summary>
/// Configure Tab
/// </summary>
[Route("ConfigureTab")]
public IActionResult ConfigureTab()
{
return View();
}
/// <summary>
/// Send Notification Tab
/// </summary>
[Route("SendNotification")]
public IActionResult SendNotification()
{
return View();
}
public IActionResult Index()
{
return View();
}
private async Task<List<string>> GetChannelsList(GraphServiceClient graphClient, string tenantId, string groupId)
{
var result = await graphClient.Teams[groupId].Channels.Request()
.GetAsync();
return result.Select(r => r.DisplayName).ToList();
}
private async Task<List<string>> GetPermissionGrants(GraphServiceClient graphClient, string tenantId, string groupId)
{
var result = await graphClient.Groups[groupId].PermissionGrants.Request()
.GetAsync();
return result.Select(r => r.Permission).ToList();
}
/// <summary>
///Get Authenticated Client
/// </summary>
private async Task<GraphServiceClient> GetAuthenticatedClient(string tenantId)
{
var accessToken = await GetToken();
var graphClient = new GraphServiceClient(
new DelegateAuthenticationProvider(
requestMessage =>
{
// Append the access token to the request.
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
// Get event times in the current time zone.
requestMessage.Headers.Add("Prefer", "outlook.timezone=\"" + TimeZoneInfo.Local.Id + "\"");
return Task.CompletedTask;
}));
return graphClient;
}
/// <summary>
/// Get the list of installed app for the user.
/// </summary>
/// <param name="reciepientUserId"> Id of the user whom notification is to be sent</param>
/// <returns>Status which indicates notification sent of failed</returns>
[HttpPost]
[Route("GetInstalledAppList")]
public async Task<JsonResult> GetInstalledAppList(string reciepientUserId)
{
// Replace with your Graph API endpoint and access token
string graphApiEndpoint = $"https://graph.microsoft.com/v1.0/users/{reciepientUserId}/teamwork/installedApps/?$expand=teamsAppDefinition";
var accessToken = await GetToken();
// Create an HttpClient instance
using (HttpClient client = new HttpClient())
{
// Set the base address for the Graph API
client.BaseAddress = new Uri(graphApiEndpoint);
// Set the authorization header with the access token
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
try
{
// Make a GET request to retrieve user data
HttpResponseMessage response = await client.GetAsync(graphApiEndpoint);
// Check if the request was successful
if (response.IsSuccessStatusCode)
{
// Read and display the response content
string responseBody = await response.Content.ReadAsStringAsync();
var responseData = JsonConvert.DeserializeObject<ResponseData>(responseBody);
var installedAppList = responseData.Value;
foreach(AppData element in installedAppList)
{
if (element.TeamsAppDefinition.DisplayName == "RSC feed")
{
appId = element.Id;
}
};
if(appId != null)
{
await SendNotification(reciepientUserId, appId);
return Json("Message sent successfully");
}
else
{
return Json("App not installed for the user");
}
}
else
{
Console.WriteLine($"Error: {response.StatusCode}");
return Json("Error occured");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
return Json("Error occured"+ ex.Message);
}
}
}
/// <summary>
/// Send activity feed notification to user.
/// </summary>
/// <param name="reciepientUserId"> Id of the user whom notification is to be sent</param>
/// <param name="appId">App id for rsc app.</param>
/// <returns></returns>
public async Task<string> SendNotification(string reciepientUserId, string appId)
{
// Set your Graph API endpoint and access token
string graphApiEndpoint = $"https://graph.microsoft.com/beta/users/{reciepientUserId}/teamwork/sendActivityNotification";
var accessToken = await GetToken();
// Create a JSON payload for the activity feed notification
string jsonPayload = @"{
""topic"": {
""source"": ""entityUrl"",
""value"": ""https://graph.microsoft.com/beta/users/" + reciepientUserId + "/teamwork/installedApps/" + appId + @"""
},
""activityType"": ""taskCreated"",
""previewText"": {
""content"": ""New Task Created""
},
""templateParameters"": [{
""name"": ""taskName"",
""value"": ""test""
}]
}";
using (HttpClient httpClient = new HttpClient())
{
// Set the base URL for the Graph API
httpClient.BaseAddress = new Uri(graphApiEndpoint);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
try
{
// Create a POST request with the JSON payload
HttpResponseMessage response = await httpClient.PostAsync(graphApiEndpoint, new StringContent(jsonPayload, Encoding.UTF8, "application/json"));
// Check if the request was successful
if (response.IsSuccessStatusCode)
{
// Parse and print the response content
string content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
return "true";
}
else
{
Console.WriteLine($"Error: {response.StatusCode}");
return "Notification sent";
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
return "Notification failed";
}
}
}
/// <summary>
/// Get Token for given tenant.
/// </summary>
/// <param name="tenantId"></param>
/// <returns></returns>
public async Task<string> GetToken()
{
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(_configuration["ClientId"])
.WithClientSecret(_configuration["ClientSecret"])
.WithAuthority($"https://login.microsoftonline.com/{_configuration["TenantId"]}")
.WithRedirectUri("https://daemon")
.Build();
string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
var result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
return result.AccessToken;
}
}
}