support arbitrary attachments

This commit is contained in:
Régis Hanol
2013-07-10 22:54:05 +02:00
parent e8c1a81e87
commit 27ab5f471c
5 changed files with 61 additions and 38 deletions

View File

@ -1,9 +1,9 @@
require 'digest/sha1'
require 'image_sizer'
require 's3'
require 'local_store'
require 'tempfile'
require 'pathname'
require_dependency 's3'
require_dependency 'local_store'
class Upload < ActiveRecord::Base
belongs_to :user
@ -48,24 +48,25 @@ class Upload < ActiveRecord::Base
sha1 = Digest::SHA1.file(file.tempfile).hexdigest
# check if the file has already been uploaded
unless upload = Upload.where(sha1: sha1).first
# retrieve image info
image_info = FastImage.new(file.tempfile, raise_on_failure: true)
# compute image aspect ratio
width, height = ImageSizer.resize(*image_info.size)
# create a db record (so we can use the id)
upload = Upload.create!({
user_id: user_id,
original_filename: file.original_filename,
filesize: File.size(file.tempfile),
sha1: sha1,
width: width,
height: height,
url: ""
})
# make sure we're at the beginning of the file (FastImage is moving the pointer)
file.rewind
# deal with width & heights for images
if SiteSetting.authorized_image?(file)
# retrieve image info
image_info = FastImage.new(file.tempfile, raise_on_failure: true)
# compute image aspect ratio
upload.width, upload.height = ImageSizer.resize(*image_info.size)
# make sure we're at the beginning of the file (FastImage is moving the pointer)
file.rewind
end
# store the file and update its url
upload.url = Upload.store_file(file, sha1, image_info, upload.id)
upload.url = Upload.store_file(file, sha1, upload.id)
# save the url
upload.save
end
@ -73,9 +74,9 @@ class Upload < ActiveRecord::Base
upload
end
def self.store_file(file, sha1, image_info, upload_id)
return S3.store_file(file, sha1, image_info, upload_id) if SiteSetting.enable_s3_uploads?
return LocalStore.store_file(file, sha1, image_info, upload_id)
def self.store_file(file, sha1, upload_id)
return S3.store_file(file, sha1, upload_id) if SiteSetting.enable_s3_uploads?
return LocalStore.store_file(file, sha1, upload_id)
end
def self.remove_file(url)
@ -92,29 +93,15 @@ class Upload < ActiveRecord::Base
end
def self.is_local?(url)
url.start_with?(base_url)
!SiteSetting.enable_s3_uploads? && url.start_with?(LocalStore.base_url)
end
def self.is_on_s3?(url)
SiteSetting.enable_s3_uploads? && url.start_with?(S3.base_url)
end
def self.base_url
asset_host.present? ? asset_host : Discourse.base_url_no_prefix
end
def self.asset_host
ActionController::Base.asset_host
end
def self.get_from_url(url)
if has_been_uploaded?(url)
if m = LocalStore.uploaded_regex.match(url)
Upload.where(id: m[:upload_id]).first
elsif is_on_s3?(url)
Upload.where(url: url).first
end
end
Upload.where(url: url).first if has_been_uploaded?(url)
end
end