2023-01-20 21:22:08 +00:00
|
|
|
# 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
|
|
|
|
|
2023-02-08 20:08:02 +00:00
|
|
|
# La salida del log
|
|
|
|
#
|
|
|
|
# @return [IO]
|
|
|
|
attr_reader :logger_out
|
|
|
|
|
2023-01-20 21:22:08 +00:00
|
|
|
# La instancia es única
|
|
|
|
validates_uniqueness_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
|
2023-01-20 21:28:29 +00:00
|
|
|
scope :with_about_to_expire_tokens, lambda {
|
2023-01-20 21:22:08 +00:00
|
|
|
where('expires_at > ? and expires_at < ?', Time.now, Time.now + 1.hour)
|
2023-01-20 21:28:29 +00:00
|
|
|
}
|
2023-01-20 21:22:08 +00:00
|
|
|
|
|
|
|
# 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
|
2023-02-08 20:08:02 +00:00
|
|
|
@client ||= DistributedPress::V1::Client.new(url: instance, token: token, logger: logger)
|
2023-01-20 21:22:08 +00:00
|
|
|
end
|
|
|
|
|
2023-01-20 23:34:27 +00:00
|
|
|
# @return [String]
|
|
|
|
def to_s
|
|
|
|
"Distributed Press <#{instance}>"
|
|
|
|
end
|
|
|
|
|
2023-02-09 23:01:22 +00:00
|
|
|
# Devuelve el hostname de la instancia
|
|
|
|
#
|
|
|
|
# @return [String]
|
|
|
|
def hostname
|
|
|
|
@hostname ||= URI.parse(instance).hostname
|
|
|
|
end
|
|
|
|
|
2023-02-08 20:08:02 +00:00
|
|
|
# @return [Logger]
|
|
|
|
def logger
|
|
|
|
@logger ||=
|
|
|
|
begin
|
|
|
|
@logger_out, @logger_in = IO.pipe
|
|
|
|
::Logger.new @logger_in, formatter: formatter
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2023-01-20 21:22:08 +00:00
|
|
|
private
|
|
|
|
|
2023-02-08 20:08:02 +00:00
|
|
|
def formatter
|
|
|
|
@formatter ||= lambda do |_, _, _, msg|
|
|
|
|
"#{msg}\n"
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2023-01-20 21:22:08 +00:00
|
|
|
# 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
|