aboutsummaryrefslogtreecommitdiff
path: root/lib/mailchimp.ex
blob: 15f53233b53f1bbae794b7b450e5e1423c3fd1fd (plain)
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
defmodule Mailchimp do
  use Application
  use GenServer
  require Logger

  @apikey Application.get_env :mailchimp, :apikey

  ### Public API
  def start_link do
    shard = get_shard
    apiroot = "https://#{shard}.api.mailchimp.com/3.0/"
    config = %{apiroot: apiroot, apikey: @apikey}
    GenServer.start_link(Mailchimp, config, name: :mailchimp)
  end

  def get_account_details do
    GenServer.call(:mailchimp, :account_details)
  end

  def get_all_lists do
    GenServer.call(:mailchimp, :all_lists)
  end

  def get_list_members(list_id) do
    GenServer.call(:mailchimp, {:list_members, list_id})
  end

  def add_member(list_id, email) do
    GenServer.call(:mailchimp, {:add_member, list_id, email})
  end

  def add_pending_member(list_id, email) do
    GenServer.call(:mailchimp, {:add_pending_member, list_id, email})
  end

  ### Server API
  def handle_call(:account_details, _from, config) do
    details = Mailchimp.Account.get_details(config)
    {:reply, details, config}
  end

  def handle_call(:all_lists, _from, config) do
    lists = Mailchimp.List.all(config)
    {:reply, lists, config}
  end

  def handle_call({:list_members, list_id}, _from, config) do
    members = Mailchimp.List.members(config, list_id)
    {:reply, members, config}
  end

  def handle_call({:add_member, list_id, email}, _from, config) do
    member = Mailchimp.List.add_member(config, %{"list_id" => list_id, "email" => email})
    {:reply, member, config}
  end

  def get_shard do
    parts = @apikey
    |> String.split(~r{-})

    case length(parts) do
      2 ->
        List.last parts
      _ ->
        Logger.error "This doesn't look like an API Key: #{@apikey}"
        Logger.info "The API Key should have both a key and a server name, separated by a dash, like this: abcdefg8abcdefg6abcdefg4-us1"
        {:error}
    end
  end

end