summaryrefslogtreecommitdiff
path: root/app/controllers/concerns/snippets_actions.rb
blob: b12aee346eda82f68ac3341a37350283dbbfc4d0 (plain)
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
# frozen_string_literal: true

module SnippetsActions
  extend ActiveSupport::Concern
  include SendsBlob

  def edit
    # We need to load some info from the existing blob
    snippet.content = blob.data
    snippet.file_name = blob.path

    render 'edit'
  end

  def raw
    workhorse_set_content_type!

    # Until we don't migrate all snippets to version
    # snippets we need to support old `SnippetBlob`
    # blobs
    if defined?(blob.snippet)
      send_data(
        convert_line_endings(blob.data),
        type: 'text/plain; charset=utf-8',
        disposition: content_disposition,
        filename: Snippet.sanitized_file_name(blob.name)
      )
    else
      send_blob(
        snippet.repository,
        blob,
        inline: content_disposition == 'inline',
        allow_caching: snippet.public?
      )
    end
  end

  def js_request?
    request.format.js?
  end

  private

  def content_disposition
    @disposition ||= params[:inline] == 'false' ? 'attachment' : 'inline'
  end

  # rubocop:disable Gitlab/ModuleWithInstanceVariables
  def blob
    return unless snippet

    @blob ||= if Feature.enabled?(:version_snippets, current_user) && !snippet.repository.empty?
                snippet.blobs.first
              else
                snippet.blob
              end
  end
  # rubocop:enable Gitlab/ModuleWithInstanceVariables

  def convert_line_endings(content)
    params[:line_ending] == 'raw' ? content : content.gsub(/\r\n/, "\n")
  end

  def check_repository_error
    repository_errors = Array(snippet.errors.delete(:repository))

    flash.now[:alert] = repository_errors.first if repository_errors.present?
    recaptcha_check_with_fallback(repository_errors.empty?) { render :edit }
  end
end