-
Notifications
You must be signed in to change notification settings - Fork 46
/
Functions.cs
186 lines (162 loc) · 7.38 KB
/
Functions.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
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Azure.EventGrid.Models;
using Microsoft.Azure.SignalR.Common;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.EventGrid;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Extensions.SignalRService;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace FunctionApp
{
public static class Functions
{
[FunctionName("negotiate")]
public static SignalRConnectionInfo GetSignalRInfo(
[HttpTrigger(AuthorizationLevel.Anonymous)] HttpRequest req,
[SignalRConnectionInfo(HubName = "simplechat", UserId = "{headers.x-ms-signalr-userid}")] SignalRConnectionInfo connectionInfo)
{
return connectionInfo;
}
//// Each function must have a unique name, you can uncomment this one and comment the above GetSignalRInfo() function to have a try.
//// This "negotiate" function shows how to utilize ServiceManager to generate access token and client url to Azure SignalR service.
//[FunctionName("negotiate")]
//public static SignalRConnectionInfo GetSignalRInfo(
// [HttpTrigger(AuthorizationLevel.Anonymous)] HttpRequest req)
//{
// var userId = req.Query["userid"];
// var hubName = req.Query["hubname"];
// var connectionInfo = new SignalRConnectionInfo();
// var serviceManager = StaticServiceHubContextStore.Get().ServiceManager;
// connectionInfo.AccessToken = serviceManager
// .GenerateClientAccessToken(
// hubName,
// userId,
// new List<Claim> { new Claim("claimType", "claimValue") });
// connectionInfo.Url = serviceManager.GetClientEndpoint(hubName);
// return connectionInfo;
//}
[FunctionName("broadcast")]
public static async Task Broadcast(
[HttpTrigger(AuthorizationLevel.Anonymous, "post")]HttpRequest req,
[SignalR(HubName = "simplechat")]IAsyncCollector<SignalRMessage> signalRMessages)
{
var message = new JsonSerializer().Deserialize<ChatMessage>(new JsonTextReader(new StreamReader(req.Body)));
var serviceHubContext = await StaticServiceHubContextStore.Get().GetAsync("simplechat");
await serviceHubContext.Clients.All.SendAsync("newMessage", message);
}
[FunctionName("messages")]
public static Task SendMessage(
[HttpTrigger(AuthorizationLevel.Anonymous, "post")]HttpRequest req,
[SignalR(HubName = "simplechat")]IAsyncCollector<SignalRMessage> signalRMessages)
{
var message = new JsonSerializer().Deserialize<ChatMessage>(new JsonTextReader(new StreamReader(req.Body)));
return signalRMessages.AddAsync(
new SignalRMessage
{
UserId = message.Recipient,
GroupName = message.Groupname,
Target = "newMessage",
Arguments = new[] { message }
});
}
[FunctionName("addToGroup")]
public static Task AddToGroup(
[HttpTrigger(AuthorizationLevel.Anonymous, "post")]HttpRequest req,
[SignalR(HubName = "simplechat")]IAsyncCollector<SignalRGroupAction> signalRGroupActions)
{
var message = new JsonSerializer().Deserialize<ChatMessage>(new JsonTextReader(new StreamReader(req.Body)));
var decodedfConnectionId = GetBase64DecodedString(message.ConnectionId);
return signalRGroupActions.AddAsync(
new SignalRGroupAction
{
ConnectionId = decodedfConnectionId,
UserId = message.Recipient,
GroupName = message.Groupname,
Action = GroupAction.Add
});
}
[FunctionName("removeFromGroup")]
public static Task RemoveFromGroup(
[HttpTrigger(AuthorizationLevel.Anonymous, "post")]HttpRequest req,
[SignalR(HubName = "simplechat")]IAsyncCollector<SignalRGroupAction> signalRGroupActions)
{
var message = new JsonSerializer().Deserialize<ChatMessage>(new JsonTextReader(new StreamReader(req.Body)));
var decodedfConnectionId = GetBase64DecodedString(message.ConnectionId);
return signalRGroupActions.AddAsync(
new SignalRGroupAction
{
ConnectionId = message.ConnectionId,
UserId = message.Recipient,
GroupName = message.Groupname,
Action = GroupAction.Remove
});
}
private static string GetBase64EncodedString(string source)
{
if (string.IsNullOrEmpty(source))
{
return source;
}
return Convert.ToBase64String(Encoding.UTF8.GetBytes(source));
}
private static string GetBase64DecodedString(string source)
{
if (string.IsNullOrEmpty(source))
{
return source;
}
return Encoding.UTF8.GetString(Convert.FromBase64String(source));
}
public static class EventGridTriggerCSharp
{
[FunctionName("onConnection")]
public static Task EventGridTest([EventGridTrigger]EventGridEvent eventGridEvent,
[SignalR(HubName = "simplechat")]IAsyncCollector<SignalRMessage> signalRMessages)
{
if (eventGridEvent.EventType == "Microsoft.SignalRService.ClientConnectionConnected")
{
var message = ((JObject)eventGridEvent.Data).ToObject<SignalREvent>();
return signalRMessages.AddAsync(
new SignalRMessage
{
ConnectionId = message.ConnectionId,
Target = "newConnection",
Arguments = new[] { new ChatMessage
{
// ConnectionId is not recommand to send to client directly.
// Here's a simple encryption for an easier sample.
ConnectionId = GetBase64EncodedString(message.ConnectionId),
}}
});
}
return Task.CompletedTask;
}
}
public class ChatMessage
{
public string Sender { get; set; }
public string Text { get; set; }
public string Groupname { get; set; }
public string Recipient { get; set; }
public string ConnectionId { get; set; }
public bool IsPrivate { get; set; }
}
public class SignalREvent
{
public DateTime Timestamp { get; set; }
public string HubName { get; set; }
public string ConnectionId { get; set; }
public string UserId { get; set; }
}
}
}