Class: Defile::App

Inherits:
Object
  • Object
show all
Defined in:
lib/defile/app.rb

Defined Under Namespace

Classes: Proxy

Instance Method Summary collapse

Constructor Details

#initialize(logger: nil, allow_origin: nil) ⇒ App

Returns a new instance of App.



6
7
8
9
10
# File 'lib/defile/app.rb', line 6

def initialize(logger: nil, allow_origin: nil)
  @logger = logger
  @logger ||= ::Logger.new(nil)
  @allow_origin = allow_origin
end

Instance Method Details

#call(env) ⇒ Object



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
72
73
74
75
76
77
78
79
# File 'lib/defile/app.rb', line 28

def call(env)
  @logger.info { "Defile: #{env["REQUEST_METHOD"]} #{env["PATH_INFO"]}" }
  if env["REQUEST_METHOD"] == "GET"
    backend_name, *process_args, id, filename = env["PATH_INFO"].sub(/^\//, "").split("/")
    backend = Defile.backends[backend_name]

    if backend and id
      @logger.debug { "Defile: serving #{id.inspect} from #{backend_name} backend which is of type #{backend.class}" }

      file = backend.get(id)

      unless process_args.empty?
        name = process_args.shift
        unless Defile.processors[name]
          @logger.debug { "Defile: no such processor #{name.inspect}" }
          return not_found
        end
        file = Defile.processors[name].call(file, *process_args)
      end

      peek = begin
        file.read(Defile.read_chunk_size)
      rescue => e
        log_error(e)
        return not_found
      end

      headers = {}
      headers["Access-Control-Allow-Origin"] = @allow_origin if @allow_origin

      [200, headers, Proxy.new(peek, file)]
    else
      @logger.debug { "Defile: must specify backend and id" }
      not_found
    end
  elsif env["REQUEST_METHOD"] == "POST"
    backend_name, *rest = env["PATH_INFO"].sub(/^\//, "").split("/")
    backend = Defile.backends[backend_name]

    return not_found unless rest.empty?
    return not_found unless backend and Defile.direct_upload.include?(backend_name)

    file = backend.upload(Rack::Request.new(env).params.fetch("file").fetch(:tempfile))
    [200, { "Content-Type" => "application/json" }, [{ id: file.id }.to_json]]
  else
    @logger.debug { "Defile: request methods other than GET and POST are not allowed" }
    not_found
  end
rescue => e
  log_error(e)
  [500, {}, ["error"]]
end