aboutsummaryrefslogtreecommitdiffstats
path: root/lib/biberon.rb
blob: c578b75f79bd61d3e9e26745c5da1e60943ae5b6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# frozen_string_literal: true

require 'date'
require 'roda'
require 'r18n-core'
require_relative 'biberon/models'

R18n.default_places = File.expand_path('../locales', __dir__)

module Biberon
  # Main application, associates resources with their corresponding classes
  class App < Roda
    plugin :render, engine: 'slim', layout: 'layout'
    plugin :public, gzip: true, brotli: true
    plugin :route_csrf
    plugin :sessions, secret: ENV.fetch('BIBERON_SESSION_SECRET'),
                      key: 'biberon_auth'
    plugin :cookies, domain: ENV.fetch('BIBERON_COOKIE_DOMAIN'),
                     path: '/', httponly: true,
                     secure: ENV.fetch('RACK_ENV', 'development') != 'development' # rubocop:disable Layout/LineLength

    # Log to stderr
    plugin :common_logger

    route do |r|
      r.public

      check_csrf!
      @_cookie = parse_cookie

      R18n.set cookie('l', 'fr')
      @settings = cookie('c', 'c,t,u,v,w,l,r').split(',')

      r.root do
        r.redirect "/#{session['baby_id']}" if session['baby_id']
        @title = R18n.t.home
        view 'index'
      end

      r.on 'session' do
        r.post 'create' do
          params = request.params
          clear_session
          if params['name'] && !params['name'].empty? && params['password']
            baby = ::Biberon::Baby.first(name: params['name'])
            if baby.check_password(params['password'])
              session['baby_id'] = baby.id
              r.redirect "/#{baby.id}"
            end
          end
          r.redirect '/'
        end

        r.get 'logout' do
          clear_session
          r.redirect '/'
        end
      end

      r.is 'settings' do
        @title = R18n.t.settings.settings

        r.get { view 'settings' }

        r.post do
          params = request.params
          settings = []
          if params['lang'] && ['fr', 'en'].include?(params['lang'])
            settings << "l:#{params['lang']}"
          end
          opts = []
          ['comment', 'temp', 'urines', 'vitamind', 'weight',
           'left_breast', 'right_breast'].each do |opt_name|
            opts << opt_name[0] if params[opt_name]
          end
          settings << "c:#{opts.join(',')}"
          response.set_cookie('biberon_settings', settings.join(';'))
          r.redirect '/'
        end
      end

      r.on Integer do |baby_id|
        r.redirect '/' unless session['baby_id'] == baby_id
        @baby = ::Biberon::Baby[baby_id]
        r.redirect '/' unless @baby
        @title = @baby.name
        @errors = nil

        r.get true do
          @today = Date.today
          view 'baby'
        end

        r.get 'json' do
          response['Content-Type'] = 'application/json'
          @baby.statistics.to_json
        end

        r.get('graph') { view 'graph' }

        r.get Integer do |date|
          @today = Date.strptime(date.to_s, '%Y%m%d')
          view 'baby'
        end

        r.post 'add' do
          params = request.params
          params['baby_id'] = @baby.id
          bib = ::Biberon::Biberon.new
          bib.set_fields(
            params,
            ['baby_id', 'quantity', 'weight', 'comment',
             'feces', 'urines', 'vitamind', 'temperature',
             'left_breast', 'right_breast']
          )
          bib.datetime = DateTime.strptime(
            "#{params['date']} #{params['time']}",
            '%Y%m%d %H:%M'
          )
          if bib.valid? && bib.save_changes
            redirect_to_date(r, @baby.id, params['date'])
          end
          @errors = bib.errors
          @today = Date.strptime(params['date'], '%Y%m%d')
          view 'baby'
        end

        r.post 'delete' do
          params = request.params
          bib_id = DateTime.strptime(
            "#{params['date']} #{params['time']}",
            '%Y%m%d %H:%M'
          )
          bib = @baby.biberons_dataset.where(datetime: bib_id)
          bib&.destroy
          redirect_to_date(r, @baby.id, params['date'])
        end
      end
    end

    private

    def redirect_to_date(routing, baby_id, date)
      route = "/#{baby_id}"
      route = "#{route}/#{date}" if date != Date.today.strftime('%Y%m%d')
      routing.redirect route
    end

    def cookie(key, default)
      @_cookie[key] || default
    end

    def parse_cookie
      bib_settings = request.cookies['biberon_settings'] || ''
      bib_settings.split(';').to_h do |cook|
        cook.split(':').tap { |data| data[1] ||= '-' }
      end
    end

    # rubocop:disable Layout/LineLength
    # :reek:FeatureEnvy
    def logger(message, level = :info)
      env = request.env
      $stderr << "#{env['HTTP_X_FORWARDED_FOR'] || env['REMOTE_ADDR'] || '-'} - #{env['REMOTE_USER'] || '-'} [#{Time.now.strftime('%d/%b/%Y:%H:%M:%S %z')}] [#{level.to_s.upcase}] #{message}\n"
    end
    # rubocop:enable Layout/LineLength
  end
end