1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
//! Venue interfaces

use hyper::client::Connect;
use serde_urlencoded;

use {Client, Future, Response};

pub struct Venues<C>
where
    C: Connect + Clone,
{
    client: Client<C>,
}

impl<C: Connect + Clone> Venues<C> {
    #[doc(hidden)]
    pub(crate) fn new(client: Client<C>) -> Self {
        Self { client }
    }

    /// Get the defaults for single venue
    ///
    /// See the official
    /// [api docs](https://developer.foursquare.com/docs/api/venues/details)
    /// for more information
    pub fn get<I>(&self, id: I) -> Future<Response<VenueResponse>>
    where
        I: Into<String>,
    {
        self.client.get(format!(
            "{host}/v2/venues/{id}",
            host = self.client.host,
            id = id.into()
        ))
    }

    /// Search for venues
    ///
    /// See the official
    /// [api docs](https://developer.foursquare.com/docs/api/venues/search)
    /// for more information
    pub fn search(
        &self,
        options: &SearchOptions,
    ) -> Future<Response<SearchResponse>> {
        self.client.get(format!(
            "{host}/v2/venues/search?{query}",
            host = self.client.host,
            query = serde_urlencoded::to_string(options).unwrap()
        ))
    }

    /// Type ahead suggestions
    ///
    /// See the official
    /// [api docs](https://developer.foursquare.com/docs/api/venues/suggestcompletion)
    /// for more information
    pub fn suggest(
        &self,
        options: &SuggestOptions,
    ) -> Future<Response<SuggestResponse>> {
        self.client.get(format!(
            "{host}/v2/venues/suggestcompletion?{query}",
            host = self.client.host,
            query = serde_urlencoded::to_string(options).unwrap()
        ))
    }

    /// Get recommendations on venues
    ///
    /// See the official
    /// [api docs](https://developer.foursquare.com/docs/api/venues/explore)
    /// for more information
    pub fn explore(
        &self,
        options: &ExploreOptions,
    ) -> Future<Response<ExploreResponse>> {
        self.client.get(format!(
            "{host}/v2/venues/explore?{query}",
            host = self.client.host,
            query = serde_urlencoded::to_string(options).unwrap()
        ))
    }
}

// representations

#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum Intent {
    Checkin,
    Global,
    Browse,
    Match,
}

impl Default for Intent {
    fn default() -> Self {
        Intent::Checkin
    }
}

/// Search api options.
///
/// Use SearchOptions::builder() interface to construct these
#[derive(Default, Debug, Deserialize, Serialize, Builder)]
#[builder(setter(into), default)]
pub struct SearchOptions {
    /// required unless near is provided. Latitude and longitude of the user’s location. Optional if using intent=global
    #[serde(skip_serializing_if = "String::is_empty")]
    ll: String,
    /// required unless ll is provided. A string naming a place in the world. If the near string is not geocodable, returns a failed_geocode error. Otherwise, searches within the bounds of the geocode and adds a geocode object to the response.
    #[serde(skip_serializing_if = "String::is_empty")]
    near: String,
    /// One of the values below, indicating your intent in performing the search. If no value is specified, defaults to checkin.
    intent: Option<Intent>,
    /// Limit results to venues within this many meters of the specified location. Defaults to a city-wide area. Only valid for requests with intent=browse, or requests with intent=checkin and categoryId or query. Does not apply to intent=match requests. The maximum supported radius is currently 100,000 meters.
    radius: Option<u32>,
    /// With ne, limits results to the bounding box defined by the latitude and longitude given by sw as its south-west corner, and ne as its north-east corner. The bounding box is only supported for intent=browse searches. Not valid with ll or radius. Bounding boxes with an area up to approximately 10,000 square kilometers are supported.
    sw: Option<String>,
    /// See sw.
    ne: Option<String>,
    /// A search term to be applied against venue names.
    query: Option<String>,
    /// Number of results to return, up to 50.
    limit: Option<u32>,
    /// A comma separated list of categories to limit results to. If you specify categoryId. specifying a radius may improve results. If specifying a top-level category, all sub-categories will also match the query. Does not apply to intent=match requests.
    #[serde(rename = "categoryId")]
    category_id: Option<String>,
    /// Accuracy of latitude and longitude, in meters.
    #[serde(rename = "llAcc")]
    ll_acc: Option<f64>,
    /// Altitude of the user’s location, in meters.
    alt: Option<u32>,
    /// Accuracy of the user’s altitude, in meters.
    #[serde(rename = "altAcc")]
    alt_acc: Option<f64>,
    /// A third-party URL which we will attempt to match against our map of venues to URLs.
    url: Option<String>,
    /// Identifier for a known third party that is part of our map of venues to URLs, used in conjunction with linkedId.
    #[serde(rename = "providerId")]
    provider_id: Option<String>,
    /// Identifier used by third party specified in providerId, which we will attempt to match against our map of venues to URLs.
    #[serde(rename = "linkedId")]
    linked_id: Option<String>,
    /// [Internationalization](https://developer.foursquare.com/docs/api/configuration/internationalization)
    pub locale: String,
}

