require 'mime/types' require 'open-uri' module Adparlor module Facebook module GraphApi class AdImage < GraphObject include Fields::AdImage include Traits::Methods field_attrs FIELDS allow_method :create, :destroy allow_local_method :create, :destroy def formatted_image return unless @source if %r{https?}.match(@source) file = open(@source) # return nil if we can't open the file from the url return nil if file.nil? content_type = AdImage.get_content_type(file.content_type, normalized_file_name) extension = AdImage.get_preferred_extension(content_type) # if content type or extension doesn't exist, the upload will fail on FB side return nil if content_type.nil? || extension.nil? @source = AdImage.upload_file_with_content_type(normalized_file_name, file, content_type, extension) else @source = Faraday::UploadIO.new(normalized_file_name, MIME::Types.type_for(normalized_file_name).first.content_type) end end def path raise FbError.new('required parameter account_id missing', 500) unless account_id if account_id.to_s.include?('act_') "/#{account_id}/adimages" else "/act_#{account_id}/adimages" end end def post(path, options, method = nil) raise FbError.new('update not available', 500) if method == 'UPDATE' formatted_image super path, options end def update_path path end class << self def upload_file_with_content_type(normalized_file_name, file, content_type, extension) tmp_file = Tempfile.new([File.basename(normalized_file_name), ".#{extension}"]) tmp_file.binmode tmp_file.write(file.read) tmp_file.rewind Faraday::UploadIO.new(tmp_file.path, content_type) end def get_preferred_extension(content_type) MIME::Types[content_type].first.preferred_extension end def get_content_type(header_content_type, file_name) content_type = MIME::Types.type_for(file_name) return content_type.first.content_type if !file_name.include?('safe_image.php') && !content_type.nil? header_content_type.empty? ? nil : header_content_type end end private # Remove any query string parameters before getting the mime type # should probably be done in mime types gem def normalized_file_name @source.split('?').first end end end end end