public static async Task RunOAuth2AuthTokenAsync(TestService.TestServiceClient client, string oauthScope) { #if !NETCOREAPP1_0 Console.WriteLine("running oauth2_auth_token"); ITokenAccess credential = (await GoogleCredential.GetApplicationDefaultAsync()).CreateScoped(new[] { oauthScope }); string oauth2Token = await credential.GetAccessTokenForRequestAsync(); var credentials = GoogleGrpcCredentials.FromAccessToken(oauth2Token); var request = new SimpleRequest { FillUsername = true, FillOauthScope = true }; var response = client.UnaryCall(request, new CallOptions(credentials: credentials)); Assert.False(string.IsNullOrEmpty(response.OauthScope)); Assert.True(oauthScope.Contains(response.OauthScope)); Assert.AreEqual(GetEmailFromServiceAccountFile(), response.Username); Console.WriteLine("Passed!"); #else // TODO(jtattermusch): implement this throw new NotImplementedException("Not supported on CoreCLR yet"); #endif }
/// <summary> /// Creates the channel. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The channel.</returns> private ChannelBase CreateChannel(GoogleAdsConfig config) { ChannelCredentials channelCredentials; if (config.AuthorizationMethod == AuthorizationMethod.Insecure) { channelCredentials = ChannelCredentials.Insecure; } else // if config.AuthenticationMode == AuthenticationMode.OAUTH) { channelCredentials = GoogleGrpcCredentials.ToChannelCredentials(config.Credentials); } Uri uri = new Uri(config.ServerUrl); List <ChannelOption> options = new List <ChannelOption>() { new ChannelOption(GRPC_MAX_RECEIVE_MESSAGE_LENGTH_IN_BYTES_SETTING_NAME, config.MaxReceiveMessageSizeInBytes), new ChannelOption(GRPC_MAX_METADATA_SIZE_IN_BYTES_SETTING_NAME, config.MaxMetadataSizeInBytes), }; if (config.Proxy != null) { options.Add(new ChannelOption(GRPC_HTTP_PROXY_SETTING_NAME, config.Proxy.Address.ToString())); } return(new Channel(uri.Host, uri.Port, channelCredentials, options)); }
private async Task ReAuth(CommandContext ctx) { ctx.LogInfo($"GoogleAssistant: Attempting to refresh access token."); using (IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = new ClientSecrets { ClientId = KarvisConfiguration.GoogleAssistantConfiguration.ClientId, ClientSecret = KarvisConfiguration.GoogleAssistantConfiguration.ClientSecret }, Scopes = new[] { "https://www.googleapis.com/auth/assistant-sdk-prototype" } })) { var tokenResponse = await flow.RefreshTokenAsync( KarvisConfiguration.GoogleAssistantConfiguration.DebugUser, new GoogleOAuth(KarvisConfiguration).GetRefreshTokenForUser(ctx.User.Id), new CancellationToken()); new GoogleOAuth(KarvisConfiguration).StoreCredentialsForUser( KarvisConfiguration.GoogleAssistantConfiguration.DebugUser, tokenResponse.AccessToken, tokenResponse.RefreshToken, ctx.User.Id); var channelCredentials = ChannelCredentials.Create(new SslCredentials(), GoogleGrpcCredentials.FromAccessToken(tokenResponse.AccessToken)); UserEmbeddedAssistantClients[ctx.User.Id] = new EmbeddedAssistant.EmbeddedAssistantClient( new Channel("embeddedassistant.googleapis.com", 443, channelCredentials)); } }
/// <summary> /// Creates the channel. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The channel.</returns> private static Channel CreateChannel(GoogleAdsConfig config) { ChannelCredentials channelCredentials = null; if (config.AuthorizationMethod == AuthorizationMethod.Insecure) { channelCredentials = ChannelCredentials.Insecure; } else // if config.AuthenticationMode == AuthenticationMode.OAUTH) { channelCredentials = GoogleGrpcCredentials.ToChannelCredentials(config.Credentials); } Uri uri = new Uri(config.ServerUrl); return(new Channel(uri.Host, uri.Port, channelCredentials, new List <ChannelOption>() { new ChannelOption(GRPC_MAX_RECEIVE_MESSAGE_LENGTH_IN_BYTES_SETTING_NAME, MAX_RECEIVE_MESSAGE_LENGTH_IN_BYTES), new ChannelOption(GRPC_MAX_METADATA_SIZE_IN_BYTES_SETTING_NAME, MAX_METADATA_SIZE_IN_BYTES), } )); }
private void _connect() { try { var channel_credentials = new SslCredentials(File.ReadAllText(Cert_File)); var call_credentials = GoogleGrpcCredentials.FromAccessToken(Guid); var credentials = ChannelCredentials.Create(channel_credentials, call_credentials); _channel = new Channel(Host, credentials, new ChannelOption[] { new ChannelOption(ChannelOptions.SslTargetNameOverride, Name) }); } catch { } }
/// <summary> /// Creates the channel. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The channel.</returns> private static Channel CreateChannel(GoogleAdsConfig config) { ChannelCredentials channelCredentials = GoogleGrpcCredentials.ToChannelCredentials(config.Credentials); Uri uri = new Uri(config.ServerUrl); return(new Channel(uri.Host, uri.Port, channelCredentials, new List <ChannelOption>() { new ChannelOption(GRPC_MAX_RECEIVE_MESSAGE_LENGTH_IN_BYTES_SETTING_NAME, MAX_RECEIVE_MESSAGE_LENGTH_IN_BYTES.ToString()), new ChannelOption(GRPC_MAX_METADATA_SIZE_IN_BYTES_SETTING_NAME, MAX_METADATA_SIZE_IN_BYTES.ToString()), } )); }
public static void Main(string[] args) { Console.Title = typeof(MainClass).Name; var parent = "projects/mch-test-49bba/databases/(default)"; Console.Title = parent; Boolean debug = false; if (args.Length > 0 && args[0] == "--debug") { debug = true; } if (debug) { Console.WriteLine("GOOGLE_APPLICATION_CREDENTIALS: " + Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS")); var storage = StorageClient.Create(); var buckets = storage.ListBuckets("mch-test-49bba"); foreach (var bucket in buckets) { Console.WriteLine(bucket.Name); } } GoogleCredential credential = GoogleCredential.FromFile(Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS")); if (credential == null) { Console.WriteLine("Could not create credential from file."); Console.WriteLine("GOOGLE_APPLICATION_CREDENTIALS: " + Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS")); } Grpc.Core.Channel channel = new Grpc.Core.Channel( "firestore.googleapis.com:443", GoogleGrpcCredentials.ToChannelCredentials(credential) ); Firestore.FirestoreClient fsClient = new Firestore.FirestoreClient(channel); FirestoreAdmin.FirestoreAdminClient fsAdminClient = new FirestoreAdmin.FirestoreAdminClient(channel); String baseCollectionId = "GrpcTestData"; Ftc = new FirestoreTestClass(parent, fsClient, fsAdminClient, baseCollectionId); Run(); }
/// <summary> /// Creates the channel for the new service, and sets the proxy server. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The new channel.</returns> private Channel CreateChannel(GoogleAdsConfig config) { ChannelCredentials channelCredentials = GoogleGrpcCredentials.ToChannelCredentials(config.Credentials); if (config.Proxy == null) { Environment.SetEnvironmentVariable("http_proxy", null); } else { Environment.SetEnvironmentVariable("http_proxy", config.Proxy.Address.ToString()); } Uri uri = new Uri(config.ServerUrl); return(new Channel(uri.Host, uri.Port, channelCredentials, null)); }
public static async Task RunOAuth2AuthTokenAsync(TestService.TestServiceClient client, string oauthScope) { Console.WriteLine("running oauth2_auth_token"); ITokenAccess credential = (await GoogleCredential.GetApplicationDefaultAsync()).CreateScoped(new[] { oauthScope }); string oauth2Token = await credential.GetAccessTokenForRequestAsync(); var credentials = GoogleGrpcCredentials.FromAccessToken(oauth2Token); var request = new SimpleRequest { FillUsername = true, FillOauthScope = true }; var response = client.UnaryCall(request, new CallOptions(credentials: credentials)); Assert.False(string.IsNullOrEmpty(response.OauthScope)); Assert.True(oauthScope.Contains(response.OauthScope)); Assert.AreEqual(GetEmailFromServiceAccountFile(), response.Username); Console.WriteLine("Passed!"); }
/// <summary> /// Starting point of the Google Streaming Speech-to-Text program. /// </summary> /// <param name="args">First argument must be the path to the credentials JSON file.</param> static void Main(string[] args) { if (args.Length < 1) { Console.WriteLine("Usage: GoogleCloudSpeech.exe [path to credentials JSON file]"); } else { // Create client var fileStream = new FileStream(args[0], FileMode.Open); GoogleCredential googleCredential = GoogleCredential.FromStream(fileStream); ChannelCredentials channelCredentials = GoogleGrpcCredentials.ToChannelCredentials(googleCredential); m_Channel = new Channel("speech.googleapis.com", channelCredentials); m_Client = new Speech.SpeechClient(m_Channel); // Wait to begin streaming Console.WriteLine("ready to start"); while (Console.ReadLine() != "start") { ; } Console.WriteLine("start streaming"); Task streamingTask = StreamingRequest(); // Check for input files string input; while ((input = Console.ReadLine()) != "stop") { m_AudioChunksQueue.Enqueue(ByteString.CopyFrom(File.ReadAllBytes(input))); Console.WriteLine("received audio file input"); } // Finish streaming and wait for the request to finish Console.WriteLine("stop streaming"); m_DoneStreaming = true; streamingTask.Wait(); m_Channel.ShutdownAsync().Wait(); } }
public static async Task RunOAuth2AuthTokenAsync(IChannelWrapper channel, ClientOptions options) { var client = CreateClient <TestService.TestServiceClient>(channel); var oauthScope = options.OAuthScope !; ITokenAccess credential = (await GoogleCredential.GetApplicationDefaultAsync()).CreateScoped(new[] { oauthScope }); var oauth2Token = await credential.GetAccessTokenForRequestAsync(); var credentials = GoogleGrpcCredentials.FromAccessToken(oauth2Token); var request = new SimpleRequest { FillUsername = true, FillOauthScope = true }; var response = await client.UnaryCallAsync(request, new CallOptions(credentials : credentials)); Assert.IsFalse(string.IsNullOrEmpty(response.OauthScope)); Assert.IsTrue(oauthScope.Contains(response.OauthScope)); Assert.AreEqual(GetEmailFromServiceAccountFile(), response.Username); }
public IZeebeClientFinalBuildStep UseAccessToken(string accessToken) { Credentials = ChannelCredentials.Create(Credentials, GoogleGrpcCredentials.FromAccessToken(accessToken)); return(this); }
public static void executeProbes(string api) { StackdriverUtilClass util = new StackdriverUtilClass(api); GoogleCredential auth = GoogleCredential.GetApplicationDefault(); //GoogleCredential auth = GoogleCredential.FromFile(Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS")); ClientBase client; ProbeTestsBaseClass test; System.Type type; Dictionary <string, string> probe_functions = new Dictionary <string, string>(); if (api == "firestore") { Grpc.Core.Channel channel = new Grpc.Core.Channel(_FIRESTORE_TARGET, GoogleGrpcCredentials.ToChannelCredentials(auth)); client = new Firestore.FirestoreClient(channel); test = new FirestoreProbesTestClass(); probe_functions = (test as FirestoreProbesTestClass).GetProbFunctions(); type = typeof(FirestoreProbesTestClass); } else if (api == "spanner") { Grpc.Core.Channel channel = new Grpc.Core.Channel(_SPANNER_TARGET, GoogleGrpcCredentials.ToChannelCredentials(auth)); client = new Spanner.SpannerClient(channel); test = new SpannerProbesTestClass(); probe_functions = (test as SpannerProbesTestClass).GetProbFunctions(); type = typeof(SpannerProbesTestClass); } else { Console.WriteLine("grpc not implemented for {0}", api); return; } //object value = test.GetType().GetMethod("GetProbFunctions").Invoke(test,null); //probe_functions = value.GetType().GetProperties() int total = probe_functions.Count; int success = 0; Dictionary <string, long> metrics = new Dictionary <string, long>(); foreach (var probe in probe_functions) { Console.WriteLine("{0}", probe.Key); MethodInfo fun = type.GetMethod(probe.Value); object[] parameters = new object[] { client, metrics }; try { if (api == "firestore") { fun.Invoke((test as FirestoreProbesTestClass), parameters); } else { fun.Invoke((test as SpannerProbesTestClass), parameters); } success++; } catch (Exception error) { Console.WriteLine("{0}", error); util.reportError(error); } } if (success == total) { util.setSuccess(true); } util.addMetrics(metrics); util.outputMetrics(); if (success != total) { return; } }
public static ChannelCredentials ToChannelCredential(this GoogleCredential credential) { return(GoogleGrpcCredentials.ToChannelCredentials(credential)); }
public async Task Assist(CommandContext ctx, int @in = 48000, int @out = 16000, int inChan = 1, int outChan = 1, string raw = null) { if (!ctx.Services.GetService <IProvideAudioState>().SpeechFromUser.ContainsKey(ctx.User.Id)) { return; } var buff = ctx.Services.GetService <IProvideAudioState>().SpeechFromUser[ctx.User.Id].ToArray(); AssistantConfig.AudioInConfig = new AudioInConfig() { Encoding = AudioInConfig.Types.Encoding.Linear16, SampleRateHertz = 16000 }; if (raw != "raw") { buff = AudioConverter.Resample(buff, @in, @out, inChan, outChan); } else { AssistantConfig.AudioInConfig.SampleRateHertz = AudioFormat.Default.SampleRate; } var token = new GoogleOAuth(KarvisConfiguration).GetTokenForUser(ctx.User.Id); if (string.IsNullOrWhiteSpace(token)) { await ctx.RespondAsync("Sorry, you have not signed up."); return; } if (!UserEmbeddedAssistantClients.ContainsKey(ctx.User.Id)) { var channelCredentials = ChannelCredentials.Create(new SslCredentials(), GoogleGrpcCredentials.FromAccessToken(token)); UserEmbeddedAssistantClients[ctx.User.Id] = new EmbeddedAssistant.EmbeddedAssistantClient(new Channel("embeddedassistant.googleapis.com", 443, channelCredentials)); } using (var call = UserEmbeddedAssistantClients[ctx.User.Id].Assist()) { try { var configRequest = new AssistRequest() { AudioIn = ByteString.Empty, Config = AssistantConfig }; ctx.LogInfo($"GoogleAssistant: Sending config message: Audio IsEmpty: {configRequest.AudioIn.IsEmpty}, Request Size: {configRequest.CalculateSize()}"); await call.RequestStream.WriteAsync(configRequest); await SendAudioInChunks(call, ctx, buff); await call.RequestStream.CompleteAsync(); ctx.LogInfo($"GoogleAssistant: Completing request and awaiting response."); var audioOut = new List <byte>(); await call.ResponseStream.ForEachAsync((response) => ProcessVoiceAssistResponse(response, ctx, ref audioOut)); if (audioOut.Any()) { var voiceConnection = await ctx.EnsureVoiceConnection(); if (voiceConnection == null || (voiceConnection.Channel != ctx.Member?.VoiceState?.Channel)) { throw new InvalidOperationException($"I'm not connected to your voice channel, so I can't speak."); } var audio = AudioConverter.Resample(audioOut.ToArray(), 16000, 48000, 1, 2); voiceConnection.SendSpeaking(); voiceConnection.GetTransmitStream().Write(audio, 0, audio.Length); voiceConnection.GetTransmitStream().Flush(); voiceConnection.SendSpeaking(false); } try { var status = call.GetStatus(); ctx.LogInfo($"GoogleAssistant: Final Status: {status.StatusCode}, Detail: {status.Detail}."); } catch (InvalidOperationException ex) { } } catch (RpcException ex) { ctx.LogError($"GoogleAssistant: Exception: {ex.StatusCode}, {ex.Status.Detail}, {ex.Message}."); if (ex.StatusCode == StatusCode.Unauthenticated) { if (!UserGoogleAuthRetries.ContainsKey(ctx.User.Id)) { UserGoogleAuthRetries[ctx.User.Id] = 0; } if (UserGoogleAuthRetries[ctx.User.Id] < 3) { UserGoogleAuthRetries[ctx.User.Id]++; await ReAuth(ctx); await Assist(ctx, @in, @out, inChan, outChan, raw); } else { UserGoogleAuthRetries[ctx.User.Id] = 0; } } } catch (Exception ex) { await ctx.RespondAsync($"Sorry, {ctx.User.Username}, I can't google. \n\n``{ex.Message}``"); } } }
public async Task TextAssist(CommandContext ctx, [RemainingText] string query) { if (ctx.User?.Id == null) { return; } var token = new GoogleOAuth(KarvisConfiguration).GetTokenForUser(ctx.User.Id); if (string.IsNullOrWhiteSpace(token)) { await ctx.RespondAsync("Sorry, you have not signed up."); return; } if (!UserEmbeddedAssistantClients.ContainsKey(ctx.User.Id)) { var channelCredentials = ChannelCredentials.Create(new SslCredentials(), GoogleGrpcCredentials.FromAccessToken(token)); UserEmbeddedAssistantClients[ctx.User.Id] = new EmbeddedAssistant.EmbeddedAssistantClient(new Channel("embeddedassistant.googleapis.com", 443, channelCredentials)); } using (var call = UserEmbeddedAssistantClients[ctx.User.Id].Assist()) { try { AssistantConfig.AudioInConfig = null; AssistantConfig.TextQuery = query; var request = new AssistRequest() { AudioIn = ByteString.Empty, Config = AssistantConfig }; ctx.LogInfo($"GoogleAssistant: Sending config message: Audio IsEmpty: {request.AudioIn.IsEmpty}, Request Size: {request.CalculateSize()}"); await call.RequestStream.WriteAsync(request); await call.RequestStream.CompleteAsync(); ctx.LogInfo($"GoogleAssistant: Completing request and awaiting response."); var audioOut = new List <byte>(); await call.ResponseStream.ForEachAsync((response) => ProcessTextAssistResponse(response, ctx, ref audioOut)); try { var status = call.GetStatus(); ctx.LogInfo($"GoogleAssistant: Final Status: {status.StatusCode}, Detail: {status.Detail}."); } catch (InvalidOperationException ex) { } if (audioOut.Any()) { var voiceConnection = await ctx.EnsureVoiceConnection(); if (voiceConnection == null || (voiceConnection.Channel != ctx.Member?.VoiceState?.Channel)) { throw new InvalidOperationException($"I'm not connected to your voice channel, so I can't speak."); } var audio = AudioConverter.Resample(audioOut.ToArray(), 16000, 48000, 1, 2); voiceConnection.SendSpeaking(); voiceConnection.GetTransmitStream().Write(audio, 0, audio.Length); voiceConnection.GetTransmitStream().Flush(); voiceConnection.SendSpeaking(false); } } catch (RpcException ex) { ctx.LogError($"GoogleAssistant: Exception: {ex.StatusCode}, Detail: {ex.Status.Detail}, Message: {ex.Message}."); if (ex.StatusCode == StatusCode.Unauthenticated) { if (!UserGoogleAuthRetries.ContainsKey(ctx.User.Id)) { UserGoogleAuthRetries[ctx.User.Id] = 0; } if (UserGoogleAuthRetries[ctx.User.Id] < 3) { UserGoogleAuthRetries[ctx.User.Id]++; await ReAuth(ctx); await TextAssist(ctx, query); } else { UserGoogleAuthRetries[ctx.User.Id] = 0; } } ctx.LogError($"GoogleAssistant: Exception: {ex.StatusCode}, Detail: {ex.Status.Detail}, Message: {ex.Message}."); } catch (Exception ex) { await ctx.RespondAsync($"Sorry, {ctx.User.Username}, I can't google. \n\n``{ex.Message}``"); } } }