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