summaryrefslogtreecommitdiff
path: root/lib/lsg_irc/link_plugin/imgur.ex
diff options
context:
space:
mode:
Diffstat (limited to 'lib/lsg_irc/link_plugin/imgur.ex')
-rw-r--r--lib/lsg_irc/link_plugin/imgur.ex84
1 files changed, 84 insertions, 0 deletions
diff --git a/lib/lsg_irc/link_plugin/imgur.ex b/lib/lsg_irc/link_plugin/imgur.ex
new file mode 100644
index 0000000..9ce3cf3
--- /dev/null
+++ b/lib/lsg_irc/link_plugin/imgur.ex
@@ -0,0 +1,84 @@
+defmodule LSG.IRC.LinkPlugin.Imgur do
+ @behaviour LSG.IRC.LinkPlugin
+
+ @moduledoc """
+ # Imgur link preview
+
+ No options.
+
+ Needs to have a Imgur API key configured:
+
+ ```
+ config :lsg, :imgur,
+ client_id: "xxxxxxxx",
+ client_secret: "xxxxxxxxxxxxxxxxxxxx"
+ ```
+ """
+
+ def match(uri = %URI{host: "imgur.com", path: "/a/"<>album_id}, _) do
+ {true, %{album_id: album_id}}
+ end
+ def match(uri = %URI{host: "imgur.com", path: "/gallery/"<>album_id}, _) do
+ {true, %{album_id: album_id}}
+ end
+ def match(uri = %URI{host: "i.imgur.com", path: "/"<>image}, _) do
+ [hash, _] = String.split(image, ".", parts: 2)
+ {true, %{image_id: hash}}
+ end
+ def match(_, _), do: false
+
+ def expand(_uri, %{album_id: album_id}, opts) do
+ expand_imgur_album(album_id, opts)
+ end
+
+ def expand(_uri, %{image_id: image_id}, opts) do
+ expand_imgur_image(image_id, opts)
+ end
+
+ def expand_imgur_image(image_id, opts) do
+ client_id = Keyword.get(Application.get_env(:lsg, :imgur, []), :client_id, "42")
+ headers = [{"Authorization", "Client-ID #{client_id}"}]
+ options = []
+ case HTTPoison.get("https://api.imgur.com/3/image/#{image_id}", headers, options) do
+ {:ok, %HTTPoison.Response{status_code: 200, body: body}} ->
+ {:ok, json} = Jason.decode(body)
+ data = json["data"]
+ IO.puts inspect(json)
+ title = String.slice(data["title"] || data["description"], 0, 180)
+ nsfw = if data["nsfw"], do: "(NSFW) - ", else: ""
+ {:ok, "#{nsfw}#{title}"}
+ other ->
+ :error
+ end
+ end
+
+ def expand_imgur_album(album_id, opts) do
+ client_id = Keyword.get(Application.get_env(:lsg, :imgur, []), :client_id, "42")
+ headers = [{"Authorization", "Client-ID #{client_id}"}]
+ options = []
+ case HTTPoison.get("https://api.imgur.com/3/album/#{album_id}", headers, options) do
+ {:ok, %HTTPoison.Response{status_code: 200, body: body}} ->
+ {:ok, json} = Jason.decode(body)
+ data = json["data"]
+ title = data["title"]
+ nsfw = data["nsfw"]
+ nsfw = if nsfw, do: "(NSFW) - ", else: ""
+ if data["images_count"] == 1 do
+ [image] = data["images"]
+ title = if title || data["title"] do
+ title = [title, data["title"]] |> Enum.filter(fn(x) -> x end) |> Enum.uniq() |> Enum.join(" — ")
+ "#{title} — "
+ else
+ ""
+ end
+ {:ok, "#{nsfw}#{title}#{image["link"]}"}
+ else
+ title = if title, do: title, else: "Untitled album"
+ {:ok, "#{nsfw}#{title} - #{data["images_count"]} images"}
+ end
+ other ->
+ :error
+ end
+ end
+
+end