defmodule Untappd do @env Mix.env @version Mix.Project.config[:version] require Logger def auth_url() do client_id = Keyword.get(env(), :client_id) url = NolaWeb.Router.Helpers.untappd_callback_url(NolaWeb.Endpoint, :callback) "https://untappd.com/oauth/authenticate/?client_id=#{client_id}&response_type=code&redirect_url=#{URI.encode(url)}" end def auth_callback(code) do client_id = Keyword.get(env(), :client_id) client_secret = Keyword.get(env(), :client_secret) url = NolaWeb.Router.Helpers.untappd_callback_url(NolaWeb.Endpoint, :callback) params = %{ "client_id" => client_id, "client_secret" => client_secret, "response_type" => code, "redirect_url" => url, "code" => code } case HTTPoison.get("https://untappd.com/oauth/authorize", headers(), params: params) do {:ok, %HTTPoison.Response{status_code: 200, body: body}} -> json = Poison.decode!(body) {:ok, get_in(json, ["response", "access_token"])} error -> Logger.error("Untappd auth callback failed: #{inspect error}") :error end end def maybe_checkin(account, beer_id) do if token = IRC.Account.get_meta(account, "untappd-token") do checkin(token, beer_id) else {:error, :no_token} end end def checkin(token, beer_id) do params = get_params(token: token) |> Map.put("timezone", "CEST") |> Map.put("bid", beer_id) form_params = params |> Enum.into([]) case HTTPoison.post("https://api.untappd.com/v4/checkin/add", {:form, form_params}, headers(), params: params) do {:ok, %HTTPoison.Response{status_code: 200, body: body}} -> body = Jason.decode!(body) |> Map.get("response") {:ok, body} {:ok, resp = %HTTPoison.Response{status_code: code, body: body}} -> Logger.warn "Untappd checkin error: #{inspect resp}" {:error, {:http_error, code}} {:error, error} -> {:error, {:http_error, error}} end end def search_beer(query, params \\ []) do params = get_params(params) |> Map.put("q", query) |> Map.put("limit", 10) #|> Map.put("sort", "name") case HTTPoison.get("https://api.untappd.com/v4/search/beer", headers(), params: params) do {:ok, %HTTPoison.Response{status_code: 200, body: body}} -> {:ok, Jason.decode!(body)} error -> Logger.error("Untappd search error: #{inspect error}") end end def get_params(params) do auth = %{"client_id" => Keyword.get(env(), :client_id), "client_secret" => Keyword.get(env(), :client_secret)} if token = Keyword.get(params, :token) do Map.put(auth, "access_token", token) else auth end end def headers(extra \\ []) do client_id = Keyword.get(env(), :client_id) extra ++ [ {"user-agent", "dmzbot (#{client_id}; #{@version}-#{@env})"} ] end def env() do Application.get_env(:lsg, :untappd) end end