Packages

A Slack Web API client generatef from their OpenAPI specs.

Current section

Files

Jump to
box lib box.ex
Raw

lib/box.ex

defmodule Box do
@moduledoc """
Box file sharing API client.
"""
alias Tesla.Multipart
@box_api_url "https://api.box.com/2.0"
@box_upload_url "https://upload.box.com/api/2.0"
@doc """
folder_items returns the items in a folder.
"""
def folder_items(client, folder, fields \\ []) do
{:ok, response} =
Tesla.get(client, @box_api_url <> "/folders/#{folder}/items",
query: [fields: Enum.join(fields, ",")]
)
{:ok, response.body}
end
@doc """
folder_from_path returns the folder id for a path in Box
"""
def folder_from_path(_client, path) do
if path == "/" or path == "." do
{:ok, %{id: "0"}}
else
# TODO: fetch id for other paths
raise "not implemented: folder_from_path #{path}"
end
end
@doc """
file_from_path returns the file name and id for a path in Box
"""
def file_from_path(client, path) do
filename = Path.basename(path)
{:ok, folder} = folder_from_path(client, Path.dirname(path))
{:ok, files} = folder_items(client, folder.id, [:id, :name])
case Enum.find(files.entries, fn f -> f.type == "file" and f.name == filename end) do
nil -> {:error, "file not found"}
f -> {:ok, f}
end
end
@doc """
create_shared_link from a file.
"""
def create_shared_link(client, file_id) do
# https://developer.box.com/reference#shared-link-object
{:ok, response} =
Tesla.put(client, @box_api_url <> "/files/#{file_id}", %{
shared_link: %{
access: "open",
# TODO: password, unshared_at?
permissions: %{
can_download: true
}
}
})
{:ok, response.body}
end
def file_info(client, file_id) do
fields = [
:type,
:id,
:sequence_id,
:etag,
:name,
:created_at,
:modified_at,
:description,
:size,
:path_collection,
:created_by,
:modified_by,
:trashed_at,
:purged_at,
:content_created_at,
:content_modified_at,
:owned_by,
:shared_link,
:folder_upload_email,
:parent,
:item_status,
:item_collection,
:sync_state,
:has_collaborations,
:permissions,
:tags,
:sha1,
:shared_link,
:version_number,
:comment_count,
:lock,
:extension,
:is_package,
:can_non_owners_invite
]
{:ok, response} =
Tesla.get(client, @box_api_url <> "/files/#{file_id}",
query: [fields: Enum.join(fields, ",")]
)
{:ok, response.body}
end
def upload(client, path, folder_id, name) do
attributes =
Jason.encode!(%{
name: name,
parent: %{id: folder_id}
})
mp =
Multipart.new()
|> Multipart.add_field("attributes", attributes)
|> Multipart.add_file(path)
{:ok, response} = Tesla.post(client, @box_upload_url <> "/files/content", mp)
case response.status do
201 ->
{:ok, response.body}
_ ->
{:error, response.status, response.body}
end
end
end