1package entitysearch
2
3// Copyright (c) Microsoft and contributors.  All rights reserved.
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13//
14// See the License for the specific language governing permissions and
15// limitations under the License.
16//
17// Code generated by Microsoft (R) AutoRest Code Generator.
18// Changes may cause incorrect behavior and will be lost if the code is regenerated.
19
20import (
21	"context"
22	"github.com/Azure/go-autorest/autorest"
23	"github.com/Azure/go-autorest/autorest/azure"
24	"net/http"
25)
26
27// EntitiesClient is the the Entity Search API lets you send a search query to Bing and get back search results that
28// include entities and places. Place results include restaurants, hotel, or other local businesses. For places, the
29// query can specify the name of the local business or it can ask for a list (for example, restaurants near me). Entity
30// results include persons, places, or things. Place in this context is tourist attractions, states, countries, etc.
31type EntitiesClient struct {
32	BaseClient
33}
34
35// NewEntitiesClient creates an instance of the EntitiesClient client.
36func NewEntitiesClient() EntitiesClient {
37	return NewEntitiesClientWithBaseURI(DefaultBaseURI)
38}
39
40// NewEntitiesClientWithBaseURI creates an instance of the EntitiesClient client.
41func NewEntitiesClientWithBaseURI(baseURI string) EntitiesClient {
42	return EntitiesClient{NewWithBaseURI(baseURI)}
43}
44
45// Search sends the search request.
46// Parameters:
47// query - the user's search term.
48// acceptLanguage - a comma-delimited list of one or more languages to use for user interface strings. The list
49// is in decreasing order of preference. For additional information, including expected format, see
50// [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This header and the setLang query
51// parameter are mutually exclusive; do not specify both. If you set this header, you must also specify the cc
52// query parameter. Bing will use the first supported language it finds from the list, and combine that
53// language with the cc parameter value to determine the market to return results for. If the list does not
54// include a supported language, Bing will find the closest language and market that supports the request, and
55// may use an aggregated or default market for the results instead of a specified one. You should use this
56// header and the cc query parameter only if you specify multiple languages; otherwise, you should use the mkt
57// and setLang query parameters. A user interface string is a string that's used as a label in a user
58// interface. There are very few user interface strings in the JSON response objects. Any links in the response
59// objects to Bing.com properties will apply the specified language.
60// pragma - by default, Bing returns cached content, if available. To prevent Bing from returning cached
61// content, set the Pragma header to no-cache (for example, Pragma: no-cache).
62// userAgent - the user agent originating the request. Bing uses the user agent to provide mobile users with an
63// optimized experience. Although optional, you are strongly encouraged to always specify this header. The
64// user-agent should be the same string that any commonly used browser would send. For information about user
65// agents, see [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).
66// clientID - bing uses this header to provide users with consistent behavior across Bing API calls. Bing often
67// flights new features and improvements, and it uses the client ID as a key for assigning traffic on different
68// flights. If you do not use the same client ID for a user across multiple requests, then Bing may assign the
69// user to multiple conflicting flights. Being assigned to multiple conflicting flights can lead to an
70// inconsistent user experience. For example, if the second request has a different flight assignment than the
71// first, the experience may be unexpected. Also, Bing can use the client ID to tailor web results to that
72// client ID’s search history, providing a richer experience for the user. Bing also uses this header to help
73// improve result rankings by analyzing the activity generated by a client ID. The relevance improvements help
74// with better quality of results delivered by Bing APIs and in turn enables higher click-through rates for the
75// API consumer. IMPORTANT: Although optional, you should consider this header required. Persisting the client
76// ID across multiple requests for the same end user and device combination enables 1) the API consumer to
77// receive a consistent user experience, and 2) higher click-through rates via better quality of results from
78// the Bing APIs. Each user that uses your application on the device must have a unique, Bing generated client
79// ID. If you do not include this header in the request, Bing generates an ID and returns it in the
80// X-MSEdge-ClientID response header. The only time that you should NOT include this header in a request is the
81// first time the user uses your app on that device. Use the client ID for each Bing API request that your app
82// makes for this user on the device. Persist the client ID. To persist the ID in a browser app, use a
83// persistent HTTP cookie to ensure the ID is used across all sessions. Do not use a session cookie. For other
84// apps such as mobile apps, use the device's persistent storage to persist the ID. The next time the user uses
85// your app on that device, get the client ID that you persisted. Bing responses may or may not include this
86// header. If the response includes this header, capture the client ID and use it for all subsequent Bing
87// requests for the user on that device. If you include the X-MSEdge-ClientID, you must not include cookies in
88// the request.
89// clientIP - the IPv4 or IPv6 address of the client device. The IP address is used to discover the user's
90// location. Bing uses the location information to determine safe search behavior. Although optional, you are
91// encouraged to always specify this header and the X-Search-Location header. Do not obfuscate the address (for
92// example, by changing the last octet to 0). Obfuscating the address results in the location not being
93// anywhere near the device's actual location, which may result in Bing serving erroneous results.
94// location - a semicolon-delimited list of key/value pairs that describe the client's geographical location.
95// Bing uses the location information to determine safe search behavior and to return relevant local content.
96// Specify the key/value pair as <key>:<value>. The following are the keys that you use to specify the user's
97// location. lat (required): The latitude of the client's location, in degrees. The latitude must be greater
98// than or equal to -90.0 and less than or equal to +90.0. Negative values indicate southern latitudes and
99// positive values indicate northern latitudes. long (required): The longitude of the client's location, in
100// degrees. The longitude must be greater than or equal to -180.0 and less than or equal to +180.0. Negative
101// values indicate western longitudes and positive values indicate eastern longitudes. re (required): The
102// radius, in meters, which specifies the horizontal accuracy of the coordinates. Pass the value returned by
103// the device's location service. Typical values might be 22m for GPS/Wi-Fi, 380m for cell tower triangulation,
104// and 18,000m for reverse IP lookup. ts (optional): The UTC UNIX timestamp of when the client was at the
105// location. (The UNIX timestamp is the number of seconds since January 1, 1970.) head (optional): The client's
106// relative heading or direction of travel. Specify the direction of travel as degrees from 0 through 360,
107// counting clockwise relative to true north. Specify this key only if the sp key is nonzero. sp (optional):
108// The horizontal velocity (speed), in meters per second, that the client device is traveling. alt (optional):
109// The altitude of the client device, in meters. are (optional): The radius, in meters, that specifies the
110// vertical accuracy of the coordinates. Specify this key only if you specify the alt key. Although many of the
111// keys are optional, the more information that you provide, the more accurate the location results are.
112// Although optional, you are encouraged to always specify the user's geographical location. Providing the
113// location is especially important if the client's IP address does not accurately reflect the user's physical
114// location (for example, if the client uses VPN). For optimal results, you should include this header and the
115// X-MSEdge-ClientIP header, but at a minimum, you should include this header.
116// countryCode - a 2-character country code of the country where the results come from. This API supports only
117// the United States market. If you specify this query parameter, it must be set to us. If you set this
118// parameter, you must also specify the Accept-Language header. Bing uses the first supported language it finds
119// from the languages list, and combine that language with the country code that you specify to determine the
120// market to return results for. If the languages list does not include a supported language, Bing finds the
121// closest language and market that supports the request, or it may use an aggregated or default market for the
122// results instead of a specified one. You should use this query parameter and the Accept-Language query
123// parameter only if you specify multiple languages; otherwise, you should use the mkt and setLang query
124// parameters. This parameter and the mkt query parameter are mutually exclusive—do not specify both.
125// market - the market where the results come from. You are strongly encouraged to always specify the market,
126// if known. Specifying the market helps Bing route the request and return an appropriate and optimal response.
127// This parameter and the cc query parameter are mutually exclusive—do not specify both.
128// responseFilter - a comma-delimited list of answers to include in the response. If you do not specify this
129// parameter, the response includes all search answers for which there's relevant data.
130// responseFormat - the media type to use for the response. The following are the possible case-insensitive
131// values: JSON, JSONLD. The default is JSON. If you specify JSONLD, the response body includes JSON-LD objects
132// that contain the search results.
133// safeSearch - a filter used to filter adult content. Off: Return webpages with adult text, images, or videos.
134// Moderate: Return webpages with adult text, but not adult images or videos. Strict: Do not return webpages
135// with adult text, images, or videos. The default is Moderate. If the request comes from a market that Bing's
136// adult policy requires that safeSearch is set to Strict, Bing ignores the safeSearch value and uses Strict.
137// If you use the site: query operator, there is the chance that the response may contain adult content
138// regardless of what the safeSearch query parameter is set to. Use site: only if you are aware of the content
139// on the site and your scenario supports the possibility of adult content.
140// setLang - the language to use for user interface strings. Specify the language using the ISO 639-1 2-letter
141// language code. For example, the language code for English is EN. The default is EN (English). Although
142// optional, you should always specify the language. Typically, you set setLang to the same language specified
143// by mkt unless the user wants the user interface strings displayed in a different language. This parameter
144// and the Accept-Language header are mutually exclusive; do not specify both. A user interface string is a
145// string that's used as a label in a user interface. There are few user interface strings in the JSON response
146// objects. Also, any links to Bing.com properties in the response objects apply the specified language.
147func (client EntitiesClient) Search(ctx context.Context, query string, acceptLanguage string, pragma string, userAgent string, clientID string, clientIP string, location string, countryCode string, market string, responseFilter []AnswerType, responseFormat []ResponseFormat, safeSearch SafeSearch, setLang string) (result SearchResponse, err error) {
148	req, err := client.SearchPreparer(ctx, query, acceptLanguage, pragma, userAgent, clientID, clientIP, location, countryCode, market, responseFilter, responseFormat, safeSearch, setLang)
149	if err != nil {
150		err = autorest.NewErrorWithError(err, "entitysearch.EntitiesClient", "Search", nil, "Failure preparing request")
151		return
152	}
153
154	resp, err := client.SearchSender(req)
155	if err != nil {
156		result.Response = autorest.Response{Response: resp}
157		err = autorest.NewErrorWithError(err, "entitysearch.EntitiesClient", "Search", resp, "Failure sending request")
158		return
159	}
160
161	result, err = client.SearchResponder(resp)
162	if err != nil {
163		err = autorest.NewErrorWithError(err, "entitysearch.EntitiesClient", "Search", resp, "Failure responding to request")
164	}
165
166	return
167}
168
169// SearchPreparer prepares the Search request.
170func (client EntitiesClient) SearchPreparer(ctx context.Context, query string, acceptLanguage string, pragma string, userAgent string, clientID string, clientIP string, location string, countryCode string, market string, responseFilter []AnswerType, responseFormat []ResponseFormat, safeSearch SafeSearch, setLang string) (*http.Request, error) {
171	queryParameters := map[string]interface{}{
172		"q": autorest.Encode("query", query),
173	}
174	if len(countryCode) > 0 {
175		queryParameters["cc"] = autorest.Encode("query", countryCode)
176	}
177	if len(market) > 0 {
178		queryParameters["mkt"] = autorest.Encode("query", market)
179	} else {
180		queryParameters["mkt"] = autorest.Encode("query", "en-us")
181	}
182	if responseFilter != nil && len(responseFilter) > 0 {
183		queryParameters["ResponseFilter"] = autorest.Encode("query", responseFilter, ",")
184	}
185	if responseFormat != nil && len(responseFormat) > 0 {
186		queryParameters["ResponseFormat"] = autorest.Encode("query", responseFormat, ",")
187	}
188	if len(string(safeSearch)) > 0 {
189		queryParameters["SafeSearch"] = autorest.Encode("query", safeSearch)
190	}
191	if len(setLang) > 0 {
192		queryParameters["SetLang"] = autorest.Encode("query", setLang)
193	}
194
195	preparer := autorest.CreatePreparer(
196		autorest.AsGet(),
197		autorest.WithBaseURL(client.BaseURI),
198		autorest.WithPath("/entities"),
199		autorest.WithQueryParameters(queryParameters),
200		autorest.WithHeader("X-BingApis-SDK", "true"))
201	if len(acceptLanguage) > 0 {
202		preparer = autorest.DecoratePreparer(preparer,
203			autorest.WithHeader("Accept-Language", autorest.String(acceptLanguage)))
204	}
205	if len(pragma) > 0 {
206		preparer = autorest.DecoratePreparer(preparer,
207			autorest.WithHeader("Pragma", autorest.String(pragma)))
208	}
209	if len(userAgent) > 0 {
210		preparer = autorest.DecoratePreparer(preparer,
211			autorest.WithHeader("User-Agent", autorest.String(userAgent)))
212	}
213	if len(clientID) > 0 {
214		preparer = autorest.DecoratePreparer(preparer,
215			autorest.WithHeader("X-MSEdge-ClientID", autorest.String(clientID)))
216	}
217	if len(clientIP) > 0 {
218		preparer = autorest.DecoratePreparer(preparer,
219			autorest.WithHeader("X-MSEdge-ClientIP", autorest.String(clientIP)))
220	}
221	if len(location) > 0 {
222		preparer = autorest.DecoratePreparer(preparer,
223			autorest.WithHeader("X-Search-Location", autorest.String(location)))
224	}
225	return preparer.Prepare((&http.Request{}).WithContext(ctx))
226}
227
228// SearchSender sends the Search request. The method will close the
229// http.Response Body if it receives an error.
230func (client EntitiesClient) SearchSender(req *http.Request) (*http.Response, error) {
231	return autorest.SendWithSender(client, req,
232		autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
233}
234
235// SearchResponder handles the response to the Search request. The method always
236// closes the http.Response Body.
237func (client EntitiesClient) SearchResponder(resp *http.Response) (result SearchResponse, err error) {
238	err = autorest.Respond(
239		resp,
240		client.ByInspecting(),
241		azure.WithErrorUnlessStatusCode(http.StatusOK),
242		autorest.ByUnmarshallingJSON(&result),
243		autorest.ByClosing())
244	result.Response = autorest.Response{Response: resp}
245	return
246}
247