1// Copyright 2020 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// Code generated by protoc-gen-go_gapic. DO NOT EDIT.
16
17package dialogflow
18
19import (
20	"context"
21	"fmt"
22	"math"
23	"net/url"
24	"time"
25
26	"cloud.google.com/go/longrunning"
27	lroauto "cloud.google.com/go/longrunning/autogen"
28	"github.com/golang/protobuf/proto"
29	structpbpb "github.com/golang/protobuf/ptypes/struct"
30	gax "github.com/googleapis/gax-go/v2"
31	"google.golang.org/api/iterator"
32	"google.golang.org/api/option"
33	gtransport "google.golang.org/api/transport/grpc"
34	dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2"
35	longrunningpb "google.golang.org/genproto/googleapis/longrunning"
36	"google.golang.org/grpc"
37	"google.golang.org/grpc/codes"
38	"google.golang.org/grpc/metadata"
39)
40
41var newIntentsClientHook clientHook
42
43// IntentsCallOptions contains the retry settings for each method of IntentsClient.
44type IntentsCallOptions struct {
45	ListIntents        []gax.CallOption
46	GetIntent          []gax.CallOption
47	CreateIntent       []gax.CallOption
48	UpdateIntent       []gax.CallOption
49	DeleteIntent       []gax.CallOption
50	BatchUpdateIntents []gax.CallOption
51	BatchDeleteIntents []gax.CallOption
52}
53
54func defaultIntentsClientOptions() []option.ClientOption {
55	return []option.ClientOption{
56		option.WithEndpoint("dialogflow.googleapis.com:443"),
57		option.WithGRPCDialOption(grpc.WithDisableServiceConfig()),
58		option.WithScopes(DefaultAuthScopes()...),
59		option.WithGRPCDialOption(grpc.WithDefaultCallOptions(
60			grpc.MaxCallRecvMsgSize(math.MaxInt32))),
61	}
62}
63
64func defaultIntentsCallOptions() *IntentsCallOptions {
65	return &IntentsCallOptions{
66		ListIntents: []gax.CallOption{
67			gax.WithRetry(func() gax.Retryer {
68				return gax.OnCodes([]codes.Code{
69					codes.Unavailable,
70					codes.DeadlineExceeded,
71				}, gax.Backoff{
72					Initial:    100 * time.Millisecond,
73					Max:        60000 * time.Millisecond,
74					Multiplier: 1.30,
75				})
76			}),
77		},
78		GetIntent: []gax.CallOption{
79			gax.WithRetry(func() gax.Retryer {
80				return gax.OnCodes([]codes.Code{
81					codes.Unavailable,
82					codes.DeadlineExceeded,
83				}, gax.Backoff{
84					Initial:    100 * time.Millisecond,
85					Max:        60000 * time.Millisecond,
86					Multiplier: 1.30,
87				})
88			}),
89		},
90		CreateIntent: []gax.CallOption{},
91		UpdateIntent: []gax.CallOption{},
92		DeleteIntent: []gax.CallOption{
93			gax.WithRetry(func() gax.Retryer {
94				return gax.OnCodes([]codes.Code{
95					codes.Unavailable,
96					codes.DeadlineExceeded,
97				}, gax.Backoff{
98					Initial:    100 * time.Millisecond,
99					Max:        60000 * time.Millisecond,
100					Multiplier: 1.30,
101				})
102			}),
103		},
104		BatchUpdateIntents: []gax.CallOption{},
105		BatchDeleteIntents: []gax.CallOption{
106			gax.WithRetry(func() gax.Retryer {
107				return gax.OnCodes([]codes.Code{
108					codes.Unavailable,
109					codes.DeadlineExceeded,
110				}, gax.Backoff{
111					Initial:    100 * time.Millisecond,
112					Max:        60000 * time.Millisecond,
113					Multiplier: 1.30,
114				})
115			}),
116		},
117	}
118}
119
120// IntentsClient is a client for interacting with Dialogflow API.
121//
122// Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
123type IntentsClient struct {
124	// Connection pool of gRPC connections to the service.
125	connPool gtransport.ConnPool
126
127	// The gRPC API client.
128	intentsClient dialogflowpb.IntentsClient
129
130	// LROClient is used internally to handle longrunning operations.
131	// It is exposed so that its CallOptions can be modified if required.
132	// Users should not Close this client.
133	LROClient *lroauto.OperationsClient
134
135	// The call options for this service.
136	CallOptions *IntentsCallOptions
137
138	// The x-goog-* metadata to be sent with each request.
139	xGoogMetadata metadata.MD
140}
141
142// NewIntentsClient creates a new intents client.
143//
144// An intent represents a mapping between input from a user and an action to
145// be taken by your application. When you pass user input to the
146// DetectIntent (or
147// StreamingDetectIntent) method, the
148// Dialogflow API analyzes the input and searches
149// for a matching intent. If no match is found, the Dialogflow API returns a
150// fallback intent (is_fallback = true).
151//
152// You can provide additional information for the Dialogflow API to use to
153// match user input to an intent by adding the following to your intent.
154//
155//   Contexts - provide additional context for intent analysis. For
156//   example, if an intent is related to an object in your application that
157//   plays music, you can provide a context to determine when to match the
158//   intent if the user input is “turn it off”. You can include a context
159//   that matches the intent when there is previous user input of
160//   “play music”, and not when there is previous user input of
161//   “turn on the light”.
162//
163//   Events - allow for matching an intent by using an event name
164//   instead of user input. Your application can provide an event name and
165//   related parameters to the Dialogflow API to match an intent. For
166//   example, when your application starts, you can send a welcome event
167//   with a user name parameter to the Dialogflow API to match an intent with
168//   a personalized welcome message for the user.
169//
170//   Training phrases - provide examples of user input to train the
171//   Dialogflow API agent to better match intents.
172//
173// For more information about intents, see the
174// Dialogflow
175// documentation (at https://cloud.google.com/dialogflow/docs/intents-overview).
176func NewIntentsClient(ctx context.Context, opts ...option.ClientOption) (*IntentsClient, error) {
177	clientOpts := defaultIntentsClientOptions()
178
179	if newIntentsClientHook != nil {
180		hookOpts, err := newIntentsClientHook(ctx, clientHookParams{})
181		if err != nil {
182			return nil, err
183		}
184		clientOpts = append(clientOpts, hookOpts...)
185	}
186
187	connPool, err := gtransport.DialPool(ctx, append(clientOpts, opts...)...)
188	if err != nil {
189		return nil, err
190	}
191	c := &IntentsClient{
192		connPool:    connPool,
193		CallOptions: defaultIntentsCallOptions(),
194
195		intentsClient: dialogflowpb.NewIntentsClient(connPool),
196	}
197	c.setGoogleClientInfo()
198
199	c.LROClient, err = lroauto.NewOperationsClient(ctx, gtransport.WithConnPool(connPool))
200	if err != nil {
201		// This error "should not happen", since we are just reusing old connection pool
202		// and never actually need to dial.
203		// If this does happen, we could leak connp. However, we cannot close conn:
204		// If the user invoked the constructor with option.WithGRPCConn,
205		// we would close a connection that's still in use.
206		// TODO: investigate error conditions.
207		return nil, err
208	}
209	return c, nil
210}
211
212// Connection returns a connection to the API service.
213//
214// Deprecated.
215func (c *IntentsClient) Connection() *grpc.ClientConn {
216	return c.connPool.Conn()
217}
218
219// Close closes the connection to the API service. The user should invoke this when
220// the client is no longer required.
221func (c *IntentsClient) Close() error {
222	return c.connPool.Close()
223}
224
225// setGoogleClientInfo sets the name and version of the application in
226// the `x-goog-api-client` header passed on each request. Intended for
227// use by Google-written clients.
228func (c *IntentsClient) setGoogleClientInfo(keyval ...string) {
229	kv := append([]string{"gl-go", versionGo()}, keyval...)
230	kv = append(kv, "gapic", versionClient, "gax", gax.Version, "grpc", grpc.Version)
231	c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...))
232}
233
234// ListIntents returns the list of all intents in the specified agent.
235func (c *IntentsClient) ListIntents(ctx context.Context, req *dialogflowpb.ListIntentsRequest, opts ...gax.CallOption) *IntentIterator {
236	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
237	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
238	opts = append(c.CallOptions.ListIntents[0:len(c.CallOptions.ListIntents):len(c.CallOptions.ListIntents)], opts...)
239	it := &IntentIterator{}
240	req = proto.Clone(req).(*dialogflowpb.ListIntentsRequest)
241	it.InternalFetch = func(pageSize int, pageToken string) ([]*dialogflowpb.Intent, string, error) {
242		var resp *dialogflowpb.ListIntentsResponse
243		req.PageToken = pageToken
244		if pageSize > math.MaxInt32 {
245			req.PageSize = math.MaxInt32
246		} else {
247			req.PageSize = int32(pageSize)
248		}
249		err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
250			var err error
251			resp, err = c.intentsClient.ListIntents(ctx, req, settings.GRPC...)
252			return err
253		}, opts...)
254		if err != nil {
255			return nil, "", err
256		}
257
258		it.Response = resp
259		return resp.Intents, resp.NextPageToken, nil
260	}
261	fetch := func(pageSize int, pageToken string) (string, error) {
262		items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
263		if err != nil {
264			return "", err
265		}
266		it.items = append(it.items, items...)
267		return nextPageToken, nil
268	}
269	it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
270	it.pageInfo.MaxSize = int(req.PageSize)
271	it.pageInfo.Token = req.PageToken
272	return it
273}
274
275// GetIntent retrieves the specified intent.
276func (c *IntentsClient) GetIntent(ctx context.Context, req *dialogflowpb.GetIntentRequest, opts ...gax.CallOption) (*dialogflowpb.Intent, error) {
277	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
278	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
279	opts = append(c.CallOptions.GetIntent[0:len(c.CallOptions.GetIntent):len(c.CallOptions.GetIntent)], opts...)
280	var resp *dialogflowpb.Intent
281	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
282		var err error
283		resp, err = c.intentsClient.GetIntent(ctx, req, settings.GRPC...)
284		return err
285	}, opts...)
286	if err != nil {
287		return nil, err
288	}
289	return resp, nil
290}
291
292// CreateIntent creates an intent in the specified agent.
293func (c *IntentsClient) CreateIntent(ctx context.Context, req *dialogflowpb.CreateIntentRequest, opts ...gax.CallOption) (*dialogflowpb.Intent, error) {
294	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
295	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
296	opts = append(c.CallOptions.CreateIntent[0:len(c.CallOptions.CreateIntent):len(c.CallOptions.CreateIntent)], opts...)
297	var resp *dialogflowpb.Intent
298	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
299		var err error
300		resp, err = c.intentsClient.CreateIntent(ctx, req, settings.GRPC...)
301		return err
302	}, opts...)
303	if err != nil {
304		return nil, err
305	}
306	return resp, nil
307}
308
309// UpdateIntent updates the specified intent.
310func (c *IntentsClient) UpdateIntent(ctx context.Context, req *dialogflowpb.UpdateIntentRequest, opts ...gax.CallOption) (*dialogflowpb.Intent, error) {
311	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "intent.name", url.QueryEscape(req.GetIntent().GetName())))
312	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
313	opts = append(c.CallOptions.UpdateIntent[0:len(c.CallOptions.UpdateIntent):len(c.CallOptions.UpdateIntent)], opts...)
314	var resp *dialogflowpb.Intent
315	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
316		var err error
317		resp, err = c.intentsClient.UpdateIntent(ctx, req, settings.GRPC...)
318		return err
319	}, opts...)
320	if err != nil {
321		return nil, err
322	}
323	return resp, nil
324}
325
326// DeleteIntent deletes the specified intent and its direct or indirect followup intents.
327func (c *IntentsClient) DeleteIntent(ctx context.Context, req *dialogflowpb.DeleteIntentRequest, opts ...gax.CallOption) error {
328	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "name", url.QueryEscape(req.GetName())))
329	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
330	opts = append(c.CallOptions.DeleteIntent[0:len(c.CallOptions.DeleteIntent):len(c.CallOptions.DeleteIntent)], opts...)
331	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
332		var err error
333		_, err = c.intentsClient.DeleteIntent(ctx, req, settings.GRPC...)
334		return err
335	}, opts...)
336	return err
337}
338
339// BatchUpdateIntents updates/Creates multiple intents in the specified agent.
340//
341// Operation <response: BatchUpdateIntentsResponse>
342func (c *IntentsClient) BatchUpdateIntents(ctx context.Context, req *dialogflowpb.BatchUpdateIntentsRequest, opts ...gax.CallOption) (*BatchUpdateIntentsOperation, error) {
343	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
344	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
345	opts = append(c.CallOptions.BatchUpdateIntents[0:len(c.CallOptions.BatchUpdateIntents):len(c.CallOptions.BatchUpdateIntents)], opts...)
346	var resp *longrunningpb.Operation
347	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
348		var err error
349		resp, err = c.intentsClient.BatchUpdateIntents(ctx, req, settings.GRPC...)
350		return err
351	}, opts...)
352	if err != nil {
353		return nil, err
354	}
355	return &BatchUpdateIntentsOperation{
356		lro: longrunning.InternalNewOperation(c.LROClient, resp),
357	}, nil
358}
359
360// BatchDeleteIntents deletes intents in the specified agent.
361//
362// Operation <response: google.protobuf.Empty>
363func (c *IntentsClient) BatchDeleteIntents(ctx context.Context, req *dialogflowpb.BatchDeleteIntentsRequest, opts ...gax.CallOption) (*BatchDeleteIntentsOperation, error) {
364	md := metadata.Pairs("x-goog-request-params", fmt.Sprintf("%s=%v", "parent", url.QueryEscape(req.GetParent())))
365	ctx = insertMetadata(ctx, c.xGoogMetadata, md)
366	opts = append(c.CallOptions.BatchDeleteIntents[0:len(c.CallOptions.BatchDeleteIntents):len(c.CallOptions.BatchDeleteIntents)], opts...)
367	var resp *longrunningpb.Operation
368	err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
369		var err error
370		resp, err = c.intentsClient.BatchDeleteIntents(ctx, req, settings.GRPC...)
371		return err
372	}, opts...)
373	if err != nil {
374		return nil, err
375	}
376	return &BatchDeleteIntentsOperation{
377		lro: longrunning.InternalNewOperation(c.LROClient, resp),
378	}, nil
379}
380
381// BatchDeleteIntentsOperation manages a long-running operation from BatchDeleteIntents.
382type BatchDeleteIntentsOperation struct {
383	lro *longrunning.Operation
384}
385
386// BatchDeleteIntentsOperation returns a new BatchDeleteIntentsOperation from a given name.
387// The name must be that of a previously created BatchDeleteIntentsOperation, possibly from a different process.
388func (c *IntentsClient) BatchDeleteIntentsOperation(name string) *BatchDeleteIntentsOperation {
389	return &BatchDeleteIntentsOperation{
390		lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}),
391	}
392}
393
394// Wait blocks until the long-running operation is completed, returning the response and any errors encountered.
395//
396// See documentation of Poll for error-handling information.
397func (op *BatchDeleteIntentsOperation) Wait(ctx context.Context, opts ...gax.CallOption) error {
398	return op.lro.WaitWithInterval(ctx, nil, time.Minute, opts...)
399}
400
401// Poll fetches the latest state of the long-running operation.
402//
403// Poll also fetches the latest metadata, which can be retrieved by Metadata.
404//
405// If Poll fails, the error is returned and op is unmodified. If Poll succeeds and
406// the operation has completed with failure, the error is returned and op.Done will return true.
407// If Poll succeeds and the operation has completed successfully,
408// op.Done will return true, and the response of the operation is returned.
409// If Poll succeeds and the operation has not completed, the returned response and error are both nil.
410func (op *BatchDeleteIntentsOperation) Poll(ctx context.Context, opts ...gax.CallOption) error {
411	return op.lro.Poll(ctx, nil, opts...)
412}
413
414// Metadata returns metadata associated with the long-running operation.
415// Metadata itself does not contact the server, but Poll does.
416// To get the latest metadata, call this method after a successful call to Poll.
417// If the metadata is not available, the returned metadata and error are both nil.
418func (op *BatchDeleteIntentsOperation) Metadata() (*structpbpb.Struct, error) {
419	var meta structpbpb.Struct
420	if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata {
421		return nil, nil
422	} else if err != nil {
423		return nil, err
424	}
425	return &meta, nil
426}
427
428// Done reports whether the long-running operation has completed.
429func (op *BatchDeleteIntentsOperation) Done() bool {
430	return op.lro.Done()
431}
432
433// Name returns the name of the long-running operation.
434// The name is assigned by the server and is unique within the service from which the operation is created.
435func (op *BatchDeleteIntentsOperation) Name() string {
436	return op.lro.Name()
437}
438
439// BatchUpdateIntentsOperation manages a long-running operation from BatchUpdateIntents.
440type BatchUpdateIntentsOperation struct {
441	lro *longrunning.Operation
442}
443
444// BatchUpdateIntentsOperation returns a new BatchUpdateIntentsOperation from a given name.
445// The name must be that of a previously created BatchUpdateIntentsOperation, possibly from a different process.
446func (c *IntentsClient) BatchUpdateIntentsOperation(name string) *BatchUpdateIntentsOperation {
447	return &BatchUpdateIntentsOperation{
448		lro: longrunning.InternalNewOperation(c.LROClient, &longrunningpb.Operation{Name: name}),
449	}
450}
451
452// Wait blocks until the long-running operation is completed, returning the response and any errors encountered.
453//
454// See documentation of Poll for error-handling information.
455func (op *BatchUpdateIntentsOperation) Wait(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.BatchUpdateIntentsResponse, error) {
456	var resp dialogflowpb.BatchUpdateIntentsResponse
457	if err := op.lro.WaitWithInterval(ctx, &resp, time.Minute, opts...); err != nil {
458		return nil, err
459	}
460	return &resp, nil
461}
462
463// Poll fetches the latest state of the long-running operation.
464//
465// Poll also fetches the latest metadata, which can be retrieved by Metadata.
466//
467// If Poll fails, the error is returned and op is unmodified. If Poll succeeds and
468// the operation has completed with failure, the error is returned and op.Done will return true.
469// If Poll succeeds and the operation has completed successfully,
470// op.Done will return true, and the response of the operation is returned.
471// If Poll succeeds and the operation has not completed, the returned response and error are both nil.
472func (op *BatchUpdateIntentsOperation) Poll(ctx context.Context, opts ...gax.CallOption) (*dialogflowpb.BatchUpdateIntentsResponse, error) {
473	var resp dialogflowpb.BatchUpdateIntentsResponse
474	if err := op.lro.Poll(ctx, &resp, opts...); err != nil {
475		return nil, err
476	}
477	if !op.Done() {
478		return nil, nil
479	}
480	return &resp, nil
481}
482
483// Metadata returns metadata associated with the long-running operation.
484// Metadata itself does not contact the server, but Poll does.
485// To get the latest metadata, call this method after a successful call to Poll.
486// If the metadata is not available, the returned metadata and error are both nil.
487func (op *BatchUpdateIntentsOperation) Metadata() (*structpbpb.Struct, error) {
488	var meta structpbpb.Struct
489	if err := op.lro.Metadata(&meta); err == longrunning.ErrNoMetadata {
490		return nil, nil
491	} else if err != nil {
492		return nil, err
493	}
494	return &meta, nil
495}
496
497// Done reports whether the long-running operation has completed.
498func (op *BatchUpdateIntentsOperation) Done() bool {
499	return op.lro.Done()
500}
501
502// Name returns the name of the long-running operation.
503// The name is assigned by the server and is unique within the service from which the operation is created.
504func (op *BatchUpdateIntentsOperation) Name() string {
505	return op.lro.Name()
506}
507
508// IntentIterator manages a stream of *dialogflowpb.Intent.
509type IntentIterator struct {
510	items    []*dialogflowpb.Intent
511	pageInfo *iterator.PageInfo
512	nextFunc func() error
513
514	// Response is the raw response for the current page.
515	// It must be cast to the RPC response type.
516	// Calling Next() or InternalFetch() updates this value.
517	Response interface{}
518
519	// InternalFetch is for use by the Google Cloud Libraries only.
520	// It is not part of the stable interface of this package.
521	//
522	// InternalFetch returns results from a single call to the underlying RPC.
523	// The number of results is no greater than pageSize.
524	// If there are no more results, nextPageToken is empty and err is nil.
525	InternalFetch func(pageSize int, pageToken string) (results []*dialogflowpb.Intent, nextPageToken string, err error)
526}
527
528// PageInfo supports pagination. See the google.golang.org/api/iterator package for details.
529func (it *IntentIterator) PageInfo() *iterator.PageInfo {
530	return it.pageInfo
531}
532
533// Next returns the next result. Its second return value is iterator.Done if there are no more
534// results. Once Next returns Done, all subsequent calls will return Done.
535func (it *IntentIterator) Next() (*dialogflowpb.Intent, error) {
536	var item *dialogflowpb.Intent
537	if err := it.nextFunc(); err != nil {
538		return item, err
539	}
540	item = it.items[0]
541	it.items = it.items[1:]
542	return item, nil
543}
544
545func (it *IntentIterator) bufLen() int {
546	return len(it.items)
547}
548
549func (it *IntentIterator) takeBuf() interface{} {
550	b := it.items
551	it.items = nil
552	return b
553}
554