-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
CallingServerClient.cs
500 lines (465 loc) · 25.2 KB
/
CallingServerClient.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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.Communication.Pipeline;
namespace Azure.Communication.CallingServer
{
/// <summary>
/// The Azure Communication Services Calling Server client.
/// </summary>
public class CallingServerClient
{
internal readonly ClientDiagnostics _clientDiagnostics;
internal readonly HttpPipeline _pipeline;
internal readonly string _resourceEndpoint;
internal readonly ContentDownloader _contentDownloader;
internal CallConnectionsRestClient CallConnectionRestClient { get; }
internal ServerCallsRestClient ServerCallRestClient { get; }
#region public constructors
/// <summary> Initializes a new instance of <see cref="CallingServerClient"/>.</summary>
/// <param name="connectionString">Connection string acquired from the Azure Communication Services resource.</param>
public CallingServerClient(string connectionString)
: this(
ConnectionString.Parse(Argument.CheckNotNullOrEmpty(connectionString, nameof(connectionString))),
new CallingServerClientOptions())
{ }
/// <summary> Initializes a new instance of <see cref="CallingServerClient"/>.</summary>
/// <param name="connectionString">Connection string acquired from the Azure Communication Services resource.</param>
/// <param name="options">Client option exposing <see cref="ClientOptions.Diagnostics"/>, <see cref="ClientOptions.Retry"/>, <see cref="ClientOptions.Transport"/>, etc.</param>
public CallingServerClient(string connectionString, CallingServerClientOptions options)
: this(
ConnectionString.Parse(Argument.CheckNotNullOrEmpty(connectionString, nameof(connectionString))),
Argument.CheckNotNull(options, nameof(options)))
{ }
/// <summary> Initializes a new instance of <see cref="CallingServerClient"/>.</summary>
/// <param name="endpoint">The URI of the Azure Communication Services resource.</param>
/// <param name="credential">The TokenCredential used to authenticate requests, such as DefaultAzureCredential.</param>
public CallingServerClient(Uri endpoint, TokenCredential credential)
: this(
Argument.CheckNotNull(endpoint, nameof(endpoint)).AbsoluteUri,
Argument.CheckNotNull(credential, nameof(credential)),
new CallingServerClientOptions())
{ }
/// <summary> Initializes a new instance of <see cref="CallingServerClient"/>.</summary>
/// <param name="endpoint">The URI of the Azure Communication Services resource.</param>
/// <param name="credential">The TokenCredential used to authenticate requests, such as DefaultAzureCredential.</param>
/// <param name="options">Client option exposing <see cref="ClientOptions.Diagnostics"/>, <see cref="ClientOptions.Retry"/>, <see cref="ClientOptions.Transport"/>, etc.</param>
public CallingServerClient(Uri endpoint, TokenCredential credential, CallingServerClientOptions options)
: this(
Argument.CheckNotNull(endpoint, nameof(endpoint)).AbsoluteUri,
Argument.CheckNotNull(credential, nameof(credential)),
Argument.CheckNotNull(options, nameof(options)))
{ }
#endregion
#region private constructors
private CallingServerClient(ConnectionString connectionString, CallingServerClientOptions options)
: this(connectionString.GetRequired("endpoint"), options.BuildHttpPipeline(connectionString), options)
{ }
private CallingServerClient(string endpoint, TokenCredential tokenCredential, CallingServerClientOptions options)
: this(endpoint, options.BuildHttpPipeline(tokenCredential), options)
{ }
private CallingServerClient(string endpoint, HttpPipeline httpPipeline, CallingServerClientOptions options)
{
_pipeline = httpPipeline;
_resourceEndpoint = endpoint;
_clientDiagnostics = new ClientDiagnostics(options);
_contentDownloader = new(this);
CallConnectionRestClient = new CallConnectionsRestClient(_clientDiagnostics, httpPipeline, endpoint, options.ApiVersion);
ServerCallRestClient = new ServerCallsRestClient(_clientDiagnostics, httpPipeline, endpoint, options.ApiVersion);
}
#endregion
/// <summary>Initializes a new instance of <see cref="CallingServerClient"/> for mocking.</summary>
protected CallingServerClient()
{
_pipeline = null;
_resourceEndpoint = null;
_clientDiagnostics = null;
_contentDownloader = new(this);
CallConnectionRestClient = null;
ServerCallRestClient = null;
}
/// Create an outgoing call from source to target identities.
/// <param name="source"> The source identity </param>
/// <param name="targets"> The target identities. </param>
/// <param name="options"> The call options. </param>
/// <param name="cancellationToken"> The cancellation token. </param>
/// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
/// <exception cref="ArgumentNullException"><paramref name="targets"/> is null.</exception>
/// <exception cref="ArgumentNullException"><paramref name="options"/> is null.</exception>
public virtual async Task<Response<CallConnection>> CreateCallConnectionAsync(CommunicationIdentifier source, IEnumerable<CommunicationIdentifier> targets, CreateCallOptions options, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(CallingServerClient)}.{nameof(CreateCallConnection)}");
scope.Start();
try
{
Argument.AssertNotNull(source, nameof(source));
Argument.AssertNotNullOrEmpty(targets, nameof(targets));
Argument.AssertNotNull(options, nameof(options));
var createCallResponse = await CallConnectionRestClient.CreateCallAsync(
source: CommunicationIdentifierSerializer.Serialize(source),
targets: targets.Select(t => CommunicationIdentifierSerializer.Serialize(t)),
callbackUri: options.CallbackUri?.AbsoluteUri,
requestedMediaTypes: options.RequestedMediaTypes,
requestedCallEvents: options.RequestedCallEvents,
alternateCallerId: options.AlternateCallerId == null ? null : new PhoneNumberIdentifierModel(options.AlternateCallerId.PhoneNumber),
subject: options.Subject,
cancellationToken: cancellationToken
).ConfigureAwait(false);
return Response.FromValue(
new CallConnection(createCallResponse.Value.CallConnectionId, CallConnectionRestClient, _clientDiagnostics),
createCallResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// Create an outgoing call from source to target identities.
/// <param name="source"> The source identity </param>
/// <param name="targets"> The target identities. </param>
/// <param name="options"> The call options. </param>
/// <param name="cancellationToken"> The cancellation token. </param>
/// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
/// <exception cref="ArgumentNullException"><paramref name="targets"/> is null.</exception>
/// <exception cref="ArgumentNullException"><paramref name="options"/> is null.</exception>
public virtual Response<CallConnection> CreateCallConnection(CommunicationIdentifier source, IEnumerable<CommunicationIdentifier> targets, CreateCallOptions options, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(CallingServerClient)}.{nameof(CreateCallConnection)}");
scope.Start();
try
{
Argument.AssertNotNull(source, nameof(source));
Argument.AssertNotNullOrEmpty(targets, nameof(targets));
Argument.AssertNotNull(options, nameof(options));
var createCallResponse = CallConnectionRestClient.CreateCall(
source: CommunicationIdentifierSerializer.Serialize(source),
targets: targets.Select(t => CommunicationIdentifierSerializer.Serialize(t)),
callbackUri: options.CallbackUri?.AbsoluteUri,
requestedMediaTypes: options.RequestedMediaTypes,
requestedCallEvents: options.RequestedCallEvents,
alternateCallerId: options.AlternateCallerId == null ? null : new PhoneNumberIdentifierModel(options.AlternateCallerId.PhoneNumber),
subject: options.Subject,
cancellationToken: cancellationToken
);
return Response.FromValue(
new CallConnection(createCallResponse.Value.CallConnectionId, CallConnectionRestClient, _clientDiagnostics),
createCallResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// Join the call using server call id.
/// <param name="serverCallId"> The server call id. </param>
/// <param name="source"> The source identity. </param>
/// <param name="callOptions"> The call Options. </param>
/// <param name="cancellationToken"> The cancellation token. </param>
/// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
/// <exception cref="ArgumentNullException"><paramref name="serverCallId"/> is null.</exception>
/// <exception cref="ArgumentNullException"><paramref name="callOptions"/> is null.</exception>
public virtual async Task<Response<CallConnection>> JoinCallAsync(string serverCallId, CommunicationIdentifier source, JoinCallOptions callOptions, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(CallingServerClient)}.{nameof(JoinCall)}");
scope.Start();
try
{
Argument.AssertNotNull(source, nameof(source));
Argument.AssertNotNull(callOptions, nameof(callOptions));
var joinCallResponse = await ServerCallRestClient.JoinCallAsync(
serverCallId: serverCallId,
source: CommunicationIdentifierSerializer.Serialize(source),
callbackUri: callOptions.CallbackUri?.AbsoluteUri,
requestedMediaTypes: callOptions.RequestedMediaTypes,
requestedCallEvents: callOptions.RequestedCallEvents,
subject: null,
cancellationToken: cancellationToken
).ConfigureAwait(false);
return Response.FromValue(
new CallConnection(joinCallResponse.Value.CallConnectionId, CallConnectionRestClient, _clientDiagnostics),
joinCallResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// Join the call using server call id.
/// <param name="serverCallId"> The server call id. </param>
/// <param name="source"> The source identity. </param>
/// <param name="callOptions"> The call Options. </param>
/// <param name="cancellationToken"> The cancellation token. </param>
/// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
/// <exception cref="ArgumentNullException"><paramref name="serverCallId"/> is null.</exception>
/// <exception cref="ArgumentNullException"><paramref name="callOptions"/> is null.</exception>
public virtual Response<CallConnection> JoinCall(string serverCallId, CommunicationIdentifier source, JoinCallOptions callOptions, CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(CallingServerClient)}.{nameof(JoinCall)}");
scope.Start();
try
{
Argument.AssertNotNull(source, nameof(source));
Argument.AssertNotNull(callOptions, nameof(callOptions));
var joinCallResponse = ServerCallRestClient.JoinCall(
serverCallId: serverCallId,
source: CommunicationIdentifierSerializer.Serialize(source),
callbackUri: callOptions.CallbackUri?.AbsoluteUri,
requestedMediaTypes: callOptions.RequestedMediaTypes,
requestedCallEvents: callOptions.RequestedCallEvents,
subject: null,
cancellationToken: cancellationToken
);
return Response.FromValue(
new CallConnection(joinCallResponse.Value.CallConnectionId, CallConnectionRestClient, _clientDiagnostics),
joinCallResponse.GetRawResponse());
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary> Initializes a new instance of CallConnection. <see cref="CallConnection"/>.</summary>
/// <param name="callConnectionId"> The thread id for the ChatThreadClient instance. </param>
public virtual CallConnection GetCallConnection(string callConnectionId)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(CallingServerClient)}.{nameof(CallingServerClient)}");
scope.Start();
try
{
Argument.AssertNotNullOrEmpty(callConnectionId, nameof(callConnectionId));
return new CallConnection(callConnectionId, CallConnectionRestClient, _clientDiagnostics);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Initializes a server call.
/// </summary>
/// <param name="serverCallId">The server call id. </param>
/// <returns></returns>
public virtual ServerCall InitializeServerCall(string serverCallId)
{
using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(CallingServerClient)}.{nameof(InitializeServerCall)}");
scope.Start();
try
{
Argument.AssertNotNull(serverCallId, nameof(serverCallId));
return new ServerCall(serverCallId, ServerCallRestClient, _clientDiagnostics);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// The <see cref="DownloadStreamingAsync(Uri, HttpRange, CancellationToken)"/>
/// operation downloads the recording's content.
///
/// </summary>
/// <param name="sourceEndpoint">
/// Recording's content's url location.
/// </param>
/// <param name="range">
/// If provided, only download the bytes of the content in the specified range.
/// If not provided, download the entire content.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be canceled.
/// </param>
/// <returns>
/// A <see cref="Response{Stream}"/> containing the
/// downloaded content.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual async Task<Response<Stream>> DownloadStreamingAsync(
Uri sourceEndpoint,
HttpRange range = default,
CancellationToken cancellationToken = default) =>
await _contentDownloader.DownloadStreamingInternal(
sourceEndpoint,
range,
async: true,
cancellationToken)
.ConfigureAwait(false);
/// <summary>
/// The <see cref="DownloadStreaming(Uri, HttpRange, CancellationToken)"/>
/// operation downloads the recording's content.
///
/// </summary>
/// <param name="sourceEndpoint">
/// Recording's content's url location.
/// </param>
/// <param name="range">
/// If provided, only download the bytes of the content in the specified range.
/// If not provided, download the entire content.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be canceled.
/// </param>
/// <returns>
/// A <see cref="Response{Stream}"/> containing the
/// downloaded content.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Response<Stream> DownloadStreaming(
Uri sourceEndpoint,
HttpRange range = default,
CancellationToken cancellationToken = default) =>
_contentDownloader.DownloadStreamingInternal(
sourceEndpoint,
range,
async: false,
cancellationToken)
.EnsureCompleted();
/// <summary>
/// The <see cref="DownloadTo(Uri, Stream, ContentTransferOptions, CancellationToken)"/>
/// operation downloads the specified content using parallel requests,
/// and writes the content to <paramref name="destinationStream"/>.
/// </summary>
/// <param name="sourceEndpoint">
/// A <see cref="Uri"/> with the Recording's content's url location.
/// </param>
/// <param name="destinationStream">
/// A <see cref="Stream"/> to write the downloaded content to.
/// </param>
/// <param name="transferOptions">
/// Optional <see cref="ContentTransferOptions"/> to configure
/// parallel transfer behavior.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be canceled.
/// </param>
/// <returns>
/// A <see cref="Response"/> describing the operation.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Response DownloadTo(Uri sourceEndpoint, Stream destinationStream,
ContentTransferOptions transferOptions = default, CancellationToken cancellationToken = default) =>
_contentDownloader.StagedDownloadAsync(sourceEndpoint, destinationStream, transferOptions, async: false, cancellationToken: cancellationToken).EnsureCompleted();
/// <summary>
/// The <see cref="DownloadToAsync(Uri, Stream, ContentTransferOptions, CancellationToken)"/>
/// operation downloads the specified content using parallel requests,
/// and writes the content to <paramref name="destinationStream"/>.
/// </summary>
/// <param name="sourceEndpoint">
/// A <see cref="Uri"/> with the Recording's content's url location.
/// </param>
/// <param name="destinationStream">
/// A <see cref="Stream"/> to write the downloaded content to.
/// </param>
/// <param name="transferOptions">
/// Optional <see cref="ContentTransferOptions"/> to configure
/// parallel transfer behavior.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be canceled.
/// </param>
/// <returns>
/// A <see cref="Response"/> describing the operation.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual async Task<Response> DownloadToAsync(Uri sourceEndpoint, Stream destinationStream, ContentTransferOptions transferOptions = default, CancellationToken cancellationToken = default) =>
await _contentDownloader.StagedDownloadAsync(sourceEndpoint, destinationStream, transferOptions, async: true, cancellationToken: cancellationToken).ConfigureAwait(false);
/// <summary>
/// The <see cref="DownloadTo(Uri, string, ContentTransferOptions, CancellationToken)"/>
/// operation downloads the specified content using parallel requests,
/// and writes the content to <paramref name="destinationPath"/>.
/// </summary>
/// <param name="sourceEndpoint">
/// A <see cref="Uri"/> with the Recording's content's url location.
/// </param>
/// <param name="destinationPath">
/// A file path to write the downloaded content to.
/// </param>
/// <param name="transferOptions">
/// Optional <see cref="ContentTransferOptions"/> to configure
/// parallel transfer behavior.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be canceled.
/// </param>
/// <returns>
/// A <see cref="Response"/> describing the operation.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual Response DownloadTo(Uri sourceEndpoint, string destinationPath,
ContentTransferOptions transferOptions = default, CancellationToken cancellationToken = default)
{
using Stream destination = File.Create(destinationPath);
return _contentDownloader.StagedDownloadAsync(sourceEndpoint, destination, transferOptions,
async: false, cancellationToken: cancellationToken).EnsureCompleted();
}
/// <summary>
/// The <see cref="DownloadToAsync(Uri, string, ContentTransferOptions, CancellationToken)"/>
/// operation downloads the specified content using parallel requests,
/// and writes the content to <paramref name="destinationPath"/>.
/// </summary>
/// <param name="sourceEndpoint">
/// A <see cref="Uri"/> with the Recording's content's url location.
/// </param>
/// <param name="destinationPath">
/// A file path to write the downloaded content to.
/// </param>
/// <param name="transferOptions">
/// Optional <see cref="ContentTransferOptions"/> to configure
/// parallel transfer behavior.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate
/// notifications that the operation should be canceled.
/// </param>
/// <returns>
/// A <see cref="Response"/> describing the operation.
/// </returns>
/// <remarks>
/// A <see cref="RequestFailedException"/> will be thrown if
/// a failure occurs.
/// </remarks>
public virtual async Task<Response> DownloadToAsync(Uri sourceEndpoint, string destinationPath,
ContentTransferOptions transferOptions = default, CancellationToken cancellationToken = default)
{
using Stream destination = File.Create(destinationPath);
return await _contentDownloader.StagedDownloadAsync(sourceEndpoint, destination, transferOptions,
async: true, cancellationToken: cancellationToken).ConfigureAwait(false);
}
}
}