debian-mirror-gitlab/app/services/wikis/create_attachment_service.rb

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

87 lines
2.3 KiB
Ruby
Raw Normal View History

2018-11-20 20:47:30 +05:30
# frozen_string_literal: true
module Wikis
class CreateAttachmentService < Files::CreateService
2019-12-04 20:38:33 +05:30
ATTACHMENT_PATH = 'uploads'
2018-11-20 20:47:30 +05:30
MAX_FILENAME_LENGTH = 255
2020-05-24 23:13:21 +05:30
attr_reader :container
delegate :wiki, to: :container
2018-11-20 20:47:30 +05:30
delegate :repository, to: :wiki
2020-05-24 23:13:21 +05:30
def initialize(container:, current_user: nil, params: {})
super(nil, current_user, params)
2018-11-20 20:47:30 +05:30
2020-05-24 23:13:21 +05:30
@container = container
2018-11-20 20:47:30 +05:30
@file_name = clean_file_name(params[:file_name])
@file_path = File.join(ATTACHMENT_PATH, SecureRandom.hex, @file_name) if @file_name
@commit_message ||= "Upload attachment #{@file_name}"
@branch_name ||= wiki.default_branch
end
def create_commit!
2021-09-30 23:02:18 +05:30
wiki.create_wiki_repository
2018-11-20 20:47:30 +05:30
commit_result(create_transformed_commit(@file_content))
2021-09-30 23:02:18 +05:30
rescue Wiki::CouldNotCreateWikiError
raise_error("Error creating the wiki repository")
2018-11-20 20:47:30 +05:30
end
private
def clean_file_name(file_name)
return unless file_name.present?
file_name = truncate_file_name(file_name)
# CommonMark does not allow Urls with whitespaces, so we have to replace them
# Using the same regex Carrierwave use to replace invalid characters
file_name.gsub(CarrierWave::SanitizedFile.sanitize_regexp, '_')
end
def truncate_file_name(file_name)
return file_name if file_name.length <= MAX_FILENAME_LENGTH
extension = File.extname(file_name)
truncate_at = MAX_FILENAME_LENGTH - extension.length - 1
base_name = File.basename(file_name, extension)[0..truncate_at]
base_name + extension
end
def validate!
validate_file_name!
validate_permissions!
end
def validate_file_name!
raise_error('The file name cannot be empty') unless @file_name
end
def validate_permissions!
2020-05-24 23:13:21 +05:30
unless can?(current_user, :create_wiki, container)
2018-11-20 20:47:30 +05:30
raise_error('You are not allowed to push to the wiki')
end
end
def create_transformed_commit(content)
repository.create_file(
current_user,
@file_path,
content,
message: @commit_message,
branch_name: @branch_name,
author_email: @author_email,
author_name: @author_name)
end
def commit_result(commit_id)
{
file_name: @file_name,
file_path: @file_path,
branch: @branch_name,
commit: commit_id
}
end
end
end