Class: CopyTunerClient::CopyrayMiddleware

Inherits:
Object
  • Object
show all
Defined in:
lib/copy_tuner_client/copyray_middleware.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ CopyrayMiddleware

Returns a new instance of CopyrayMiddleware.



7
8
9
# File 'lib/copy_tuner_client/copyray_middleware.rb', line 7

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/copy_tuner_client/copyray_middleware.rb', line 11

def call(env)
  CopyTunerClient::TranslationLog.clear
  status, headers, response = @app.call(env)
  if html_headers?(status, headers) && body = response_body(response)
    csp_nonce = env['action_dispatch.content_security_policy_nonce'] || env['secure_headers_content_security_policy_nonce']
    # NOTE: CSS/JS 挿入の前に Rewriter を通す。serialize 後も </body> は必ず出力されるので
    # append_to_html_body の rindex は機能し、CSS/JS タグはトークン非含有なので二重処理も起きない。
    # NOTE: skipped は data-copyray-key を付与できなかったこと(巨大DOM/Nokogiri例外)を表す。
    # JS にこれを伝え、オーバーレイ非対応である旨をツールバーで案内させる。
    body, skipped = CopyTunerClient::Copyray::Rewriter.rewrite(body)
    body = append_css(body, csp_nonce)
    body = append_js(body, csp_nonce, skipped: skipped)
    content_length = body.bytesize.to_s
    headers['Content-Length'] = content_length
    # maintains compatibility with other middlewares
    if defined?(ActionDispatch::Response::RackBody) && ActionDispatch::Response::RackBody === response
      ActionDispatch::Response.new(status, headers, [body]).to_a
    else
      [status, headers, [body]]
    end
  else
    [status, headers, response]
  end
end