download_service.rb 1.0 KB
Newer Older
J
Jared Szechy 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
module Projects
  class DownloadService < BaseService

    WHITELIST = [
      /^[^.]+\.fogbugz.com$/
    ]

    def initialize(project, url)
      @project, @url = project, url
    end

    def execute
      return nil unless valid_url?(@url)

      uploader = FileUploader.new(@project)
      uploader.download!(@url)
      uploader.store!

      filename = uploader.image? ? uploader.file.basename : uploader.file.filename

D
Douwe Maan 已提交
21 22 23 24
      escaped_filename = filename.gsub("]", "\\]")
      markdown = "[#{escaped_filename}](#{uploader.secure_url})"
      markdown.prepend("!") if uploader.image?

J
Jared Szechy 已提交
25 26 27
      {
        'alt'       => filename,
        'url'       => uploader.secure_url,
D
Douwe Maan 已提交
28 29
        'is_image'  => uploader.image?,
        'markdown'  => markdown
J
Jared Szechy 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
      }
    end

    private

    def valid_url?(url)
      url && http?(url) && valid_domain?(url)
    end

    def http?(url)
      url =~ /\A#{URI::regexp(['http', 'https'])}\z/
    end

    def valid_domain?(url)
      host = URI.parse(url).host
      WHITELIST.any? { |entry| entry === host }
    end
  end
end