Sha256: 4dbda1c9d22aca21224cc07c20efce98dd953348ba9217e5857cdfb527c8c5ca

Contents?: true

Size: 1.73 KB

Versions: 2

Compression:

Stored size: 1.73 KB

Contents

module PushToSNS
  class SendPushNotification
    def initialize(device, configuration = PushToSNS.configuration)
      self.device = device
      self.configuration = configuration
    end

    def perform(payload)
      ensure_endpoint_arn_is_enabled
      notification = build_push_notification(payload)

      response = AWS.sns.client.publish(
        message_structure: "json",
        message: notification.message.to_json,
        target_arn: configuration.apply(:read_endpoint_arn, device)
      )

      response[:message_id]
    rescue AWS::SNS::Errors::EndpointDisabled => _exception
      perform(payload)
    end

    private

    attr_accessor :device, :configuration

    def build_push_notification(payload)
      case configuration.apply(:read_source, device)
      when "ios"
        IosPushNotification.new(device, payload, configuration)
      when "android"
        AndroidPushNotification.new(device, payload, configuration)
      end
    end

    def ensure_endpoint_arn_is_enabled
      attributes = get_endpoint_attributes

      if attributes["Enabled"].downcase == "false" || attributes["Token"] != device_id
        enable_endpoint_arn
      end
    end

    def get_endpoint_attributes
      AWS.sns.client.get_endpoint_attributes(
        endpoint_arn: endpoint_arn
      )[:attributes]
    end

    def enable_endpoint_arn
      AWS.sns.client.set_endpoint_attributes(
        endpoint_arn: endpoint_arn,
        attributes: {
          "Enabled" => "True",
          "Token" => device_id
        }
      )[:endpoint_arn]
    end

    def device_id
      @device_id ||= configuration.apply(:read_device_id, device)
    end

    def endpoint_arn
      @endpoint_arn ||= configuration.apply(:read_endpoint_arn, device)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
push_to_sns-0.2.0 lib/push_to_sns/send_push_notification.rb
push_to_sns-0.1.1 lib/push_to_sns/send_push_notification.rb