| | | 1 | | using System; |
| | | 2 | | using System.Linq; |
| | | 3 | | using System.Net.Http; |
| | | 4 | | using System.Net.Http.Headers; |
| | | 5 | | using System.Reflection; |
| | | 6 | | using System.Text; |
| | | 7 | | using System.Threading; |
| | | 8 | | using System.Threading.Tasks; |
| | | 9 | | using Google.Protobuf; |
| | | 10 | | |
| | | 11 | | namespace Livekit.Server.Sdk.Dotnet |
| | | 12 | | { |
| | | 13 | | /// <summary> |
| | | 14 | | /// Base class of the service clients: holds the credentials and the <see cref="HttpClient"/>, signs every |
| | | 15 | | /// call with a short-lived token and sends it as a Twirp request. |
| | | 16 | | /// </summary> |
| | | 17 | | public class BaseService |
| | | 18 | | { |
| | 1 | 19 | | private static readonly HttpClientHandler SharedHandler = new HttpClientHandler(); |
| | | 20 | | |
| | 1 | 21 | | private static readonly MediaTypeHeaderValue ProtobufContentType = new MediaTypeHeaderValue( |
| | 1 | 22 | | "application/protobuf" |
| | 1 | 23 | | ); |
| | | 24 | | |
| | | 25 | | // Product token sent as User-Agent: livekit-server-sdk-dotnet/<version> |
| | 1 | 26 | | private static readonly ProductInfoHeaderValue UserAgent = new ProductInfoHeaderValue( |
| | 1 | 27 | | "livekit-server-sdk-dotnet", |
| | 1 | 28 | | SdkVersion() |
| | 1 | 29 | | ); |
| | | 30 | | |
| | | 31 | | private readonly string apiKey; |
| | | 32 | | private readonly string apiSecret; |
| | | 33 | | private readonly Uri baseUri; |
| | | 34 | | |
| | | 35 | | /// <summary> |
| | | 36 | | /// The <see cref="HttpClient"/> the requests are sent with: the one supplied to the constructor, or one |
| | | 37 | | /// owned by the SDK (which shares a connection pool with the other SDK-owned clients). |
| | | 38 | | /// </summary> |
| | | 39 | | protected readonly HttpClient httpClient; |
| | | 40 | | |
| | | 41 | | /// <summary> |
| | | 42 | | /// Stores the credentials and the <see cref="HttpClient"/> the requests are sent with. |
| | | 43 | | /// </summary> |
| | | 44 | | /// <param name="host">URL of the LiveKit server, <c>http(s)://</c> or <c>ws(s)://</c>; a subpath such as <c>htt |
| | | 45 | | /// <param name="apiKey">API key; the <c>LIVEKIT_API_KEY</c> environment variable when omitted.</param> |
| | | 46 | | /// <param name="apiSecret">API secret; the <c>LIVEKIT_API_SECRET</c> environment variable when omitted.</param> |
| | | 47 | | /// <param name="client">Optional <see cref="HttpClient"/> to send the requests with. The SDK never modifies it, |
| | 120 | 48 | | public BaseService( |
| | 120 | 49 | | string host, |
| | 120 | 50 | | string apiKey = null, |
| | 120 | 51 | | string apiSecret = null, |
| | 120 | 52 | | HttpClient client = null |
| | 120 | 53 | | ) |
| | 120 | 54 | | { |
| | 120 | 55 | | this.apiKey = apiKey ?? Environment.GetEnvironmentVariable("LIVEKIT_API_KEY"); |
| | 120 | 56 | | this.apiSecret = apiSecret ?? Environment.GetEnvironmentVariable("LIVEKIT_API_SECRET"); |
| | | 57 | | |
| | 120 | 58 | | if (string.IsNullOrEmpty(this.apiKey) || string.IsNullOrEmpty(this.apiSecret)) |
| | 2 | 59 | | { |
| | 2 | 60 | | throw new ArgumentException("apiKey and apiSecret must be set"); |
| | | 61 | | } |
| | 118 | 62 | | if (Encoding.UTF8.GetBytes(this.apiSecret).Length < 32) |
| | 1 | 63 | | { |
| | 1 | 64 | | throw new ArgumentException( |
| | 1 | 65 | | "apiSecret must be at least 256 bits long. Currently it is " |
| | 1 | 66 | | + Encoding.UTF8.GetBytes(this.apiSecret).Length * 8 |
| | 1 | 67 | | + " bits long" |
| | 1 | 68 | | ); |
| | | 69 | | } |
| | | 70 | | |
| | 117 | 71 | | baseUri = new Uri(WithTrailingSlash(ToHttpScheme(host))); |
| | 117 | 72 | | if (client == null) |
| | 77 | 73 | | { |
| | | 74 | | // SDK-owned clients share one handler (and its connection pool): service clients |
| | | 75 | | // are often created per request and never disposed |
| | 77 | 76 | | httpClient = new HttpClient(SharedHandler, false) { BaseAddress = baseUri }; |
| | 77 | 77 | | } |
| | | 78 | | else |
| | 40 | 79 | | { |
| | | 80 | | // A caller-supplied client may be shared with other code (or other service |
| | | 81 | | // clients) and may already have sent requests, so it is never modified: the base |
| | | 82 | | // address, the bearer token and the user agent travel with each request instead. |
| | 40 | 83 | | httpClient = client; |
| | 40 | 84 | | } |
| | 117 | 85 | | } |
| | | 86 | | |
| | | 87 | | /// <summary> |
| | | 88 | | /// Sends one Twirp call: a protobuf-encoded POST to <paramref name="route"/> (relative |
| | | 89 | | /// to the host, e.g. <c>twirp/livekit.RoomService/CreateRoom</c>) signed with |
| | | 90 | | /// <paramref name="bearerToken"/>, parsed with <paramref name="parser"/>. Every call builds |
| | | 91 | | /// its own request, so concurrent calls never share headers and the shared |
| | | 92 | | /// <see cref="HttpClient"/> is left untouched. A non-2xx answer is raised as |
| | | 93 | | /// <see cref="TwirpException"/>. |
| | | 94 | | /// </summary> |
| | | 95 | | internal async Task<TResponse> SendAsync<TRequest, TResponse>( |
| | | 96 | | string route, |
| | | 97 | | TRequest request, |
| | | 98 | | MessageParser<TResponse> parser, |
| | | 99 | | string bearerToken, |
| | | 100 | | CancellationToken cancellationToken = default |
| | | 101 | | ) |
| | | 102 | | where TRequest : IMessage |
| | | 103 | | where TResponse : IMessage<TResponse> |
| | 301 | 104 | | { |
| | 301 | 105 | | using (var content = new ByteArrayContent(request.ToByteArray())) |
| | 301 | 106 | | { |
| | 301 | 107 | | content.Headers.ContentType = ProtobufContentType; |
| | | 108 | | using ( |
| | 301 | 109 | | var message = new HttpRequestMessage(HttpMethod.Post, new Uri(baseUri, route)) |
| | | 110 | | ) |
| | 301 | 111 | | { |
| | 301 | 112 | | message.Content = content; |
| | 301 | 113 | | message.Headers.Authorization = new AuthenticationHeaderValue( |
| | 301 | 114 | | "Bearer", |
| | 301 | 115 | | bearerToken |
| | 301 | 116 | | ); |
| | | 117 | | // A request header replaces the client's default one, so keep the caller's own |
| | | 118 | | // User-Agent products and add the SDK's after them |
| | 907 | 119 | | foreach (var product in httpClient.DefaultRequestHeaders.UserAgent) |
| | 2 | 120 | | { |
| | 2 | 121 | | message.Headers.UserAgent.Add(product); |
| | 2 | 122 | | } |
| | 301 | 123 | | message.Headers.UserAgent.Add(UserAgent); |
| | | 124 | | |
| | | 125 | | using ( |
| | 301 | 126 | | var response = await httpClient |
| | 301 | 127 | | .SendAsync(message, cancellationToken) |
| | 301 | 128 | | .ConfigureAwait(false) |
| | | 129 | | ) |
| | 300 | 130 | | { |
| | 300 | 131 | | var body = await response |
| | 300 | 132 | | .Content.ReadAsByteArrayAsync() |
| | 300 | 133 | | .ConfigureAwait(false); |
| | 300 | 134 | | if (!response.IsSuccessStatusCode) |
| | 16 | 135 | | { |
| | 16 | 136 | | throw TwirpException.FromResponse( |
| | 16 | 137 | | Encoding.UTF8.GetString(body), |
| | 16 | 138 | | (int)response.StatusCode |
| | 16 | 139 | | ); |
| | | 140 | | } |
| | 284 | 141 | | return parser.ParseFrom(body); |
| | | 142 | | } |
| | | 143 | | } |
| | | 144 | | } |
| | 284 | 145 | | } |
| | | 146 | | |
| | | 147 | | private static string SdkVersion() |
| | 1 | 148 | | { |
| | 1 | 149 | | var assembly = typeof(BaseService).Assembly; |
| | 1 | 150 | | var informational = assembly |
| | 1 | 151 | | .GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false) |
| | 1 | 152 | | .OfType<AssemblyInformationalVersionAttribute>() |
| | 1 | 153 | | .FirstOrDefault(); |
| | 1 | 154 | | var version = informational != null ? informational.InformationalVersion : null; |
| | 1 | 155 | | if (string.IsNullOrEmpty(version)) |
| | 0 | 156 | | { |
| | 0 | 157 | | version = assembly.GetName().Version?.ToString(3) ?? "0.0.0"; |
| | 0 | 158 | | } |
| | 1 | 159 | | var plus = version.IndexOf('+'); |
| | 1 | 160 | | return plus >= 0 ? version.Substring(0, plus) : version; |
| | 1 | 161 | | } |
| | | 162 | | |
| | | 163 | | // LIVEKIT_URL is usually the WebSocket URL of the server; the service APIs speak HTTP on |
| | | 164 | | // the same host (the Node and Python SDKs do the same conversion) |
| | | 165 | | private static string ToHttpScheme(string host) |
| | 117 | 166 | | { |
| | 117 | 167 | | if (host == null) |
| | 0 | 168 | | { |
| | 0 | 169 | | return null; |
| | | 170 | | } |
| | 117 | 171 | | if (host.StartsWith("wss://", StringComparison.OrdinalIgnoreCase)) |
| | 1 | 172 | | { |
| | 1 | 173 | | return "https://" + host.Substring("wss://".Length); |
| | | 174 | | } |
| | 116 | 175 | | if (host.StartsWith("ws://", StringComparison.OrdinalIgnoreCase)) |
| | 1 | 176 | | { |
| | 1 | 177 | | return "http://" + host.Substring("ws://".Length); |
| | | 178 | | } |
| | 115 | 179 | | return host; |
| | 117 | 180 | | } |
| | | 181 | | |
| | | 182 | | // Twirp routes are relative ("twirp/livekit.X/Y") and System.Uri drops the last path |
| | | 183 | | // segment of a base address without a trailing "/" when resolving a relative reference, |
| | | 184 | | // so "https://my.server.com/livekit" would send requests to "https://my.server.com/twirp/...". |
| | | 185 | | // Append the slash so hosts with a subpath work whether or not the caller added it. |
| | | 186 | | private static string WithTrailingSlash(string host) |
| | 117 | 187 | | { |
| | 117 | 188 | | if (host == null || host.EndsWith("/", StringComparison.Ordinal)) |
| | 1 | 189 | | { |
| | 1 | 190 | | return host; |
| | | 191 | | } |
| | 116 | 192 | | return host + "/"; |
| | 117 | 193 | | } |
| | | 194 | | |
| | | 195 | | /// <summary> |
| | | 196 | | /// Builds the bearer token of a call that needs <paramref name="videoGrants"/>, valid for |
| | | 197 | | /// <see cref="Constants.DefaultTtl"/>. |
| | | 198 | | /// </summary> |
| | | 199 | | /// <param name="videoGrants">Room permissions the call needs.</param> |
| | | 200 | | /// <returns>The signed JWT, sent as bearer token.</returns> |
| | | 201 | | protected string AuthHeader(VideoGrants videoGrants) |
| | 253 | 202 | | { |
| | 253 | 203 | | var accessToken = new AccessToken(apiKey, apiSecret); |
| | 253 | 204 | | accessToken.WithGrants(videoGrants); |
| | 253 | 205 | | accessToken.WithTtl(Constants.DefaultTtl); |
| | | 206 | | |
| | 253 | 207 | | return accessToken.ToJwt(); |
| | 253 | 208 | | } |
| | | 209 | | |
| | | 210 | | /// <summary> |
| | | 211 | | /// Builds the bearer token of a SIP call that needs <paramref name="videoGrants"/> and |
| | | 212 | | /// <paramref name="sipGrants"/>, valid for <see cref="Constants.DefaultTtl"/>. |
| | | 213 | | /// </summary> |
| | | 214 | | /// <param name="videoGrants">Room permissions the call needs.</param> |
| | | 215 | | /// <param name="sipGrants">SIP permissions the call needs.</param> |
| | | 216 | | /// <returns>The signed JWT, sent as bearer token.</returns> |
| | | 217 | | protected string AuthHeader(VideoGrants videoGrants, SIPGrants sipGrants) |
| | 48 | 218 | | { |
| | 48 | 219 | | var accessToken = new AccessToken(apiKey, apiSecret); |
| | 48 | 220 | | accessToken.WithGrants(videoGrants); |
| | 48 | 221 | | accessToken.WithSipGrants(sipGrants); |
| | 48 | 222 | | accessToken.WithTtl(Constants.DefaultTtl); |
| | | 223 | | |
| | 48 | 224 | | return accessToken.ToJwt(); |
| | 48 | 225 | | } |
| | | 226 | | } |
| | | 227 | | } |