impl SearchOptions {
    pub fn builder() -> SearchOptionsBuilder {
        SearchOptionsBuilder::default()
    }
}

#[derive(Default, Debug, Deserialize, Serialize, Builder)]
#[builder(setter(into), default)]
pub struct SuggestOptions {
    /// required Latitude and longitude of the user’s location. (Required for query searches)
    #[serde(skip_serializing_if = "String::is_empty")]
    ll: String,
    /// required unless ll is provided. A string naming a place in the world. If the near string is not geocodable, returns a failed_geocode error. Otherwise, searches within the bounds of the geocode. Adds a geocode object to the response. (Required for query searches)
    #[serde(skip_serializing_if = "String::is_empty")]
    near: String,
    /// Limit results to venues within this many meters of the specified location. Defaults to a city-wide area. Only valid for requests with intent=browse, or requests with intent=checkin and categoryId or query. Does not apply to intent=match requests. The maximum supported radius is currently 100,000 meters.
    radius: Option<u32>,
    /// With ne, limits results to the bounding box defined by the latitude and longitude given by sw as its south-west corner, and ne as its north-east corner. The bounding box is only supported for intent=browse searches. Not valid with ll or radius. Bounding boxes with an area up to approximately 10,000 square kilometers are supported.
    sw: Option<String>,
    /// See sw.
    ne: Option<String>,
    /// A search term to be applied against venue names.
    query: Option<String>,
    /// Number of results to return, up to 50.
    limit: Option<u32>,
    /// Accuracy of latitude and longitude, in meters.
    #[serde(rename = "llAcc")]
    ll_acc: Option<f64>,
    /// Altitude of the user’s location, in meters.
    alt: Option<u32>,
    /// Accuracy of the user’s altitude, in meters.
    #[serde(rename = "altAcc")]
    alt_acc: Option<f64>,
    /// [Internationalization](https://developer.foursquare.com/docs/api/configuration/internationalization)
    pub locale: String,
}

impl SuggestOptions {
    pub fn builder() -> SuggestOptionsBuilder {
        SuggestOptionsBuilder::default()
    }
}

/// Explore api options.
///
/// Use ExploreOptions::builder() interface to construct these
#[derive(Default, Debug, Deserialize, Serialize, Builder)]
#[builder(setter(into), default)]
pub struct ExploreOptions {
    /// required unless near is provided. Latitude and longitude of the user’s location.
    #[serde(skip_serializing_if = "String::is_empty")]
    ll: String,
    /// required unless ll is provided. A string naming a place in the world. If the near string is not geocodable, returns a failed_geocode error. Otherwise, searches within the bounds of the geocode and adds a geocode object to the response.
    #[serde(skip_serializing_if = "String::is_empty")]
    near: String,
    /// Accuracy of latitude and longitude, in meters.
    #[serde(rename = "llAcc")]
    ll_acc: Option<f64>,
    /// Altitude of the user’s location, in meters.
    alt: Option<u32>,
    /// Accuracy of the user’s altitude, in meters.
    #[serde(rename = "altAcc")]
    alt_acc: Option<f64>,
    /// Radius to search within, in meters. If radius is not specified, a suggested radius will be used based on the density of venues in the area. The maximum supported radius is currently 100,000 meters.
    radius: Option<u32>,
    /// One of food, drinks, coffee, shops, arts, outdoors, sights, trending, nextVenues (venues frequently visited after a given venue), or topPicks (a mix of recommendations generated without a query from the user). Choosing one of these limits results to venues with the specified category or property.
    section: Option<String>,
    /// A term to be searched against a venue’s tips, category, etc. The query parameter has no effect when a section is specified.
    query: Option<String>,
    /// Number of results to return, up to 50.
    limit: Option<u32>,
    /// Used to page through results, up to 50.
    offset: Option<u32>,
    /// Pass new or old to limit results to places the acting user hasn’t been or has been, respectively. Omitting this parameter returns a mixture of old and new venues.
    novelty: Option<String>,
    /// Pass visited or notvisited to limit results to places the acting user’s friends have or haven’t been, respectively. Omitting this parameter returns a mixture of venues to which the user’s friends have or haven’t been.
    #[serde(rename = "friendVisits")]
    friend_visits: Option<String>,
    /// Pass any to retrieve results for any time of day. Omitting this parameter returns results targeted to the current time of day.
    time: Option<String>,
    /// Pass any to retrieve results for any day of the week. Omitting this parameter returns results targeted to the current day of the week.
    day: Option<String>,
    /// Boolean flag to include a photo in the response for each venue, if one is available. Default is 0 (no photos). Photos are returned as part of the venue JSON object.
    #[serde(rename = "venuePhotos")]
    venue_photos: Option<u16>, // 1 or 0
    /// A venue ID to use in combination with the intent=nextVenues parameter, which returns venues users often visit after a given venue. If intent=nextVenues is specified but lastVenue is not, the user’s last check-in will be used if it is within 2 hours. If the user has not checked in within the last 2 hours, no results will be returned.
    #[serde(rename = "lastVenue")]
    last_venue: Option<String>,
    /// Boolean flag to only include venues that are open now. This prefers official provider hours but falls back to popular check-in hours.
    #[serde(rename = "openNow")]
    open_now: Option<u16>, // 1 or 0
    /// Boolean flag to sort the results by distance instead of relevance.
    #[serde(rename = "sortByDistance")]
    sort_by_distance: Option<u16>, // 1 or 0,
    /// Comma separated list of price points. Currently the valid range of price points are [1,2,3,4], 1 being the least expensive, 4 being the most expensive. For food venues, in the United States, 1 is < $10 an entree, 2 is $10-$20 an entree, 3 is $20-$30 an entree, 4 is > $30 an entree.
    price: Option<String>,
    /// Boolean flag to only include venues that the user has saved on their To-Do list or to another list.
    saved: Option<u16>, // 1 or 0
    /// [Internationalization](https://developer.foursquare.com/docs/api/configuration/internationalization)
    pub locale: String,
}

