Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """Support for the Foursquare (Swarm) API."""
2 
3 from http import HTTPStatus
4 import logging
5 
6 from aiohttp import web
7 import requests
8 import voluptuous as vol
9 
10 from homeassistant.components.http import KEY_HASS, HomeAssistantView
11 from homeassistant.const import CONF_ACCESS_TOKEN
12 from homeassistant.core import HomeAssistant, ServiceCall
14 from homeassistant.helpers.typing import ConfigType
15 
16 _LOGGER = logging.getLogger(__name__)
17 
18 CONF_PUSH_SECRET = "push_secret"
19 
20 DOMAIN = "foursquare"
21 
22 EVENT_CHECKIN = "foursquare.checkin"
23 EVENT_PUSH = "foursquare.push"
24 
25 SERVICE_CHECKIN = "checkin"
26 
27 CHECKIN_SERVICE_SCHEMA = vol.Schema(
28  {
29  vol.Optional("alt"): cv.string,
30  vol.Optional("altAcc"): cv.string,
31  vol.Optional("broadcast"): cv.string,
32  vol.Optional("eventId"): cv.string,
33  vol.Optional("ll"): cv.string,
34  vol.Optional("llAcc"): cv.string,
35  vol.Optional("mentions"): cv.string,
36  vol.Optional("shout"): cv.string,
37  vol.Required("venueId"): cv.string,
38  }
39 )
40 
41 CONFIG_SCHEMA = vol.Schema(
42  {
43  DOMAIN: vol.Schema(
44  {
45  vol.Required(CONF_ACCESS_TOKEN): cv.string,
46  vol.Required(CONF_PUSH_SECRET): cv.string,
47  }
48  )
49  },
50  extra=vol.ALLOW_EXTRA,
51 )
52 
53 
54 def setup(hass: HomeAssistant, config: ConfigType) -> bool:
55  """Set up the Foursquare component."""
56  config = config[DOMAIN]
57 
58  def checkin_user(call: ServiceCall) -> None:
59  """Check a user in on Swarm."""
60  url = f"https://api.foursquare.com/v2/checkins/add?oauth_token={config[CONF_ACCESS_TOKEN]}&v=20160802&m=swarm"
61  response = requests.post(url, data=call.data, timeout=10)
62 
63  if response.status_code not in (HTTPStatus.OK, HTTPStatus.CREATED):
64  _LOGGER.exception(
65  "Error checking in user. Response %d: %s:",
66  response.status_code,
67  response.reason,
68  )
69 
70  hass.bus.fire(EVENT_CHECKIN, {"text": response.text})
71 
72  # Register our service with Home Assistant.
73  hass.services.register(
74  DOMAIN, "checkin", checkin_user, schema=CHECKIN_SERVICE_SCHEMA
75  )
76 
77  hass.http.register_view(FoursquarePushReceiver(config[CONF_PUSH_SECRET]))
78 
79  return True
80 
81 
82 class FoursquarePushReceiver(HomeAssistantView):
83  """Handle pushes from the Foursquare API."""
84 
85  requires_auth = False
86  url = "/api/foursquare"
87  name = "foursquare"
88 
89  def __init__(self, push_secret: str) -> None:
90  """Initialize the OAuth callback view."""
91  self.push_secretpush_secret = push_secret
92 
93  async def post(self, request: web.Request) -> web.Response | None:
94  """Accept the POST from Foursquare."""
95  try:
96  data = await request.json()
97  except ValueError:
98  return self.json_message("Invalid JSON", HTTPStatus.BAD_REQUEST)
99 
100  secret = data.pop("secret", None)
101 
102  _LOGGER.debug("Received Foursquare push: %s", data)
103 
104  if self.push_secretpush_secret != secret:
105  _LOGGER.error(
106  "Received Foursquare push with invalid push secret: %s", secret
107  )
108  return self.json_message("Incorrect secret", HTTPStatus.BAD_REQUEST)
109 
110  request.app[KEY_HASS].bus.async_fire(EVENT_PUSH, data)
111  return None
web.Response|None post(self, web.Request request)
Definition: __init__.py:93
bool setup(HomeAssistant hass, ConfigType config)
Definition: __init__.py:54