lib/discourse_theme/uploader.rb in discourse_theme-0.1.6 vs lib/discourse_theme/uploader.rb in discourse_theme-0.1.7
- old
+ new
@@ -1,11 +1,14 @@
class DiscourseTheme::Uploader
+ THEME_CREATOR_REGEX = /^https:\/\/theme-creator.discourse.org$/i
+
def initialize(dir:, api_key:, site:)
@dir = dir
@api_key = api_key
@site = site
+ @is_theme_creator = !!(THEME_CREATOR_REGEX =~ site)
@theme_id = nil
end
def compress_dir(gzip, dir)
sgz = Zlib::GzipWriter.new(File.open(gzip, 'wb'))
@@ -53,18 +56,24 @@
value: value
}]
}
}
- uri = URI.parse(@site + "/admin/themes/#{@theme_id}?api_key=#{@api_key}")
+ endpoint =
+ if @is_theme_creator
+ "/user_themes/#{@theme_id}"
+ else
+ "/admin/themes/#{@theme_id}?api_key=#{@api_key}"
+ end
+ uri = URI.parse(@site + endpoint)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = URI::HTTPS === uri
request = Net::HTTP::Put.new(uri.request_uri, 'Content-Type' => 'application/json')
request.body = args.to_json
-
+ add_headers(request)
http.start do |h|
response = h.request(request)
if response.code.to_i == 200
json = JSON.parse(response.body)
if diagnose_errors(json) == 0
@@ -78,20 +87,27 @@
def upload_full_theme
filename = "#{Pathname.new(Dir.tmpdir).realpath}/bundle_#{SecureRandom.hex}.tar.gz"
compress_dir(filename, @dir)
- # new full upload endpoint
- uri = URI.parse(@site + "/admin/themes/import.json?api_key=#{@api_key}")
+ endpoint =
+ if @is_theme_creator
+ "/user_themes/import.json"
+ else
+ "/admin/themes/import.json?api_key=#{@api_key}"
+ end
+
+ uri = URI.parse(@site + endpoint)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = URI::HTTPS === uri
File.open(filename) do |tgz|
request = Net::HTTP::Post::Multipart.new(
uri.request_uri,
"bundle" => UploadIO.new(tgz, "application/tar+gzip", "bundle.tar.gz"),
)
+ add_headers(request)
response = http.request(request)
if response.code.to_i == 201
json = JSON.parse(response.body)
@theme_id = json["theme"]["id"]
if diagnose_errors(json) == 0
@@ -105,6 +121,14 @@
end
ensure
FileUtils.rm_f filename
end
+
+ private
+
+ def add_headers(request)
+ if @is_theme_creator
+ request["User-Api-Key"] = @api_key
+ end
+ end
end