├── .formatter.exs ├── .github ├── FUNDING.yml └── workflows │ ├── ci.yml │ └── stale.yml ├── .gitignore ├── LICENSE ├── README.md ├── lib ├── capsule.ex ├── capsule │ ├── locator.ex │ ├── storage.ex │ ├── upload.ex │ └── uploader.ex └── errors │ ├── invalid_locator.ex │ └── invalid_storage.ex ├── mix.exs ├── mix.lock └── test ├── capsule ├── locator_test.exs ├── upload_test.exs └── uploader_test.exs ├── capsule_test.exs ├── support └── mock_storage.ex └── test_helper.exs /.formatter.exs: -------------------------------------------------------------------------------- 1 | # Used by "mix format" 2 | [ 3 | inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] 4 | ] 5 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [tfwright] 2 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: push 4 | 5 | jobs: 6 | test: 7 | runs-on: ubuntu-latest 8 | 9 | env: 10 | MIX_ENV: test 11 | 12 | strategy: 13 | matrix: 14 | elixir: ["1.13.x"] 15 | otp: ["24.x"] 16 | 17 | steps: 18 | - uses: actions/checkout@v1 19 | - name: Set up Elixir 20 | uses: erlef/setup-beam@v1 21 | with: 22 | elixir-version: ${{ matrix.elixir }} 23 | otp-version: ${{ matrix.otp }} 24 | - uses: actions/cache@v2 25 | with: 26 | path: deps 27 | key: ${{ runner.os }}-${{ matrix.otp }}-${{ matrix.elixir }}-deps-${{ hashFiles(format('{0}{1}', github.workspace, '/mix.lock')) }} 28 | - name: Install Dependencies 29 | run: | 30 | mix local.rebar --force 31 | mix local.hex --force 32 | mix deps.get 33 | - name: Create tmp dir 34 | run: mkdir tmp 35 | - name: Run Tests 36 | run: mix test 37 | 38 | dialyzer: 39 | runs-on: ubuntu-latest 40 | 41 | container: 42 | image: bitwalker/alpine-elixir:1.13 43 | 44 | steps: 45 | - uses: actions/checkout@v1 46 | - uses: actions/cache@v2 47 | with: 48 | path: _build 49 | key: build-${{ hashFiles(format('{0}{1}', github.workspace, '/mix.lock')) }} 50 | - name: Install Dependencies 51 | run: | 52 | mix local.rebar --force 53 | mix local.hex --force 54 | mix deps.get 55 | - name: Create plts dir 56 | run: mkdir -p priv/plts 57 | - uses: actions/cache@v2 58 | with: 59 | path: priv/plts 60 | key: plts-${{ hashFiles(format('{0}{1}', github.workspace, '/mix.lock')) }} 61 | - name: Run mix dialyzer 62 | run: mix dialyzer 63 | -------------------------------------------------------------------------------- /.github/workflows/stale.yml: -------------------------------------------------------------------------------- 1 | # This workflow warns and then closes issues and PRs that have had no activity for a specified amount of time. 2 | # 3 | # You can adjust the behavior by modifying this file. 4 | # For more information, see: 5 | # https://github.com/actions/stale 6 | name: Mark stale issues and pull requests 7 | 8 | on: 9 | schedule: 10 | - cron: '19 21 * * *' 11 | 12 | jobs: 13 | stale: 14 | 15 | runs-on: ubuntu-latest 16 | permissions: 17 | issues: write 18 | pull-requests: write 19 | 20 | steps: 21 | - uses: actions/stale@v5 22 | with: 23 | days-before-stale: 30 24 | repo-token: ${{ secrets.GITHUB_TOKEN }} 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # The directory Mix will write compiled artifacts to. 2 | /_build/ 3 | 4 | # If you run "mix test --cover", coverage assets end up here. 5 | /cover/ 6 | 7 | # The directory Mix downloads your dependencies sources to. 8 | /deps/ 9 | 10 | # Where third-party dependencies like ExDoc output generated docs. 11 | /doc/ 12 | 13 | # Ignore .fetch files in case you like to edit your project deps locally. 14 | /.fetch 15 | 16 | # If the VM crashes, it generates a dump, let's ignore it too. 17 | erl_crash.dump 18 | 19 | # Also ignore archive artifacts (built via "mix archive.build"). 20 | *.ez 21 | 22 | # Ignore package tarball (built via "mix hex.build"). 23 | capsule-*.tar 24 | 25 | /tmp/ 26 | 27 | /priv/ 28 | 29 | /archives 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Capsule 2 | 3 | Upload and store files in Elixir apps with minimal (currently zero) dependencies. 4 | 5 | [![hex package](https://img.shields.io/hexpm/v/capsule.svg)](https://hex.pm/packages/capsule) 6 | [![CI status](https://github.com/elixir-capsule/capsule/workflows/CI/badge.svg)](https://github.com/elixir-capsule/capsule/actions) 7 | 8 | :warning: Although it has been in production use since 2021 without significant issues, Capsule remains in active development. Accepting file uploads introduces specific security vulnerabilities. Use at your own risk. 9 | 10 | ## Concepts 11 | 12 | Capsule intentionally strips file storage logic down to its most composable parts and lets you decide how you want to use them. These components are: [storage](#storage), [upload](#upload), [locator](#locator), and optionally, [uploader](#uploader), which provides a more ergonomic API for the other 3. 13 | 14 | It is intentionally agnostic about versions, transformation, validations, etc. Most of the convenience offered by other libraries around these features comes at the cost of locking in dependence on specific tools and hiding complexity. Capsule puts a premium on simplicity and explicitness. 15 | 16 | So what does it do? Here's a theoretical example of a use case with an Ecto1 schema, which stores the file retrieved from a URL, along with some additional metadata: 17 | 18 | ``` 19 | def create_attachment(upload, user) do 20 | Multi.new() 21 | |> Multi.run(:upload, fn _, _ -> 22 | YourStorage.put(upload, prefix: :crypto.hash(:md5, [user.id, url]) |> Base.encode16()) 23 | end) 24 | |> Multi.insert(:attachment, fn %{upload: file_id} -> 25 | %Attachment{file_data: Locator.new!(id: file_id, storage: YourStorage, metadata: %{type: "document"}) 26 | end) 27 | |> Repo.transaction() 28 | end 29 | ``` 30 | 31 | Then to access the file: 32 | 33 | ``` 34 | %Attachment{file_data: file} = attachment 35 | 36 | {:ok, contents} = Disk.read(file.id) 37 | ``` 38 | 39 | 1 *See [integrations](#integrations) for streamlined use with Ecto.* 40 | 41 | ### Storage 42 | 43 | A "storage" is a [behaviour](https://elixirschool.com/en/lessons/advanced/behaviours/) that implements the following "file-like" callbacks: 44 | 45 | * read 46 | * put 47 | * delete 48 | * stream! 49 | 50 | Implementing your own storage is as easy as creating a module that quacks this way. Each callback should accept an optional list of options as the last arg. Which options are supported is up to the module that implements the callbacks. 51 | 52 | ### Upload 53 | 54 | Upload is a [protocol](https://elixir-lang.org/getting-started/protocols.html) consisting of the following two functions: 55 | 56 | * contents 57 | * name 58 | 59 | A storage uses this interface to figure how to extract the file data from a given struct and how to identify it. See `Capsule.Locator` for an example of how this protocol can be implemented. 60 | 61 | ### Locator 62 | 63 | Locators are the mediators between storages and uploads. They represent where an uploaded file was stored so it can be retrieved. They contain a unique id, the name of the storage to which the file was uploaded, and a map of user defined metadata. 64 | 65 | Locator also implements the upload protocol, which means moving a file from one storage to another is straightforward, and very useful for "promoting" a file from temporary (e.g. Disk) to permanent (e.g. S3) storage2: 66 | 67 | ``` 68 | old_file_data = %Locator{id: "/path/to/file.jpg", storage: Disk, metadata: %{}} 69 | {:ok, new_id} = S3.put(old_file_data)` 70 | ``` 71 | 72 | Note: always remember to take care of cleaning up the old file as Capsule *never* automatically removes files: 73 | 74 | `Disk.delete(old_file_data.id)` 75 | 76 | 2 *As of version 0.6 Capsule all built-in storages and upload protocols except for Locator have been moved to [elixir-capsule/supplement](https://github.com/elixir-capsule/supplement).* 77 | 78 | ### Uploader 79 | 80 | This helper was added in order to support DRYing up storage access. In most apps, there are certain types of assets that will be uploaded and handled in a similar, if not the same way, if only when it comes to where they are stored. You can `use` the uploader to codify the handling for specific types of assets. 81 | 82 | ``` 83 | defmodule AvatarUploader do 84 | use Capsule.Uploader, storages: [cache: Disk, store: S3] 85 | 86 | def build_options(upload, :cache, opts) do 87 | Keyword.put(opts, :prefix, "cache/#{Date.utc_today()}") 88 | end 89 | 90 | def build_options(upload, :store, opts) do 91 | opts 92 | |> Keyword.put(:prefix, "users/#{opts[:user_id]}/avatar") 93 | |> Keyword.drop([:user_id]) 94 | end 95 | 96 | def build_metadata(upload, :store, _), do: [uploaded_at: DateTime.utc_now()] 97 | end 98 | ``` 99 | 100 | Then you can get the files where they need to be without constructing all the options everywhere they might be uploaded: `AvatarUploader.store(upload, :store, user_id: 1)` 101 | 102 | Note: as this example demonstrates, the function can receive arbitrary data and use it to customize how it builds the storage options before they are passed on. 103 | 104 | ## Integrations 105 | 106 | Capsule's module design is intended to make it easy to implement your own custom utilities for handling files in the way you need. However, anticipating the most common use cases, it can be augmented with the following add-ons. 107 | 108 | ### [CapsuleEcto](https://github.com/elixir-capsule/capsule_ecto) 109 | 110 | Provides the `Capsule.Ecto.Type` for Ecto schema fields which handles persisting Locator data in your repository. 111 | 112 | ### [CapsuleSupplement](https://github.com/elixir-capsule/supplement) 113 | 114 | Contains a collection of some common file storages (including S3/Digital Ocean) and uploads (including `Plug.Upload`). 115 | 116 | That's it! Happy uploading. 117 | -------------------------------------------------------------------------------- /lib/capsule.ex: -------------------------------------------------------------------------------- 1 | defmodule Capsule do 2 | alias Capsule.Locator 3 | alias Capsule.Errors.InvalidStorage 4 | 5 | def add_metadata(%Locator{} = locator, key, val), 6 | do: add_metadata(locator, %{to_string(key) => val}) 7 | 8 | def add_metadata(%Locator{} = locator, data) when is_list(data), 9 | do: add_metadata(locator, Map.new(data, fn {k, v} -> {to_string(k), v} end)) 10 | 11 | def add_metadata(%Locator{} = locator, data), 12 | do: %{ 13 | locator 14 | | metadata: 15 | data 16 | |> Map.new(fn {k, v} -> {to_string(k), v} end) 17 | |> Map.merge(locator.metadata, fn _, new_value, _ -> new_value end) 18 | } 19 | 20 | def storage!(%Locator{storage: module_name}) when is_binary(module_name) do 21 | module_name 22 | |> String.replace_prefix("", "Elixir.") 23 | |> String.replace_prefix("Elixir.Elixir", "Elixir") 24 | |> String.to_existing_atom() 25 | rescue 26 | ArgumentError -> raise InvalidStorage 27 | end 28 | 29 | def storage!(%Locator{storage: module_name}) when is_atom(module_name), do: module_name 30 | end 31 | -------------------------------------------------------------------------------- /lib/capsule/locator.ex: -------------------------------------------------------------------------------- 1 | defmodule Capsule.Locator do 2 | defstruct [:id, :storage, metadata: %{}] 3 | 4 | @type t() :: %__MODULE__{ 5 | id: String.t(), 6 | storage: String.t(), 7 | metadata: map() 8 | } 9 | 10 | def new!(attrs) do 11 | case new(attrs) do 12 | {:ok, locator} -> locator 13 | {:error, error} -> raise(Capsule.Errors.InvalidLocator, error) 14 | end 15 | end 16 | 17 | def new(attrs) when is_list(attrs), 18 | do: attrs |> Map.new() |> new() 19 | 20 | def new(map = %{"id" => id, "storage" => storage}), 21 | do: new(%{id: id, storage: storage, metadata: Map.get(map, "metadata")}) 22 | 23 | def new(map) when is_map_key(map, :id) and is_map_key(map, :storage) do 24 | __MODULE__ 25 | |> struct(map) 26 | |> validate() 27 | end 28 | 29 | def new(_), do: {:error, "data must contain id and storage keys"} 30 | 31 | defp validate(%{id: id}) when not is_binary(id), do: {:error, "id must be binary"} 32 | 33 | defp validate(%{storage: storage}) 34 | when (not is_binary(storage) and not is_atom(storage)) or is_nil(storage), 35 | do: {:error, "storage must be string or atom"} 36 | 37 | defp validate(struct), do: {:ok, struct} 38 | end 39 | -------------------------------------------------------------------------------- /lib/capsule/storage.ex: -------------------------------------------------------------------------------- 1 | defmodule Capsule.Storage do 2 | alias Capsule.Upload 3 | 4 | @type option :: {atom(), any()} 5 | @type locator_id :: String.t() 6 | @type error :: {:error, String.t()} 7 | 8 | @callback read(locator_id, [option]) :: {:ok, binary()} | error 9 | @callback read(locator_id) :: {:ok, binary()} | error 10 | 11 | @callback stream!(locator_id, [option]) :: Enumerable.t() 12 | @callback stream!(locator_id) :: Enumerable.t() 13 | 14 | @callback put(Upload.t(), [option]) :: {:ok, locator_id} | error 15 | @callback put(Upload.t()) :: {:ok, locator_id} | error 16 | 17 | @callback delete(locator_id, [option]) :: :ok | error 18 | @callback delete(locator_id) :: :ok | error 19 | end 20 | -------------------------------------------------------------------------------- /lib/capsule/upload.ex: -------------------------------------------------------------------------------- 1 | defprotocol Capsule.Upload do 2 | @spec contents(struct()) :: {:ok, iodata()} | {:error, String.t()} 3 | def contents(upload) 4 | 5 | @spec name(struct()) :: String.t() 6 | def name(upload) 7 | end 8 | 9 | defimpl Capsule.Upload, for: Capsule.Locator do 10 | def contents(locator), do: Capsule.storage!(locator).read(locator.id) 11 | 12 | def name(%{metadata: %{name: name}}), do: name 13 | def name(%{id: id}), do: id 14 | end 15 | -------------------------------------------------------------------------------- /lib/capsule/uploader.ex: -------------------------------------------------------------------------------- 1 | defmodule Capsule.Uploader do 2 | alias Capsule.Locator 3 | 4 | @type storage :: atom() 5 | @type option :: {atom(), any()} 6 | 7 | @callback store(any(), storage, [option]) :: {:ok, Locator.t()} | {:error, any()} 8 | @callback build_options(any(), storage, [option]) :: [option] 9 | @callback build_metadata(Locator.t(), storage, [option]) :: Keyword.t() | map() 10 | 11 | defmacro __using__(opts) do 12 | quote bind_quoted: [opts: opts] do 13 | @behaviour Capsule.Uploader 14 | 15 | @storages Keyword.fetch!(opts, :storages) 16 | 17 | @impl Capsule.Uploader 18 | def store(upload, storage_key, opts \\ []) do 19 | storage = fetch_storage!(upload, storage_key) 20 | 21 | upload 22 | |> storage.put(build_options(upload, storage_key, opts)) 23 | |> case do 24 | {:ok, id} -> 25 | locator = 26 | Capsule.add_metadata( 27 | Locator.new!(id: id, storage: storage), 28 | build_metadata(upload, storage_key, opts) 29 | ) 30 | 31 | {:ok, locator} 32 | 33 | error_tuple -> 34 | error_tuple 35 | end 36 | end 37 | 38 | @impl Capsule.Uploader 39 | def build_metadata(_, _, _), do: [] 40 | 41 | @impl Capsule.Uploader 42 | def build_options(_, _, instance_opts), do: instance_opts 43 | 44 | defp fetch_storage!(upload, storage) do 45 | @storages 46 | |> case do 47 | {m, f, a} -> apply(m, f, [upload | a]) 48 | storages when is_list(storages) -> storages 49 | end 50 | |> Keyword.fetch(storage) 51 | |> case do 52 | {:ok, storage} -> 53 | storage 54 | 55 | _ -> 56 | raise "#{storage} not found in #{__MODULE__} storages. Available: #{inspect(Keyword.keys(@storages))}" 57 | end 58 | end 59 | 60 | defoverridable build_options: 3, build_metadata: 3 61 | end 62 | end 63 | end 64 | -------------------------------------------------------------------------------- /lib/errors/invalid_locator.ex: -------------------------------------------------------------------------------- 1 | defmodule Capsule.Errors.InvalidLocator do 2 | defexception message: "locator is invalid" 3 | end 4 | -------------------------------------------------------------------------------- /lib/errors/invalid_storage.ex: -------------------------------------------------------------------------------- 1 | defmodule Capsule.Errors.InvalidStorage do 2 | defexception message: "storage is invalid" 3 | end 4 | -------------------------------------------------------------------------------- /mix.exs: -------------------------------------------------------------------------------- 1 | defmodule Capsule.MixProject do 2 | use Mix.Project 3 | 4 | def project do 5 | [ 6 | app: :capsule, 7 | description: "Uploaded file management for Elixir", 8 | version: "0.10.0", 9 | elixir: "~> 1.11", 10 | start_permanent: Mix.env() == :prod, 11 | deps: deps(), 12 | dialyzer: dialyzer(), 13 | elixirc_paths: elixirc_paths(Mix.env()), 14 | name: "Capsule", 15 | source_url: "https://github.com/elixir-capsule/capsule", 16 | package: package() 17 | ] 18 | end 19 | 20 | # Run "mix help compile.app" to learn about applications. 21 | def application do 22 | [ 23 | extra_applications: [:logger, :inets] 24 | ] 25 | end 26 | 27 | # Run "mix help deps" to learn about dependencies. 28 | defp deps do 29 | [ 30 | {:ex_doc, ">= 0.0.0", only: :dev, runtime: false}, 31 | {:dialyxir, "~> 1.0", only: :dev, runtime: false} 32 | ] 33 | end 34 | 35 | defp dialyzer do 36 | [ 37 | plt_core_path: "priv/plts", 38 | plt_file: {:no_warn, "priv/plts/dialyzer.plt"} 39 | ] 40 | end 41 | 42 | defp elixirc_paths(:test), do: ["lib", "test/support"] 43 | defp elixirc_paths(_), do: ["lib"] 44 | 45 | defp package do 46 | [ 47 | maintainers: ["Thomas Floyd Wright"], 48 | licenses: ["Apache-2.0"], 49 | links: %{"GitHub" => "https://github.com/elixir-capsule/capsule"} 50 | ] 51 | end 52 | end 53 | -------------------------------------------------------------------------------- /mix.lock: -------------------------------------------------------------------------------- 1 | %{ 2 | "dialyxir": {:hex, :dialyxir, "1.0.0", "6a1fa629f7881a9f5aaf3a78f094b2a51a0357c843871b8bc98824e7342d00a5", [:mix], [{:erlex, ">= 0.2.6", [hex: :erlex, repo: "hexpm", optional: false]}], "hexpm", "aeb06588145fac14ca08d8061a142d52753dbc2cf7f0d00fc1013f53f8654654"}, 3 | "earmark_parser": {:hex, :earmark_parser, "1.4.10", "6603d7a603b9c18d3d20db69921527f82ef09990885ed7525003c7fe7dc86c56", [:mix], [], "hexpm", "8e2d5370b732385db2c9b22215c3f59c84ac7dda7ed7e544d7c459496ae519c0"}, 4 | "erlex": {:hex, :erlex, "0.2.6", "c7987d15e899c7a2f34f5420d2a2ea0d659682c06ac607572df55a43753aa12e", [:mix], [], "hexpm", "2ed2e25711feb44d52b17d2780eabf998452f6efda104877a3881c2f8c0c0c75"}, 5 | "ex_doc": {:hex, :ex_doc, "0.22.2", "03a2a58bdd2ba0d83d004507c4ee113b9c521956938298eba16e55cc4aba4a6c", [:mix], [{:earmark_parser, "~> 1.4.0", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_elixir, "~> 0.14", [hex: :makeup_elixir, repo: "hexpm", optional: false]}], "hexpm", "cf60e1b3e2efe317095b6bb79651f83a2c1b3edcb4d319c421d7fcda8b3aff26"}, 6 | "makeup": {:hex, :makeup, "1.0.3", "e339e2f766d12e7260e6672dd4047405963c5ec99661abdc432e6ec67d29ef95", [:mix], [{:nimble_parsec, "~> 0.5", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "2e9b4996d11832947731f7608fed7ad2f9443011b3b479ae288011265cdd3dad"}, 7 | "makeup_elixir": {:hex, :makeup_elixir, "0.14.1", "4f0e96847c63c17841d42c08107405a005a2680eb9c7ccadfd757bd31dabccfb", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "f2438b1a80eaec9ede832b5c41cd4f373b38fd7aa33e3b22d9db79e640cbde11"}, 8 | "nimble_parsec": {:hex, :nimble_parsec, "0.6.0", "32111b3bf39137144abd7ba1cce0914533b2d16ef35e8abc5ec8be6122944263", [:mix], [], "hexpm", "27eac315a94909d4dc68bc07a4a83e06c8379237c5ea528a9acff4ca1c873c52"}, 9 | } 10 | -------------------------------------------------------------------------------- /test/capsule/locator_test.exs: -------------------------------------------------------------------------------- 1 | defmodule Capsule.LocatorTest do 2 | use ExUnit.Case 3 | doctest Capsule 4 | 5 | alias Capsule.Locator 6 | 7 | describe "new/1 with keyword list" do 8 | test "returns struct" do 9 | assert {:ok, %Locator{}} = Locator.new(id: "fake", storage: "Fake") 10 | end 11 | end 12 | 13 | describe "new/1 with map with required string keys" do 14 | test "returns struct" do 15 | assert {:ok, %Locator{}} = Locator.new(%{"id" => "fake", "storage" => "Fake"}) 16 | end 17 | end 18 | 19 | describe "new/1 with map with atom storage" do 20 | test "returns struct" do 21 | assert {:ok, %Locator{}} = Locator.new(%{id: "fake", storage: Capsule.Storages.Mock}) 22 | end 23 | end 24 | 25 | describe "new/1 with map with required atom keys" do 26 | test "returns struct" do 27 | assert {:ok, %Locator{}} = Locator.new(%{id: "fake", storage: "Fake"}) 28 | end 29 | end 30 | 31 | describe "new/1 with map missing keys" do 32 | test "returns struct" do 33 | assert {:error, _} = Locator.new(%{id: "fake"}) 34 | end 35 | end 36 | 37 | describe "new/1 with map with invalid id type" do 38 | test "returns error" do 39 | assert {:error, _} = Locator.new(%{id: 5, storage: "fake"}) 40 | end 41 | end 42 | 43 | describe "new/1 with map with nil storage" do 44 | test "returns error" do 45 | assert {:error, _} = Locator.new(%{id: "fake", storage: nil}) 46 | end 47 | end 48 | 49 | describe "new! with nil id" do 50 | test "raises error" do 51 | assert_raise(Capsule.Errors.InvalidLocator, fn -> 52 | Locator.new!(%{"id" => nil}) 53 | end) 54 | end 55 | end 56 | end 57 | -------------------------------------------------------------------------------- /test/capsule/upload_test.exs: -------------------------------------------------------------------------------- 1 | defmodule Capsule.UploadTest do 2 | use ExUnit.Case 3 | doctest Capsule 4 | 5 | alias Capsule.{Upload, Locator} 6 | 7 | describe "Locator" do 8 | test "name returns name metadata if present" do 9 | assert "test" = Upload.name(%Locator{metadata: %{name: "test"}}) 10 | end 11 | end 12 | end 13 | -------------------------------------------------------------------------------- /test/capsule/uploader_test.exs: -------------------------------------------------------------------------------- 1 | defmodule Capsule.UploaderTest do 2 | use ExUnit.Case 3 | doctest Capsule 4 | 5 | alias Capsule.{Locator, Uploader} 6 | 7 | defmodule BasicUploader do 8 | use Uploader, storages: [temp: Capsule.Storages.Mock, perm: Capsule.Storages.Mock] 9 | end 10 | 11 | defmodule DynamicUploader do 12 | use Uploader, storages: {__MODULE__, :get_storages, []} 13 | 14 | def get_storages(_), do: [temp: Capsule.Storages.Mock] 15 | end 16 | 17 | describe "store/2 with basic uploader and valid storage key" do 18 | setup do 19 | %{result: BasicUploader.store(%Locator{id: "fake"}, :temp)} 20 | end 21 | 22 | test "succeeds", %{result: result} do 23 | assert {:ok, _} = result 24 | end 25 | 26 | test "returns locator", %{result: result} do 27 | assert {_, %Locator{}} = result 28 | end 29 | end 30 | 31 | describe "store/2 with basic uploader invalid storage key" do 32 | test "raises" do 33 | assert_raise(RuntimeError, fn -> 34 | BasicUploader.store(%Locator{id: "fake"}, :wrong) 35 | end) 36 | end 37 | end 38 | 39 | describe "store/2 with dynamic uploader and valid storage key" do 40 | setup do 41 | %{result: BasicUploader.store(%Locator{id: "fake"}, :temp)} 42 | end 43 | 44 | test "succeeds", %{result: result} do 45 | assert {:ok, _} = result 46 | end 47 | end 48 | end 49 | -------------------------------------------------------------------------------- /test/capsule_test.exs: -------------------------------------------------------------------------------- 1 | defmodule CapsuleTest do 2 | use ExUnit.Case 3 | doctest Capsule 4 | 5 | alias Capsule.Locator 6 | 7 | describe "add_metadata/2 with map" do 8 | test "merges data into existing metadata" do 9 | assert %{metadata: %{"a" => 1, "b" => 2}} = 10 | Capsule.add_metadata(%Locator{metadata: %{"a" => 1}}, %{b: 2}) 11 | end 12 | end 13 | 14 | describe "add_metadata/2 with list" do 15 | test "merges data into existing metadata" do 16 | assert %{metadata: %{"a" => 1, "b" => 2}} = 17 | Capsule.add_metadata(%Locator{metadata: %{"a" => 1}}, b: 2) 18 | end 19 | end 20 | 21 | describe "add_metadata/3" do 22 | test "merges val into existing metadata at given key" do 23 | assert %{metadata: %{"a" => 1, "b" => 2}} = 24 | Capsule.add_metadata(%Locator{metadata: %{"a" => 1}}, :b, 2) 25 | end 26 | end 27 | 28 | describe "storage!/1 with binary storage" do 29 | test "returns storage module" do 30 | assert Capsule.Storages.Mock = 31 | Capsule.storage!(%Locator{storage: "Elixir.Capsule.Storages.Mock"}) 32 | end 33 | 34 | test "handles storage without Elixir prefix" do 35 | assert Capsule.Storages.Mock = Capsule.storage!(%Locator{storage: "Capsule.Storages.Mock"}) 36 | end 37 | 38 | test "raises error on invalid storage" do 39 | assert_raise Capsule.Errors.InvalidStorage, fn -> 40 | Capsule.storage!(%Locator{storage: "what"}) 41 | end 42 | end 43 | end 44 | 45 | describe "storage!/1 with atom storage" do 46 | test "returns storage module" do 47 | assert Capsule.Storages.Mock = Capsule.storage!(%Locator{storage: Capsule.Storages.Mock}) 48 | end 49 | 50 | test "returns module" do 51 | assert Capsule.Storages.Mock = Capsule.storage!(%Locator{storage: "Capsule.Storages.Mock"}) 52 | end 53 | end 54 | end 55 | -------------------------------------------------------------------------------- /test/support/mock_storage.ex: -------------------------------------------------------------------------------- 1 | defmodule Capsule.Storages.Mock do 2 | alias Capsule.Storage 3 | 4 | @behaviour Storage 5 | 6 | @impl Storage 7 | def put(_id, opts \\ []) do 8 | {:ok, Keyword.get(opts, :id, to_string(:erlang.ref_to_list(:erlang.make_ref())))} 9 | end 10 | 11 | @impl Storage 12 | def delete(_id, _opts \\ []), do: {:ok, nil} 13 | 14 | @impl Storage 15 | def read(_id, _opts \\ []), do: {:ok, "mock file contents"} 16 | 17 | @impl Storage 18 | def stream!(_id, _opts \\ []), 19 | do: "mock file contents" |> StringIO.open() |> elem(1) |> IO.stream(:line) 20 | end 21 | -------------------------------------------------------------------------------- /test/test_helper.exs: -------------------------------------------------------------------------------- 1 | ExUnit.start() 2 | --------------------------------------------------------------------------------