# frozen_string_literal: true require 'distributed_press/v1' # Almacena el token de autenticación y la URL, por ahora solo vamos # a tener uno, pero queda abierta la posibilidad de agregar más. class DistributedPressPublisher < ApplicationRecord # Cifrar la información del token en la base de datos has_encrypted :token # La salida del log # # @return [IO] attr_reader :logger_out # La instancia es necesaria pero no única validates_presence_of :instance # El token es necesario validates_presence_of :token # Mantener la fecha de vencimiento actualizada before_save :update_expires_at_from_token!, :update_token_from_client! # Devuelve todos los tokens que vencen en una hora scope :with_about_to_expire_tokens, lambda { where('expires_at > ? and expires_at < ?', Time.now, Time.now + 1.hour) } # Instancia un cliente de Distributed Press a partir del token. Al # cargar un token a punto de vencer se renueva automáticamente. # # @return [DistributedPress::V1::Client] def client @client ||= DistributedPress::V1::Client.new(url: instance, token: token, logger: logger) end # @return [String] def to_s "Distributed Press <#{instance}>" end # Devuelve el hostname de la instancia # # @return [String] def hostname @hostname ||= URI.parse(instance).hostname end # @return [Logger] def logger @logger ||= begin @logger_out, @logger_in = IO.pipe ::Logger.new @logger_in, formatter: formatter end end private def formatter @formatter ||= lambda do |_, _, _, msg| "#{msg}\n" end end # Actualiza o desactiva la fecha de vencimiento a partir de la # información del token. # # @return [nil] def update_expires_at_from_token! self.expires_at = client.token.forever? ? nil : client.token.expires_at nil end # Actualiza el token a partir del cliente, que ya actualiza el token # automáticamente. # # @return [nil] def update_token_from_client! self.token = client.token.to_s nil end end