module Hse class Remote attr_accessor :app_dir, :env #, :document, :config_path, :revision attr_reader :config def initialize(app_dir, env = 'default') #, config_path = nil) self.env = env self.app_dir = File.expand_path(app_dir) + '/' #self.config_path = config_path #load_config load_couchapprc end # def config_path=(config_path) # @config_path = config_path || File.join(app_dir, 'config.js') # end # def load_config # if File.readable?(config_path) # @config = JSON.parse(File.read(config_path)) # else # raise "Could not find config at '#{config_path}'. Run `soca init`" # end # end def load_couchapprc @config ||= {} @config['couchapprc'] = JSON.parse(File.read(File.join(app_dir, '.couchapprc'))) puts "COUCHAPPRC #{@config['couchapprc']}" #run_hooks!(:after_load_couchapprc) end def db_url if env =~ /^https?\:\/\// # the env is actual a db_url env else env_config = config['couchapprc']['env'][env] raise "No such env: #{env}" unless env_config && env_config['db'] puts "DB URL #{env_config['db']}" env_config['db'] end end def get doc path = "#{db_url}/#{doc[:_id]}" response = Typhoeus::Request.get(path) puts "GET Response: #{response.code} #{response.body[0..200]}" response.code == 200 ? response.body : nil end def user email, push server = "#{db_url}".split("/")[0..-2].join("/") path = "#{server}/_users/org.couchdb.user:#{email}" response = Typhoeus::Request.get(path) #puts "GET Response: #{response.code} #{response.body[0..200]}" response.code == 200 ? response.body : nil user = JSON.parse(response.body) puts user.inspect return unless push # curl -vX PUT $HOST/_users/org.couchdb.user:bob -d '{"name":"bob", "password":"bobspassword", "roles":[], "type":"user"}' -H "Content-Type: application/json" picture = email.split("@").first id = "org.couchdb.user:#{email}" newuser = {type:"user", roles:[], _id: id, name: email, password:email, email: email, picture: picture, iterations:1000} newuser["_rev"] = user["_rev"] if user json = newuser.to_json path = "#{server}/_users/#{id}" #headers = {"Content-Type" => "application/json"} response = Typhoeus::Request.put(path, body:json) puts "PUT Response: #{response.code} #{response.body[0..200]}" end def get_doc_revision doc puts "getting current revision" current = get doc if current current_json = JSON.parse(current) #self.revision = current_json['_rev'] puts "current revision: #{current_json['_rev']}" end current ? current_json['_rev'] : nil end def put id, body = "" path = "#{db_url}/#{id}" puts "remote: PUT path #{path}" puts "remote: PUT body: #{body[0..80]} ..." response = Typhoeus::Request.put(path, :body => body) puts "PUT Response: #{response.code} #{response.body[0..200]}" response end end end