# typed: strict # frozen_string_literal: true class YettoService cattr_reader :yetto_client, instance_accessor: false do Httpsensible::Client.new(user_agent: "PlugApp/#{PlugApp::Application::GIT_SHA}") end PROTOCOL = Rails.env.development? ? "http" : "https" YETTO_API_VERSION_TLD = "#{PROTOCOL}://#{YETTO_API_TLD}/#{YETTO_API_VERSION}" JWT_ALGORITHM = "RS256" class << self def perform_token_exchange(plug_installation_id) encoded_jwt = Httpsensible::JWT.encode_jwt(YETTO_PLUG_PEM, YETTO_PLUG_ID) response = yetto_client.with(headers: { "Authorization" => "Bearer #{encoded_jwt}" }).post("#{YETTO_API_VERSION_TLD}/plugs/installations/#{plug_installation_id}/access_tokens") body = response.parsed_json_body body["token"] end def get_plug_installation(plug_installation_id) token = perform_token_exchange(plug_installation_id) yetto_client.with(headers: { "Authorization" => "Bearer #{token}" }).get("#{YETTO_API_VERSION_TLD}/installations/#{plug_installation_id}") end def update_installation(plug_installation_id, params) plug_installation = {} plug_installation[:settings] = params[:plug_installation].fetch(:settings, {}) plug_installation[:credentials] = params[:plug_installation].fetch(:credentials, {}) token = perform_token_exchange(plug_installation_id) yetto_client.with(headers: { "Authorization" => "Bearer #{token}" }).patch("#{YETTO_API_VERSION_TLD}/installations/#{plug_installation_id}", json: plug_installation) end def create_inbox_switch(inbox_id, plug_installation_id, params) inbox_id = params.fetch(:inbox).fetch(:id) payload = { name: "After install", } token = perform_token_exchange(plug_installation_id) yetto_client.with(headers: { "Authorization" => "Bearer #{token}" }).post("#{YETTO_API_VERSION_TLD}/inboxes/#{inbox_id}/switches", json: payload) end def create_message(inbox_id, plug_installation_id, params) payload = params[:payload] token = perform_token_exchange(plug_installation_id) yetto_client.with(headers: { "Authorization" => "Bearer #{token}" }).post("#{YETTO_API_VERSION_TLD}/inboxes/#{inbox_id}/messages", json: payload) end end end