Skip to content

Instantly share code, notes, and snippets.

@dmitriid
Last active February 25, 2016 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmitriid/9aa808e8f5b7ce2fcb2d to your computer and use it in GitHub Desktop.
Save dmitriid/9aa808e8f5b7ce2fcb2d to your computer and use it in GitHub Desktop.
Auto screenshot uploader w/Elixir

Running

> ies -S mix
elixir> Slax.Monitor start

Source

##mix.exs

defmodule Slax.Mixfile do
  use Mix.Project

  def project do
    [app: :slax,
     version: "0.0.1",
     elixir: "~> 1.2",
     build_embedded: Mix.env == :prod,
     start_permanent: Mix.env == :prod,
     deps: deps]
  end

  def application do
    [applications: [:logger, :ex_aws, :httpoison, :exfswatch]]
  end

  defp deps do
    [
      ex_aws:    "~> 0.4.10",
      poison:    "~> 1.2",
      httpoison: "~> 0.7",
      zbase32: "~> 1.0.0",
      arc: "~> 0.3.0",
      exfswatch: "~> 0.1.0"
    ]
  end
end

config/config.exs

use Mix.Config

config :slax, :ex_aws,
   access_key_id: "s3_access_key",
   secret_access_key: "s3_secret_key",
   region: "us-east-1"

##lib/slax.ex

defmodule Slax do
  use ExAws.S3.Client, otp_app: :slax
  require Logger

  def go(path0) do
    path = path0 |> String.strip
    contents = path |> File.read!

    name = "#{path |> Path.basename |> :erlang.adler32 |> Integer.to_string |> ZBase32.encode}#{path |> Path.extname}"

    size = File.stat!(path).size |> Integer.to_string

    put_object("media.dmitriid.com/i",
              name,
              contents,
              [ {:content_type, "image/png"},
                {:content_length, size},
                {:acl, :public_read}
              ])
    "http://dmitriid.com/i/#{name}" |> IO.puts
    #Slax.TempImg.store(path)

  end
end

##lib/slax.monitor.ex

defmodule Slax.Monitor do
  use ExFSWatch, dirs: ["/Users/dmitriid/Desktop"]
  def callback(:stop) do
    IO.puts "STOP"
  end

  def callback(file_path, events0) do
    events = events0 |> List.flatten

    is_worth_it = (:created in events) or (:renamed in events) or (:modified in events)
    exists = File.exists?(file_path)
    uploadable = Regex.match? ~r/(\.png|\.jpeg|\.jpg|\.gif)/, Path.extname(file_path)

    case is_worth_it and exists and uploadable do
      true ->
        IO.inspect "Uploading #{file_path}"
        result = Slax.go file_path
        IO.inspect result
        IO.inspect ""
      false ->
        :ok
    end
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment