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