Class: Murlsh::UrlServer

Inherits:
Object
  • Object
show all
Includes:
HeadFromGet
Defined in:
lib/murlsh/url_server.rb

Overview

Build responses for HTTP requests.

Instance Method Summary collapse

Methods included from HeadFromGet

#head

Constructor Details

#initialize(config) ⇒ UrlServer

Returns a new instance of UrlServer.



11
12
13
# File 'lib/murlsh/url_server.rb', line 11

def initialize(config)
  @config = config
end

Instance Method Details

#get(req) ⇒ Object

Respond to a GET request. Return a page of urls based on the query string parameters.



17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/murlsh/url_server.rb', line 17

def get(req)
  last_db_update = File::Stat.new(@config['db_file']).mtime

  resp = Rack::Response.new

  resp['Cache-Control'] = 'must-revalidate, max-age=0'
  resp['Content-Type'] = 'text/html; charset=utf-8'
  resp['ETag'] = "W/\"#{last_db_update.to_i}#{req.params.sort}\""
  resp['Last-Modified'] = last_db_update.httpdate

  resp.body = Murlsh::UrlBody.new(@config, req, resp['Content-Type'])

  resp
end

#post(req) ⇒ Object

Respond to a POST request. Add the new url and return json.



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
# File 'lib/murlsh/url_server.rb', line 33

def post(req)
  auth = req.params['auth']
  if user = auth.empty? ? nil : Murlsh::Auth.new(
    @config.fetch('auth_file')).auth(auth)

    mu = Murlsh::Url.new do |u|
      u.time = if req.params['time']
        Time.at(req.params['time'].to_f).utc
      else
        Time.now.utc
      end
      u.url = req.params['url']
      u.email = user[:email]
      u.name = user[:name]
      u.via = req.params['via']  unless req.params['via'].to_s.empty?
    end

    begin
      # validate before add_pre plugins have run and also after (in save!)
      raise ActiveRecord::RecordInvalid.new(mu)  unless mu.valid?
      Murlsh::Plugin.hooks('add_pre') { |p| p.run mu, @config }
      mu.save!
      Murlsh::Plugin.hooks('add_post') { |p| p.run mu, @config }
      response_body, response_code = [mu], 200
    rescue ActiveRecord::RecordInvalid => error
      response_body = {
        'url' => error.record,
        'errors' => error.record.errors,
        }
      response_code = 500
    end
  else
    response_body, response_code = '', 403
  end

  Rack::Response.new(response_body.to_json, response_code, {
    'Content-Type' => 'application/json' })
end