diff --git a/.formatter.exs b/.formatter.exs new file mode 100644 index 0000000..d2cda26 --- /dev/null +++ b/.formatter.exs @@ -0,0 +1,4 @@ +# Used by "mix format" +[ + inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] +] diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8f6624d --- /dev/null +++ b/.gitignore @@ -0,0 +1,24 @@ +# The directory Mix will write compiled artifacts to. +/_build/ + +# If you run "mix test --cover", coverage assets end up here. +/cover/ + +# The directory Mix downloads your dependencies sources to. +/deps/ + +# Where third-party dependencies like ExDoc output generated docs. +/doc/ + +# Ignore .fetch files in case you like to edit your project deps locally. +/.fetch + +# If the VM crashes, it generates a dump, let's ignore it too. +erl_crash.dump + +# Also ignore archive artifacts (built via "mix archive.build"). +*.ez + +# Ignore package tarball (built via "mix hex.build"). +stein_sms-*.tar + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..9745662 --- /dev/null +++ b/LICENSE @@ -0,0 +1,7 @@ +Copyright 2021 SmartLogic + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..027027b --- /dev/null +++ b/README.md @@ -0,0 +1,21 @@ +# SteinSms + +**TODO: Add description** + +## Installation + +If [available in Hex](https://hex.pm/docs/publish), the package can be installed +by adding `stein_sms` to your list of dependencies in `mix.exs`: + +```elixir +def deps do + [ + {:stein_sms, "~> 0.1.0"} + ] +end +``` + +Documentation can be generated with [ExDoc](https://github.com/elixir-lang/ex_doc) +and published on [HexDocs](https://hexdocs.pm). Once published, the docs can +be found at [https://hexdocs.pm/stein_sms](https://hexdocs.pm/stein_sms). + diff --git a/lib/stein/sms.ex b/lib/stein/sms.ex new file mode 100644 index 0000000..39f67eb --- /dev/null +++ b/lib/stein/sms.ex @@ -0,0 +1,30 @@ +defmodule Stein.SMS do + @moduledoc """ + An extension to Stein that handles SMS + """ + + use Supervisor + + def start_link(config) do + Supervisor.start_link(__MODULE__, config) + end + + def init(config = %Stein.SMS.Development{}) do + children = [ + {Stein.SMS.Config, config}, + {Stein.SMS.Cache, config.cache} + ] + + Supervisor.init(children, strategy: :one_for_one) + end + + def init(config = %Stein.SMS.Twilio{}) do + children = [ + {Stein.SMS.Config, config}, + {Stein.SMS.Cache, config.cache}, + {Finch, name: config.finch_name} + ] + + Supervisor.init(children, strategy: :one_for_one) + end +end diff --git a/lib/stein/sms/cache.ex b/lib/stein/sms/cache.ex new file mode 100644 index 0000000..b3db0f3 --- /dev/null +++ b/lib/stein/sms/cache.ex @@ -0,0 +1,71 @@ +defmodule Stein.SMS.Cache do + @moduledoc """ + A development cache for text messages that were sent + """ + + use GenServer + + defstruct ets_key: :stein_sms_cache, name: __MODULE__ + + require Logger + + def cache(config, text_message) do + GenServer.call(config.name, {:cache, text_message}) + end + + def text_messages(config) do + Enum.map(keys(config.ets_key), fn key -> + {:ok, text_message} = get(config.ets_key, key) + text_message + end) + end + + @doc false + def get(ets_key, key) do + case :ets.lookup(ets_key, key) do + [{^key, value}] -> + {:ok, value} + + _ -> + {:error, :not_found} + end + end + + @doc false + def keys(ets_key) do + key = :ets.first(ets_key) + keys(key, [], ets_key) + end + + def keys(:"$end_of_table", accumulator, _ets_key), do: accumulator + + def keys(current_key, accumulator, ets_key) do + next_key = :ets.next(ets_key, current_key) + keys(next_key, [current_key | accumulator], ets_key) + end + + def start_link(config) do + GenServer.start_link(__MODULE__, config, name: config.name) + end + + @impl true + def init(config) do + {:ok, config, {:continue, :start_cache}} + end + + @impl true + def handle_continue(:start_cache, state) do + :ets.new(state.ets_key, [:set, :protected, :named_table]) + + {:noreply, state} + end + + @impl true + def handle_call({:cache, text_message}, _from, state) do + Logger.info("Caching sent text - #{inspect(text_message)}") + + :ets.insert(state.ets_key, {text_message.id, text_message}) + + {:reply, :ok, state} + end +end diff --git a/lib/stein/sms/config.ex b/lib/stein/sms/config.ex new file mode 100644 index 0000000..4f37fda --- /dev/null +++ b/lib/stein/sms/config.ex @@ -0,0 +1,30 @@ +defmodule Stein.SMS.Config do + @moduledoc """ + Configuration cache for Stein.SMS + + Start with the configuration that should be generally used in your + application. It will be stored in `:persistent_term` for quick access. + """ + + use GenServer + + def get() do + :persistent_term.get(__MODULE__) + end + + def start_link(config) do + GenServer.start_link(__MODULE__, config) + end + + @impl true + def init(config) do + {:ok, config, {:continue, :cache_config}} + end + + @impl true + def handle_continue(:cache_config, state) do + :persistent_term.put(__MODULE__, state) + + {:noreply, state} + end +end diff --git a/lib/stein/sms/development.ex b/lib/stein/sms/development.ex new file mode 100644 index 0000000..9902973 --- /dev/null +++ b/lib/stein/sms/development.ex @@ -0,0 +1,40 @@ +defmodule Stein.SMS.Development do + @moduledoc """ + Development service for Stein.SMS + + Caches all texts being sent from your application in `Stein.SMS.Cache` + """ + + alias Stein.SMS.Cache + alias Stein.SMS.TextMessage + + defstruct cache: %Stein.SMS.Cache{} + + @doc false + def generate_id() do + bytes = + Enum.reduce(1..4, <<>>, fn _, bytes -> + bytes <> <> + end) + + Base.encode16(bytes, case: :lower) + end + + defimpl Stein.SMS.Service do + alias Stein.SMS.Development + + def send_text(config, from, to, message) do + text_message = %TextMessage{ + id: Development.generate_id(), + from: from, + to: to, + message: message, + sent_at: DateTime.utc_now() + } + + Cache.cache(config.cache, text_message) + + :ok + end + end +end diff --git a/lib/stein/sms/service.ex b/lib/stein/sms/service.ex new file mode 100644 index 0000000..64c573c --- /dev/null +++ b/lib/stein/sms/service.ex @@ -0,0 +1,11 @@ +defprotocol Stein.SMS.Service do + @moduledoc """ + Protocol for defining an SMS service + + Currently defined services: + - `Stein.SMS.Twilio`: send texts via twilio + - `Stein.SMS.Development`: send texts in a development mode, caching texts + """ + + def send_text(_config, from, to, message) +end diff --git a/lib/stein/sms/text_message.ex b/lib/stein/sms/text_message.ex new file mode 100644 index 0000000..1f2815f --- /dev/null +++ b/lib/stein/sms/text_message.ex @@ -0,0 +1,7 @@ +defmodule Stein.SMS.TextMessage do + @moduledoc """ + Development struct for containing information about a sent text + """ + + defstruct [:id, :from, :to, :message, :sent_at] +end diff --git a/lib/stein/sms/twilio.ex b/lib/stein/sms/twilio.ex new file mode 100644 index 0000000..4a0ec9f --- /dev/null +++ b/lib/stein/sms/twilio.ex @@ -0,0 +1,83 @@ +defmodule Stein.SMS.Twilio do + @moduledoc """ + Twilio service for Stein.SMS + + Sends texts via Twilio messaging API + + Configuration required: + - `account_sid`: Find this on the Twilio Dashboard + - `auth_token`: Find this on the Twilio Dashboard + """ + + @enforce_keys [:account_sid, :auth_token] + defstruct [:account_sid, :auth_token, cache: %Stein.SMS.Cache{}, finch_name: Stein.SMS.Twilio] + + defmodule Exception do + defexception [:body, :code, :reason, :status] + + def message(struct) do + """ + Twilio failed an API request + + Error Code: #{struct.code} - #{struct.reason} + + Status: #{struct.status} + Body: + #{inspect(struct.body, pretty: true)} + """ + end + end + + defimpl Stein.SMS.Service do + alias Stein.SMS.Twilio + + @twilio_base_url "https://api.twilio.com/2010-04-01/Accounts/" + + def send_text(config, from, to, message) do + basic_auth = "#{config.account_sid}:#{config.auth_token}" |> Base.encode64() + api_url = "#{@twilio_base_url}#{config.account_sid}/Messages.json" + + req_headers = [ + {"Authorization", "Basic #{basic_auth}"}, + {"Content-Type", "application/x-www-form-urlencoded"} + ] + + req_body = + URI.encode_query(%{ + "Body" => message, + "From" => from, + "To" => to + }) + + request = Finch.build(:post, api_url, req_headers, req_body) + + case Finch.request(request, config.finch_name) do + {:ok, %{status: 201}} -> + :ok + + {:ok, %{body: body, status: 400}} -> + body = Jason.decode!(body) + + exception = %Twilio.Exception{ + code: body["code"], + body: body, + reason: body["message"], + status: 400 + } + + {:error, exception} + + {:ok, %{body: body, status: status}} -> + body = Jason.decode!(body) + + exception = %Twilio.Exception{ + body: body, + reason: "Unknown error", + status: status + } + + {:error, exception} + end + end + end +end diff --git a/mix.exs b/mix.exs new file mode 100644 index 0000000..6a1baf4 --- /dev/null +++ b/mix.exs @@ -0,0 +1,29 @@ +defmodule SteinSms.MixProject do + use Mix.Project + + def project do + [ + app: :stein_sms, + version: "0.1.0", + elixir: "~> 1.10", + start_permanent: Mix.env() == :prod, + deps: deps() + ] + end + + # Run "mix help compile.app" to learn about applications. + def application do + [ + extra_applications: [:logger] + ] + end + + # Run "mix help deps" to learn about dependencies. + defp deps do + [ + {:credo, "~> 1.1", only: [:dev, :test]}, + {:finch, "~> 0.8"}, + {:jason, "~> 1.0"} + ] + end +end diff --git a/mix.lock b/mix.lock new file mode 100644 index 0000000..aff398b --- /dev/null +++ b/mix.lock @@ -0,0 +1,31 @@ +%{ + "bcrypt_elixir": {:hex, :bcrypt_elixir, "2.3.0", "6cb662d5c1b0a8858801cf20997bd006e7016aa8c52959c9ef80e0f34fb60b7a", [:make, :mix], [{:comeonin, "~> 5.3", [hex: :comeonin, repo: "hexpm", optional: false]}, {:elixir_make, "~> 0.6", [hex: :elixir_make, repo: "hexpm", optional: false]}], "hexpm", "2c81d61d4f6ed0e5cf7bf27a9109b791ff216a1034b3d541327484f46dd43769"}, + "bunt": {:hex, :bunt, "0.2.0", "951c6e801e8b1d2cbe58ebbd3e616a869061ddadcc4863d0a2182541acae9a38", [:mix], [], "hexpm", "7af5c7e09fe1d40f76c8e4f9dd2be7cebd83909f31fee7cd0e9eadc567da8353"}, + "castore": {:hex, :castore, "0.1.11", "c0665858e0e1c3e8c27178e73dffea699a5b28eb72239a3b2642d208e8594914", [:mix], [], "hexpm", "91b009ba61973b532b84f7c09ce441cba7aa15cb8b006cf06c6f4bba18220081"}, + "certifi": {:hex, :certifi, "2.6.1", "dbab8e5e155a0763eea978c913ca280a6b544bfa115633fa20249c3d396d9493", [:rebar3], [], "hexpm", "524c97b4991b3849dd5c17a631223896272c6b0af446778ba4675a1dff53bb7e"}, + "combine": {:hex, :combine, "0.10.0", "eff8224eeb56498a2af13011d142c5e7997a80c8f5b97c499f84c841032e429f", [:mix], [], "hexpm", "1b1dbc1790073076580d0d1d64e42eae2366583e7aecd455d1215b0d16f2451b"}, + "comeonin": {:hex, :comeonin, "5.3.2", "5c2f893d05c56ae3f5e24c1b983c2d5dfb88c6d979c9287a76a7feb1e1d8d646", [:mix], [], "hexpm", "d0993402844c49539aeadb3fe46a3c9bd190f1ecf86b6f9ebd71957534c95f04"}, + "credo": {:hex, :credo, "1.5.6", "e04cc0fdc236fefbb578e0c04bd01a471081616e741d386909e527ac146016c6", [:mix], [{:bunt, "~> 0.2.0", [hex: :bunt, repo: "hexpm", optional: false]}, {:file_system, "~> 0.2.8", [hex: :file_system, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "4b52a3e558bd64e30de62a648518a5ea2b6e3e5d2b164ef5296244753fc7eb17"}, + "decimal": {:hex, :decimal, "2.0.0", "a78296e617b0f5dd4c6caf57c714431347912ffb1d0842e998e9792b5642d697", [:mix], [], "hexpm", "34666e9c55dea81013e77d9d87370fe6cb6291d1ef32f46a1600230b1d44f577"}, + "ecto": {:hex, :ecto, "3.7.0", "0b250b4aa5a9cdb80252802bd535c54c963e2d83f5bd179a57c093ed0779994b", [:mix], [{:decimal, "~> 1.6 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: true]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "3a212cecd544a6f3d00921bc3e7545070eb50b9a1454525323027bf07eba1165"}, + "elixir_make": {:hex, :elixir_make, "0.6.2", "7dffacd77dec4c37b39af867cedaabb0b59f6a871f89722c25b28fcd4bd70530", [:mix], [], "hexpm", "03e49eadda22526a7e5279d53321d1cced6552f344ba4e03e619063de75348d9"}, + "elixir_uuid": {:hex, :elixir_uuid, "1.2.1", "dce506597acb7e6b0daeaff52ff6a9043f5919a4c3315abb4143f0b00378c097", [:mix], [], "hexpm", "f7eba2ea6c3555cea09706492716b0d87397b88946e6380898c2889d68585752"}, + "file_system": {:hex, :file_system, "0.2.10", "fb082005a9cd1711c05b5248710f8826b02d7d1784e7c3451f9c1231d4fc162d", [:mix], [], "hexpm", "41195edbfb562a593726eda3b3e8b103a309b733ad25f3d642ba49696bf715dc"}, + "finch": {:hex, :finch, "0.8.1", "761e39640c98d12c9ac7aa15b4d0732205669b20055e26bcc8da7ce826070fdc", [:mix], [{:castore, "~> 0.1", [hex: :castore, repo: "hexpm", optional: false]}, {:mint, "~> 1.3", [hex: :mint, repo: "hexpm", optional: false]}, {:nimble_options, "~> 0.3.5", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:nimble_pool, "~> 0.2", [hex: :nimble_pool, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "bc80f759f701dd56793f4edfaa6dc6480707c23046fde3a98c9887b164924cad"}, + "gettext": {:hex, :gettext, "0.18.2", "7df3ea191bb56c0309c00a783334b288d08a879f53a7014341284635850a6e55", [:mix], [], "hexpm", "f9f537b13d4fdd30f3039d33cb80144c3aa1f8d9698e47d7bcbcc8df93b1f5c5"}, + "hackney": {:hex, :hackney, "1.17.4", "99da4674592504d3fb0cfef0db84c3ba02b4508bae2dff8c0108baa0d6e0977c", [:rebar3], [{:certifi, "~>2.6.1", [hex: :certifi, repo: "hexpm", optional: false]}, {:idna, "~>6.1.0", [hex: :idna, repo: "hexpm", optional: false]}, {:metrics, "~>1.0.0", [hex: :metrics, repo: "hexpm", optional: false]}, {:mimerl, "~>1.1", [hex: :mimerl, repo: "hexpm", optional: false]}, {:parse_trans, "3.3.1", [hex: :parse_trans, repo: "hexpm", optional: false]}, {:ssl_verify_fun, "~>1.1.0", [hex: :ssl_verify_fun, repo: "hexpm", optional: false]}, {:unicode_util_compat, "~>0.7.0", [hex: :unicode_util_compat, repo: "hexpm", optional: false]}], "hexpm", "de16ff4996556c8548d512f4dbe22dd58a587bf3332e7fd362430a7ef3986b16"}, + "idna": {:hex, :idna, "6.1.1", "8a63070e9f7d0c62eb9d9fcb360a7de382448200fbbd1b106cc96d3d8099df8d", [:rebar3], [{:unicode_util_compat, "~>0.7.0", [hex: :unicode_util_compat, repo: "hexpm", optional: false]}], "hexpm", "92376eb7894412ed19ac475e4a86f7b413c1b9fbb5bd16dccd57934157944cea"}, + "jason": {:hex, :jason, "1.2.2", "ba43e3f2709fd1aa1dce90aaabfd039d000469c05c56f0b8e31978e03fa39052", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "18a228f5f0058ee183f29f9eae0805c6e59d61c3b006760668d8d18ff0d12179"}, + "metrics": {:hex, :metrics, "1.0.1", "25f094dea2cda98213cecc3aeff09e940299d950904393b2a29d191c346a8486", [:rebar3], [], "hexpm", "69b09adddc4f74a40716ae54d140f93beb0fb8978d8636eaded0c31b6f099f16"}, + "mimerl": {:hex, :mimerl, "1.2.0", "67e2d3f571088d5cfd3e550c383094b47159f3eee8ffa08e64106cdf5e981be3", [:rebar3], [], "hexpm", "f278585650aa581986264638ebf698f8bb19df297f66ad91b18910dfc6e19323"}, + "mint": {:hex, :mint, "1.3.0", "396b3301102f7b775e103da5a20494b25753aed818d6d6f0ad222a3a018c3600", [:mix], [{:castore, "~> 0.1.0", [hex: :castore, repo: "hexpm", optional: true]}], "hexpm", "a9aac960562e43ca69a77e5176576abfa78b8398cec5543dd4fb4ab0131d5c1e"}, + "nimble_options": {:hex, :nimble_options, "0.3.6", "365d03c05d43483d3eacf820671dafce5b49d692667b3bb8cae28447fd2414ef", [:mix], [], "hexpm", "1c1d3536c4aee1be2c8f3c691bf27c62dbd88d9bb3a0b1a011913453932e8c15"}, + "nimble_pool": {:hex, :nimble_pool, "0.2.4", "1db8e9f8a53d967d595e0b32a17030cdb6c0dc4a451b8ac787bf601d3f7704c3", [:mix], [], "hexpm", "367e8071e137b787764e6a9992ccb57b276dc2282535f767a07d881951ebeac6"}, + "parse_trans": {:hex, :parse_trans, "3.3.1", "16328ab840cc09919bd10dab29e431da3af9e9e7e7e6f0089dd5a2d2820011d8", [:rebar3], [], "hexpm", "07cd9577885f56362d414e8c4c4e6bdf10d43a8767abb92d24cbe8b24c54888b"}, + "ssl_verify_fun": {:hex, :ssl_verify_fun, "1.1.6", "cf344f5692c82d2cd7554f5ec8fd961548d4fd09e7d22f5b62482e5aeaebd4b0", [:make, :mix, :rebar3], [], "hexpm", "bdb0d2471f453c88ff3908e7686f86f9be327d065cc1ec16fa4540197ea04680"}, + "stein": {:hex, :stein, "0.5.4", "7d768c6926af3fa446d31ce94cbafd1c5ec92972be52dede5284583eff91223d", [:mix], [{:bcrypt_elixir, "~> 2.0", [hex: :bcrypt_elixir, repo: "hexpm", optional: false]}, {:ecto, "~> 3.0", [hex: :ecto, repo: "hexpm", optional: false]}, {:elixir_uuid, "~> 1.2", [hex: :elixir_uuid, repo: "hexpm", optional: false]}, {:timex, "~> 3.5", [hex: :timex, repo: "hexpm", optional: false]}], "hexpm", "b794e44b078e327251331daa79315c03b5e173160c4ccc6324c6e5886da940d0"}, + "telemetry": {:hex, :telemetry, "1.0.0", "0f453a102cdf13d506b7c0ab158324c337c41f1cc7548f0bc0e130bbf0ae9452", [:rebar3], [], "hexpm", "73bc09fa59b4a0284efb4624335583c528e07ec9ae76aca96ea0673850aec57a"}, + "timex": {:hex, :timex, "3.7.6", "502d2347ec550e77fdf419bc12d15bdccd31266bb7d925b30bf478268098282f", [:mix], [{:combine, "~> 0.10", [hex: :combine, repo: "hexpm", optional: false]}, {:gettext, "~> 0.10", [hex: :gettext, repo: "hexpm", optional: false]}, {:tzdata, "~> 1.0", [hex: :tzdata, repo: "hexpm", optional: false]}], "hexpm", "a296327f79cb1ec795b896698c56e662ed7210cc9eb31f0ab365eb3a62e2c589"}, + "tzdata": {:hex, :tzdata, "1.1.0", "72f5babaa9390d0f131465c8702fa76da0919e37ba32baa90d93c583301a8359", [:mix], [{:hackney, "~> 1.17", [hex: :hackney, repo: "hexpm", optional: false]}], "hexpm", "18f453739b48d3dc5bcf0e8906d2dc112bb40baafe2c707596d89f3c8dd14034"}, + "unicode_util_compat": {:hex, :unicode_util_compat, "0.7.0", "bc84380c9ab48177092f43ac89e4dfa2c6d62b40b8bd132b1059ecc7232f9a78", [:rebar3], [], "hexpm", "25eee6d67df61960cf6a794239566599b09e17e668d3700247bc498638152521"}, +} diff --git a/test/test_helper.exs b/test/test_helper.exs new file mode 100644 index 0000000..869559e --- /dev/null +++ b/test/test_helper.exs @@ -0,0 +1 @@ +ExUnit.start() diff --git a/verify.sh b/verify.sh new file mode 100755 index 0000000..48e80a0 --- /dev/null +++ b/verify.sh @@ -0,0 +1,35 @@ +#!/bin/bash + +set -e + +GREEN='\033[0;32m' +BOLD=$(tput bold) +NORM=$(tput sgr0) + +# $1 should be the header text +# Usage: header "foobar" +function header() { + echo + echo -e "${GREEN}${BOLD}$1${NORM}" +} + +function lint() { + header "LINTING" + mix format --check-formatted + mix compile --force --warnings-as-errors + mix credo +} + +function test() { + header "TESTING" + mix test +} + +function audit() { + header "AUDITING" + mix hex.audit +} + +lint +test +audit