-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTBetaWebhookHandler.cs
More file actions
272 lines (213 loc) · 7.31 KB
/
TBetaWebhookHandler.cs
File metadata and controls
272 lines (213 loc) · 7.31 KB
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
258
259
260
261
262
263
264
265
266
267
268
269
270
using Newtonsoft.Json;
using PX.Common;
using PX.Data;
using PX.Data.Webhooks;
using PX.DbServices;
using PX.Objects;
using PX.Objects.CR;
using PX.Objects.IN;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Results;
using OpenTokSDK;
using System.Net.Http.Headers;
using System.Net;
using System.Text;
using Newtonsoft;
namespace TeamBeta2021
{
public class TBetaWebhookHandler : IWebhookHandler
{
/*
* (POST) {webhook_url}?role=[local/remote]&action=getToken
(GET) {webhook_url}?role=[local/remote]&action=getSession&id=[id]
(POST) {webhook_url}?role=[local/remote]&action=startRecording&id=[id]
(POST) {webhook_url}?role=[local/remote]&action=stopRecording&id=[id]
*/
public async Task<System.Web.Http.IHttpActionResult> ProcessRequestAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
var _queryParameters = HttpUtility.ParseQueryString(request.RequestUri.Query);
string action = _queryParameters.Get("action");
switch (action)
{
case "getToken":
return await getToken(request);
case "getSession":
return await getSession(request);
case "startRecording":
return new OkResult(request); // startRecording(request);
case "stopRecording":
return new OkResult(request); //stopRecording(request);
default:
return new OkResult(request);
}
}
public HttpResponseMessage buildResponse(System.Net.HttpStatusCode status, string content)
{
var response = new HttpResponseMessage( status);
response.Content = new StringContent(content);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return response;
}
public class JsonTextActionResult : IHttpActionResult
{
public HttpRequestMessage Request { get; }
public string JsonText { get; }
public JsonTextActionResult(HttpRequestMessage request, string jsonText)
{
Request = request;
JsonText = jsonText;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.FromResult(Execute());
}
public HttpResponseMessage Execute()
{
var response = this.Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(JsonText, Encoding.UTF8, "application/json");
return response;
}
}
public class InvalidHttpActionResult : IHttpActionResult
{
private readonly string _message;
private readonly HttpStatusCode _statusCode;
public InvalidHttpActionResult(HttpStatusCode statusCode, string message)
{
_statusCode = statusCode;
_message = message;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
HttpResponseMessage response = new HttpResponseMessage(_statusCode)
{
Content = new StringContent(_message)
};
return Task.FromResult(response);
}
}
private OpenTok getOpenTok()
{
using (var scope = GetUserScope())
{
var graph = PXGraph.CreateInstance<TBetaCredSetup>();
TBetaCred creds = graph.Creds.Select();
return new OpenTok(Convert.ToInt32(creds.Apikey), creds.VSecret);
}
}
private void saveSessionId(string id, string sessionId)
{
using (var scope = GetUserScope())
{
Guid noteID = Guid.Parse(id);
PXDatabase.Update<CRActivity>(
new PXDataFieldAssign<CRActivity.body>(sessionId),
new PXDataFieldRestrict<CRActivity.noteID>(PXDbType.UniqueIdentifier, 16, noteID, PXComp.EQ)
);
}
}
private string getSessionId(string id)
{
using (var scope = GetUserScope())
{
Guid noteID = Guid.Parse(id);
PXDataRecord rec = PXDatabase.SelectSingle<CRActivity>(
new PXDataField<CRActivity.body>(),
new PXDataFieldValue<CRActivity.noteID>(PXDbType.UniqueIdentifier, 16, noteID)
);
return rec.GetString(0);
}
}
public class TokenOptions
{
public string sessionID { get; set; }
public string role { get; set; }
public string data { get; set; }
}
private async Task<System.Web.Http.IHttpActionResult> getToken(HttpRequestMessage request)
{
var _queryParameters = HttpUtility.ParseQueryString(request.RequestUri.Query);
string client = _queryParameters.Get("role");
var body = await request.Content.ReadAsStringAsync();
var options = JsonConvert.DeserializeObject<TokenOptions>(body);
var openTok = getOpenTok();
var token = openTok.GenerateToken(options.sessionID, role: Role.PUBLISHER, data: options.data);
return new JsonTextActionResult(request, token); ;
}
private async Task<System.Web.Http.IHttpActionResult> getSession(HttpRequestMessage request)
{
var openTok = getOpenTok();
var _queryParameters = HttpUtility.ParseQueryString(request.RequestUri.Query);
string client = _queryParameters.Get("role");
string id = _queryParameters.Get("nid");
string sessionId = null;
switch (client)
{
case "local":
// Create session, turn on automatic recording
var session = openTok.CreateSession(mediaMode: MediaMode.ROUTED, archiveMode: ArchiveMode.ALWAYS);
sessionId = session.Id;
saveSessionId(id, sessionId);
break;
case "remote":
sessionId = getSessionId(id);
break;
}
DateTime today = DateTime.Now;
DateTime tomorrow = today.AddDays(1);
string expiration = tomorrow.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ");
return new JsonTextActionResult(request, "{\"sessionId\":\""+ sessionId + "\",\"code\":\"" + id + "\",\"expiration\":\"" + expiration + "\"}");
}
//private string StartRecording(HttpRequestMessage request)
// {
// string noteId = System.Web.HttpContext.Current.Request.QueryString["id"];
// // Load the sessionID
// PXDataRecord rec = PXDatabase.SelectSingle<CRActivity>(
// new PXDataField<TBetaCRActivityExtension.sessionID>(),
// new PXDataFieldValue<CRActivity.noteID>(PXDbType.UniqueIdentifier, 6, id)
// );
// string sessionId = rec.GetString(0);
// var openTokService = new OpenTokService();
// var archive = openTokService.OpenTok.StartArchive(sessionId, "Archiving Video", true, true, OpenTokSDK.OutputMode.COMPOSED);
// return archive.Id.ToString();
//}
//private string StopRecording(HttpRequestMessage request)
// {
// string noteId = System.Web.HttpContext.Current.Request.QueryString["id"];
// var openTokService = new OpenTokService();
// var archive = openTokService.OpenTok.StopArchive(noteId);
// return archive.Id.ToString();
//}
/// <summary>
/// Defines the LoginScope to be used for the WebHooks
/// </summary>
/// <returns></returns>
private IDisposable GetUserScope()
{
//todo: For now we will use admin but we will want to throttle back to a
// user with restricted access as to reduce any risk of attack.
// perhaps this can be configured in the Surveys Preferences/Setup page.
var userName = "admin";
if (PXDatabase.Companies.Length > 0)
{
var company = PXAccess.GetCompanyName();
if (string.IsNullOrEmpty(company))
{
company = PXDatabase.Companies[0];
}
userName = userName + "@" + company;
}
return new PXLoginScope(userName);
}
}
}