lib/dashx/client.rb in dashx-0.1.3 vs lib/dashx/client.rb in dashx-0.2.0

- old
+ new

@@ -43,34 +43,34 @@ if !config.target_installation.nil? headers['X-Target-Installation'] = config.target_installation end self.class.headers(headers) - end + end - def deliver(urn, parcel) - options = if urn.is_a?(String) && parcel != nil - symbolize_keys! parcel - check_presence!(parcel[:to], 'Recipient (:to)') + def deliver(urn, options) + contentTypeIdentifier, contentIdentifier = urn.split(/\//, 2) - contentTypeIdentifier, contentIdentifier = urn.split(/\//, 2) + options ||= {} - { - contentTypeIdentifier: contentTypeIdentifier, - contentIdentifier: contentIdentifier, - attachments: [], - cc: [], - bcc: [], - }.merge(parcel) - else - symbolize_keys! urn - check_presence!(urn[:from], 'Sender (:from)') + symbolize_keys! options - { attachments: [], cc: [], bcc: [] }.merge(urn) - end + options[:content] ||= {} - make_graphql_request(CREATE_DELIVERY_REQUEST, options) + [:to, :cc, :bcc].each do |kind| + value = options.delete(kind) + + options[:content][kind] ||= value if value + options[:content][kind] = wrap_array(options[:content][kind]) if options[:content][kind] + end + + params = { + contentTypeIdentifier: contentTypeIdentifier, + contentIdentifier: contentIdentifier + }.merge(options) + + make_graphql_request(CREATE_DELIVERY_REQUEST, params) end def identify(uid, options) symbolize_keys! options @@ -87,34 +87,44 @@ symbolize_keys! data unless data.nil? make_graphql_request(TRACK_EVENT_REQUEST, { event: event, uid: uid, data: data }) end - def generate_identity_token(uid) + def generate_identity_token(uid, options = {}) check_presence!(uid, 'uid') + symbolize_keys! options + kind = options[:kind] || 'regular' + plain_text = "v1;#{kind};#{uid}" + cipher = OpenSSL::Cipher::AES.new(256, :GCM).encrypt cipher.key = @config.private_key nonce = cipher.random_iv cipher.iv = nonce - encrypted = cipher.update(uid) + cipher.final + encrypted = cipher.update(plain_text) + cipher.final encrypted_token = "#{nonce}#{encrypted}#{cipher.auth_tag}" Base64.urlsafe_encode64(encrypted_token) end private def make_graphql_request(request, params) body = { query: request, variables: { input: params } }.to_json - request = self.class.post('/graphql', { body: body }) + response = self.class.post('/graphql', { body: body }) + raise "Request Failed: #{response}" if !response.success? || response.parsed_response.nil? || !response.parsed_response['errors'].nil? + response end def symbolize_keys!(hash) new_hash = hash.each_with_object({}) do |(k, v), memo| memo[k.to_sym] = v end hash.replace(new_hash) + end + + def wrap_array(obj) + obj.is_a?(Array) ? obj : [obj] end def check_presence!(obj, name = obj) raise ArgumentError, "#{name} cannot be blank." if obj.nil? || (obj.is_a?(String) && obj.empty?) end