2022-07-12 10:55:28 +02:00
|
|
|
defmodule Mobilizon.Service.Pictures.Unsplash do
|
|
|
|
@moduledoc """
|
|
|
|
[Unsplash](https://unsplash.com) backend.
|
|
|
|
"""
|
|
|
|
|
|
|
|
alias Mobilizon.Service.HTTP.GenericJSONClient
|
2022-08-26 16:08:58 +02:00
|
|
|
alias Mobilizon.Service.Pictures.{Information, Provider}
|
2022-07-12 10:55:28 +02:00
|
|
|
require Logger
|
|
|
|
|
|
|
|
@unsplash_api "/search/photos"
|
|
|
|
@unsplash_name "Unsplash"
|
|
|
|
|
|
|
|
@behaviour Provider
|
|
|
|
|
|
|
|
@impl Provider
|
|
|
|
@doc """
|
|
|
|
Unsplash implementation for `c:Mobilizon.Service.Geospatial.Provider.geocode/3`.
|
|
|
|
"""
|
2022-11-04 09:26:45 +01:00
|
|
|
@spec search(String.t(), keyword()) :: Information.t()
|
2022-07-12 10:55:28 +02:00
|
|
|
def search(location, _options \\ []) do
|
|
|
|
url = "#{unsplash_endpoint()}#{@unsplash_api}?query=#{location}&orientation=landscape"
|
|
|
|
|
|
|
|
client =
|
|
|
|
GenericJSONClient.client(headers: [{:Authorization, "Client-ID #{unsplash_access_key()}"}])
|
|
|
|
|
|
|
|
with {:ok, %{status: 200, body: body}} <- GenericJSONClient.get(client, url),
|
2022-11-07 18:59:46 +01:00
|
|
|
results <- body["results"],
|
|
|
|
{:empty, false} <- {:empty, Enum.empty?(results)},
|
|
|
|
selected_picture <- Enum.random(results) do
|
2022-07-12 10:55:28 +02:00
|
|
|
%Information{
|
2022-08-26 16:08:58 +02:00
|
|
|
url: selected_picture["urls"]["small"],
|
2022-07-12 10:55:28 +02:00
|
|
|
author: %{
|
2022-08-26 16:08:58 +02:00
|
|
|
name: selected_picture["user"]["name"],
|
|
|
|
url: "#{selected_picture["user"]["links"]["html"]}#{unsplash_utm_source()}"
|
2022-07-12 10:55:28 +02:00
|
|
|
},
|
|
|
|
source: %{
|
|
|
|
name: @unsplash_name,
|
|
|
|
url: unsplash_url()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
else
|
2022-11-07 18:59:46 +01:00
|
|
|
{:empty, false} ->
|
|
|
|
nil
|
|
|
|
|
2022-07-12 10:55:28 +02:00
|
|
|
_ ->
|
|
|
|
nil
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2022-11-04 09:26:45 +01:00
|
|
|
@impl Provider
|
|
|
|
@doc """
|
|
|
|
Returns the CSP configuration for this search provider to work
|
|
|
|
"""
|
|
|
|
def csp do
|
|
|
|
:mobilizon
|
|
|
|
|> Application.get_env(__MODULE__, [])
|
|
|
|
|> Keyword.get(:csp_policy, [])
|
|
|
|
end
|
|
|
|
|
2022-07-12 10:55:28 +02:00
|
|
|
defp unsplash_app_name do
|
|
|
|
Application.get_env(:mobilizon, __MODULE__) |> get_in([:app_name])
|
|
|
|
end
|
|
|
|
|
|
|
|
defp unsplash_utm_source do
|
|
|
|
"?utm_source=#{unsplash_app_name()}&utm_medium=referral"
|
|
|
|
end
|
|
|
|
|
|
|
|
defp unsplash_url do
|
|
|
|
"https://unsplash.com/#{unsplash_utm_source()}"
|
|
|
|
end
|
|
|
|
|
|
|
|
defp unsplash_endpoint do
|
|
|
|
Application.get_env(:mobilizon, __MODULE__) |> get_in([:endpoint]) ||
|
|
|
|
"https://api.unsplash.com"
|
|
|
|
end
|
|
|
|
|
|
|
|
defp unsplash_access_key do
|
|
|
|
Application.get_env(:mobilizon, __MODULE__) |> get_in([:access_key])
|
|
|
|
end
|
|
|
|
end
|