require_relative '../../rest_client' require_relative 'message' require_relative 'series' require_relative 'speaker' require_relative 'tag' require_relative 'client/response' module WCC module Media class Client < RestClient PARAMS = %w[ limit offset order_by sort target ].freeze def initialize(**options) options = { api_url: 'https://media.watermark.org/api/v1/', response_class: Response }.merge!(options) super(**options) end MESSAGES_FILTERS = %w[ on_or_after_date on_or_before_date tag_id speaker_id scripture_book_id series_id title_like legacy_id ].freeze def messages_list(**filters) query = extract_params(filters) query = query.merge!(apply_filters(filters, MESSAGES_FILTERS)) resp = get('messages', query) resp.assert_ok! resp.items.map { |m| WCC::Media::Message.new(m) } end def message(id) resp = get("messages/#{id}") resp.assert_ok! WCC::Media::Message.new(resp.body['message'], resp.headers.freeze) end SERIES_FILTERS = %w[ begin_on_or_before_date begin_on_or_after_date end_on_or_before_date end_on_or_after_date tag_id speaker_id scripture_book_id title_like legacy_id ] def series_list(**filters) query = extract_params(filters) query = query.merge!(apply_filters(filters, SERIES_FILTERS)) resp = get('series', query) resp.assert_ok! resp.items.map { |s| WCC::Media::Series.new(s) } end def series(id) resp = get("series/#{id}") resp.assert_ok! WCC::Media::Series.new(resp.body['series'], resp.headers.freeze) end SPEAKERS_FILTERS = %w[ featured name_like tag_id ] def speakers_list(**filters) query = extract_params(filters) query = query.merge!(apply_filters(filters, SPEAKERS_FILTERS)) resp = get('speakers', query) resp.assert_ok! resp.items.map { |s| WCC::Media::Speaker.new(s) } end def speaker(id) resp = get("speakers/#{id}") resp.assert_ok! WCC::Media::Speaker.new(resp.body['speaker'], resp.headers.freeze) end TAGS_FILTERS = %w[ name_like ] def tags_list(**filters) query = extract_params(filters) query = query.merge!(apply_filters(filters, TAGS_FILTERS)) resp = get('tags', query) resp.assert_ok! resp.items.map { |s| WCC::Media::Tag.new(s) } end def tag(id) resp = get("tags/#{id}") resp.assert_ok! WCC::Media::Tag.new(resp.body['tag'], resp.headers.freeze) end private def extract_params(filters) filters.each_with_object({}) do |(k, _v), h| k_s = k.to_s h[k_s] = filters.delete(k) if PARAMS.include?(k_s) end end def apply_filters(filters, expected_filters) defaults = default_filters(expected_filters) || {} filters.each_with_object(defaults) do |(k, v), h| k = k.to_s raise ArgumentError, "Unknown filter '#{k}'" unless expected_filters.include?(k) h["filter[#{k}]"] = v end end def default_filters(expected_filters) @options[:default_filters]&.each_with_object({}) do |(k, v), h| k = k.to_s h["filter[#{k}]"] = v if expected_filters.include?(k) end end end end end