require "net/http" require 'open-uri' require 'zip/zip' class StoreApiController < ApplicationController def confirmation site_token = params[:site_token] store_token = params[:store_token] puts current_site.to_s if current_site.uid.eql?(site_token) current_site.store_token = store_token current_site.save render :json => {"success" => true}.to_json else render :json => {"success" => false}.to_json end end def install_module if current_site.store_token.nil? response = {"success" => false} elsif current_site.store_token == params[:site_token] file = File.join(Rails.root,"downloaded_extensions.rb") g = "gem '#{params[:module_key]}', git: '#{params[:git_path]}'" File.open(file,"a+") { |f| f.puts(g) } if !directory_exists?(File.join(Rails.root,"app","templates","#{Site.first.template}","modules","#{params[:module_key]}")) download_template(params[:template],params[:template_filename]) end response = {"success" => true} else response = {"success" => false} end render :json => response.to_json if response["success"] bundle_install # give_permissions(params[:module_key]) end end def uninstall_module file = File.join(Rails.root,"downloaded_extensions.rb") data = File.read(file) g = "gem '#{params[:module_key]}', git: '#{params[:git_path]}'\n" data = data.gsub(g,"") File.write(file,data) bundle_install render :json => {"success" => true}.to_json end def render_license_denied render :layout => "back_end" end private def bundle_install Bundler.with_clean_env { `cd #{Rails.root} && BUNDLE_GEMFILE=downloaded_extensions.rb bundle update && bundle` } %x(kill -s USR2 `cat tmp/pids/unicorn.pid`) sleep 5 end def restart_server_after_install %x(kill -s USR2 `cat tmp/pids/unicorn.pid`) sleep 5 end def download_template(url,name) dir = File.join(Rails.root,"public","template_cache") destination = File.join(Rails.root,"app","templates","#{Site.first.template}","modules") if !directory_exists?(dir) Dir.mkdir dir end zipfile = File.join(Rails.root, "public" , "template_cache", name) open(zipfile, 'wb') do |fo| fo.print open(url).read end unzip_file(zipfile,destination) end def directory_exists?(directory) File.directory?(directory) end def unzip_file (file, destination) Zip::ZipFile.open(file) { |zip_file| zip_file.each { |f| f_path=File.join(destination, f.name) FileUtils.mkdir_p(File.dirname(f_path)) zip_file.extract(f, f_path) unless File.exist?(f_path) } } FileUtils.rm_rf(File.join(Rails.root,"public","template_cache")) end end