BigW Consortium Gitlab

file_uploader.rb 1.82 KB
Newer Older
1
class FileUploader < GitlabUploader
2
  include RecordsUploads
3
  include UploaderHelper
4

5
  MARKDOWN_PATTERN = %r{\!?\[.*?\]\(/uploads/(?<secret>[0-9a-f]{32})/(?<file>.*?)\)}
6

7 8
  storage :file

9 10 11 12 13 14 15
  def self.absolute_path(upload_record)
    File.join(
      self.dynamic_path_segment(upload_record.model),
      upload_record.path
    )
  end

16 17 18 19 20 21 22
  # Not using `GitlabUploader.base_dir` because all project namespaces are in
  # the `public/uploads` dir.
  #
  def self.base_dir
    root_dir
  end

23 24 25 26 27 28 29 30 31 32 33 34 35
  # Returns the part of `store_dir` that can change based on the model's current
  # path
  #
  # This is used to build Upload paths dynamically based on the model's current
  # namespace and path, allowing us to ignore renames or transfers.
  #
  # model - Object that responds to `path_with_namespace`
  #
  # Returns a String without a trailing slash
  def self.dynamic_path_segment(model)
    File.join(CarrierWave.root, base_dir, model.path_with_namespace)
  end

36
  attr_accessor :model
37
  attr_reader :secret
38

39 40
  def initialize(model, secret = nil)
    @model = model
41
    @secret = secret || generate_secret
42 43 44
  end

  def store_dir
45
    File.join(dynamic_path_segment, @secret)
46 47
  end

48 49 50 51
  def relative_path
    self.file.path.sub("#{dynamic_path_segment}/", '')
  end

52 53 54 55
  def to_markdown
    to_h[:markdown]
  end

56
  def to_h
57
    filename = image_or_video? ? self.file.basename : self.file.filename
58 59
    escaped_filename = filename.gsub("]", "\\]")

60
    markdown = "[#{escaped_filename}](#{secure_url})"
61
    markdown.prepend("!") if image_or_video? || dangerous?
62 63 64

    {
      alt:      filename,
65
      url:      secure_url,
66 67 68
      markdown: markdown
    }
  end
69

70 71
  private

72 73 74 75
  def dynamic_path_segment
    self.class.dynamic_path_segment(model)
  end

76
  def generate_secret
77 78
    SecureRandom.hex
  end
79 80 81 82

  def secure_url
    File.join('/uploads', @secret, file.filename)
  end
83
end