# frozen_string_literal: true require 'active_job' require 'toot' require 'wcc/auth' require 'wcc/data' class WCC::Media::Engine < ::Rails::Engine isolate_namespace WCC::Media class << self def subscribe(channel, handler = nil, &block) handler ||= Proc.new(&block) with_toot_config do |c| c.subscribe :media, channel, handler end end def initialized # Don't register subscriptions unless # 1. we mounted the engine and # 2. something subscribed. ::Toot.config.callback_url && ::Toot.config.subscriptions.any? { |s| s.source.name == :media } end def register_subscriptions return unless initialized raise StandardError, "WCC::Auth must be configured" unless WCC::Auth.config.app_name.present? && WCC::Auth.config.app_url.present? RegistersSubscriptionsJob.perform_later end # Ensures toot is configured properly with the Media channel. Note this is # not done until an actual subscription is requested. def with_toot_config(&block) return ::Toot.config(&block) if @configured ::Toot.config do |c| media_api_url = WCC::Media::Client.default.api_url c.source :media, channel_prefix: "org.watermark.media.", subscription_url: URI.join(media_api_url, '/toot/subscriptions') # Note - use the [] method to override only if not set in client already c[:http_connection] ||= Faraday::Connection.new do |conn| conn.use :client_app_token conn.adapter :net_http end yield c end @configured = true end end initializer 'configure WCC::Media Toots' do ActiveSupport::Notifications.subscribe 'routes_loaded.engine.media.wcc' do ::Toot.config.callback_url ||= Rails.application.routes.url_helpers.wcc_media_url + '/callbacks' WCC::Media::Engine.register_subscriptions end end config.generators do |g| g.test_framework :rspec, fixture: false end class RegistersSubscriptionsJob < ::ActiveJob::Base self.queue_adapter = :async def perform Toot::RegistersSubscriptions.call rescue WCC::Data::Mapper::ServiceUnavailable => e _handle_error(e) rescue Faraday::ConnectionFailed => e _handle_error(e) rescue Faraday::TimeoutError => e _handle_error(e) rescue Toot::RegisterSubscriptionFailure => e raise unless e.status == 503 _handle_error(e) end private def _handle_error(err) logger.error "Server is down (will not retry): #{err.class} #{err}" end end end