2014-05-23 04:22:00 -04:00
|
|
|
class FileUploader < CarrierWave::Uploader::Base
|
2015-11-14 13:29:58 -05:00
|
|
|
include UploaderHelper
|
2016-03-24 05:01:30 -04:00
|
|
|
MARKDOWN_PATTERN = %r{\!?\[.*?\]\(/uploads/(?<secret>[0-9a-f]{32})/(?<file>.*?)\)}
|
2015-11-14 13:29:58 -05:00
|
|
|
|
2014-05-23 04:22:00 -04:00
|
|
|
storage :file
|
|
|
|
|
2015-02-20 09:37:37 -05:00
|
|
|
attr_accessor :project, :secret
|
|
|
|
|
2016-03-29 06:12:57 -04:00
|
|
|
def initialize(project, secret = nil)
|
2015-02-16 13:58:40 -05:00
|
|
|
@project = project
|
2016-03-29 06:12:57 -04:00
|
|
|
@secret = secret || self.class.generate_secret
|
2014-05-23 04:22:00 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def base_dir
|
2015-02-20 09:37:37 -05:00
|
|
|
"uploads"
|
2014-05-23 04:22:00 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def store_dir
|
2015-02-16 13:58:40 -05:00
|
|
|
File.join(base_dir, @project.path_with_namespace, @secret)
|
2014-05-23 04:22:00 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def cache_dir
|
2015-02-16 13:58:40 -05:00
|
|
|
File.join(base_dir, 'tmp', @project.path_with_namespace, @secret)
|
2014-05-23 04:22:00 -04:00
|
|
|
end
|
|
|
|
|
2015-02-20 09:56:12 -05:00
|
|
|
def secure_url
|
2015-10-06 10:09:03 -04:00
|
|
|
File.join("/uploads", @secret, file.filename)
|
2015-02-20 09:56:12 -05:00
|
|
|
end
|
2016-01-08 11:38:53 -05:00
|
|
|
|
2016-03-30 04:56:25 -04:00
|
|
|
def to_markdown
|
|
|
|
to_h[:markdown]
|
|
|
|
end
|
|
|
|
|
2016-01-08 11:38:53 -05:00
|
|
|
def to_h
|
2016-04-03 01:00:06 -04:00
|
|
|
filename = image_or_video? ? self.file.basename : self.file.filename
|
2016-01-08 11:38:53 -05:00
|
|
|
escaped_filename = filename.gsub("]", "\\]")
|
|
|
|
|
|
|
|
markdown = "[#{escaped_filename}](#{self.secure_url})"
|
2016-04-03 01:00:06 -04:00
|
|
|
markdown.prepend("!") if image_or_video?
|
2016-01-08 11:38:53 -05:00
|
|
|
|
|
|
|
{
|
|
|
|
alt: filename,
|
|
|
|
url: self.secure_url,
|
|
|
|
markdown: markdown
|
|
|
|
}
|
|
|
|
end
|
2016-03-30 06:11:27 -04:00
|
|
|
|
|
|
|
def self.generate_secret
|
|
|
|
SecureRandom.hex
|
|
|
|
end
|
2014-05-23 04:22:00 -04:00
|
|
|
end
|