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) + '/' load_couchapprc end def load_couchapprc @config ||= {} @config['couchapprc'] = JSON.parse(File.read(File.join(app_dir, '.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_id id path = "#{db_url}/#{id}?include_docs=true" response = RestClient.get path, :content_type => :json, :accept => :json # rescue nil return "no _id #{id}" unless response.code == 200 result = JSON.parse(response.body) response.code == 200 ? result : nil end def user email, push server = "#{db_url}".split("/")[0..-2].join("/") path = "#{server}/_users/org.couchdb.user:#{email}" puts "USER PATH #{path}" #response = Typhoeus::Request.get(path) response = RestClient.get path, :content_type => :json, :accept => :json # rescue nil puts "GET Response: #{response.code} #{response.body[0..200]}" response.code == 200 ? response.body : nil user = JSON.parse(response.body) pp user 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 #{doc[:_id]}" current = get_id doc[:_id] rescue nil if current puts "current revision: #{current['_rev']}" end current ? current['_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 def push_docs docs docs = docs.kind_of?(Array) ? docs : [docs] docs.each_slice(1000) do |chunk| json =RestClient.post "#{db_url}/_bulk_docs", {"docs" => chunk}.to_json, :content_type => :json, :accept => :json JSON.parse(json) puts "pushed #{chunk.size}" end true end end end