impl ExploreOptions {
    pub fn builder() -> ExploreOptionsBuilder {
        ExploreOptionsBuilder::default()
    }
}

#[derive(Debug, Deserialize, Serialize)]
pub struct Coords {
    pub lat: f64,
    pub lng: f64,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct Contact {
    pub phone: Option<String>,
    #[serde(rename = "formattedPhone")]
    pub formatted_phone: Option<String>,
    pub twitter: Option<String>,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct Price {
    pub tier: u16,
    pub message: String,
    pub currency: String,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct Location {
    pub address: Option<String>,
    #[serde(rename = "crossStreet")]
    pub cross_street: Option<String>,
    pub lat: f64,
    pub lng: f64,
    pub distance: Option<u32>,
    #[serde(rename = "postalCode")]
    pub postal_code: Option<String>,
    /// Returns  None for suggest requests
    pub cc: Option<String>,
    pub city: Option<String>,
    pub state: Option<String>,
    pub country: String,
    /// Returns None for suggest requests
    #[serde(rename = "formattedAddress")]
    pub formatted_address: Option<Vec<String>>,
}

/// Icon photo
///
/// Pieces needed to construct category icons at various sizes. Combine prefix with a size (32, 44, 64, and 88 are available) and suffix, e.g. https://foursquare.com/img/categories/food/default_64.png. To get an image with a gray background, use bg_ before the size, e.g. https://foursquare.com/img/categories_v2/food/icecream_bg_32.png.
#[derive(Debug, Deserialize, Serialize)]
pub struct Icon {
    pub prefix: String,
    pub suffix: String,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct Category {
    pub id: String,
    pub name: String,
    #[serde(rename = "pluralName")]
    pub plural_name: String,
    #[serde(rename = "shortName")]
    pub short_name: String,
    pub icon: Icon,
    pub primary: Option<bool>,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct Menu {
    pub label: String,
    pub url: String,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct Photos {
    pub count: u64,
    pub groups: Vec<Group<PhotoItem>>,
}

/// venue photo
///
/// see [this doc](https://developer.foursquare.com/docs/api/photos/details)
/// for photo url construction
#[derive(Debug, Deserialize, Serialize)]
pub struct PhotoItem {
    pub id: String,
    pub prefix: String,
    pub suffix: String,
    pub width: u16,
    pub height: u16,
    pub user: User,
    pub visibility: String,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct User {
    pub id: String,
    #[serde(rename = "firstName")]
    pub first_name: String,
    #[serde(rename = "lastName")]
    pub last_name: String,
    pub photo: UserPhoto,
}

/// user photo
///
/// see [this doc](https://developer.foursquare.com/docs/api/photos/details)
/// for photo url construction
#[derive(Debug, Deserialize, Serialize)]
pub struct UserPhoto {
    pub prefix: String,
    pub suffix: String,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct Hours {
    pub status: Option<String>,
    #[serde(rename = "isOpen")]
    pub is_open: bool,
    #[serde(rename = "isLocalHoliday")]
    pub is_local_holiday: bool,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct Venue {
    /// A unique string identifier for this venue.
    pub id: String,
    /// The best known name for this venue.
    pub name: String,
    /// An object containing none, some, or all of twitter, phone, and formattedPhone. All are strings.
    /// Will be None for suggest requests
    pub contact: Option<Contact>,
    /// An object containing none, some, or all of address (street address), crossStreet, city, state, postalCode, country, lat, lng, and distance. All fields are strings, except for lat, lng, and distance. Distance is measured in meters. Some venues have their locations intentionally hidden for privacy reasons (such as private residences). If this is the case, the parameter isFuzzed will be set to true, and the lat/lng parameters will have reduced precision.
    pub location: Location,
    /// An array, possibly empty, of categories that have been applied to this venue. One of the categories will have a primary field indicating that it is the primary category for the venue. For the complete category tree, see categories.
    pub categories: Vec<Category>,
    /// Boolean indicating whether the owner of this business has claimed it and verified the information.
    /// Will be be None for suggest requests
    pub verified: Option<bool>,
    // Contains checkinsCount (total checkins ever here), usersCount (total users who have ever checked in here), and tipCount (number of tips here).
    // pub stats: Stats
    /// URL of the venue’s website, typically provided by the venue manager.
    pub url: Option<String>,
    /// Contains the hours during the week that the venue is open along with any named hours segments in a human-readable format. For machine readable hours see venues/hours
    pub hours: Option<Hours>,
    /// Contains the hours during the week when people usually go to the venue. For machine readable hours see venues/hours.
    #[serde(rename = "hasMenu")]
    pub has_menu: Option<bool>,
    /// An object containing url and mobileUrl that display the menu information for this venue.
    pub menu: Option<Menu>,
    /// An object containing the price tier from 1 (least pricey) - 4 (most pricey) and a message describing the price tier.
    pub price: Option<Price>,
    // Information about who is here now. If present, there is always a count, the number of people here. If viewing details and there is a logged-in user, there is also a groups field with friends and others as types.
    // pub hereNow: ???
    // Seconds since epoch when the venue was created.
    // pub createdAt: ???
    /// A count and groups of photos for this venue. Group types are checkin and venue. Not all items will be present.
    /// Will typically not be present for search requests
    pub photos: Option<Photos>,
    // Contains the total count of tips and groups with friends and others as groupTypes. Groups may change over time.
    // pub tips: ??,
    // ??
    #[serde(rename = "referralId")]
    pub referral_id: Option<String>,
    #[serde(rename = "hasPerk")]
    pub has_perk: Option<bool>,
    /// Numerical rating of the venue (0 through 10). Not all venues will have a rating.
    pub rating: Option<f32>,
    #[serde(rename = "ratingSignals")]
    pub rating_signals: Option<u64>,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct SuggestResponse {
    pub minivenues: Vec<Venue>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct SearchResponse {
    pub venues: Vec<Venue>,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct VenueItem {
    pub venue: Venue,
    #[serde(rename = "referralId")]
    pub referral_id: String,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct Group<I> {
    pub name: String,
    #[serde(rename = "type")]
    pub group_type: String,
    pub count: Option<u64>,
    pub items: Vec<I>,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct ExploreResponse {
    /// If no radius was specified in the request, presents the radius that was used for the query (based upon the density of venues in the query area).
    #[serde(rename = "suggestedRadius")]
    pub suggested_radius: u32,
    /// A text name for the location the user searched, e.g. “SoHo”.
    #[serde(rename = "headerLocation")]
    pub header_location: String,
    /// A full text name for the location the user searched, e.g. “SoHo, New York”.
    #[serde(rename = "headerFullLocation")]
    pub header_full_location: String,
    #[serde(rename = "headerLocationGranularity")]
    pub header_location_granularity: String,
    pub query: Option<String>,
    #[serde(rename = "totalResults")]
    pub total_results: u64,
    /// An array of objects representing groups of recommendations. Each group contains a type such as “recommended” a human-readable (eventually localized) name such as “Recommended Places,” and an array items of recommendation objects, which have an ordered list of objects which contain reasons and venue. The reasons are count and items, where each item has a type such as “social” and a message about why this place may be of interest to the acting user. The venues are compact venues that include stats and hereNow data. We encourage clients to be robust against the introduction or removal of group types by treating the groups as opaque objects to be displayed or by placing unfamiliar groups in a catchall group.
    pub groups: Vec<Group<VenueItem>>,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct VenueResponse {
    pub venue: Venue,
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn search_options_serialize() {
        assert_eq!(
            serde_urlencoded::to_string(
                &SearchOptions::builder().near("foo bar").build().unwrap(),
            ).unwrap(),
            "near=foo+bar"
        )
    }

    #[test]
    fn default_intent() {
        let default: Intent = Default::default();
        assert_eq!(default, Intent::Checkin)
    }
}