debian-mirror-gitlab/lib/gitlab/gfm/uploads_rewriter.rb

70 lines
1.7 KiB
Ruby
Raw Normal View History

2019-02-15 15:39:39 +05:30
# frozen_string_literal: true
2017-08-17 22:00:37 +05:30
require 'fileutils'
2016-06-02 11:05:42 +05:30
module Gitlab
module Gfm
##
# Class that rewrites markdown links for uploads
#
# Using a pattern defined in `FileUploader` it copies files to a new
2019-02-15 15:39:39 +05:30
# project and rewrites all links to uploads in a given text.
2016-06-02 11:05:42 +05:30
#
#
class UploadsRewriter
def initialize(text, source_project, _current_user)
@text = text
@source_project = source_project
@pattern = FileUploader::MARKDOWN_PATTERN
end
2019-02-15 15:39:39 +05:30
def rewrite(target_parent)
2016-06-02 11:05:42 +05:30
return @text unless needs_rewrite?
@text.gsub(@pattern) do |markdown|
2020-03-28 13:19:24 +05:30
Gitlab::Utils.check_path_traversal!($~[:file])
2016-06-02 11:05:42 +05:30
file = find_file(@source_project, $~[:secret], $~[:file])
2018-10-15 14:42:47 +05:30
break markdown unless file.try(:exists?)
2016-06-02 11:05:42 +05:30
2019-02-15 15:39:39 +05:30
klass = target_parent.is_a?(Namespace) ? NamespaceFileUploader : FileUploader
moved = klass.copy_to(file, target_parent)
2019-10-12 21:52:04 +05:30
moved_markdown = moved.markdown_link
# Prevents rewrite of plain links as embedded
if was_embedded?(markdown)
moved_markdown
else
moved_markdown.sub(/\A!/, "")
end
2016-06-02 11:05:42 +05:30
end
end
def needs_rewrite?
files.any?
end
def files
referenced_files = @text.scan(@pattern).map do
find_file(@source_project, $~[:secret], $~[:file])
end
referenced_files.compact.select(&:exists?)
end
2019-10-12 21:52:04 +05:30
def was_embedded?(markdown)
markdown.starts_with?("!")
end
2016-06-02 11:05:42 +05:30
private
def find_file(project, secret, file)
2018-03-17 18:26:18 +05:30
uploader = FileUploader.new(project, secret: secret)
2016-06-02 11:05:42 +05:30
uploader.retrieve_from_store!(file)
2018-11-08 19:23:39 +05:30
uploader
2017-08-17 22:00:37 +05:30
end
2016-06-02 11:05:42 +05:30
end
end
end