repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/auto_source.rb
lib/html2rss/auto_source.rb
# frozen_string_literal: true require 'parallel' require 'dry-validation' module Html2rss ## # The AutoSource class automatically extracts articles from a given URL by # utilizing a collection of Scrapers. These scrapers analyze and # parse popular structured data formats—such as schema, microdata, and # open graph—to identify and compile article elements into unified articles. # # Scrapers supporting plain HTML are also available for sites without structured data, # though results may vary based on page markup. # # @see Html2rss::AutoSource::Scraper::Schema # @see Html2rss::AutoSource::Scraper::SemanticHtml # @see Html2rss::AutoSource::Scraper::Html class AutoSource DEFAULT_CONFIG = { scraper: { schema: { enabled: true }, json_state: { enabled: true }, semantic_html: { enabled: true }, html: { enabled: true, minimum_selector_frequency: Scraper::Html::DEFAULT_MINIMUM_SELECTOR_FREQUENCY, use_top_selectors: Scraper::Html::DEFAULT_USE_TOP_SELECTORS }, rss_feed_detector: { enabled: true } }, cleanup: Cleanup::DEFAULT_CONFIG }.freeze Config = Dry::Schema.Params do optional(:scraper).hash do optional(:schema).hash do optional(:enabled).filled(:bool) end optional(:json_state).hash do optional(:enabled).filled(:bool) end optional(:semantic_html).hash do optional(:enabled).filled(:bool) end optional(:html).hash do optional(:enabled).filled(:bool) optional(:minimum_selector_frequency).filled(:integer, gt?: 0) optional(:use_top_selectors).filled(:integer, gt?: 0) end optional(:rss_feed_detector).hash do optional(:enabled).filled(:bool) end end optional(:cleanup).hash do optional(:keep_different_domain).filled(:bool) optional(:min_words_title).filled(:integer, gt?: 0) end end def initialize(response, opts = DEFAULT_CONFIG) @parsed_body = response.parsed_body @url = response.url @opts = opts end def articles @articles ||= extract_articles rescue Html2rss::AutoSource::Scraper::NoScraperFound => error Log.warn "No auto source scraper found for URL: #{url}. Skipping auto source. (#{error.message})" [] end private attr_reader :url, :parsed_body def extract_articles scrapers = Scraper.from(parsed_body, @opts[:scraper]) return [] if scrapers.empty? articles = Parallel.flat_map(scrapers, in_threads: thread_count_for(scrapers)) do |scraper| instance = scraper.new(parsed_body, url:, **scraper_options_for(scraper)) run_scraper(instance) end Cleanup.call(articles, url:, **cleanup_options) end def run_scraper(instance) instance.each.map do |article_hash| RssBuilder::Article.new(**article_hash, scraper: instance.class) end end def scraper_options_for(scraper) @opts.fetch(:scraper, {}).fetch(scraper.options_key, {}) end def cleanup_options @opts.fetch(:cleanup, {}) end def thread_count_for(scrapers) count = [scrapers.size, Parallel.processor_count].min count.zero? ? 1 : count end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/rss_builder.rb
lib/html2rss/rss_builder.rb
# frozen_string_literal: true require 'rss' module Html2rss ## # Builds an RSS Feed by providing channel, articles and stylesheets. class RssBuilder class << self def add_item(article, item_maker) add_item_string_values(article, item_maker) add_item_categories(article, item_maker) Enclosure.add(article.enclosure, item_maker) add_item_guid(article, item_maker) end private def add_item_string_values(article, item_maker) %i[title description author].each do |attr| next unless (value = article.send(attr)) next if value.empty? item_maker.send(:"#{attr}=", value) end item_maker.link = article.url.to_s if article.url item_maker.pubDate = article.published_at&.rfc2822 end def add_item_categories(article, item_maker) article.categories.each { |category| item_maker.categories.new_category.content = category } end def add_item_guid(article, item_maker) item_maker.guid.tap do |guid| guid.content = article.guid guid.isPermaLink = false end end end ## # @param channel [Html2rss::RssBuilder::Channel] The channel information for the RSS feed. # @param articles [Array<Html2rss::RssBuilder::Article>] The list of articles to include in the RSS feed. # @param stylesheets [Array<Hash>] An optional array of stylesheet configurations. def initialize(channel:, articles:, stylesheets: []) @channel = channel @articles = articles @stylesheets = stylesheets end def call RSS::Maker.make('2.0') do |maker| Stylesheet.add(maker, stylesheets) make_channel(maker.channel) make_items(maker) end end private attr_reader :channel, :articles def stylesheets @stylesheets.map { |style| Stylesheet.new(**style) } end def make_channel(maker) %i[language title description ttl].each do |key| maker.public_send(:"#{key}=", channel.public_send(key)) end maker.link = channel.url.to_s maker.generator = generator maker.updated = channel.last_build_date end def make_items(maker) articles.each do |article| maker.items.new_item { |item_maker| self.class.add_item(article, item_maker) } end end def generator scraper_namespace_regex = /(?<namespace>Html2rss|Scraper)::/ scraper_counts = articles.flat_map(&:scraper).tally.map do |klass, count| scraper_name = klass.to_s.gsub(scraper_namespace_regex, '') "#{scraper_name} (#{count})" end "html2rss V. #{Html2rss::VERSION} (scrapers: #{scraper_counts.join(', ')})" end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/html_navigator.rb
lib/html2rss/html_navigator.rb
# frozen_string_literal: true module Html2rss ## # HtmlNavigator provides methods to navigate through HTML nodes. class HtmlNavigator class << self ## # Returns the first parent that satisfies the condition. # If the condition is met, it returns the node itself. # # @param node [Nokogiri::XML::Node] The node to start the search from. # @param condition [Proc] The condition to be met. # @return [Nokogiri::XML::Node, nil] The first parent that satisfies the condition. def parent_until_condition(node, condition) while node && !node.document? && node.name != 'html' return node if condition.call(node) node = node.parent end end ## # Think of it as `css_upwards` method. # It searches for the closest parent that matches the given selector. def find_closest_selector_upwards(current_tag, selector) while current_tag found = current_tag.at_css(selector) return found if found return nil unless current_tag.respond_to?(:parent) current_tag = current_tag.parent end end ## # Searches for the closest parent that matches the given tag name. def find_tag_in_ancestors(current_tag, tag_name) return current_tag if current_tag.name == tag_name current_tag.ancestors(tag_name).first end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/rendering.rb
lib/html2rss/rendering.rb
# frozen_string_literal: true module Html2rss # Namespace for HTML rendering logic, used to generate rich content such as # images, audio, video, or embedded documents for feed descriptions. # # @example # Html2rss::Rendering::ImageRenderer.new(...).to_html # Html2rss::Rendering::MediaRenderer.for(...) # # @see Html2rss::Rendering::DescriptionBuilder module Rendering end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/url.rb
lib/html2rss/url.rb
# frozen_string_literal: true require 'addressable/uri' require 'cgi' module Html2rss ## # A value object representing a resolved, absolute URL with built-in operations. # Provides URL resolution, sanitization, and titleization capabilities. # # @example Creating a URL from a relative path # url = Url.from_relative('/path/to/article', 'https://example.com') # url.to_s # => "https://example.com/path/to/article" # # @example Sanitizing a raw URL string # url = Url.sanitize('https://example.com/ ') # url.to_s # => "https://example.com/" # # @example Getting titleized versions # url = Url.from_relative('/foo-bar/baz.txt', 'https://example.com') # url.titleized # => "Foo Bar Baz" # url.channel_titleized # => "example.com: Foo Bar Baz" class Url include Comparable # Regular expression for basic URI format validation URI_REGEXP = Addressable::URI::URIREGEX SUPPORTED_SCHEMES = %w[http https].to_set.freeze ## # Creates a URL from a relative path and base URL. # # @param relative_url [String, Html2rss::Url] the relative URL to resolve # @param base_url [String, Html2rss::Url] the base URL to resolve against # @return [Url] the resolved absolute URL # @raise [ArgumentError] if the URL cannot be parsed def self.from_relative(relative_url, base_url) url = Addressable::URI.parse(relative_url.to_s.strip) return new(url) if url.absolute? base_uri = Addressable::URI.parse(base_url.to_s) base_uri.path = '/' if base_uri.path.empty? new(base_uri.join(url).normalize) end ## # Creates a URL by sanitizing a raw URL string. # Removes spaces and extracts the first valid URL from the string. # # @param raw_url [String] the raw URL string to sanitize # @return [Url, nil] the sanitized URL, or nil if no valid URL found def self.sanitize(raw_url) matched_urls = raw_url.to_s.scan(%r{(?:(?:https?|ftp|mailto)://|mailto:)[^\s<>"]+}) url = matched_urls.first.to_s.strip return nil if url.empty? new(Addressable::URI.parse(url).normalize) end ## # Creates a URL for channel use with validation. # Validates that the URL meets channel requirements (absolute, no @, supported schemes). # # @param url_string [String] the URL string to validate and parse # @return [Url] the validated and parsed URL # @raise [ArgumentError] if the URL doesn't meet channel requirements # @example Creating a channel URL # Url.for_channel('https://example.com') # # => #<Html2rss::Url:... @uri=#<Addressable::URI:... URI:https://example.com>> # @example Invalid channel URL # Url.for_channel('/relative/path') # # => raises ArgumentError: "URL must be absolute" def self.for_channel(url_string) return nil if url_string.nil? || url_string.empty? stripped = url_string.strip return nil if stripped.empty? url = parse_and_normalize_url(stripped) validate_channel_url(url) url end ## # Parses and normalizes a URL string. # # @param url_string [String] the URL string to parse # @return [Url] the parsed and normalized URL # @raise [ArgumentError] if the URL cannot be parsed def self.parse_and_normalize_url(url_string) # Parse and normalize the URL directly since we expect absolute URLs # Using from_relative with same parameter is confusing - this is clearer new(Addressable::URI.parse(url_string).normalize) rescue Addressable::URI::InvalidURIError raise ArgumentError, 'URL must be absolute' end ## # Validates that a URL meets channel requirements. # # @param url [Url] the URL to validate # @raise [ArgumentError] if the URL doesn't meet channel requirements def self.validate_channel_url(url) raise ArgumentError, 'URL must be absolute' unless url.absolute? raise ArgumentError, 'URL must not contain an @ character' if url.to_s.include?('@') scheme = url.scheme raise ArgumentError, "URL scheme '#{scheme}' is not supported" unless SUPPORTED_SCHEMES.include?(scheme) end private_class_method :parse_and_normalize_url, :validate_channel_url ## # @param uri [Addressable::URI] the underlying Addressable::URI object (internal use only) def initialize(uri) @uri = uri.freeze freeze end # Delegate common URI operations to the underlying URI def to_s = @uri.to_s def scheme = @uri.scheme def host = @uri.host def path = @uri.path def query = @uri.query def fragment = @uri.fragment def absolute? = @uri.absolute? ## # Returns a titleized representation of the URL path. # Converts the path to a human-readable title by cleaning and capitalizing words. # Removes file extensions and special characters, then capitalizes each word. # # @return [String] the titleized path, or empty string if path is empty # @example Basic titleization # url = Url.from_string('https://example.com/foo-bar/baz.txt') # url.titleized # => "Foo Bar Baz" # @example With URL encoding # url = Url.from_string('https://example.com/hello%20world/article.html') # url.titleized # => "Hello World Article" def titleized path = @uri.path return '' if path.empty? nicer_path = CGI.unescapeURIComponent(path) .split('/') .flat_map do |part| part.gsub(/[^a-zA-Z0-9.]/, ' ').gsub(/\s+/, ' ').split end nicer_path.map!(&:capitalize) File.basename(nicer_path.join(' '), '.*') end ## # Returns a titleized representation of the URL with prefixed host. # Creates a channel title by combining host and path information. # Useful for RSS channel titles that need to identify the source. # # @return [String] the titleized channel URL # @example With path # url = Url.from_string('https://example.com/foo-bar/baz') # url.channel_titleized # => "example.com: Foo Bar Baz" # @example Without path (root URL) # url = Url.from_string('https://example.com') # url.channel_titleized # => "example.com" def channel_titleized nicer_path = CGI.unescapeURIComponent(@uri.path).split('/').reject(&:empty?) host = @uri.host nicer_path.any? ? "#{host}: #{nicer_path.map(&:capitalize).join(' ')}" : host end ## # Compares this URL with another URL for equality. # URLs are considered equal if their string representations are the same. # # @param other [Url] the other URL to compare with # @return [Integer] -1, 0, or 1 for less than, equal, or greater than def <=>(other) to_s <=> other.to_s end ## # Returns true if this URL is equal to another URL. # # @param other [Object] the other object to compare with # @return [Boolean] true if the URLs are equal def ==(other) other.is_a?(Url) && to_s == other.to_s end ## # Supports hash-based comparisons by ensuring equality semantics match `hash`. # # @param other [Object] the other object to compare with # @return [Boolean] true if the URLs are considered equal def eql?(other) other.is_a?(Url) && to_s == other.to_s end ## # Returns the hash code for this URL. # # @return [Integer] the hash code def hash to_s.hash end ## # Returns a string representation of the URL for debugging. # # @return [String] the debug representation def inspect "#<#{self.class}:#{object_id} @uri=#{@uri.inspect}>" end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/cli.rb
lib/html2rss/cli.rb
# frozen_string_literal: true require 'thor' ## # The Html2rss namespace / command line interface. module Html2rss ## # The Html2rss command line interface. class CLI < Thor check_unknown_options! def self.exit_on_failure? true end desc 'feed YAML_FILE [feed_name]', 'Print RSS built from the YAML_FILE file to stdout' method_option :params, type: :hash, optional: true, required: false, default: {} method_option :strategy, type: :string, desc: 'The strategy to request the URL', enum: %w[faraday browserless], default: 'faraday' def feed(yaml_file, feed_name = nil) config = Html2rss.config_from_yaml_file(yaml_file, feed_name) config[:strategy] ||= options[:strategy]&.to_sym config[:params] = options[:params] || {} puts Html2rss.feed(config) end desc 'auto [URL]', 'Automatically sources an RSS feed from the URL' method_option :strategy, type: :string, desc: 'The strategy to request the URL', enum: %w[faraday browserless], default: 'faraday' method_option :items_selector, type: :string, desc: 'CSS selector for items (will be enhanced) (optional)' def auto(url) strategy = options.fetch(:strategy, 'faraday').to_sym puts Html2rss.auto_source(url, strategy:, items_selector: options[:items_selector]) end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/selectors.rb
lib/html2rss/selectors.rb
# frozen_string_literal: true require 'nokogiri' module Html2rss ## # This scraper is designed to scrape articles from a given HTML page using CSS # selectors defined in the feed config. # # It supports the traditional feed configs that html2rss originally provided, # ensuring compatibility with existing setups. # # Additionally, it uniquely offers the capability to convert JSON into XML, # extending its versatility for diverse data processing workflows. class Selectors # rubocop:disable Metrics/ClassLength class InvalidSelectorName < Html2rss::Error; end include Enumerable # A context instance passed to item extractors and post-processors. Context = Struct.new('Context', :options, :item, :config, :scraper, keyword_init: true) DEFAULT_CONFIG = { items: { enhance: true } }.freeze ITEMS_SELECTOR_KEY = :items ITEM_TAGS = %i[title url description author comments published_at guid enclosure categories].freeze SPECIAL_ATTRIBUTES = Set[:guid, :enclosure, :categories].freeze # Mapping of new attribute names to their legacy names for backward compatibility. RENAMED_ATTRIBUTES = { published_at: %i[updated pubDate] }.freeze ## # Initializes a new Selectors instance. # # @param response [RequestService::Response] The response object. # @param selectors [Hash] A hash of CSS selectors. # @param time_zone [String] Time zone string used for date parsing. def initialize(response, selectors:, time_zone:) @response = response @url = response.url @selectors = selectors @time_zone = time_zone validate_url_and_link_exclusivity! fix_url_and_link! handle_renamed_attributes! @rss_item_attributes = @selectors.keys & Html2rss::RssBuilder::Article::PROVIDED_KEYS end ## # Returns articles extracted from the response. # Reverses order if config specifies reverse ordering. # # @return [Array<Html2rss::RssBuilder::Article>] def articles @articles ||= @selectors.dig(ITEMS_SELECTOR_KEY, :order) == 'reverse' ? to_a.tap(&:reverse!) : to_a end ## # Iterates over each scraped article. # # @yield [article] Gives each article as an Html2rss::RssBuilder::Article. # @return [Enumerator] An enumerator if no block is given. def each(&) return enum_for(:each) unless block_given? enhance = enhance? parsed_body.css(items_selector).each do |item| article_hash = extract_article(item) enhance_article_hash(article_hash, item) if enhance yield Html2rss::RssBuilder::Article.new(**article_hash, scraper: self.class) end end ## # Returns the CSS selector for the items. # @return [String] the CSS selector for the items def items_selector = @selectors.dig(ITEMS_SELECTOR_KEY, :selector) ## @return [Boolean] whether to enhance the article hash with auto_source's semantic HTML extraction. def enhance? = !!@selectors.dig(ITEMS_SELECTOR_KEY, :enhance) ## # Extracts an article hash for a given item element. # # @param item [Nokogiri::XML::Element] The element to extract from. # @return [Hash] Hash of attributes for the article. def extract_article(item) @rss_item_attributes.to_h { |key| [key, select(key, item)] }.compact end ## # Enhances the article hash using semantic HTML extraction. # Only adds keys that are missing from the original hash. # # @param article_hash [Hash] The original article hash. # @param article_tag [Nokogiri::XML::Element] HTML element to extract additional info from. # @return [Hash] The enhanced article hash. def enhance_article_hash(article_hash, article_tag) extracted = HtmlExtractor.new(article_tag, base_url: @url).call return article_hash unless extracted extracted.each_with_object(article_hash) do |(key, value), hash| next if value.nil? || (hash.key?(key) && hash[key]) hash[key] = value end end ## # Selects the value for a given attribute from an HTML element. # # @param name [Symbol, String] Name of the attribute. # @param item [Nokogiri::XML::Element] The HTML element to process. # @return [Object, Array<Object>] The selected value(s). # @raise [InvalidSelectorName] If the attribute name is invalid or not defined. def select(name, item) name = name.to_sym raise InvalidSelectorName, "Attribute selector '#{name}' is reserved for items." if name == ITEMS_SELECTOR_KEY selector_key, config = selector_config_for(name) if SPECIAL_ATTRIBUTES.member?(selector_key) select_special(selector_key, item:, config:) else select_regular(selector_key, item:, config:) end end private attr_reader :response def validate_url_and_link_exclusivity! return unless @selectors.key?(:url) && @selectors.key?(:link) raise InvalidSelectorName, 'You must either use "url" or "link" your selectors. Using both is not supported.' end def fix_url_and_link! return if @selectors[:url] || !@selectors.key?(:link) @selectors = @selectors.dup @selectors[:url] = @selectors[:link] end def handle_renamed_attributes! RENAMED_ATTRIBUTES.each_pair do |new_name, old_names| old_names.each do |old_name| next unless @selectors.key?(old_name) Html2rss::Log.warn("Selector '#{old_name}' is deprecated. Please rename to '#{new_name}'.") @selectors[new_name] ||= @selectors.delete(old_name) end end end def parsed_body @parsed_body ||= if response.json_response? fragment = ObjectToXmlConverter.new(response.parsed_body).call Nokogiri::HTML5.fragment(fragment) else response.parsed_body end end def select_special(name, item:, config:) case name when :enclosure enclosure(item:, config:) when :guid Array(config).map { |selector_name| select(selector_name, item) } when :categories select_categories(category_selectors: config, item:) end end def select_regular(_name, item:, config:) value = Extractors.get(config.merge(channel: channel_context), item) if value && (post_process_steps = config[:post_process]) steps = post_process_steps.is_a?(Array) ? post_process_steps : [post_process_steps] value = post_process(item, value, steps) end value end def post_process(item, value, post_process_steps) post_process_steps.each do |options| context = Context.new(config: { channel: { url: @url, time_zone: @time_zone } }, item:, scraper: self, options:) value = PostProcessors.get(options[:name], value, context) end value end def select_categories(category_selectors:, item:) Array(category_selectors).flat_map do |selector_name| extract_category_values(selector_name, item:) end end def extract_category_values(selector_name, item:) selector_key, config = selector_config_for(selector_name, allow_nil: true) return [] unless config nodes = extract_nodes(item:, config:) return Array(select_regular(selector_key, item:, config:)) unless node_set_with_multiple_elements?(nodes) Array(nodes).flat_map { |node| extract_categories_from_node(node, item:, config:) } end def extract_categories_from_node(node, item:, config:) values = Extractors.get(category_node_options(config), node) values = apply_post_process_steps(item:, value: values, post_process_steps: config[:post_process]) Array(values).filter_map { |category| extract_category_text(category) } end def extract_category_text(category) text = case category when Nokogiri::XML::Node, Nokogiri::XML::NodeSet HtmlExtractor.extract_visible_text(category) else category&.to_s end stripped = text&.strip stripped unless stripped.nil? || stripped.empty? end def node_set_with_multiple_elements?(nodes) nodes.is_a?(Nokogiri::XML::NodeSet) && nodes.length > 1 end def category_node_options(selector_config) selector_config.merge(channel: channel_context, selector: nil) end def apply_post_process_steps(item:, value:, post_process_steps:) return value unless value && post_process_steps steps = post_process_steps.is_a?(Array) ? post_process_steps : [post_process_steps] post_process(item, value, steps) end def selector_config_for(name, allow_nil: false) selector_key = name.to_sym return [selector_key, @selectors[selector_key]] if @selectors.key?(selector_key) return [selector_key, nil] if allow_nil raise InvalidSelectorName, "Selector for '#{selector_key}' is not defined." end def extract_nodes(item:, config:) return unless config.respond_to?(:[]) && config[:selector] Extractors.element(item, config[:selector]) end def channel_context { url: @url, time_zone: @time_zone } end # @return [Hash] enclosure details. def enclosure(item:, config:) url = Url.from_relative(select_regular(:enclosure, item:, config:), @url) { url:, type: config[:content_type] } end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/config.rb
lib/html2rss/config.rb
# frozen_string_literal: true require 'yaml' module Html2rss ## # The provided configuration is used to generate the RSS feed. # This class provides methods to load and process configuration from a YAML file, # supporting both single and multiple feed configurations. # # Configuration is validated during initialization. class Config class InvalidConfig < Html2rss::Error; end class << self ## # Loads the feed configuration from a YAML file. # # Supports multiple feeds defined under the specified key (default :feeds). # # @param file [String] the YAML file to load. # @param feed_name [String, nil] the feed name when using multiple feeds. # @param multiple_feeds_key [Symbol] the key under which multiple feeds are defined. # @return [Hash<Symbol, Object>] the configuration hash. # @raise [ArgumentError] if the file doesn't exist or feed is not found. def load_yaml(file, feed_name = nil, multiple_feeds_key: MultipleFeedsConfig::CONFIG_KEY_FEEDS) raise ArgumentError, "File '#{file}' does not exist" unless File.exist?(file) raise ArgumentError, "`#{multiple_feeds_key}` is a reserved feed name" if feed_name == multiple_feeds_key yaml = YAML.safe_load_file(file, symbolize_names: true) return yaml unless yaml.key?(multiple_feeds_key) config = yaml.dig(multiple_feeds_key, feed_name.to_sym) raise ArgumentError, "Feed '#{feed_name}' not found under `#{multiple_feeds_key}` key." unless config MultipleFeedsConfig.to_single_feed(config, yaml, multiple_feeds_key:) end ## # Processes the provided configuration hash, applying dynamic parameters if given, # and returns a new configuration object. # # @param config [Hash<Symbol, Object>] the configuration hash. # @param params [Hash<Symbol, Object>, nil] dynamic parameters for string formatting. # @return [Html2rss::Config] the configuration object. def from_hash(config, params: nil) config = config.dup if params DynamicParams.call(config[:headers], params) DynamicParams.call(config[:channel], params) end new(config) end ## # Provides a default configuration. # # @return [Hash<Symbol, Object>] a hash with default configuration values. def default_config { strategy: RequestService.default_strategy_name, channel: { time_zone: 'UTC' }, headers: RequestHeaders.browser_defaults, stylesheets: [] } end end ## # Initializes the configuration object. # # Processes deprecated attributes, applies default values, and validates the configuration. # # @param config [Hash<Symbol, Object>] the configuration hash. # @raise [InvalidConfig] if the configuration fails validation. def initialize(config) prepared_config = prepare_config(config) validator = Validator.new.call(prepared_config) raise InvalidConfig, "Invalid configuration: #{validator.errors.to_h}" unless validator.success? validated_config = validator.to_h validated_config[:headers] = RequestHeaders.normalize( validated_config[:headers], channel_language: validated_config.dig(:channel, :language), url: validated_config.dig(:channel, :url) ) @config = validated_config.freeze end def strategy = config[:strategy] def stylesheets = config[:stylesheets] def headers = config[:headers] def channel = config[:channel] def url = config.dig(:channel, :url) def time_zone = config.dig(:channel, :time_zone) def selectors = config[:selectors] def auto_source = config[:auto_source] private attr_reader :config def handle_deprecated_channel_attributes(config) { strategy: RequestService.default_strategy_name, headers: {} }.each_pair do |key, default_value| if !config[key] && (value = config.dig(:channel, key)) Log.warn("The `channel.#{key}` key is deprecated. Please move the definition of `#{key}` to the top level.") config[key] = value end config[key] ||= default_value end config end def apply_default_config(config) deep_merge(self.class.default_config, config) end def apply_default_selectors_config(config) deep_merge({ selectors: Selectors::DEFAULT_CONFIG }, config) end def apply_default_auto_source_config(config) deep_merge({ auto_source: Html2rss::AutoSource::DEFAULT_CONFIG }, config) end def prepare_config(config) config = config.dup if config.frozen? config = handle_deprecated_channel_attributes(config) config = apply_default_config(config) config = apply_default_selectors_config(config) if config[:selectors] config = apply_default_auto_source_config(config) if config[:auto_source] config end def deep_merge(base_config, override_config) base_config.merge(override_config) do |_key, oldval, newval| oldval.is_a?(Hash) && newval.is_a?(Hash) ? deep_merge(oldval, newval) : newval end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/error.rb
lib/html2rss/error.rb
# frozen_string_literal: true module Html2rss # The Html2rss::Error base class. class Error < StandardError; end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/auto_source/cleanup.rb
lib/html2rss/auto_source/cleanup.rb
# frozen_string_literal: true module Html2rss class AutoSource ## # Cleanup is responsible for cleaning up the extracted articles. # :reek:MissingSafeMethod { enabled: false } # It applies various strategies to filter and refine the article list. class Cleanup DEFAULT_CONFIG = { keep_different_domain: false, min_words_title: 3 }.freeze VALID_SCHEMES = %w[http https].to_set.freeze class << self def call(articles, url:, keep_different_domain:, min_words_title:) Log.debug "Cleanup: start with #{articles.size} articles" articles.select!(&:valid?) deduplicate_by!(articles, :url) keep_only_http_urls!(articles) reject_different_domain!(articles, url) unless keep_different_domain keep_only_with_min_words_title!(articles, min_words_title:) Log.debug "Cleanup: end with #{articles.size} articles" articles end ## # Deduplicates articles by a given key. # # @param articles [Array<Article>] The list of articles to process. # @param key [Symbol] The key to deduplicate by. def deduplicate_by!(articles, key) seen = {} articles.reject! do |article| value = article.public_send(key) value.nil? || seen.key?(value).tap { seen[value] = true } end end ## # Keeps only articles with HTTP or HTTPS URLs. # # @param articles [Array<Article>] The list of articles to process. def keep_only_http_urls!(articles) articles.select! { |article| VALID_SCHEMES.include?(article.url&.scheme) } end ## # Rejects articles that have a URL not on the same domain as the source. # # @param articles [Array<Article>] The list of articles to process. # @param base_url [Html2rss::Url] The source URL to compare against. def reject_different_domain!(articles, base_url) base_host = base_url.host articles.select! { |article| article.url&.host == base_host } end ## # Keeps only articles with a title that is present and has at least `min_words_title` words. # # @param articles [Array<Article>] The list of articles to process. # @param min_words_title [Integer] The minimum number of words in the title. def keep_only_with_min_words_title!(articles, min_words_title:) articles.select! do |article| article.title ? word_count_at_least?(article.title, min_words_title) : true end end private def word_count_at_least?(str, min_words) count = 0 str.to_s.scan(/\p{Alnum}+/) do count += 1 return true if count >= min_words end false end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/auto_source/scraper.rb
lib/html2rss/auto_source/scraper.rb
# frozen_string_literal: true module Html2rss class AutoSource ## # The Scraper module contains all scrapers that can be used to extract articles. # Each scraper should implement a `call` method that returns an array of article hashes. # Each scraper should also implement an `articles?` method that returns true if the scraper # can potentially be used to extract articles from the given HTML. # module Scraper SCRAPERS = [ Schema, JsonState, SemanticHtml, Html, RssFeedDetector ].freeze ## # Error raised when no suitable scraper is found. class NoScraperFound < Html2rss::Error; end ## # Returns an array of scrapers that claim to find articles in the parsed body. # @param parsed_body [Nokogiri::HTML::Document] The parsed HTML body. # @param opts [Hash] The options hash. # @return [Array<Class>] An array of scraper classes that can handle the parsed body. def self.from(parsed_body, opts = Html2rss::AutoSource::DEFAULT_CONFIG[:scraper]) scrapers = SCRAPERS.select { |scraper| opts.dig(scraper.options_key, :enabled) } scrapers.select! { |scraper| scraper.articles?(parsed_body) } raise NoScraperFound, 'No scrapers found for URL.' if scrapers.empty? scrapers end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/auto_source/scraper/semantic_html.rb
lib/html2rss/auto_source/scraper/semantic_html.rb
# frozen_string_literal: true require 'parallel' module Html2rss class AutoSource module Scraper ## # Scrapes articles by looking for common markup tags (article, section, li) # containing an <a href> tag. # # See: # 1. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/article class SemanticHtml include Enumerable ## # Map of parent element names to CSS selectors for finding <a href> tags. ANCHOR_TAG_SELECTORS = [ ['article', 'article:not(:has(article)) a[href]'], ['section', 'section:not(:has(section)) a[href]'], ['li', 'li:not(:has(li)) a[href]'], ['tr', 'tr:not(:has(tr)) a[href]'], ['div', 'div:not(:has(div)) a[href]'] ].freeze def self.options_key = :semantic_html # Check if the parsed_body contains articles # @param parsed_body [Nokogiri::HTML::Document] The parsed HTML document # @return [Boolean] True if articles are found, otherwise false. def self.articles?(parsed_body) return false unless parsed_body ANCHOR_TAG_SELECTORS.any? do |(_tag_name, selector)| parsed_body.at_css(selector) end end # @param parsed_body [Nokogiri::HTML::Document] The parsed HTML document. # @param url [String] The base URL. # @param extractor [Class] The extractor class to handle article extraction. # @param opts [Hash] Additional options. def initialize(parsed_body, url:, extractor: HtmlExtractor, **opts) @parsed_body = parsed_body @url = url @extractor = extractor @opts = opts end attr_reader :parsed_body ## # Yields article hashes extracted from the HTML. # @yieldparam [Hash] The scraped article hash. # @return [Enumerator] Enumerator for the scraped articles. def each return enum_for(:each) unless block_given? each_candidate do |article_tag| if (article_hash = @extractor.new(article_tag, base_url: @url).call) yield article_hash end end end private # @yield [Nokogiri::XML::Element] Gives each found article tag. def each_candidate ANCHOR_TAG_SELECTORS.each do |tag_name, selector| parsed_body.css(selector).each do |anchor| next if anchor.path.match?(Html::TAGS_TO_IGNORE) # Traverse ancestors to find the parent tag matching tag_name article_tag = HtmlNavigator.find_tag_in_ancestors(anchor, tag_name) yield article_tag if article_tag end end end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/auto_source/scraper/rss_feed_detector.rb
lib/html2rss/auto_source/scraper/rss_feed_detector.rb
# frozen_string_literal: true module Html2rss class AutoSource module Scraper ## # Detects RSS, Atom, and JSON feeds in HTML link tags and creates articles for them. # This scraper is used as a fallback when no other scrapers can find articles. # # Features: # - Detects RSS, Atom, and JSON feeds via <link rel="alternate"> tags # - Creates helpful articles with clickable links to discovered feeds # - Uses monthly rotating GUIDs to keep articles visible in feed readers # - Includes security measures to prevent XSS attacks # - Optimized for performance with cached operations # # @example HTML that will be detected # <link rel="alternate" type="application/rss+xml" href="/feed.xml" title="RSS Feed"> # <link rel="alternate" type="application/atom+xml" href="/atom.xml" title="Atom Feed"> # <link rel="alternate" type="application/json" href="/feed.json" title="JSON Feed"> class RssFeedDetector include Enumerable # CSS selector for detecting feed link tags FEED_LINK_SELECTOR = 'link[rel="alternate"][type*="application/"]' # Default categories for all feed articles DEFAULT_CATEGORIES = %w[feed auto-detected].freeze # Feed type detection patterns FEED_TYPE_PATTERNS = { json: /\.json$/, atom: /atom/, rss: // # default fallback }.freeze def self.options_key = :rss_feed_detector ## # Check if the parsed_body contains RSS feed link tags. # This scraper should only be used as a fallback when other scrapers fail. # @param parsed_body [Nokogiri::HTML::Document] The parsed HTML document # @return [Boolean] True if RSS feeds are found, otherwise false. def self.articles?(parsed_body) return false unless parsed_body parsed_body.css(FEED_LINK_SELECTOR).any? end # @param parsed_body [Nokogiri::HTML::Document] The parsed HTML document. # @param url [String, Html2rss::Url] The base URL. # @param opts [Hash] Additional options (unused but kept for consistency). def initialize(parsed_body, url:, **opts) @parsed_body = parsed_body @url = url.is_a?(Html2rss::Url) ? url : Html2rss::Url.from_relative(url.to_s, url.to_s) @opts = opts end attr_reader :parsed_body ## # Yields article hashes for each discovered RSS feed. # @yieldparam [Hash] The RSS feed article hash. # @return [Enumerator] Enumerator for the discovered RSS feeds. def each return enum_for(:each) unless block_given? @timestamp = Time.now @current_month = @timestamp.strftime('%Y-%m') @site_name = extract_site_name @parsed_body.css(FEED_LINK_SELECTOR).each do |link| feed_url = link['href'] next if feed_url.nil? || feed_url.empty? article_hash = create_article_hash(link, feed_url) yield article_hash if article_hash end end private def create_article_hash(link, feed_url) absolute_url = Html2rss::Url.from_relative(feed_url, @url) feed_title = link['title']&.strip feed_type = detect_feed_type(feed_url) build_article_hash(absolute_url, feed_title, feed_type) rescue StandardError => error Log.warn "RssFeedDetector: Failed to create article for feed URL '#{feed_url}': #{error.message}" nil end def build_article_hash(absolute_url, feed_title, feed_type) { title: feed_title || "Subscribe to #{feed_type} Feed", url: absolute_url, description: create_description(absolute_url, feed_type, feed_title), id: generate_monthly_id(absolute_url), published_at: @timestamp, categories: create_categories(feed_type), author: @site_name, scraper: self.class } end def generate_monthly_id(absolute_url) # Generate a GUID that changes monthly to ensure articles appear as "unread" # This makes the gem a good internet citizen by periodically reminding users # about available RSS feeds "rss-feed-#{absolute_url.hash.abs}-#{@current_month}" end def detect_feed_type(feed_url) url_lower = feed_url.downcase case url_lower when FEED_TYPE_PATTERNS[:json] then 'JSON Feed' when FEED_TYPE_PATTERNS[:atom] then 'Atom' else 'RSS' end end def create_description(absolute_url, feed_type, feed_title) safe_url = absolute_url.to_s html_content = if feed_title "This website has a #{feed_type} feed available: <a href=\"#{safe_url}\">#{feed_title}</a>" else "This website has a #{feed_type} feed available at <a href=\"#{safe_url}\">#{safe_url}</a>" end # Sanitize HTML to allow safe HTML while preventing XSS sanitize_html(html_content) end def sanitize_html(html_content) # Use the same sanitization as the rest of the project context = { config: { channel: { url: @url } } } Html2rss::Selectors::PostProcessors::SanitizeHtml.new(html_content, context).get end def create_categories(feed_type) categories = DEFAULT_CATEGORIES.dup categories << feed_type.downcase.tr(' ', '-') categories end def extract_site_name # Try to extract site name from the HTML title first title = @parsed_body.at_css('title')&.text&.strip return title if title && !title.empty? # Fallback to URL using Html2rss::Url#channel_titleized @url.channel_titleized end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/auto_source/scraper/json_state.rb
lib/html2rss/auto_source/scraper/json_state.rb
# frozen_string_literal: true require 'json' module Html2rss class AutoSource module Scraper # # Scrapes JSON state blobs embedded in script tags such as Next.js, Nuxt, # or custom window globals. The scraper searches `<script type="application/json">` # tags and well-known JavaScript globals for arrays of article-like hashes # and normalises them to a structure compatible with HtmlExtractor. class JsonState include Enumerable JSON_SCRIPT_SELECTOR = 'script[type="application/json"]' GLOBAL_ASSIGNMENT_PATTERNS = [ /(?:window|self|globalThis)\.__NEXT_DATA__\s*=\s*/m, /(?:window|self|globalThis)\.__NUXT__\s*=\s*/m, /(?:window|self|globalThis)\.STATE\s*=\s*/m ].freeze TITLE_KEYS = %w[title headline name text].freeze URL_KEYS = %w[url link href permalink slug path canonicalUrl shortUrl].freeze DESCRIPTION_KEYS = %w[description summary excerpt dek subheading].freeze IMAGE_KEYS = %w[image imageUrl thumbnailUrl thumbnail src featuredImage coverImage heroImage].freeze PUBLISHED_AT_KEYS = %w[published_at publishedAt datePublished date publicationDate pubDate updatedAt updated_at createdAt created_at].freeze CATEGORY_KEYS = %w[categories tags section sections topic topics channel].freeze ID_KEYS = %w[id guid uuid slug key].freeze # Scans DOM nodes for JSON payloads containing article data. module DocumentScanner module_function def json_documents(parsed_body) script_documents(parsed_body) + assignment_documents(parsed_body) end def script_documents(parsed_body) parsed_body.css(JSON_SCRIPT_SELECTOR).filter_map { parse_json(_1.text) } end def assignment_documents(parsed_body) parsed_body.css('script').filter_map { parse_assignment(_1.text) } end def parse_assignment(text) payload = assignment_payload(text) parse_json(payload) if payload end def assignment_payload(text) trimmed = text.to_s.strip return if trimmed.empty? GLOBAL_ASSIGNMENT_PATTERNS.each do |pattern| next unless trimmed.match?(pattern) payload = trimmed.sub(pattern, '') return extract_assignment_payload(payload) end nil end def extract_assignment_payload(text) extract_json_block(text) || text end def extract_json_block(text) start_index = text.index(/[\[{]/) return unless start_index stop_index = scan_for_json_end(text, start_index) text[start_index..stop_index] if stop_index end # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity def scan_for_json_end(text, start_index) stack = [] in_string = false escape = false text.each_char.with_index do |char, index| next if index < start_index if in_string if escape escape = false elsif char == '\\' escape = true elsif char == '"' in_string = false end next end case char when '"' in_string = true when '{' stack << '}' when '[' stack << ']' when '}', ']' expected = stack.pop return index if expected == char && stack.empty? end end nil end # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity def parse_json(payload) return unless payload JSON.parse(payload, symbolize_names: true) rescue JSON::ParserError => error parse_js_object(payload, error) end def parse_js_object(payload, _original_error) coerced = coerce_javascript_object(payload) return unless coerced # Some sites emit JavaScript object literals (unquoted keys, trailing commas). # Coerce those payloads into valid JSON so we keep the same parsing pipeline. JSON.parse(coerced, symbolize_names: true) rescue JSON::ParserError => error Html2rss::Log.debug do "fallback also failed (#{error.message})" end nil end def coerce_javascript_object(payload) string = payload.dup # KISS approach: mutate common JS literal quirks instead of a full parser. strip_trailing_commas(quote_unquoted_keys(string)) end def quote_unquoted_keys(jsonish) jsonish.gsub(/(\A\s*|[{,\[]\s*)([A-Za-z_]\w*)(\s*:)/) do "#{Regexp.last_match(1)}\"#{Regexp.last_match(2)}\"#{Regexp.last_match(3)}" end end def strip_trailing_commas(jsonish) jsonish.gsub(/,(\s*[\]}])/, '\1') end end private_constant :DocumentScanner # Retrieves values from heterogeneous objects by probing multiple keys. module ValueFinder module_function def fetch(object, keys) case object when Hash then fetch_from_hash(object, keys) when Array then fetch_from_array(object, keys) end end def fetch_from_hash(hash, keys) keys.each do |key| string_key = key.to_s return hash[string_key] if hash.key?(string_key) symbol_key = string_key.to_sym return hash[symbol_key] if hash.key?(symbol_key) end fetch_nested(hash[:attributes] || hash['attributes'], keys) || fetch_nested(hash[:data] || hash['data'], keys) end def fetch_from_array(array, keys) array.each do |entry| result = fetch(entry, keys) return result if result end nil end def fetch_nested(value, keys) fetch(value, keys) if value end end private_constant :ValueFinder # Identifies arrays that look like collections of article hashes. module CandidateDetector module_function def candidate_array?(document) case document when Array return true if array_of_articles?(document) document.any? { traversable_candidate?(_1) } when Hash then document.each_value.any? { candidate_array?(_1) } else false end end def traversable_candidate?(value) case value when Array, Hash then candidate_array?(value) else false end end def array_of_articles?(array) array.any? do |element| next unless element.is_a?(Hash) title_from(element) && url_from(element) end end def title_from(object) ValueFinder.fetch(object, TITLE_KEYS) end def url_from(object) ValueFinder.fetch(object, URL_KEYS) end end private_constant :CandidateDetector # Shapes raw entries into the structure required downstream. module ArticleNormalizer module_function # rubocop:disable Metrics/MethodLength def normalise(entry, base_url:) return unless entry.is_a?(Hash) title = string(ValueFinder.fetch(entry, TITLE_KEYS)) description = string(ValueFinder.fetch(entry, DESCRIPTION_KEYS)) article_url = resolve_link(entry, keys: URL_KEYS, base_url:, log_key: 'JsonState: invalid URL encountered') return unless article_url return if title.nil? && description.nil? { title:, description:, url: article_url, image: resolve_link(entry, keys: IMAGE_KEYS, base_url:, log_key: 'JsonState: invalid image URL encountered'), published_at: string(ValueFinder.fetch(entry, PUBLISHED_AT_KEYS)), categories: categories(entry), id: identifier(entry, article_url) }.compact end # rubocop:enable Metrics/MethodLength def string(value) trimmed = value.to_s.strip trimmed unless trimmed.empty? end def resolve_link(entry, keys:, base_url:, log_key:) value = ValueFinder.fetch(entry, keys) value = ValueFinder.fetch(value, keys) if value.is_a?(Hash) string = string(value) return unless string Url.from_relative(string, base_url) rescue ArgumentError Log.debug(log_key, url: string) nil end # rubocop:disable Metrics/MethodLength def categories(entry) raw = ValueFinder.fetch(entry, CATEGORY_KEYS) names = case raw when Array then raw when Hash then raw.values when String then [raw] else [] end result = names.flat_map do |value| case value when Hash string(ValueFinder.fetch(value, %w[name title label])) else string(value) end end.compact result.uniq! result unless result.empty? end # rubocop:enable Metrics/MethodLength def identifier(entry, article_url) value = ValueFinder.fetch(entry, ID_KEYS) value = ValueFinder.fetch(value, ID_KEYS) if value.is_a?(Hash) string(value) || article_url.to_s end end private_constant :ArticleNormalizer def self.options_key = :json_state class << self def articles?(parsed_body) return false unless parsed_body DocumentScanner.json_documents(parsed_body).any? { CandidateDetector.candidate_array?(_1) } end def json_documents(parsed_body) DocumentScanner.json_documents(parsed_body) end end def initialize(parsed_body, url:, **_opts) @parsed_body = parsed_body @url = url end attr_reader :parsed_body def each return enum_for(:each) unless block_given? DocumentScanner.json_documents(parsed_body).each do |document| discover_articles(document) do |article| yield article if article end end end private attr_reader :url def discover_articles(document, &block) case document when Array then handle_array(document, &block) when Hash then document.each_value { discover_articles(_1, &block) if traversable?(_1) } end end def handle_array(array, &block) if CandidateDetector.array_of_articles?(array) array.each do |entry| yield(ArticleNormalizer.normalise(entry, base_url: url)) end else array.each { discover_articles(_1, &block) if traversable?(_1) } end end def traversable?(value) value.is_a?(Array) || value.is_a?(Hash) end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/auto_source/scraper/schema.rb
lib/html2rss/auto_source/scraper/schema.rb
# frozen_string_literal: true require 'json' require 'nokogiri' module Html2rss class AutoSource module Scraper ## # Scrapes articles from Schema.org objects, by looking for the objects in: # <script type="application/ld+json"> "schema" tags. # # See: # 1. https://schema.org/docs/full.html # 2. https://developers.google.com/search/docs/appearance/structured-data/article#microdata class Schema include Enumerable TAG_SELECTOR = 'script[type="application/ld+json"]' def self.options_key = :schema class << self def articles?(parsed_body) parsed_body.css(TAG_SELECTOR).any? { |script| supported_schema_type?(script) } end def supported_schema_type?(script) supported_types = Thing::SUPPORTED_TYPES | ItemList::SUPPORTED_TYPES supported_types.any? { |type| script.text.match?(/"@type"\s*:\s*"#{Regexp.escape(type)}"/) } end ## # Returns a flat array # of all supported schema objects # by recursively traversing the given `object`. # # @param object [Hash, Array, Nokogiri::XML::Element] # @return [Array<Hash>] the schema_objects, or an empty array # :reek:DuplicateMethodCall def from(object) case object when Nokogiri::XML::Element from(parse_script_tag(object)) when Hash supported_schema_object?(object) ? [object] : object.values.flat_map { |item| from(item) } when Array object.flat_map { |item| from(item) } else [] end end def supported_schema_object?(object) scraper_for_schema_object(object) ? true : false end ## # @return [Scraper::Schema::Thing, Scraper::Schema::ItemList, nil] a class responding to `#call` def scraper_for_schema_object(schema_object) type = schema_object[:@type] if Thing::SUPPORTED_TYPES.member?(type) Thing elsif ItemList::SUPPORTED_TYPES.member?(type) ItemList else Log.debug("Schema#scraper_for_schema_object: Unsupported schema object @type: #{type}") nil end end private def parse_script_tag(script_tag) JSON.parse(script_tag.text, symbolize_names: true) rescue JSON::ParserError => error Log.warn('Schema#schema_objects: Failed to parse JSON', error: error.message) [] end end def initialize(parsed_body, url:, **opts) @parsed_body = parsed_body @url = url @opts = opts end ## # @yield [Hash] Each scraped article_hash # @return [Array<Hash>] the scraped article_hashes def each(&) return enum_for(:each) unless block_given? schema_objects.filter_map do |schema_object| next unless (klass = self.class.scraper_for_schema_object(schema_object)) next unless (results = klass.new(schema_object, url:).call) if results.is_a?(Array) results.each { |result| yield(result) } # rubocop:disable Style/ExplicitBlockArgument else yield(results) end end end private def schema_objects @parsed_body.css(TAG_SELECTOR).flat_map do |tag| Schema.from(tag) end end attr_reader :parsed_body, :url end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/auto_source/scraper/html.rb
lib/html2rss/auto_source/scraper/html.rb
# frozen_string_literal: true require 'nokogiri' module Html2rss class AutoSource module Scraper ## # Scrapes articles from HTML pages by # finding similar structures around anchor tags in the parsed_body. class Html include Enumerable TAGS_TO_IGNORE = /(nav|footer|header|svg|script|style)/i DEFAULT_MINIMUM_SELECTOR_FREQUENCY = 2 DEFAULT_USE_TOP_SELECTORS = 5 def self.options_key = :html def self.articles?(parsed_body) new(parsed_body, url: '').any? end ## # Simplify an XPath selector by removing the index notation. def self.simplify_xpath(xpath) xpath.gsub(/\[\d+\]/, '') end # @param parsed_body [Nokogiri::HTML::Document] The parsed HTML document. # @param url [String] The base URL. # @param extractor [Class] The extractor class to handle article extraction. # @param opts [Hash] Additional options. def initialize(parsed_body, url:, extractor: HtmlExtractor, **opts) @parsed_body = parsed_body @url = url @extractor = extractor @opts = opts end attr_reader :parsed_body ## # @yieldparam [Hash] The scraped article hash # @return [Enumerator] Enumerator for the scraped articles def each return enum_for(:each) unless block_given? filtered_selectors.each do |selector| parsed_body.xpath(selector).each do |selected_tag| next if selected_tag.path.match?(Html::TAGS_TO_IGNORE) article_tag = HtmlNavigator.parent_until_condition(selected_tag, method(:article_tag_condition?)) if article_tag && (article_hash = @extractor.new(article_tag, base_url: @url).call) yield article_hash end end end end def article_tag_condition?(node) # Ignore tags that are below a tag which is in TAGS_TO_IGNORE. return false if node.path.match?(TAGS_TO_IGNORE) return true if %w[body html].include?(node.name) count_of_anchors_below = node.name == 'a' ? 1 : node.css('a').size return true if node.parent.css('a').size > count_of_anchors_below false end private ## # Find relevant anchors in root. # @return [Set<String>] The set of XPath selectors def selectors @selectors ||= Hash.new(0).tap do |selectors| @parsed_body.at_css('body').traverse do |node| next if !node.element? || node.name != 'a' || String(node['href']).empty? path = self.class.simplify_xpath(node.path) next if path.match?(TAGS_TO_IGNORE) selectors[path] += 1 end end end ## # Filter the frequent selectors by the minimum_selector_frequency and use_top_selectors. # @return [Array<String>] The filtered selectors def filtered_selectors selectors.keys.sort_by { |key| selectors[key] } .last(use_top_selectors) .filter_map do |key| selectors[key] >= minimum_selector_frequency ? key : nil end end def minimum_selector_frequency = @opts[:minimum_selector_frequency] || DEFAULT_MINIMUM_SELECTOR_FREQUENCY def use_top_selectors = @opts[:use_top_selectors] || DEFAULT_USE_TOP_SELECTORS end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/auto_source/scraper/schema/category_extractor.rb
lib/html2rss/auto_source/scraper/schema/category_extractor.rb
# frozen_string_literal: true module Html2rss class AutoSource module Scraper class Schema ## # Extracts categories from Schema.org structured data. module CategoryExtractor ## # Extracts categories from a schema object. # # @param schema_object [Hash] The schema object # @return [Array<String>] Array of category strings def self.call(schema_object) # Build union of all category sources field_categories = extract_field_categories(schema_object) about_categories = extract_about_categories(schema_object) (field_categories | about_categories).to_a end ## # Extracts categories from keywords, categories, and tags fields. # # @param schema_object [Hash] The schema object # @return [Set<String>] Set of category strings def self.extract_field_categories(schema_object) Set.new.tap do |categories| %w[keywords categories tags].each do |field| categories.merge(extract_field_value(schema_object, field)) end end end ## # Extracts categories from the about field. # # @param schema_object [Hash] The schema object # @return [Set<String>] Set of category strings def self.extract_about_categories(schema_object) about = schema_object[:about] return Set.new unless about if about.is_a?(Array) extract_about_array(about) elsif about.is_a?(String) extract_string_categories(about) else Set.new end end ## # Extracts categories from a single field value. # # @param schema_object [Hash] The schema object # @param field [String] The field name # @return [Set<String>] Set of category strings def self.extract_field_value(schema_object, field) value = schema_object[field.to_sym] return Set.new unless value if value.is_a?(Array) Set.new(value.map(&:to_s).reject(&:empty?)) elsif value.is_a?(String) extract_string_categories(value) else Set.new end end ## # Extracts categories from an about array. # # @param about [Array] The about array # @return [Set<String>] Set of category strings def self.extract_about_array(about) Set.new.tap do |categories| about.each do |item| if item.is_a?(Hash) && item[:name] categories.add(item[:name].to_s) elsif item.is_a?(String) categories.add(item) end end end end ## # Extracts categories from a string by splitting on separators. # # @param string [String] The string to process # @return [Set<String>] Set of category strings def self.extract_string_categories(string) Set.new(string.split(/[,;|]/).map(&:strip).reject(&:empty?)) end end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/auto_source/scraper/schema/item_list.rb
lib/html2rss/auto_source/scraper/schema/item_list.rb
# frozen_string_literal: true module Html2rss class AutoSource module Scraper class Schema ## # Handles schema.org ItemList objects, which contain # 1. itemListElements, and/or # 2. interesting attributes, i.e. description, url, image, itself. # # @see https://schema.org/ItemList class ItemList < Thing SUPPORTED_TYPES = Set['ItemList'] # @return [Array<Hash>] the scraped article hashes with DEFAULT_ATTRIBUTES def call hashes = [super] return hashes unless (elements = @schema_object[:itemListElement]) elements = [elements] unless elements.is_a?(Array) elements.each do |schema_object| hashes << ListItem.new(schema_object, url: @url).call end hashes end end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/auto_source/scraper/schema/thing.rb
lib/html2rss/auto_source/scraper/schema/thing.rb
# frozen_string_literal: true require 'date' module Html2rss class AutoSource module Scraper class Schema ## # A Thing is kind of the 'base class' for Schema.org schema_objects. # # @see https://schema.org/Thing class Thing SUPPORTED_TYPES = %w[ AdvertiserContentArticle AnalysisNewsArticle APIReference Article AskPublicNewsArticle BackgroundNewsArticle BlogPosting DiscussionForumPosting LiveBlogPosting NewsArticle OpinionNewsArticle Report ReportageNewsArticle ReviewNewsArticle SatiricalArticle ScholarlyArticle SocialMediaPosting TechArticle ].to_set.freeze DEFAULT_ATTRIBUTES = %i[id title description url image published_at categories].freeze def initialize(schema_object, url:) @schema_object = schema_object @url = url end # @return [Hash] the scraped article hash with DEFAULT_ATTRIBUTES def call DEFAULT_ATTRIBUTES.to_h do |attribute| [attribute, public_send(attribute)] end end def id return @id if defined?(@id) id = (schema_object[:@id] || url&.path).to_s return if id.empty? @id = id end def title = schema_object[:title] def description schema_object.values_at(:description, :schema_object_body, :abstract) .max_by { |string| string.to_s.size } end # @return [Html2rss::Url, nil] the URL of the schema object def url url = schema_object[:url] if url.to_s.empty? Log.debug("Schema#Thing.url: no url in schema_object: #{schema_object.inspect}") return end Url.from_relative(url, @url) end def image if (image_url = image_urls.first) Url.from_relative(image_url, @url) end end def published_at = schema_object[:datePublished] def categories return @categories if defined?(@categories) @categories = CategoryExtractor.call(schema_object) end attr_reader :schema_object def image_urls schema_object.values_at(:image, :thumbnailUrl).filter_map do |object| next unless object if object.is_a?(String) object elsif object.is_a?(Hash) && object[:@type] == 'ImageObject' object[:url] || object[:contentUrl] end end end end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/auto_source/scraper/schema/list_item.rb
lib/html2rss/auto_source/scraper/schema/list_item.rb
# frozen_string_literal: true module Html2rss class AutoSource module Scraper class Schema ## # # @see https://schema.org/ListItem class ListItem < Thing def id = (id = (schema_object.dig(:item, :@id) || super).to_s).empty? ? nil : id def title = schema_object.dig(:item, :name) || super || url&.titleized def description = schema_object.dig(:item, :description) || super # @return [Html2rss::Url, nil] def url url = schema_object.dig(:item, :url) || super Url.from_relative(url, @url) if url end end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/rendering/pdf_renderer.rb
lib/html2rss/rendering/pdf_renderer.rb
# frozen_string_literal: true require 'cgi' module Html2rss module Rendering # Renders an HTML <iframe> for PDF documents. class PdfRenderer def initialize(url:) @url = url end def to_html %(<iframe src="#{escaped_url}" width="100%" height="75vh" sandbox="" referrerpolicy="no-referrer" loading="lazy"> </iframe>) end private def escaped_url CGI.escapeHTML(@url.to_s) end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/rendering/video_renderer.rb
lib/html2rss/rendering/video_renderer.rb
# frozen_string_literal: true require 'cgi' module Html2rss module Rendering # Renders an HTML <video> tag from a URL and type. class VideoRenderer def initialize(url:, type:) @url = url @type = type end def to_html %(<video controls preload="none" referrerpolicy="no-referrer" crossorigin="anonymous" playsinline> <source src="#{escaped_url}" type="#{escaped_type}"> </video>) end private def escaped_url CGI.escapeHTML(@url.to_s) end def escaped_type CGI.escapeHTML(@type.to_s) end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/rendering/image_renderer.rb
lib/html2rss/rendering/image_renderer.rb
# frozen_string_literal: true require 'cgi' module Html2rss module Rendering # Renders an HTML <img> tag from a URL and title. class ImageRenderer def initialize(url:, title:) @url = url @title = title end def to_html %(<img src="#{@url}" alt="#{escaped_title}" title="#{escaped_title}" loading="lazy" referrerpolicy="no-referrer" decoding="async" crossorigin="anonymous">).delete("\n").gsub(/\s+/, ' ') end private def escaped_title CGI.escapeHTML(@title.to_s) end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/rendering/media_table_renderer.rb
lib/html2rss/rendering/media_table_renderer.rb
# frozen_string_literal: true require 'cgi' module Html2rss module Rendering # Renders a collapsible table of all available media resources. # # Creates an HTML <details><summary> section with a table listing # all enclosures and fallback images found for an article. # # @example Basic usage # renderer = MediaTableRenderer.new( # enclosures: [enclosure1, enclosure2], # image: "https://example.com/image.jpg" # ) # html = renderer.to_html # class MediaTableRenderer TABLE_HTML = <<~HTML.strip.freeze <table> <thead> <tr> <th>Type</th> <th>URL</th> <th>Actions</th> </tr> </thead> <tbody> %<rows>s </tbody> </table> HTML PREFIX_TYPE_MAPPINGS = { 'image/' => { icon: '🖼️', label: 'Image', action_text: 'View' }, 'video/' => { icon: '🎥', label: 'Video', action_text: 'Play' }, 'audio/' => { icon: '🎵', label: 'Audio', action_text: 'Play' } }.freeze STRING_TYPE_MAPPINGS = { 'application/pdf' => { icon: '📄', label: 'PDF Document', action_text: 'Open' } }.freeze # @param enclosures [Array<Html2rss::RssBuilder::Enclosure>, nil] Media enclosures # @param image [String, Html2rss::Url, nil] Fallback image URL def initialize(enclosures:, image:) @enclosures = Array(enclosures) @image = image @type_mapping_cache = {} @has_image_enclosure = @enclosures.any? { |enclosure| enclosure.type&.start_with?('image/') } end # Generates the complete media table HTML. # # @return [String, nil] The complete media table or nil if no media available def to_html return nil unless media? <<~HTML.strip <details> <summary>Available resources</summary> #{format(TABLE_HTML, rows: table_rows)} </details> HTML end private def media? @enclosures.any? || @image end def table_rows rows = @enclosures.map { |enclosure| enclosure_row(enclosure) } rows << image_row(@image) if @image && !@has_image_enclosure rows.join("\n") end def enclosure_row(enclosure) mapping = type_mapping_for(enclosure.type) escaped = escape_url(enclosure.url) type_icon = mapping&.fetch(:icon, nil) || '📎' type_label = mapping&.fetch(:label, nil) || 'File' <<~HTML.strip <tr> <td>#{type_icon} #{type_label}</td> <td><a href="#{escaped}" target="_blank" rel="nofollow noopener noreferrer">#{escaped}</a></td> <td>#{action_links_for(escaped, mapping)}</td> </tr> HTML end def image_row(url) escaped = escape_url(url) <<~HTML.strip <tr> <td>🖼️ Image</td> <td><a href="#{escaped}" target="_blank" rel="nofollow noopener noreferrer">#{escaped}</a></td> <td>#{action_links_html(escaped, 'View')}</td> </tr> HTML end def action_links_for(escaped_url, mapping) action_text = mapping&.fetch(:action_text, nil) return download_link(escaped_url) unless action_text action_links_html(escaped_url, action_text) end def action_links_html(escaped_url, action_text) <<~HTML.strip <a href="#{escaped_url}" target="_blank" rel="nofollow noopener noreferrer">#{action_text}</a> | #{download_link(escaped_url)} HTML end def download_link(escaped_url) <<~HTML.strip <a href="#{escaped_url}" target="_blank" rel="nofollow noopener noreferrer" download="">Download</a> HTML end def type_mapping_for(type) return if type.nil? return @type_mapping_cache[type] if @type_mapping_cache.key?(type) @type_mapping_cache[type] = STRING_TYPE_MAPPINGS[type] || prefix_mapping_for(type) end def prefix_mapping_for(type) PREFIX_TYPE_MAPPINGS.each do |prefix, mapping| return mapping if type.start_with?(prefix) end nil end def escape_url(url) CGI.escapeHTML(url.to_s) end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/rendering/audio_renderer.rb
lib/html2rss/rendering/audio_renderer.rb
# frozen_string_literal: true require 'cgi' module Html2rss module Rendering # Renders an HTML <audio> tag from a URL and type. class AudioRenderer def initialize(url:, type:) @url = url @type = type end def to_html %(<audio controls preload="none" referrerpolicy="no-referrer" crossorigin="anonymous"> <source src="#{escaped_url}" type="#{escaped_type}"> </audio>) end private def escaped_url CGI.escapeHTML(@url.to_s) end def escaped_type CGI.escapeHTML(@type.to_s) end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/rendering/media_renderer.rb
lib/html2rss/rendering/media_renderer.rb
# frozen_string_literal: true module Html2rss module Rendering # Picks the appropriate media renderer based on the enclosure type or fallback image. # # Factory class that creates the correct renderer for different media types. # Supports images, audio, video, and PDF documents. # # @example With enclosure # MediaRenderer.for(enclosure: enclosure_obj, image: nil, title: "Title") # # => ImageRenderer, VideoRenderer, AudioRenderer, or PdfRenderer # # @example With fallback image # MediaRenderer.for(enclosure: nil, image: "image.jpg", title: "Title") # # => ImageRenderer # class MediaRenderer # Creates the appropriate media renderer. # # @param enclosure [Html2rss::RssBuilder::Enclosure, nil] The media enclosure # @param image [String, Html2rss::Url, nil] Fallback image URL # @param title [String] Title for alt text and accessibility # @return [ImageRenderer, VideoRenderer, AudioRenderer, PdfRenderer, nil] The appropriate renderer def self.for(enclosure:, image:, title:) return ImageRenderer.new(url: image, title:) if enclosure.nil? && image return nil unless enclosure new_from_enclosure(enclosure, title) end # @private def self.new_from_enclosure(enclosure, title) url = enclosure.url type = enclosure.type create_renderer_for_type(type, url:, title:) end # @private def self.create_renderer_for_type(type, url:, title:) case type when %r{^image/} ImageRenderer.new(url:, title:) when %r{^video/} VideoRenderer.new(url:, type:) when %r{^audio/} AudioRenderer.new(url:, type:) when 'application/pdf' PdfRenderer.new(url:) end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/rendering/description_builder.rb
lib/html2rss/rendering/description_builder.rb
# frozen_string_literal: true require 'cgi' module Html2rss module Rendering # Builds a sanitized article description from the base text, title, and optional media. # # Combines media elements (images, audio, video, PDFs) with sanitized text content # to create rich RSS descriptions that reveal more scraped information. # # @example Basic usage # builder = DescriptionBuilder.new( # base: "Article content", # title: "Article Title", # url: "https://example.com", # enclosures: [enclosure_object], # image: "https://example.com/image.jpg" # ) # description = builder.call # class DescriptionBuilder ## # Removes the specified pattern from the beginning of the text # within a given range if the pattern occurs before the range's end. # # @param text [String] # @param pattern [String] # @param end_of_range [Integer] Optional, defaults to half the text length # @return [String] def self.remove_pattern_from_start(text, pattern, end_of_range: (text.size * 0.5).to_i) return text unless text.is_a?(String) && pattern.is_a?(String) index = text.index(pattern) return text if index.nil? || index >= end_of_range text.gsub(/^(.{0,#{end_of_range}})#{Regexp.escape(pattern)}/, '\1') end # @param base [String] The base text content for the description # @param title [String] The article title (used for alt text and title removal) # @param url [String, Html2rss::Url] The article URL (used for sanitization) # @param enclosures [Array<Html2rss::RssBuilder::Enclosure>, nil] Media enclosures # @param image [String, Html2rss::Url, nil] Fallback image URL def initialize(base:, title:, url:, enclosures:, image:) @base = base.to_s @title = title @url = url @enclosures = Array(enclosures) @image = image end # Generates the complete description with media and sanitized text. # # @return [String, nil] The complete description or nil if empty def call fragments = [] fragments.concat(Array(rendered_media)) fragments << processed_base_description fragments << media_table_html result = fragments.compact.join("\n\n").strip result.empty? ? nil : result end private def rendered_media return render_enclosures if @enclosures.any? return render_fallback_image if @image [] end def render_enclosures @enclosures.filter_map do |enclosure| MediaRenderer.for(enclosure:, image: @image, title: @title)&.to_html end end def render_fallback_image [MediaRenderer.for(enclosure: nil, image: @image, title: @title)&.to_html] end def media_table_html MediaTableRenderer.new(enclosures: @enclosures, image: @image).to_html end def processed_base_description text = self.class.remove_pattern_from_start(@base, @title) Html2rss::Selectors::PostProcessors::SanitizeHtml.get(text, @url) end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/request_service/strategy.rb
lib/html2rss/request_service/strategy.rb
# frozen_string_literal: true module Html2rss class RequestService ## # Defines the interface of every request strategy. class Strategy ## # @param ctx [Context] the context for the request def initialize(ctx) @ctx = ctx end ## # Executes the request. # @return [Response] the response from the strategy # @raise [NotImplementedError] if the method is not implemented by the subclass def execute raise NotImplementedError, 'Subclass must implement #execute' end private # @return [Context] the context for the request attr_reader :ctx end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/request_service/response.rb
lib/html2rss/request_service/response.rb
# frozen_string_literal: true require 'nokogiri' module Html2rss class RequestService ## # To be used by strategies to provide their response. class Response ## # @param body [String] the body of the response # @param headers [Hash] the headers of the response def initialize(body:, url:, headers: {}) @body = body headers = headers.dup headers.transform_keys!(&:to_s) @headers = headers @url = url end # @return [String] the raw body of the response attr_reader :body # @return [Hash<String, Object>] the headers of the response attr_reader :headers # @return [Html2rss::Url] the URL of the response attr_reader :url def content_type = headers['content-type'] || '' def json_response? = content_type.include?('application/json') def html_response? = content_type.include?('text/html') ## # @return [Nokogiri::HTML::Document, Hash] the parsed body of the response, frozen object # @raise [UnsupportedResponseContentType] if the content type is not supported def parsed_body @parsed_body ||= if html_response? Nokogiri::HTML(body).tap do |doc| # Remove comments from the document to avoid processing irrelevant content doc.xpath('//comment()').each(&:remove) end.freeze elsif json_response? JSON.parse(body, symbolize_names: true).freeze else raise UnsupportedResponseContentType, "Unsupported content type: #{content_type}" end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/request_service/faraday_strategy.rb
lib/html2rss/request_service/faraday_strategy.rb
# frozen_string_literal: true require 'faraday' require 'faraday/follow_redirects' require 'faraday/gzip' module Html2rss class RequestService ## # Strategy to use Faraday for the request. # @see https://rubygems.org/gems/faraday class FaradayStrategy < Strategy # return [Response] def execute url_string = ctx.url.to_s request = Faraday.new(url: url_string, headers: ctx.headers) do |faraday| faraday.use Faraday::FollowRedirects::Middleware faraday.request :gzip faraday.adapter Faraday.default_adapter end response = request.get Response.new(body: response.body, headers: response.headers, url: ctx.url) end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/request_service/puppet_commander.rb
lib/html2rss/request_service/puppet_commander.rb
# frozen_string_literal: true module Html2rss class RequestService ## # Commands the Puppeteer Browser to the website and builds the Response. class PuppetCommander # @param ctx [Context] # @param browser [Puppeteer::Browser] # @param skip_request_resources [Set<String>] the resource types not to request # @param referer [String] the referer to use for the request def initialize(ctx, browser, skip_request_resources: %w[stylesheet image media font].to_set, referer: [ctx.url.scheme, ctx.url.host].join('://')) @ctx = ctx @browser = browser @skip_request_resources = skip_request_resources @referer = referer end # @return [Response] def call page = new_page url = ctx.url response = navigate_to_destination(page, url) Response.new(body: body(page), headers: response.headers, url:) ensure page&.close end ## # @return [Puppeteer::Page] # @see https://yusukeiwaki.github.io/puppeteer-ruby-docs/Puppeteer/Page.html def new_page page = browser.new_page page.extra_http_headers = ctx.headers return page if skip_request_resources.empty? page.request_interception = true page.on('request') do |request| skip_request_resources.member?(request.resource_type) ? request.abort : request.continue end page end def navigate_to_destination(page, url) page.goto(url, wait_until: 'networkidle0', referer:) end def body(page) = page.content private attr_reader :ctx, :browser, :skip_request_resources, :referer end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/request_service/context.rb
lib/html2rss/request_service/context.rb
# frozen_string_literal: true module Html2rss class RequestService ## # Holds information needed to send requests to websites. # To be passed down to the RequestService's strategies. class Context ## # @param url [String, Html2rss::Url] the URL to request # @param headers [Hash] HTTP request headers def initialize(url:, headers: {}) @url = Html2rss::Url.from_relative(url, url) @headers = headers end # @return [Html2rss::Url] the parsed and normalized URL attr_reader :url # @return [Hash] the HTTP request headers attr_reader :headers end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/request_service/browserless_strategy.rb
lib/html2rss/request_service/browserless_strategy.rb
# frozen_string_literal: true require 'puppeteer' module Html2rss class RequestService ## # Browserless.io strategy to request websites. # # Provide the WebSocket URL and your API token via environment variables: # - BROWSERLESS_IO_WEBSOCKET_URL # - BROWSERLESS_IO_API_TOKEN # # To use this strategy, you need to have a Browserless.io account or run a # local Browserless.io instance. # # @see https://www.browserless.io/ # # To run a local Browserless.io instance, you can use the following Docker command: # # ```sh # docker run \ # --rm \ # -p 3000:3000 \ # -e "CONCURRENT=10" \ # -e "TOKEN=6R0W53R135510" \ # ghcr.io/browserless/chromium # ``` # # When running locally, you can skip setting the environment variables, as above commands # are aligned with the default values. # @see https://github.com/browserless/browserless/pkgs/container/chromium class BrowserlessStrategy < Strategy # return [Response] def execute Puppeteer.connect(browser_ws_endpoint:) do |browser| PuppetCommander.new(ctx, browser).call ensure browser.disconnect end end def browser_ws_endpoint @browser_ws_endpoint ||= begin api_token = ENV.fetch('BROWSERLESS_IO_API_TOKEN', '6R0W53R135510') ws_url = ENV.fetch('BROWSERLESS_IO_WEBSOCKET_URL', 'ws://127.0.0.1:3000') "#{ws_url}?token=#{api_token}" end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/articles/deduplicator.rb
lib/html2rss/articles/deduplicator.rb
# frozen_string_literal: true require 'set' # rubocop:disable Lint/RedundantRequireStatement module Html2rss module Articles ## # Deduplicates a list of articles while preserving their original order. # # The deduplicator prefers each article's URL (combined with its ID when # available) to determine uniqueness. When no URL is present, it falls # back to the article ID, then to the GUID enriched with title and # description metadata. If none of these identifiers are available it # defaults to the article object's hash to preserve the original entry. class Deduplicator ## # @param articles [Array<Html2rss::RssBuilder::Article>] # @raise [ArgumentError] if articles are not provided def initialize(articles) raise ArgumentError, 'articles must be provided' unless articles @articles = articles end ## # Returns the list of unique articles, preserving the order of the # original collection and keeping the first occurrence of a duplicate. # @return [Array<Html2rss::RssBuilder::Article>] def call seen = Set.new articles.each_with_object([]) do |article, deduplicated| fingerprint = deduplication_fingerprint_for(article) fingerprint ||= article.hash next unless seen.add?(fingerprint) deduplicated << article end end private attr_reader :articles def deduplication_fingerprint_for(article) return unless article.respond_to?(:deduplication_fingerprint) article.deduplication_fingerprint end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/selectors/extractors.rb
lib/html2rss/selectors/extractors.rb
# frozen_string_literal: true module Html2rss class Selectors ## # Provides a namespace for item extractors. module Extractors ## # Maps the extractor name to the class implementing the extractor. # # The key is the name to use in the feed config. NAME_TO_CLASS = { attribute: Attribute, href: Href, html: Html, static: Static, text: Text }.freeze ## # Maps the extractor class to its corresponding options class. ITEM_OPTION_CLASSES = Hash.new do |hash, klass| hash[klass] = klass.const_get(:Options) end DEFAULT_EXTRACTOR = :text class << self ## # Retrieves an element from Nokogiri XML based on the selector. # # @param xml [Nokogiri::XML::Document] # @param selector [String, nil] # @return [Nokogiri::XML::ElementSet] selected XML elements def element(xml, selector) selector ? xml.css(selector) : xml end # @param attribute_options [Hash<Symbol, Object>] # Should contain at least `:extractor` (the name) and required options for that extractor. # @param xml [Nokogiri::XML::Document] # @return [Object] instance of the specified item extractor class def get(attribute_options, xml) extractor_class = NAME_TO_CLASS[attribute_options[:extractor]&.to_sym || DEFAULT_EXTRACTOR] options = ITEM_OPTION_CLASSES[extractor_class].new(attribute_options.slice(*extractor_class::Options.members)) extractor_class.new(xml, options).get end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/selectors/config.rb
lib/html2rss/selectors/config.rb
# frozen_string_literal: true require 'dry-validation' module Html2rss class Selectors ## # Validates the configuration hash for :selectors. class Config < Dry::Validation::Contract NESTING_KEY = :dynamic_keys_workaround ## # Validates the configuration of the :items selector class Items < Dry::Validation::Contract params do required(:selector).filled(:string) optional(:order).filled(included_in?: %w[reverse]) optional(:enhance).filled(:bool?) end end ## # Validates the configuration of a single selector. class Selector < Dry::Validation::Contract params do optional(:selector) optional(:extractor).filled(:string) optional(:attribute).filled(:string) optional(:static).filled(:string) optional(:post_process).array(:hash) end rule(:selector) do key(:selector).failure('`selector` must be a string') if value && !value.is_a?(String) end rule(:extractor) do # dependent on the extractor, validate required fields, (i.e. static, attribute) case value when 'attribute' key(:attribute).failure('`attribute` must be a string') unless values[:attribute].is_a?(String) when 'static' key(:static).failure('`static` must be a string') unless values[:static].is_a?(String) end end rule(:post_process).each do case (name = value[:name]) when 'gsub' key(:pattern).failure('`pattern` must be a string') unless value[:pattern].is_a?(String) key(:replacement).failure('`replacement` must be a string') unless value[:replacement].is_a?(String) when 'substring' key(:start).failure('`start` must be an integer') unless value[:start].is_a?(Integer) key(:end).failure('`end` must be an integer or omitted') if !value[:end].nil? && !value[:end].is_a?(Integer) when 'template' key(:string).failure('`string` must be a string') unless value[:string].is_a?(String) when 'html_to_markdown', 'markdown_to_html', 'parse_time', 'parse_uri', 'sanitize_html' # nothing to validate when nil key(:post_process).failure('Missing post_processor `name`') else key(:post_process).failure("Unknown post_processor `name`: #{name}") end end end ## # Validates the configuration of the :enclosure Selector class Enclosure < Selector params do optional(:content_type).filled(:string, format?: %r{^[\w-]+/[\w-]+$}) end end params do required(NESTING_KEY).hash end rule(NESTING_KEY) do value.each_pair do |selector_key, selector| case selector_key.to_sym when Selectors::ITEMS_SELECTOR_KEY Items.new.call(selector).errors.each { |error| key(selector_key).failure(error) } when :enclosure Enclosure.new.call(selector).errors.each { |error| key(selector_key).failure(error) } when :guid, :categories unless selector.is_a?(Array) key(selector_key).failure("`#{selector_key}` must be an array") next end key(selector_key).failure("`#{selector_key}` must contain at least one element") if selector.empty? selector.each do |name| next if values[NESTING_KEY].key?(name.to_sym) key(selector_key).failure("`#{selector_key}` references unspecified `#{name}`") end else # From here on, the selector is found under its "dynamic" selector_key Selector.new.call(selector).errors.each { |error| key(selector_key).failure(error) } end end end ## # Shortcut to validate the config. # @param config [Hash] the configuration hash to validate # @return [Dry::Validation::Result] the result of the validation def self.call(config) # dry-validation/schema does not support "Dynamic Keys" yet: https://github.com/dry-rb/dry-schema/issues/37 # But :selectors contains mostly "dynamic" keys, as the user defines them to extract article attributes. # --> Validate the dynamic keys manually. # To be able to specify a `rule`, nest the config under NESTING_KEY and mark that as `required`. new.call(NESTING_KEY => config) end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/selectors/object_to_xml_converter.rb
lib/html2rss/selectors/object_to_xml_converter.rb
# frozen_string_literal: true require 'cgi' module Html2rss class Selectors ## # A naive implementation of "Object to XML": converts a Ruby object to XML format. class ObjectToXmlConverter OBJECT_TO_XML_TAGS = { hash: ['<object>', '</object>'], array: ['<array>', '</array>'] }.freeze ## # @param object [Object] any Ruby object (Hash, Array, String, Symbol, etc.) def initialize(object) @object = object end ## # Converts the object to XML format. # # @return [String] representing the object in XML def call object_to_xml(@object).tap do |converted| Html2rss::Log.info "Converted to XML. Excerpt:\n\t#{converted.to_s[0..110]}…" end end private def object_to_xml(object) case object when Hash hash_to_xml(object) when Array array_to_xml(object) else CGI.escapeHTML(object.to_s) end end def hash_to_xml(object) prefix, suffix = OBJECT_TO_XML_TAGS[:hash] inner_xml = object.each_with_object(+'') do |(key, value), str| str << "<#{key}>#{object_to_xml(value)}</#{key}>" end "#{prefix}#{inner_xml}#{suffix}" end def array_to_xml(object) prefix, suffix = OBJECT_TO_XML_TAGS[:array] inner_xml = object.each_with_object(+'') { |value, str| str << object_to_xml(value) } "#{prefix}#{inner_xml}#{suffix}" end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/selectors/post_processors.rb
lib/html2rss/selectors/post_processors.rb
# frozen_string_literal: true module Html2rss class Selectors ## # Provides a namespace for attribute post processors. module PostProcessors ## # Error raised when an unknown post processor name is requested. class UnknownPostProcessorName < Html2rss::Error; end ## # Error raised when a required option is missing. class MissingOption < Html2rss::Error; end ## # Error raised when an invalid type is provided. class InvalidType < Html2rss::Error; end ## # Maps the post processor name to the class implementing the post processor. # # The key is the name to use in the feed config. NAME_TO_CLASS = { gsub: Gsub, html_to_markdown: HtmlToMarkdown, markdown_to_html: MarkdownToHtml, parse_time: ParseTime, parse_uri: ParseUri, sanitize_html: SanitizeHtml, substring: Substring, template: Template }.freeze ## # Shorthand method to instantiate the post processor and call `#get` on it def self.get(name, value, context) klass = NAME_TO_CLASS[name.to_sym] || raise(UnknownPostProcessorName, "Unknown name '#{name}'") klass.new(value, context).get end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/selectors/extractors/href.rb
lib/html2rss/selectors/extractors/href.rb
# frozen_string_literal: true module Html2rss class Selectors module Extractors ## # Returns the value of the +href+ attribute. # It always returns absolute URLs. If the extracted +href+ value is a # relative URL, it prepends the channel's URL. # # Imagine this +a+ HTML element with a +href+ attribute: # # <a href="/posts/latest-findings">...</a> # # YAML usage example: # channel: # url: http://blog-without-a-feed.example.com # ... # selectors: # link: # selector: a # extractor: href # # Would return: # 'http://blog-without-a-feed.example.com/posts/latest-findings' class Href # The available options for the href (attribute) extractor. Options = Struct.new('HrefOptions', :selector, :channel, keyword_init: true) ## # Initializes the Href extractor. # # @param xml [Nokogiri::XML::Element] # @param options [Options] def initialize(xml, options) @options = options @element = Extractors.element(xml, options.selector) @href = @element.attr('href').to_s end ## # Retrieves and returns the normalized absolute URL. # # @return [String] The absolute URL. def get return nil unless @href Url.from_relative(@href, @options.channel[:url]) end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/selectors/extractors/text.rb
lib/html2rss/selectors/extractors/text.rb
# frozen_string_literal: true module Html2rss class Selectors module Extractors ## # Return the text content of the attribute. This is the default extractor used, # when no extractor is explicitly given. # # Example HTML structure: # # <p>Lorem <b>ipsum</b> dolor ...</p> # # YAML usage example: # # selectors: # description: # selector: p # extractor: text # # Would return: # 'Lorem ipsum dolor ...' class Text # The available options for the text extractor. Options = Struct.new('TextOptions', :selector, keyword_init: true) ## # Initializes the Text extractor. # # @param xml [Nokogiri::XML::Element] # @param options [Options] def initialize(xml, options) @element = Extractors.element(xml, options.selector) end ## # Retrieves and returns the text content of the element. # # @return [String] The text content. def get @element.text.to_s.strip.gsub(/\s+/, ' ') end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/selectors/extractors/attribute.rb
lib/html2rss/selectors/extractors/attribute.rb
# frozen_string_literal: true module Html2rss class Selectors module Extractors ## # Returns the value of the attribute. # # Imagine this +time+ HTML tag with a +datetime+ attribute: # # <time datetime="2019-07-01">...</time> # # YAML usage example: # # selectors: # link: # selector: time # extractor: attribute # attribute: datetime # # Would return: # '2019-07-01' # # In case you're extracting a date or a time, consider parsing it # during post processing with {PostProcessors::ParseTime}. class Attribute # The available options for the attribute extractor. Options = Struct.new('AttributeOptions', :selector, :attribute, keyword_init: true) ## # Initializes the Attribute extractor. # # @param xml [Nokogiri::XML::Element] # @param options [Options] def initialize(xml, options) @options = options @element = Extractors.element(xml, options.selector) end ## # Retrieves and returns the attribute's value as a string. # # @return [String] The value of the attribute. def get @element.attr(@options.attribute).to_s end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/selectors/extractors/static.rb
lib/html2rss/selectors/extractors/static.rb
# frozen_string_literal: true module Html2rss class Selectors module Extractors ## # Returns a static value provided in the options. # # Example usage in YAML: # # selectors: # author: # extractor: static # static: Foobar # # Would return: # 'Foobar' class Static # The available option for the static extractor. Options = Struct.new('StaticOptions', :static, keyword_init: true) ## # Initializes the Static extractor. # # @param _xml [nil, Nokogiri::XML::Element] Unused parameter for compatibility with other extractors. # @param options [Options] Options containing the static value. def initialize(_xml, options) @options = options end ## # Retrieves and returns the static value. # # @return [String, Symbol] The static value provided in options. def get @options.static end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/selectors/extractors/html.rb
lib/html2rss/selectors/extractors/html.rb
# frozen_string_literal: true module Html2rss class Selectors module Extractors ## # Returns the HTML content of the specified element. # # Example HTML structure: # # <p>Lorem <b>ipsum</b> dolor ...</p> # # YAML usage example: # # selectors: # description: # selector: p # extractor: html # # Would return: # '<p>Lorem <b>ipsum</b> dolor ...</p>' # # Always ensure to sanitize the HTML during post-processing with # {PostProcessors::SanitizeHtml}. class Html # The available options for the html extractor. Options = Struct.new('HtmlOptions', :selector, keyword_init: true) ## # Initializes the Html extractor. # # @param xml [Nokogiri::XML::Element] # @param options [Options] def initialize(xml, options) @element = Extractors.element(xml, options.selector) end ## # Retrieves and returns the HTML content of the element. # # @return [String] The HTML content. def get @element.to_s end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/selectors/post_processors/parse_uri.rb
lib/html2rss/selectors/post_processors/parse_uri.rb
# frozen_string_literal: true module Html2rss class Selectors module PostProcessors ## # Returns the URI as String. # If the URL is relative, it builds an absolute one with the channel's URL as base. # # Imagine this HTML structure: # # <span>http://why-not-use-a-link.uh </span> # # YAML usage example: # # selectors: # link: # selector: span # extractor: text # post_process: # name: parse_uri # # Would return: # 'http://why-not-use-a-link.uh' class ParseUri < Base def self.validate_args!(value, _context) raise ArgumentError, 'The `value` option is missing or empty.' if value.to_s.empty? end ## # @return [String] def get config_url = context.dig(:config, :channel, :url) Url.from_relative(value, config_url).to_s end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/selectors/post_processors/gsub.rb
lib/html2rss/selectors/post_processors/gsub.rb
# frozen_string_literal: true require 'regexp_parser' module Html2rss class Selectors module PostProcessors ## # Imagine this HTML: # <h1>Foo bar and boo<h1> # # YAML usage example: # selectors: # title: # selector: h1 # post_process: # name: gsub # pattern: boo # replacement: baz # # Would return: # 'Foo bar and baz' # # `pattern` can be a Regexp or a String. If it is a String, it will remove # one pair of surrounding slashes ('/') to keep backwards compatibility # and then parse it to build a Regexp. # # `replacement` can be a String or a Hash. # # See the doc on [String#gsub](https://ruby-doc.org/core/String.html#method-i-gsub) for more info. class Gsub < Base def self.validate_args!(value, context) assert_type value, String, :value, context: expect_options(%i[replacement pattern], context) assert_type context.dig(:options, :replacement), [String, Hash], :replacement, context: end ## # @param value [String] # @param context [Selectors::Context] def initialize(value, context) super options = context[:options] @replacement = options[:replacement] @pattern = options[:pattern] end ## # @return [String] def get value.to_s.gsub(pattern, replacement) end private attr_accessor :replacement ## # @return [Regexp] def pattern @pattern.is_a?(String) ? parse_regexp_string(@pattern) : @pattern end ## # Parses the given String and builds a Regexp out of it. # # It will remove one pair of surrounding slashes ('/') from the String # to maintain backwards compatibility before building the Regexp. # # @param string [String] # @return [Regexp] def parse_regexp_string(string) raise ArgumentError, 'must be a string!' unless string.is_a?(String) # Only remove surrounding slashes if the string has at least 3 characters # to avoid issues with single character strings like "/" string = string[1..-2] if string.length >= 3 && string.start_with?('/') && string.end_with?('/') Regexp::Parser.parse(string, options: ::Regexp::EXTENDED | ::Regexp::IGNORECASE).to_re end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/selectors/post_processors/html_to_markdown.rb
lib/html2rss/selectors/post_processors/html_to_markdown.rb
# frozen_string_literal: true require 'reverse_markdown' module Html2rss class Selectors module PostProcessors ## # Returns HTML code as Markdown formatted String. # Before converting to markdown, the HTML is sanitized with SanitizeHtml. # Imagine this HTML structure: # # <section> # Lorem <b>ipsum</b> dolor... # <iframe src="https://evil.corp/miner"></iframe> # <script>alert();</script> # </section> # # YAML usage example: # # selectors: # description: # selector: section # extractor: html # post_process: # name: html_to_markdown # # Would return: # 'Lorem **ipsum** dolor' class HtmlToMarkdown < Base def self.validate_args!(value, context) assert_type value, String, :value, context: end ## # @return [String] formatted in Markdown def get sanitized_value = SanitizeHtml.new(value, context).get ReverseMarkdown.convert(sanitized_value) end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/selectors/post_processors/base.rb
lib/html2rss/selectors/post_processors/base.rb
# frozen_string_literal: true module Html2rss class Selectors module PostProcessors ## # All post processors must inherit from this base class and implement `self.validate_args!` and `#get`. class Base # Validates the presence of required options in the context # # @param keys [Array<Symbol>] the keys to check for presence # @param context [Hash] the context containing options # @raise [MissingOption] if any key is missing def self.expect_options(keys, context) keys.each do |key| unless (options = context[:options]).key?(key) raise MissingOption, "The `#{key}` option is missing in: #{options.inspect}", [], cause: nil end end end # Asserts that the value is of the expected type(s) # # @param value [Object] the value to check # @param types [Array<Class>, Class] the expected type(s) # @param name [String] the name of the option being checked # @param context [Selectors::Context] the context # @raise [InvalidType] if the value is not of the expected type(s) def self.assert_type(value, types = [], name, context:) return if Array(types).any? { |type| value.is_a?(type) } options = if context.is_a?(Hash) context[:options] else { file: File.basename(caller(1, 1).first.split(':').first) } end message = "The type of `#{name}` must be #{Array(types).join(' or ')}, " \ "but is: #{value.class} in: #{options.inspect}" raise InvalidType, message, [], cause: nil end ## # This method validates the arguments passed to the post processor. Must be implemented by subclasses. def self.validate_args!(_value, _context) raise NotImplementedError, 'You must implement the `validate_args!` method in the post processor' end # Initializes the post processor # # @param value [Object] the value to be processed # @param context [Selectors::Context] the context def initialize(value, context) klass = self.class # TODO: get rid of Hash klass.assert_type(context, [Selectors::Context, Hash], 'context', context:) klass.validate_args!(value, context) @value = value @context = context end attr_reader :value, :context # Abstract method to be implemented by subclasses # # @raise [NotImplementedError] if not implemented in subclass def get raise NotImplementedError, 'You must implement the `get` method in the post processor' end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/selectors/post_processors/substring.rb
lib/html2rss/selectors/post_processors/substring.rb
# frozen_string_literal: true module Html2rss class Selectors module PostProcessors ## # Returns a defined part of a String. # # Both parameters must be an Integer and they can be negative. # The +end+ parameter can be omitted, in that case it will not cut the # String at the end. # # A Regexp or a MatchString is not supported. # # See the [`String#[]`](https://ruby-doc.org/core/String.html#method-i-5B-5D) # documentation for more information. # # Imagine this HTML: # <h1>Foo bar and baz<h1> # # YAML usage example: # selectors: # title: # selector: h1 # post_process: # name: substring # start: 4 # end: 6 # # Would return: # 'bar' class Substring < Base def self.validate_args!(value, context) assert_type value, String, :value, context: options = context[:options] assert_type options[:start], Integer, :start, context: end_index = options[:end] assert_type(end_index, Integer, :end, context:) if end_index end ## # Extracts the substring from the original string based on the provided start and end indices. # # @return [String] The extracted substring. def get value[range] end ## # Determines the range for the substring extraction based on the provided start and end indices. # # @return [Range] The range object representing the start and end/Infinity (integers). def range return (start_index..) unless end_index? if start_index == end_index raise ArgumentError, 'The `start` value must be unequal to the `end` value.' end (start_index..end_index) end private def end_index? = !context[:options][:end].to_s.empty? def end_index = context[:options][:end].to_i def start_index = context[:options][:start].to_i end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/selectors/post_processors/markdown_to_html.rb
lib/html2rss/selectors/post_processors/markdown_to_html.rb
# frozen_string_literal: true require 'kramdown' require_relative 'sanitize_html' module Html2rss class Selectors module PostProcessors ## # Generates HTML from Markdown. # # It's particularly useful in conjunction with the Template post processor # to generate a description from other selectors. # # YAML usage example: # # selectors: # description: # selector: section # post_process: # - name: template # string: | # # %s # # Price: %s # methods: # - self # - price # - name: markdown_to_html # # Would e.g. return: # # <h1>Section</h1> # # <p>Price: 12.34</p> class MarkdownToHtml < Base def self.validate_args!(value, context) assert_type value, String, :value, context: end ## # Converts Markdown to sanitized HTML. # # @return [String] Sanitized HTML content def get html_content = Kramdown::Document.new(value).to_html SanitizeHtml.new(html_content, context).get end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/selectors/post_processors/template.rb
lib/html2rss/selectors/post_processors/template.rb
# frozen_string_literal: true module Html2rss class Selectors module PostProcessors ## # Returns a formatted String according to the string pattern. # It uses [Kernel#format](https://ruby-doc.org/core/Kernel.html#method-i-format) # # It supports the format pattern `%<key>s` and `%{key}`, where `key` is the key of the selector. # If `%{self}` is used, the selectors extracted value will be used. # # Imagine this HTML: # # <li> # <h1>Product</h1> # <span class="price">23,42€</span> # </li> # # # YAML usage example: # # selectors: # items: # selector: 'li' # price: # selector: '.price' # title: # selector: h1 # post_process: # name: template # string: '%{self}s (%{price})' # # Would return: # 'Product (23,42€)' class Template < Base def self.validate_args!(value, context) assert_type value, String, :value, context: string = context[:options]&.dig(:string).to_s raise InvalidType, 'The `string` template is absent.' if string.empty? end ## # @param value [String] # @param context [Selectors::Context] def initialize(value, context) super @options = context[:options] || {} @scraper = context[:scraper] @item = context[:item] @string = @options[:string].to_s end ## # @return [String] def get Html2rss::Config::DynamicParams.call(@string, {}, getter: method(:item_value), replace_missing_with: '') end private # @param key [String, Symbol] # @return [String] def item_value(key) key = key.to_sym key == :self ? value : @scraper.select(key, @item) end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/selectors/post_processors/sanitize_html.rb
lib/html2rss/selectors/post_processors/sanitize_html.rb
# frozen_string_literal: true require 'sanitize' require_relative 'html_transformers/transform_urls_to_absolute_ones' require_relative 'html_transformers/wrap_img_in_a' module Html2rss class Selectors module PostProcessors ## # Returns sanitized HTML code as String. # # It sanitizes by using the [sanitize gem](https://github.com/rgrove/sanitize) with # [Sanitize::Config::RELAXED](https://github.com/rgrove/sanitize#sanitizeconfigrelaxed). # # Furthermore, it adds: # # - `rel="nofollow noopener noreferrer"` to <a> tags # - `referrer-policy='no-referrer'` to <img> tags # - wraps all <img> tags, whose direct parent is not an <a>, into an <a> # linking to the <img>'s `src`. # # Imagine this HTML structure: # # <section> # Lorem <b>ipsum</b> dolor... # <iframe src="https://evil.corp/miner"></iframe> # <script>alert();</script> # </section> # # YAML usage example: # # selectors: # description: # selector: '.section' # extractor: html # post_process: # name: sanitize_html # # Would return: # '<p>Lorem <b>ipsum</b> dolor ...</p>' class SanitizeHtml < Base # @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy TAG_ATTRIBUTES = { 'a' => { 'rel' => 'nofollow noopener noreferrer', 'target' => '_blank' }, 'area' => { 'rel' => 'nofollow noopener noreferrer', 'target' => '_blank' }, 'img' => { 'referrerpolicy' => 'no-referrer', 'crossorigin' => 'anonymous', 'loading' => 'lazy', 'decoding' => 'async' }, 'iframe' => { 'referrerpolicy' => 'no-referrer', 'crossorigin' => 'anonymous', 'loading' => 'lazy', 'sandbox' => 'allow-same-origin', 'src' => true, 'width' => true, 'height' => true }, 'video' => { 'referrerpolicy' => 'no-referrer', 'crossorigin' => 'anonymous', 'preload' => 'none', 'playsinline' => 'true', 'controls' => 'true' }, 'audio' => { 'referrerpolicy' => 'no-referrer', 'crossorigin' => 'anonymous', 'preload' => 'none' } }.freeze def self.validate_args!(value, context) assert_type value, String, :value, context: end ## # Shorthand method to get the sanitized HTML. # @param html [String] # @param url [String, Html2rss::Url] # @return [String, nil] def self.get(html, url) return nil if String(html).empty? new(html, config: { channel: { url: } }).get end ## # @return [String, nil] def get sanitized_html = Sanitize.fragment(value, sanitize_config).to_s sanitized_html.gsub!(/\s+/, ' ') sanitized_html.strip! sanitized_html.empty? ? nil : sanitized_html end private def channel_url = context.dig(:config, :channel, :url) ## # @return [Sanitize::Config] def sanitize_config # rubocop:disable Metrics/MethodLength config = Sanitize::Config.merge( Sanitize::Config::RELAXED, attributes: { all: %w[dir lang alt title translate] }, add_attributes: TAG_ATTRIBUTES, transformers: [ method(:transform_urls_to_absolute_ones), method(:wrap_img_in_a) ] ) config[:elements].push('audio', 'video', 'source') config end ## # Wrapper for transform_urls_to_absolute_ones to pass the channel_url. # # @param env [Hash] # @return [nil] def transform_urls_to_absolute_ones(env) HtmlTransformers::TransformUrlsToAbsoluteOnes.new(channel_url).call(**env) end ## # Wrapper for wrap_img_in_a. # # @param env [Hash] # @return [nil] def wrap_img_in_a(env) HtmlTransformers::WrapImgInA.new.call(**env) end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/selectors/post_processors/parse_time.rb
lib/html2rss/selectors/post_processors/parse_time.rb
# frozen_string_literal: true require 'time' require 'tzinfo' module Html2rss class Selectors module PostProcessors ## # Returns the {https://www.w3.org/Protocols/rfc822/ RFC822} representation of a time. # # Imagine this HTML structure: # # <p>Published on <span>2019-07-02</span></p> # # YAML usage example: # # selectors: # description: # selector: span # post_process: # name: 'parse_time' # time_zone: 'Europe/Berlin' # # Would return: # "Tue, 02 Jul 2019 00:00:00 +0200" # # It uses `Time.parse`. class ParseTime < Base def self.validate_args!(value, context) assert_type(value, String, :value, context:) time_zone_value = time_zone(context) if time_zone_value.nil? || time_zone_value.empty? raise ArgumentError, 'time_zone cannot be nil or empty', [], cause: nil end assert_type(time_zone_value, String, :time_zone, context:) end def self.time_zone(context) = context.dig(:config, :channel, :time_zone) ## # Converts the provided time string to RFC822 format, taking into account the time_zone. # # @return [String] RFC822 formatted time # @raise [TZInfo::InvalidTimezoneIdentifier] if the configured time zone is invalid def get with_timezone(time_zone) { Time.parse(value).rfc822 } end private def time_zone self.class.time_zone(context) end def with_timezone(time_zone) return yield if time_zone.nil? || time_zone.empty? # Validate timezone using TZInfo TZInfo::Timezone.get(time_zone) prev_tz = ENV.fetch('TZ', Time.now.getlocal.zone) ENV['TZ'] = time_zone yield ensure ENV['TZ'] = prev_tz if prev_tz end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/selectors/post_processors/html_transformers/transform_urls_to_absolute_ones.rb
lib/html2rss/selectors/post_processors/html_transformers/transform_urls_to_absolute_ones.rb
# frozen_string_literal: true module Html2rss class Selectors module PostProcessors module HtmlTransformers ## # Transformer that converts relative URLs to absolute URLs within specified HTML elements. class TransformUrlsToAbsoluteOnes URL_ELEMENTS_WITH_URL_ATTRIBUTE = { 'a' => :href, # Visible link 'img' => :src, # Visible image 'iframe' => :src, # Embedded frame (visible content) 'audio' => :src, # Can show controls, so potentially visible 'video' => :src # Video player is visible }.freeze def initialize(channel_url) @channel_url = channel_url end ## # Transforms URLs to absolute ones. def call(node_name:, node:, **_env) return unless URL_ELEMENTS_WITH_URL_ATTRIBUTE.key?(node_name) url_attribute = URL_ELEMENTS_WITH_URL_ATTRIBUTE[node_name] url = node[url_attribute] node[url_attribute] = Url.from_relative(url, @channel_url).to_s end end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/selectors/post_processors/html_transformers/wrap_img_in_a.rb
lib/html2rss/selectors/post_processors/html_transformers/wrap_img_in_a.rb
# frozen_string_literal: true module Html2rss class Selectors module PostProcessors module HtmlTransformers ## # Transformer that wraps <img> tags into <a> tags linking to `img.src`. class WrapImgInA ## # Wraps <img> tags into <a> tags that link to `img.src`. # # @param node_name [String] # @param node [Nokogiri::XML::Node] # @return [nil] def call(node_name:, node:, **_env) return unless should_process?(node_name) wrap_image_in_anchor(node) unless already_wrapped?(node) end def should_process?(node_name) node_name == 'img' end def already_wrapped?(node) node.parent.name == 'a' end private ## # Wraps the <img> node in an <a> tag. # # @param node [Nokogiri::XML::Node] # @return [nil] def wrap_image_in_anchor(node) anchor = Nokogiri::XML::Node.new('a', node.document) anchor['href'] = node['src'] node.add_next_sibling(anchor) anchor.add_child(node.remove) end end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/rss_builder/channel.rb
lib/html2rss/rss_builder/channel.rb
# frozen_string_literal: true module Html2rss class RssBuilder ## # Extracts channel information from # 1. the HTML document's <head>. # 2. the HTTP response class Channel DEFAULT_TTL_IN_MINUTES = 360 DEFAULT_DESCRIPTION_TEMPLATE = 'Latest items from %<url>s' ## # # @param response [Html2rss::RequestService::Response] # @param overrides [Hash<Symbol, String>] - Optional, overrides for any channel attribute def initialize(response, overrides: {}) @response = response @overrides = overrides end def title @title ||= fetch_title end def url = @url ||= Html2rss::Url.from_relative(@response.url, @response.url) def description return overrides[:description] unless overrides[:description].to_s.empty? description = parsed_body.at_css('meta[name="description"]')&.[]('content') if html_response? return format(DEFAULT_DESCRIPTION_TEMPLATE, url:) if description.to_s.empty? description end def ttl return overrides[:ttl] if overrides[:ttl] if (ttl = headers['cache-control']&.match(/max-age=(\d+)/)&.[](1)) return ttl.to_i.fdiv(60).ceil end DEFAULT_TTL_IN_MINUTES end def language return overrides[:language] if overrides[:language] if (language_code = headers['content-language']&.match(/^([a-z]{2})/)) return language_code[0] end return unless html_response? parsed_body['lang'] || parsed_body.at_css('[lang]')&.[]('lang') end def author return overrides[:author] if overrides[:author] return unless html_response? parsed_body.at_css('meta[name="author"]')&.[]('content') end def last_build_date = headers['last-modified'] || Time.now def image return overrides[:image] if overrides[:image] return unless html_response? if (image_url = parsed_body.at_css('meta[property="og:image"]')&.[]('content')) Url.sanitize(image_url) end end private attr_reader :overrides def parsed_body = @parsed_body ||= @response.parsed_body def headers = @headers ||= @response.headers def html_response? = @html_response ||= @response.html_response? def fetch_title override_title = overrides[:title] return override_title if override_title return parsed_title if parsed_title url.channel_titleized end def parsed_title return unless html_response? title = parsed_body.at_css('head > title')&.text.to_s return if title.empty? title.gsub(/\s+/, ' ').strip end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/rss_builder/enclosure.rb
lib/html2rss/rss_builder/enclosure.rb
# frozen_string_literal: true require 'mime/types' module Html2rss class RssBuilder ## # Represents an enclosure for an RSS item. class Enclosure ## # Guesses the content type based on the file extension of the URL. # # @param url [Html2rss::Url] # @param default [String] default content type # @return [String] guessed content type, or default def self.guess_content_type_from_url(url, default: 'application/octet-stream') return default unless url url = url.path.split('?').first content_type = MIME::Types.type_for(File.extname(url).delete('.')) content_type.first&.to_s || 'application/octet-stream' end def self.add(enclosure, maker) return unless enclosure maker.enclosure.tap do |enclosure_maker| enclosure_maker.url = enclosure.url.to_s enclosure_maker.type = enclosure.type enclosure_maker.length = enclosure.bits_length end end def initialize(url:, type: nil, bits_length: 0) raise ArgumentError, 'An Enclosure requires an absolute URL' if !url || !url.absolute? @url = url @type = type @bits_length = bits_length end def type = @type || self.class.guess_content_type_from_url(url) attr_reader :bits_length, :url end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/rss_builder/article.rb
lib/html2rss/rss_builder/article.rb
# frozen_string_literal: true require 'zlib' require 'sanitize' require 'nokogiri' module Html2rss class RssBuilder ## # Article is a simple data object representing an article extracted from a page. # It is enumerable and responds to all keys specified in PROVIDED_KEYS. class Article include Enumerable include Comparable PROVIDED_KEYS = %i[id title description url image author guid published_at enclosures categories scraper].freeze DEDUP_FINGERPRINT_SEPARATOR = '#!/' # @param options [Hash<Symbol, String>] def initialize(**options) @to_h = {} options.each_pair { |key, value| @to_h[key] = value.freeze if value } @to_h.freeze return unless (unknown_keys = options.keys - PROVIDED_KEYS).any? Log.warn "Article: unknown keys found: #{unknown_keys.join(', ')}" end # Checks if the article is valid based on the presence of URL, ID, and either title or description. # @return [Boolean] True if the article is valid, otherwise false. def valid? !url.to_s.empty? && (!title.to_s.empty? || !description.to_s.empty?) && !id.to_s.empty? end # @yield [key, value] # @return [Enumerator] if no block is given def each return enum_for(:each) unless block_given? PROVIDED_KEYS.each { |key| yield(key, public_send(key)) } end def id @to_h[:id] end def title @to_h[:title] end def description @description ||= Rendering::DescriptionBuilder.new( base: @to_h[:description], title:, url:, enclosures:, image: ).call end # @return [Url, nil] def url @url ||= Url.sanitize(@to_h[:url]) end # @return [Url, nil] def image @image ||= Url.sanitize(@to_h[:image]) end # @return [String] def author = @to_h[:author] # Generates a unique identifier based on the URL and ID using CRC32. # @return [String] def guid @guid ||= Zlib.crc32(fetch_guid).to_s(36).encode('utf-8') end ## # Returns a deterministic fingerprint used to detect duplicate articles. # # @return [String, Integer] def deduplication_fingerprint dedup_from_url || dedup_from_id || dedup_from_guid || hash end def enclosures @enclosures ||= Array(@to_h[:enclosures]) .map { |enclosure| Html2rss::RssBuilder::Enclosure.new(**enclosure) } end # @return [Html2rss::RssBuilder::Enclosure, nil] def enclosure return @enclosure if defined?(@enclosure) case (object = @to_h[:enclosures]&.first) when Hash @enclosure = Html2rss::RssBuilder::Enclosure.new(**object) when nil @enclosure = Html2rss::RssBuilder::Enclosure.new(url: image) if image else Log.warn "Article: unknown enclosure type: #{object.class}" end end def categories @categories ||= @to_h[:categories].dup.to_a.tap do |categories| categories.map! { |category| category.to_s.strip } categories.reject!(&:empty?) categories.uniq! end end # Parses and returns the published_at time. # @return [DateTime, nil] def published_at return if (string = @to_h[:published_at].to_s.strip).empty? @published_at ||= DateTime.parse(string) rescue ArgumentError nil end def scraper @to_h[:scraper] end def <=>(other) return nil unless other.is_a?(Article) 0 if other.all? { |key, value| value == public_send(key) ? public_send(key) <=> value : false } end private def dedup_from_url return unless (value = url) [value.to_s, id].compact.join(DEDUP_FINGERPRINT_SEPARATOR) end def dedup_from_id return if id.to_s.empty? id end def dedup_from_guid value = guid return if value.to_s.empty? [value, title, description].compact.join(DEDUP_FINGERPRINT_SEPARATOR) end def fetch_guid guid = @to_h[:guid].map { |s| s.to_s.strip }.reject(&:empty?).join if @to_h[:guid].is_a?(Array) guid || [url, id].join('#!/') end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/rss_builder/stylesheet.rb
lib/html2rss/rss_builder/stylesheet.rb
# frozen_string_literal: true module Html2rss class RssBuilder ## # Represents a stylesheet. class Stylesheet class << self ## # Adds the stylesheet XML tags to the RSS. # # @param maker [RSS::Maker::RSS20] RSS maker object. # @param stylesheets [Array<Html2rss::RssBuilder::Stylesheet>] Array of stylesheet configurations. # @return [nil] def add(maker, stylesheets) stylesheets.each do |stylesheet| add_stylesheet(maker, stylesheet) end end private ## # Adds a single Stylesheet to the RSS. # # @param maker [RSS::Maker::RSS20] RSS maker object. # @param stylesheet [Html2rss::RssBuilder::Stylesheet] Stylesheet configuration. # @return [nil] def add_stylesheet(maker, stylesheet) maker.xml_stylesheets.new_xml_stylesheet do |xss| xss.href = stylesheet.href xss.type = stylesheet.type xss.media = stylesheet.media end end end TYPES = ['text/css', 'text/xsl'].to_set.freeze def initialize(href:, type:, media: 'all') raise ArgumentError, 'stylesheet.href must be a String' unless href.is_a?(String) raise ArgumentError, 'stylesheet.type invalid' unless TYPES.include?(type) raise ArgumentError, 'stylesheet.media must be a String' unless media.is_a?(String) @href = href @type = type @media = media end attr_reader :href, :type, :media # @return [String] the XML representation of the stylesheet def to_xml <<~XML <?xml-stylesheet href="#{href}" type="#{type}" media="#{media}"?> XML end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/config/multiple_feeds_config.rb
lib/html2rss/config/multiple_feeds_config.rb
# frozen_string_literal: true module Html2rss class Config # Handles multiple feeds within a single configuration hash. # Individual feed configurations should be placed under the :feeds key, # where each feed name is the key for its feed configuration. # All global configuration keys (outside :feeds) are merged into each feed's settings. class MultipleFeedsConfig CONFIG_KEY_FEEDS = :feeds class << self # Merges global configuration into each feed's configuration. # # @param config [Hash] The feed-specific configuration. # @param yaml [Hash] The full YAML configuration. # @param multiple_feeds_key [Symbol] The key under which multiple feeds are defined. # @return [Hash] The merged configuration. def to_single_feed(config, yaml, multiple_feeds_key: CONFIG_KEY_FEEDS) global_keys = yaml.keys - [multiple_feeds_key] global_keys.each do |key| config[key] = merge_key(config, yaml, key) end config end private # Merges a specific global key from the YAML configuration into the feed configuration. # # @param config [Hash] The feed-specific configuration. # @param yaml [Hash] The full YAML configuration. # @param key [Symbol] The global configuration key to merge. # @return [Object] The merged value for the key. def merge_key(config, yaml, key) global_value = yaml.fetch(key, nil) local_value = config[key] case local_value when Hash global_value.is_a?(Hash) ? global_value.merge(local_value) : local_value when Array global_value.is_a?(Array) ? global_value + local_value : local_value else global_value end end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/config/request_headers.rb
lib/html2rss/config/request_headers.rb
# frozen_string_literal: true module Html2rss class Config ## # Normalizes HTTP headers for outgoing requests. # Ensures a browser-like baseline while respecting caller overrides. class RequestHeaders DEFAULT_ACCEPT = %w[ text/html application/xhtml+xml application/xml;q=0.9 image/avif image/webp image/apng */*;q=0.8 ].join(',') DEFAULT_USER_AGENT = [ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)', 'AppleWebKit/537.36 (KHTML, like Gecko)', 'Chrome/123.0.0.0', 'Safari/537.36' ].join(' ') DEFAULT_HEADERS = { 'Accept' => DEFAULT_ACCEPT, 'Cache-Control' => 'max-age=0', 'Connection' => 'keep-alive', 'Sec-Fetch-Dest' => 'document', 'Sec-Fetch-Mode' => 'navigate', 'Sec-Fetch-Site' => 'none', 'Sec-Fetch-User' => '?1', 'Upgrade-Insecure-Requests' => '1', 'User-Agent' => DEFAULT_USER_AGENT }.freeze class << self ## # @return [Hash<String, String>] the unmodified default header set def browser_defaults DEFAULT_HEADERS.dup end ## # Normalizes the provided headers while applying Html2rss defaults. # # @param headers [Hash, nil] caller provided headers # @param channel_language [String, nil] language defined on the channel # @param url [String] request URL used to infer the Host header # @return [Hash<String, String>] normalized HTTP headers def normalize(headers, channel_language:, url:) new(headers || {}, channel_language:, url:).to_h end end def initialize(headers, channel_language:, url:) @headers = headers @channel_language = channel_language @url = url end ## # @return [Hash<String, String>] normalized HTTP headers def to_h defaults = DEFAULT_HEADERS.dup normalized = normalize_custom_headers(headers) accept_override = normalized.delete('Accept') defaults.merge!(normalized) defaults['Accept'] = normalize_accept(accept_override) defaults['Accept-Language'] = build_accept_language defaults['Host'] ||= request_host defaults.compact end private attr_reader :headers, :channel_language, :url def normalize_custom_headers(custom) custom.transform_keys { canonicalize(_1) } end def canonicalize(key) key.to_s.split('-').map!(&:capitalize).join('-') end def normalize_accept(override) return DEFAULT_ACCEPT if override.nil? || override.empty? values = accept_values(DEFAULT_ACCEPT) accept_values(override).reverse_each do |value| next if values.include?(value) values.unshift(value) end values.join(',') end def accept_values(header) header.split(',').map!(&:strip).reject(&:empty?) end def build_accept_language language = channel_language.to_s.strip return 'en-US,en;q=0.9' if language.empty? normalized = language.tr('_', '-') primary, region = normalized.split('-', 2) primary = primary.downcase region = region&.upcase return primary if region.nil? "#{primary}-#{region},#{primary};q=0.9" end def request_host return nil if url.nil? || url.empty? Html2rss::Url.from_relative(url, url).host end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/config/validator.rb
lib/html2rss/config/validator.rb
# frozen_string_literal: true require 'dry-validation' module Html2rss class Config # Validates the configuration hash using Dry::Validation. # The configuration options adhere to the documented schema in README.md. class Validator < Dry::Validation::Contract URI_REGEXP = Url::URI_REGEXP STYLESHEET_TYPES = RssBuilder::Stylesheet::TYPES LANGUAGE_FORMAT_REGEX = /\A[a-z]{2}(-[A-Z]{2})?\z/ ChannelConfig = Dry::Schema.Params do required(:url).filled(:string, format?: URI_REGEXP) optional(:title).maybe(:string) optional(:description).maybe(:string) optional(:language).maybe(:string, format?: LANGUAGE_FORMAT_REGEX) optional(:ttl).maybe(:integer, gt?: 0) optional(:time_zone).maybe(:string) end StylesheetConfig = Dry::Schema.Params do required(:href).filled(:string) required(:type).filled(:string, included_in?: STYLESHEET_TYPES) optional(:media).maybe(:string) end params do required(:strategy).filled(:symbol) required(:channel).hash(ChannelConfig) optional(:headers).hash optional(:stylesheets).array(StylesheetConfig) optional(:auto_source).hash(AutoSource::Config) optional(:selectors).hash end rule(:headers) do value&.each do |key, header_value| unless header_value.is_a?(String) key([:headers, key]).failure("must be a String, but got #{header_value.class}") end end end # Ensure at least one of :selectors or :auto_source is present. rule(:selectors, :auto_source) do unless values.key?(:selectors) || values.key?(:auto_source) base.failure("Configuration must include at least 'selectors' or 'auto_source'") end end rule(:selectors) do next unless value errors = Html2rss::Selectors::Config.call(value).errors errors.each { |error| key(:selectors).failure(error) } unless errors.empty? end # URL validation delegated to Url class rule(:channel) do next unless values[:channel]&.key?(:url) url_string = values[:channel][:url] next if url_string.nil? || url_string.empty? begin Html2rss::Url.for_channel(url_string) rescue ArgumentError => error key(%i[channel url]).failure(error.message) end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/config/dynamic_params.rb
lib/html2rss/config/dynamic_params.rb
# frozen_string_literal: true module Html2rss class Config # Processes and applies dynamic parameter formatting in configuration values. class DynamicParams class ParamsMissing < Html2rss::Error; end class << self # Recursively traverses the given value and formats any strings containing # placeholders with values from the provided params. # # @param value [String, Hash, Enumerable, Object] The value to process. # @param params [Hash] The parameters for substitution. # @param getter [Proc, nil] Optional proc to retrieve a key's value. # @param replace_missing_with [Object, nil] Value to substitute if a key is missing. # @return [Object] The processed value. def call(value, params = {}, getter: nil, replace_missing_with: nil) case value when String from_string(value, params, getter:, replace_missing_with:) when Hash from_hash(value, params, getter:, replace_missing_with:) when Enumerable from_enumerable(value, params, getter:, replace_missing_with:) else value end end private def format_params(params, getter:, replace_missing_with:) Hash.new do |hash, key| hash[key] = if getter getter.call(key) else params.fetch(key.to_sym) { params[key.to_s] } end hash[key] = replace_missing_with if hash[key].nil? && !replace_missing_with.nil? hash[key] end end def from_string(string, params, getter:, replace_missing_with:) # Return the original string if no format placeholders are found. return string unless /%\{[^{}]*\}|%<[^<>]*>/.match?(string) mapping = format_params(params, getter:, replace_missing_with:) format(string, mapping) rescue KeyError => error raise ParamsMissing, "Missing parameter for formatting: #{error.message}" if replace_missing_with.nil? string end def from_hash(hash, params, getter:, replace_missing_with:) hash.transform_keys!(&:to_sym) hash.transform_values! { |value| call(value, params, getter:, replace_missing_with:) } end def from_enumerable(enumerable, params, getter:, replace_missing_with:) enumerable.map! { |value| call(value, params, getter:, replace_missing_with:) } end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/html_extractor/enclosure_extractor.rb
lib/html2rss/html_extractor/enclosure_extractor.rb
# frozen_string_literal: true module Html2rss class HtmlExtractor ## # Extracts enclosures from HTML tags using various strategies. class EnclosureExtractor def self.call(article_tag, base_url) [ Extractors::Image, Extractors::Media, Extractors::Pdf, Extractors::Iframe, Extractors::Archive ].flat_map { |strategy| strategy.call(article_tag, base_url:) } end end module Extractors # Extracts image enclosures from HTML tags. # Finds all image sources and returns them in a format suitable for RSS. class Image def self.call(article_tag, base_url:) article_tag.css('img[src]:not([src^="data"])').filter_map do |img| src = img['src'].to_s next if src.empty? abs_url = Url.from_relative(src, base_url) { url: abs_url, type: RssBuilder::Enclosure.guess_content_type_from_url(abs_url, default: 'image/jpeg') } end end end # Extracts media enclosures (video/audio) from HTML tags. class Media def self.call(article_tag, base_url:) article_tag.css('video source[src], audio source[src], audio[src]').filter_map do |element| src = element['src'].to_s next if src.empty? { url: Url.from_relative(src, base_url), type: element['type'] } end end end # Extracts PDF enclosures from HTML tags. class Pdf def self.call(article_tag, base_url:) article_tag.css('a[href$=".pdf"]').filter_map do |link| href = link['href'].to_s next if href.empty? abs_url = Url.from_relative(href, base_url) { url: abs_url, type: RssBuilder::Enclosure.guess_content_type_from_url(abs_url) } end end end # Extracts iframe enclosures from HTML tags. class Iframe def self.call(article_tag, base_url:) article_tag.css('iframe[src]').filter_map do |iframe| src = iframe['src'] next if src.nil? || src.empty? abs_url = Url.from_relative(src, base_url) { url: abs_url, type: RssBuilder::Enclosure.guess_content_type_from_url(abs_url, default: 'text/html') } end end end # Extracts archive enclosures (zip, tar.gz, tgz) from HTML tags. class Archive def self.call(article_tag, base_url:) article_tag.css('a[href$=".zip"], a[href$=".tar.gz"], a[href$=".tgz"]').filter_map do |link| href = link['href'].to_s next if href.empty? abs_url = Url.from_relative(href, base_url) { url: abs_url, type: 'application/zip' } end end end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/html_extractor/date_extractor.rb
lib/html2rss/html_extractor/date_extractor.rb
# frozen_string_literal: true module Html2rss class HtmlExtractor # Extracts the earliest date from an article_tag. class DateExtractor # @return [DateTime, nil] def self.call(article_tag) times = article_tag.css('[datetime]').filter_map do |tag| DateTime.parse(tag['datetime']) rescue ArgumentError, TypeError nil end times.min end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
html2rss/html2rss
https://github.com/html2rss/html2rss/blob/400e796540e82a69e1f1e014b6f89c626acf32fd/lib/html2rss/html_extractor/image_extractor.rb
lib/html2rss/html_extractor/image_extractor.rb
# frozen_string_literal: true module Html2rss class HtmlExtractor ## # Image is responsible for extracting image URLs the article_tag. class ImageExtractor def self.call(article_tag, base_url:) img_src = from_source(article_tag) || from_img(article_tag) || from_style(article_tag) Url.from_relative(img_src, base_url) if img_src end def self.from_img(article_tag) article_tag.at_css('img[src]:not([src^="data"])')&.[]('src') end ## # Extracts the largest image source from the srcset attribute # of an img tag or a source tag inside a picture tag. # # @see <https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images> # @see <https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#srcset> # @see <https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture> def self.from_source(article_tag) # rubocop:disable Metrics/AbcSize hash = article_tag.css('img[srcset], picture > source[srcset]') .flat_map do |source| source['srcset'].to_s.scan(/(\S+)\s+(\d+w|\d+h)[\s,]?/).map do |url, width| next if url.nil? || url.start_with?('data:') width_value = width.to_i.zero? ? 0 : width.scan(/\d+/).first.to_i [width_value, url.strip] end end.compact.to_h hash[hash.keys.max] end def self.from_style(article_tag) article_tag.css('[style*="url"]') .filter_map { |tag| tag['style'][/url\(['"]?(.*?)['"]?\)/, 1] } .reject { |src| src.start_with?('data:') } .max_by(&:size) end end end end
ruby
MIT
400e796540e82a69e1f1e014b6f89c626acf32fd
2026-01-04T17:45:12.820049Z
false
MiderWong/homebrew-flutter
https://github.com/MiderWong/homebrew-flutter/blob/e2e0c773ea813129b75994c9a2fe3f6f8c61c560/Formula/flutter.rb
Formula/flutter.rb
class Flutter < Formula require 'json' desc "Homebrew shell for Flutter" homepage "https://flutter.io" stable do url "https://github.com/flutter/flutter.git", :branch => "stable" version "stable" end devel do url "https://github.com/flutter/flutter.git", :branch => "dev" version "dev" end bottle :unneeded def install current_ip = `curl http://api.db-ip.com/v2/free/self/ipAddress` ip_address_url = 'http://api.db-ip.com/v2/free/'.concat(current_ip) ip_address = `curl #{ip_address_url}` ip_address_hash = JSON.parse ip_address country_code = ip_address_hash["countryCode"] if (country_code == "CN") opoo "You are located in China" ENV["PUB_HOSTED_URL"] = "https://pub.flutter-io.cn" ENV["FLUTTER_STORAGE_BASE_URL"] = "https://storage.flutter-io.cn" end system "./bin/flutter" allfiles = File.join(buildpath, "**", "{*,.*}") mv Dir.glob(allfiles), Dir.glob(prefix), :force => true end def post_install rm File.join(HOMEBREW_PREFIX, "bin", "flutter.bat") chmod_R "+rwx", File.join(prefix, "bin") end def caveats <<~EOS Remove the proxy settings for command-line before you begin. Run the following command to install stable channel: brew install flutter Run the following command to install dev channel: brew install --devel flutter If you want to change channel,please run the following command: brew uninstall --force flutter rm -rf "$(brew --cache)/flutter--git" brew install (--devel) flutter If you're located in China, please follow: https://github.com/flutter/flutter/wiki/Using-Flutter-in-China After installed , please set `PUB_HOSTED_URL` & `FLUTTER_STORAGE_BASE_URL` You may wish to add the flutter-ROOT install location to your PATH: echo 'export PATH="/usr/local/opt/flutter/bin:$PATH"' >> ~/.zshrc You can use the following command to show flutter version: flutter --version Run the following command to see if there are any platform dependencies you need to complete the setup: flutter doctor Run the following command to upgrade flutter: brew reinstall (--devel) flutter EOS end test do system "false" end end
ruby
BSD-3-Clause
e2e0c773ea813129b75994c9a2fe3f6f8c61c560
2026-01-04T17:45:21.142737Z
false
willnet/committee-rails
https://github.com/willnet/committee-rails/blob/cc0d8275f285dca54e6c9b2dda7741d6c5b14c2d/spec/spec_helper.rb
spec/spec_helper.rb
$LOAD_PATH.unshift(File.dirname(__FILE__)) require 'bundler/setup' require 'action_controller/railtie' Bundler.require require 'fake_app/rails_app' require 'rspec/rails' # Requires supporting files with custom matchers and macros, etc, # in ./support/ and its subdirectories. # Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f } # RSpec.configure do |config| # # end
ruby
MIT
cc0d8275f285dca54e6c9b2dda7741d6c5b14c2d
2026-01-04T17:45:20.952077Z
false
willnet/committee-rails
https://github.com/willnet/committee-rails/blob/cc0d8275f285dca54e6c9b2dda7741d6c5b14c2d/spec/lib/methods_spec.rb
spec/lib/methods_spec.rb
require 'spec_helper' describe '#assert_schema_conform', type: :request do include Committee::Rails::Test::Methods context 'when set option' do before do RSpec.configuration.add_setting :committee_options RSpec.configuration.committee_options = { schema_path: Rails.root.join('schema', 'schema.yml').to_s, old_assert_behavior: false, query_hash_key: 'rack.request.query_hash', parse_response_by_content_type: false } end context 'and when response conform YAML Schema' do it 'pass' do post '/users', params: { nickname: 'willnet' }.to_json, headers: { 'Content-Type' => 'application/json' } assert_schema_conform(200) end context 'and request with querystring' do it 'pass' do get '/users', params: { page: 1 }, headers: { 'Content-Type' => 'application/json' } assert_schema_conform(200) end end context 'and override #request method' do def request 'hi' end it 'pass' do post '/users', params: { nickname: 'willnet' }.to_json, headers: { 'Content-Type' => 'application/json' } assert_schema_conform(200) end end context 'and override #response method' do def response 'hi' end it 'pass' do post '/users', params: { nickname: 'willnet' }.to_json, headers: { 'Content-Type' => 'application/json' } assert_schema_conform(200) end end end context "and when response doesn't conform YAML Schema" do it 'raise Committee::InvalidResponse' do patch '/users/1', params: { nickname: 'willnet' }.to_json, headers: { 'Content-Type' => 'application/json', 'Accept' => 'application/json' } expect { assert_schema_conform(200) }.to raise_error(Committee::InvalidResponse) end end context 'and when bad request' do around do |example| original_show_detailed_exceptions = Rails.application.env_config['action_dispatch.show_detailed_exceptions'] original_show_exceptions = Rails.application.env_config['action_dispatch.show_exceptions'] Rails.application.env_config['action_dispatch.show_detailed_exceptions'] = false Rails.application.env_config['action_dispatch.show_exceptions'] = :all begin example.run ensure Rails.application.env_config['action_dispatch.show_detailed_exceptions'] = original_show_detailed_exceptions Rails.application.env_config['action_dispatch.show_exceptions'] = original_show_exceptions end end it 'pass as 400' do patch '/users/0', params: { nickname: 'willnet' }.to_json, headers: { 'Content-Type': 'application/json', 'Accept' => 'application/json' } assert_schema_conform(400) end end end context 'when not set option' do context 'and when not override default setting' do before do RSpec.configuration.committee_options = nil end it 'use default setting' do post '/users', params: { nickname: 'willnet' } expect{ assert_schema_conform(200) }.to raise_error(Errno::ENOENT) # not exist doc/schema/schema.json end end context 'when override default setting' do def committee_options { schema_path: Rails.root.join('schema', 'schema.yml').to_s, old_assert_behavior: false, query_hash_key: 'rack.request.query_hash', parse_response_by_content_type: false, strict_reference_validation: true} end it 'use the setting' do post '/users', params: { nickname: 'willnet' }.to_json, headers: { 'Content-Type' => 'application/json' } assert_schema_conform(200) end end end end
ruby
MIT
cc0d8275f285dca54e6c9b2dda7741d6c5b14c2d
2026-01-04T17:45:20.952077Z
false
willnet/committee-rails
https://github.com/willnet/committee-rails/blob/cc0d8275f285dca54e6c9b2dda7741d6c5b14c2d/spec/fake_app/rails_app.rb
spec/fake_app/rails_app.rb
FakeApp = Class.new(Rails::Application) FakeApp.config.session_store :cookie_store, key: '_myapp_session' FakeApp.config.eager_load = false FakeApp.config.hosts << 'www.example.com' if FakeApp.config.respond_to?(:hosts) FakeApp.config.root = File.dirname(__FILE__) FakeApp.config.secret_key_base = 'secret' FakeApp.config.load_defaults Rails.version.split('.').first(2).join('.') FakeApp.config.action_controller.allow_forgery_protection = false FakeApp.initialize! FakeApp.routes.draw do resources :users end class ApplicationController < ActionController::Base end class UsersController < ApplicationController def index render json: [{ id: 1, nickname: 'willnet' }] end def create render json: { id: 1, nickname: 'willnet' } end def update raise ActionController::BadRequest if params[:id] == '0' render json: { id: 1 } end end
ruby
MIT
cc0d8275f285dca54e6c9b2dda7741d6c5b14c2d
2026-01-04T17:45:20.952077Z
false
willnet/committee-rails
https://github.com/willnet/committee-rails/blob/cc0d8275f285dca54e6c9b2dda7741d6c5b14c2d/lib/committee/rails.rb
lib/committee/rails.rb
require "committee/rails/version" require "committee/rails/test/methods" module Committee module Rails # Your code goes here... end end
ruby
MIT
cc0d8275f285dca54e6c9b2dda7741d6c5b14c2d
2026-01-04T17:45:20.952077Z
false
willnet/committee-rails
https://github.com/willnet/committee-rails/blob/cc0d8275f285dca54e6c9b2dda7741d6c5b14c2d/lib/committee/rails/version.rb
lib/committee/rails/version.rb
module Committee module Rails VERSION = "0.9.0" end end
ruby
MIT
cc0d8275f285dca54e6c9b2dda7741d6c5b14c2d
2026-01-04T17:45:20.952077Z
false
willnet/committee-rails
https://github.com/willnet/committee-rails/blob/cc0d8275f285dca54e6c9b2dda7741d6c5b14c2d/lib/committee/rails/request_object.rb
lib/committee/rails/request_object.rb
require 'action_dispatch/http/request' module Committee::Rails class RequestObject delegate_missing_to :@request def initialize(request) @request = request end def path URI.parse(@request.original_fullpath).path end def path_info URI.parse(@request.original_fullpath).path end def request_method @request.env['action_dispatch.original_request_method'] || @request.request_method end end end
ruby
MIT
cc0d8275f285dca54e6c9b2dda7741d6c5b14c2d
2026-01-04T17:45:20.952077Z
false
willnet/committee-rails
https://github.com/willnet/committee-rails/blob/cc0d8275f285dca54e6c9b2dda7741d6c5b14c2d/lib/committee/rails/test/methods.rb
lib/committee/rails/test/methods.rb
require 'committee' require 'committee/rails/request_object' module Committee::Rails module Test module Methods include Committee::Test::Methods def committee_options if defined?(RSpec) && (options = RSpec.try(:configuration).try(:committee_options)) options else { schema_path: default_schema, strict_reference_validation: false } end end def default_schema @default_schema ||= Committee::Drivers.load_from_file(Rails.root.join('docs', 'schema', 'schema.json').to_s) end def request_object @request_object ||= Committee::Rails::RequestObject.new(integration_session.request) end def response_data [integration_session.response.status, integration_session.response.headers, integration_session.response.body] end end end end
ruby
MIT
cc0d8275f285dca54e6c9b2dda7741d6c5b14c2d
2026-01-04T17:45:20.952077Z
false
jwagener-soundcloud/httmultiparty
https://github.com/jwagener-soundcloud/httmultiparty/blob/ab6724553f708afb40ff21607b323dd7f83cfb41/spec/httmultiparty_spec.rb
spec/httmultiparty_spec.rb
require File.expand_path(File.join(File.dirname(__FILE__), 'spec_helper')) gem 'httparty' gem 'multipart-post' require 'httparty' require 'net/http/post/multipart' describe HTTMultiParty do let(:somefile) { File.new(File.join(File.dirname(__FILE__), 'fixtures/somefile.txt')) } let(:somejpegfile) { File.new(File.join(File.dirname(__FILE__), 'fixtures/somejpegfile.jpeg')) } let(:somepngfile) { File.new(File.join(File.dirname(__FILE__), 'fixtures/somepngfile.png')) } let(:sometempfile) { Tempfile.new('sometempfile') } let(:customtestfile) { CustomTestFile.new(File.join(File.dirname(__FILE__), 'fixtures/somefile.txt')) } let(:someuploadio) { UploadIO.new(somefile, 'application/octet-stream') } let(:klass) { Class.new.tap { |k| k.instance_eval { include HTTMultiParty } } } it 'should include HTTParty module' do expect(klass.included_modules).to include HTTParty end it 'should extend HTTParty::Request::SupportedHTTPMethods with Multipart methods' do expect(HTTParty::Request::SupportedHTTPMethods).to include HTTMultiParty::MultipartPost expect(HTTParty::Request::SupportedHTTPMethods).to include HTTMultiParty::MultipartPut expect(HTTParty::Request::SupportedHTTPMethods).to include HTTMultiParty::MultipartPatch end describe '#hash_contains_files?' do it 'should return true if one of the values in the passed hash is a file' do expect(klass.send(:hash_contains_files?, a: 1, somefile: somefile)).to be_truthy end it 'should return true if one of the values in the passed hash is an upload io ' do expect(klass.send(:hash_contains_files?, a: 1, somefile: someuploadio)).to be_truthy end it 'should return true if one of the values in the passed hash is a tempfile' do expect(klass.send(:hash_contains_files?, a: 1, somefile: sometempfile)).to be_truthy end it 'should return false if none of the values in the passed hash is a file' do expect(klass.send(:hash_contains_files?, a: 1, b: 'nope')).to be_falsey end it 'should return true if passed hash includes an a array of files' do expect(klass.send(:hash_contains_files?, somefiles: [somefile, somefile])).to be_truthy end it 'should return true if passed hash includes a hash with an array of files' do expect(klass.send(:hash_contains_files?, somefiles: { in_here: [somefile, somefile] })).to be_truthy end end describe '#post' do it 'should respond to post' do expect(klass).to respond_to :post end it 'should setup new request with Net::HTTP::Post' do expect(HTTParty::Request).to receive(:new) \ .with(Net::HTTP::Post, anything, anything) \ .and_return(double('mock response', perform: nil)) klass.post('http://example.com/', {}) end describe 'when :query contains a file' do let(:query) { { somefile: somefile } } it 'should setup new request with Net::HTTP::Post::Multipart' do expect(HTTParty::Request).to receive(:new) \ .with(HTTMultiParty::MultipartPost, anything, anything) \ .and_return(double('mock response', perform: nil)) klass.post('http://example.com/', query: query) end end describe 'when :body contains a file' do let(:body) { { somefile: somefile } } it 'should setup new request with Net::HTTP::Post::Multipart' do expect(HTTParty::Request).to receive(:new) \ .with(HTTMultiParty::MultipartPost, anything, anything) \ .and_return(double('mock response', perform: nil)) klass.post('http://example.com/', body: body) end end describe 'with default_params' do let(:body) { { somefile: somefile } } it 'should include default_params also' do klass.tap do |c| c.instance_eval { default_params(token: 'fake') } end FakeWeb.register_uri(:post, 'http://example.com?token=fake', body: 'hello world') klass.post('http://example.com', body: body) end end end describe '#patch' do it 'should respond to patch' do expect(klass).to respond_to :patch end it 'should setup new request with Net::HTTP::Patch' do expect(HTTParty::Request).to receive(:new) \ .with(Net::HTTP::Patch, anything, anything) \ .and_return(double('mock response', perform: nil)) klass.patch('http://example.com/', {}) end describe 'when :query contains a file' do let(:query) { { somefile: somefile } } it 'should setup new request with Net::HTTP::Patch::Multipart' do expect(HTTParty::Request).to receive(:new) \ .with(HTTMultiParty::MultipartPatch, anything, anything) \ .and_return(double('mock response', perform: nil)) klass.patch('http://example.com/', query: query) end end describe 'when :body contains a file' do let(:body) { { somefile: somefile } } it 'should setup new request with Net::HTTP::Patch::Multipart' do expect(HTTParty::Request).to receive(:new) \ .with(HTTMultiParty::MultipartPatch, anything, anything) \ .and_return(double('mock response', perform: nil)) klass.patch('http://example.com/', body: body) end end describe 'with default_params' do let(:body) { { somefile: somefile } } it 'should include default_params also' do klass.tap do |c| c.instance_eval { default_params(token: 'fake') } end FakeWeb.register_uri(:patch, 'http://example.com?token=fake', body: 'hello world') klass.patch('http://example.com', body: body) end end end describe '#file_to_upload_io' do it 'should get the physical name of a file' do expect(HTTMultiParty.file_to_upload_io(somefile)\ .original_filename).to eq('somefile.txt') end it 'should get the physical name of a file' do # Let's pretend this is a file upload to a rack app. allow(sometempfile).to receive_messages(original_filename: 'stuff.txt') expect(HTTMultiParty.file_to_upload_io(sometempfile)\ .original_filename).to eq('stuff.txt') end it 'should get the content-type of a JPEG file' do expect(HTTMultiParty.file_to_upload_io(somejpegfile, true)\ .content_type).to eq('image/jpeg') end it 'should get the content-type of a PNG file' do expect(HTTMultiParty.file_to_upload_io(somepngfile, true)\ .content_type).to eq('image/png') end it "should get the content-type of a JPEG file as 'application/octet-stream' by default" do expect(HTTMultiParty.file_to_upload_io(somejpegfile)\ .content_type).to eq('application/octet-stream') end it "should get the content-type of a PNG file as 'application/octet-stream' by default" do expect(HTTMultiParty.file_to_upload_io(somepngfile)\ .content_type).to eq('application/octet-stream') end end describe '#flatten_params' do it 'should handle complex hashs' do expect(HTTMultiParty.flatten_params( foo: 'bar', deep: { deeper: 1, deeper2: 2, deeparray: [1, 2, 3], deephasharray: [ { id: 1 }, { id: 2 } ] } ).sort_by(&:join)).to eq([ %w(foo bar), ['deep[deeper]', 1], ['deep[deeper2]', 2], ['deep[deeparray][]', 1], ['deep[deeparray][]', 2], ['deep[deeparray][]', 3], ['deep[deephasharray][][id]', 1], ['deep[deephasharray][][id]', 2] ].sort_by(&:join)) end end describe '#query_string_normalizer' do subject { HTTMultiParty.query_string_normalizer } it 'should map a file to UploadIO' do (_, first_v) = subject.call( file: somefile ).first expect(first_v).to be_an UploadIO end it 'should use the same UploadIO' do (_, first_v) = subject.call( file: someuploadio ).first expect(first_v).to eq(someuploadio) end it 'should map a Tempfile to UploadIO' do (_, first_v) = subject.call( file: sometempfile ).first expect(first_v).to be_an UploadIO end it 'should map a CustomTestfile to UploadIO' do (_, first_v) = subject.call( file: customtestfile ).first expect(first_v).to be_an UploadIO end it 'should map an array of files to UploadIOs' do subject.call( file: [somefile, sometempfile] ).each { |(_, v)| expect(v).to be_an UploadIO } end it 'should map files in nested hashes to UploadIOs' do (_, first_v) = subject.call( foo: { bar: { baz: somefile } } ).first expect(first_v).to be_an UploadIO end it 'parses file and non-file parameters properly irrespective of their position' do response = subject.call( name: 'foo', file: somefile, title: 'bar' ) expect(response.first).to eq(%w(name foo)) expect(response.last).to eq(%w(title bar)) end describe 'when :detect_mime_type is true' do subject { HTTMultiParty.query_string_normalizer(detect_mime_type: true) } it 'should map an array of files to UploadIOs with the correct mimetypes' do result = subject.call( file: [somejpegfile, somepngfile] ) content_types = result.map { |(_, v)| v.content_type } expect(content_types).to eq(['image/jpeg', 'image/png']) end end end end
ruby
MIT
ab6724553f708afb40ff21607b323dd7f83cfb41
2026-01-04T17:45:25.267705Z
false
jwagener-soundcloud/httmultiparty
https://github.com/jwagener-soundcloud/httmultiparty/blob/ab6724553f708afb40ff21607b323dd7f83cfb41/spec/spec_helper.rb
spec/spec_helper.rb
require File.join(File.dirname(__FILE__), '..', 'lib', 'httmultiparty') require File.join(File.dirname(__FILE__), 'fixtures', 'custom_test_file') require 'fakeweb' def file_fixture(filename) open(File.join(File.dirname(__FILE__), 'fixtures', "#{filename}")).read end Dir[File.expand_path(File.join(File.dirname(__FILE__), 'support', '**', '*.rb'))].each { |f| require f } RSpec.configure do |config| config.before { FakeWeb.allow_net_connect = false } config.after { FakeWeb.allow_net_connect = true } end
ruby
MIT
ab6724553f708afb40ff21607b323dd7f83cfb41
2026-01-04T17:45:25.267705Z
false
jwagener-soundcloud/httmultiparty
https://github.com/jwagener-soundcloud/httmultiparty/blob/ab6724553f708afb40ff21607b323dd7f83cfb41/spec/fixtures/custom_test_file.rb
spec/fixtures/custom_test_file.rb
class CustomTestFile < File; end
ruby
MIT
ab6724553f708afb40ff21607b323dd7f83cfb41
2026-01-04T17:45:25.267705Z
false
jwagener-soundcloud/httmultiparty
https://github.com/jwagener-soundcloud/httmultiparty/blob/ab6724553f708afb40ff21607b323dd7f83cfb41/spec/httmultiparty/request_spec.rb
spec/httmultiparty/request_spec.rb
require 'spec_helper' class Client include HTTMultiParty base_uri 'http://example.com' default_params(token: 'test') end describe HTTMultiParty do let(:somefile) { File.new(File.join(File.dirname(__FILE__), '../fixtures/somefile.txt')) } it 'makes the request with correct query parameters' do FakeWeb.register_uri(:post, 'http://example.com/foobar?token=test', body: 'hello world') Client.post( '/foobar', body: { attachment: somefile } ) end end
ruby
MIT
ab6724553f708afb40ff21607b323dd7f83cfb41
2026-01-04T17:45:25.267705Z
false
jwagener-soundcloud/httmultiparty
https://github.com/jwagener-soundcloud/httmultiparty/blob/ab6724553f708afb40ff21607b323dd7f83cfb41/spec/httmultiparty/multipartable_spec.rb
spec/httmultiparty/multipartable_spec.rb
require File.expand_path(File.join(File.dirname(__FILE__), '../spec_helper')) describe HTTMultiParty::Multipartable do let :request_class do Class.new(Net::HTTP::Post) do include HTTMultiParty::Multipartable end end # this is how HTTParty works context 'headers set by .body= are retained if .initialize_http_header is called afterwards' do def request_with_headers(headers) request_class.new('/path').tap do |request| request.body = { some: :var } request.initialize_http_header(headers) end end context 'with a header' do subject { request_with_headers('a' => 'header').to_hash } it { is_expected.to include('content-length') } it { is_expected.to include('a') } end context 'without a header' do subject { request_with_headers(nil).to_hash } it { is_expected.to include('content-length') } it { is_expected.not_to include('a') } end end end
ruby
MIT
ab6724553f708afb40ff21607b323dd7f83cfb41
2026-01-04T17:45:25.267705Z
false
jwagener-soundcloud/httmultiparty
https://github.com/jwagener-soundcloud/httmultiparty/blob/ab6724553f708afb40ff21607b323dd7f83cfb41/lib/httmultiparty.rb
lib/httmultiparty.rb
require 'tempfile' require 'httparty' require 'net/http/post/multipart' require 'mimemagic' module HTTMultiParty def self.included(base) base.send :include, HTTParty base.extend ClassMethods end def self.file_to_upload_io(file, detect_mime_type = false) if file.respond_to? :original_filename filename = file.original_filename else filename = File.split(file.path).last end content_type = detect_mime_type ? MimeMagic.by_path(filename) : 'application/octet-stream' UploadIO.new(file, content_type, filename) end def self.query_string_normalizer(options = {}) detect_mime_type = options.fetch(:detect_mime_type, false) proc do |params| HTTMultiParty.flatten_params(params).map do |(k, v)| if file_present?(params) v = prepare_value!(v, detect_mime_type) [k, v] else "#{k}=#{v}" end end end end def self.flatten_params(params = {}, prefix = '') flattened = [] params.each do |(k, v)| if params.is_a?(Array) v = k k = '' end flattened_key = prefix == '' ? "#{k}" : "#{prefix}[#{k}]" if v.is_a?(Hash) || v.is_a?(Array) flattened += flatten_params(v, flattened_key) else flattened << [flattened_key, v] end end flattened end def self.prepare_value!(value, detect_mime_type) return value if does_not_need_conversion?(value) HTTMultiParty.file_to_upload_io(value, detect_mime_type) end def self.get(*args) Basement.get(*args) end def self.post(*args) Basement.post(*args) end def self.put(*args) Basement.put(*args) end def self.patch(*args) Basement.patch(*args) end def self.delete(*args) Basement.delete(*args) end def self.head(*args) Basement.head(*args) end def self.options(*args) Basement.options(*args) end private def self.file_present?(params) if params.is_a? Array file_present_in_array?(params) elsif params.is_a? Hash file_present_in_array?(params.values) else file?(params) end end def self.file_present_in_array?(ary) ary.any? { |a| file_present?(a) } end def self.file?(value) value.respond_to?(:read) end def self.not_a_file?(value) !file?(value) end def self.upload_io?(value) value.is_a?(UploadIO) end def self.does_not_need_conversion?(value) not_a_file?(value) || upload_io?(value) end module ClassMethods def post(path, options = {}) method = Net::HTTP::Post options[:body] ||= options.delete(:query) if hash_contains_files?(options[:body]) method = MultipartPost options[:query_string_normalizer] = HTTMultiParty.query_string_normalizer(options) end perform_request method, path, options end def put(path, options = {}) method = Net::HTTP::Put options[:body] ||= options.delete(:query) if hash_contains_files?(options[:body]) method = MultipartPut options[:query_string_normalizer] = HTTMultiParty.query_string_normalizer(options) end perform_request method, path, options end def patch(path, options={}) method = Net::HTTP::Patch options[:body] ||= options.delete(:query) if hash_contains_files?(options[:body]) method = MultipartPatch options[:query_string_normalizer] = HTTMultiParty.query_string_normalizer(options) end perform_request method, path, options end private def hash_contains_files?(hash) HTTMultiParty.file_present?(hash) end end class Basement include HTTMultiParty end end require 'httmultiparty/version' require 'httmultiparty/multipartable' require 'httmultiparty/multipart_post' require 'httmultiparty/multipart_put' require 'httmultiparty/multipart_patch'
ruby
MIT
ab6724553f708afb40ff21607b323dd7f83cfb41
2026-01-04T17:45:25.267705Z
false
jwagener-soundcloud/httmultiparty
https://github.com/jwagener-soundcloud/httmultiparty/blob/ab6724553f708afb40ff21607b323dd7f83cfb41/lib/httmultiparty/multipartable.rb
lib/httmultiparty/multipartable.rb
module HTTMultiParty::Multipartable DEFAULT_BOUNDARY = '-----------RubyMultipartPost' # prevent reinitialization of headers def initialize_http_header(initheader) super set_headers_for_body end def body=(value) @body_parts = Array(value).map { |(k, v)| Parts::Part.new(boundary, k, v) } @body_parts << Parts::EpiloguePart.new(boundary) set_headers_for_body end def boundary DEFAULT_BOUNDARY end private def set_headers_for_body if defined?(@body_parts) && @body_parts set_content_type('multipart/form-data', 'boundary' => boundary) self.content_length = @body_parts.inject(0) { |sum, i| sum + i.length } self.body_stream = CompositeReadIO.new(*@body_parts.map(&:to_io)) end end end
ruby
MIT
ab6724553f708afb40ff21607b323dd7f83cfb41
2026-01-04T17:45:25.267705Z
false
jwagener-soundcloud/httmultiparty
https://github.com/jwagener-soundcloud/httmultiparty/blob/ab6724553f708afb40ff21607b323dd7f83cfb41/lib/httmultiparty/version.rb
lib/httmultiparty/version.rb
module HTTMultiParty VERSION = '0.3.16' end
ruby
MIT
ab6724553f708afb40ff21607b323dd7f83cfb41
2026-01-04T17:45:25.267705Z
false
jwagener-soundcloud/httmultiparty
https://github.com/jwagener-soundcloud/httmultiparty/blob/ab6724553f708afb40ff21607b323dd7f83cfb41/lib/httmultiparty/multipart_patch.rb
lib/httmultiparty/multipart_patch.rb
class HTTMultiParty::MultipartPatch < Net::HTTP::Patch include HTTMultiParty::Multipartable end HTTParty::Request::SupportedHTTPMethods << HTTMultiParty::MultipartPatch
ruby
MIT
ab6724553f708afb40ff21607b323dd7f83cfb41
2026-01-04T17:45:25.267705Z
false
jwagener-soundcloud/httmultiparty
https://github.com/jwagener-soundcloud/httmultiparty/blob/ab6724553f708afb40ff21607b323dd7f83cfb41/lib/httmultiparty/multipart_put.rb
lib/httmultiparty/multipart_put.rb
class HTTMultiParty::MultipartPut < Net::HTTP::Put include HTTMultiParty::Multipartable end HTTParty::Request::SupportedHTTPMethods << HTTMultiParty::MultipartPut
ruby
MIT
ab6724553f708afb40ff21607b323dd7f83cfb41
2026-01-04T17:45:25.267705Z
false
jwagener-soundcloud/httmultiparty
https://github.com/jwagener-soundcloud/httmultiparty/blob/ab6724553f708afb40ff21607b323dd7f83cfb41/lib/httmultiparty/multipart_post.rb
lib/httmultiparty/multipart_post.rb
class HTTMultiParty::MultipartPost < Net::HTTP::Post include HTTMultiParty::Multipartable end HTTParty::Request::SupportedHTTPMethods << HTTMultiParty::MultipartPost
ruby
MIT
ab6724553f708afb40ff21607b323dd7f83cfb41
2026-01-04T17:45:25.267705Z
false
joncardasis/cocoapods-user-defined-build-types
https://github.com/joncardasis/cocoapods-user-defined-build-types/blob/e34a802bb135ed3549f2b79ac0ac146c645106a7/spec/spec_helper.rb
spec/spec_helper.rb
require 'pathname' ROOT = Pathname.new(File.expand_path('../../', __FILE__)) $:.unshift((ROOT + 'lib').to_s) $:.unshift((ROOT + 'spec').to_s) require 'bundler/setup' require 'bacon' require 'mocha-on-bacon' require 'pretty_bacon' require 'pathname' require 'cocoapods' Mocha::Configuration.prevent(:stubbing_non_existent_method) require 'cocoapods_plugin' #-----------------------------------------------------------------------------# module Pod # Disable the wrapping so the output is deterministic in the tests. # UI.disable_wrap = true # Redirects the messages to an internal store. # module UI @output = '' @warnings = '' class << self attr_accessor :output attr_accessor :warnings def puts(message = '') @output << "#{message}\n" end def warn(message = '', actions = []) @warnings << "#{message}\n" end def print(message) @output << message end end end end #-----------------------------------------------------------------------------#
ruby
MIT
e34a802bb135ed3549f2b79ac0ac146c645106a7
2026-01-04T17:45:29.409183Z
false
joncardasis/cocoapods-user-defined-build-types
https://github.com/joncardasis/cocoapods-user-defined-build-types/blob/e34a802bb135ed3549f2b79ac0ac146c645106a7/spec/command/frameworks_spec.rb
spec/command/frameworks_spec.rb
require File.expand_path('../../spec_helper', __FILE__) module Pod describe Command::Frameworks do describe 'CLAide' do it 'registers it self' do Command.parse(%w{ frameworks }).should.be.instance_of Command::Frameworks end end end end
ruby
MIT
e34a802bb135ed3549f2b79ac0ac146c645106a7
2026-01-04T17:45:29.409183Z
false
joncardasis/cocoapods-user-defined-build-types
https://github.com/joncardasis/cocoapods-user-defined-build-types/blob/e34a802bb135ed3549f2b79ac0ac146c645106a7/lib/cocoapods-user-defined-build-types.rb
lib/cocoapods-user-defined-build-types.rb
require 'cocoapods-user-defined-build-types/gem_version'
ruby
MIT
e34a802bb135ed3549f2b79ac0ac146c645106a7
2026-01-04T17:45:29.409183Z
false
joncardasis/cocoapods-user-defined-build-types
https://github.com/joncardasis/cocoapods-user-defined-build-types/blob/e34a802bb135ed3549f2b79ac0ac146c645106a7/lib/cocoapods_plugin.rb
lib/cocoapods_plugin.rb
require 'cocoapods-user-defined-build-types/main'
ruby
MIT
e34a802bb135ed3549f2b79ac0ac146c645106a7
2026-01-04T17:45:29.409183Z
false
joncardasis/cocoapods-user-defined-build-types
https://github.com/joncardasis/cocoapods-user-defined-build-types/blob/e34a802bb135ed3549f2b79ac0ac146c645106a7/lib/cocoapods-user-defined-build-types/main.rb
lib/cocoapods-user-defined-build-types/main.rb
require_relative 'private_api_hooks' module Pod class Podfile module DSL @@enable_user_defined_build_types = false def self.enable_user_defined_build_types @@enable_user_defined_build_types end def enable_user_defined_build_types! @@enable_user_defined_build_types = true end end end end module CocoapodsUserDefinedBuildTypes PLUGIN_NAME = 'cocoapods-user-defined-build-types' LATEST_SUPPORTED_COCOAPODS_VERSION = '1.9.1' @@plugin_enabled = false @@verbose_logging = false def self.plugin_enabled @@plugin_enabled end def self.verbose_logging @@verbose_logging end def self.verbose_log(str) if @@verbose_logging || ENV["CP_DEV"] Pod::UI.puts "🔥 [#{PLUGIN_NAME}] #{str}".blue end end Pod::HooksManager.register(PLUGIN_NAME, :pre_install) do |installer_context, options| if options['verbose'] != nil @@verbose_logging = options['verbose'] end if Pod::Podfile::DSL.enable_user_defined_build_types @@plugin_enabled = true else Pod::UI.warn "#{PLUGIN_NAME} is installed but the enable_user_defined_build_types! was not found in the Podfile. No build types were changed." end end end
ruby
MIT
e34a802bb135ed3549f2b79ac0ac146c645106a7
2026-01-04T17:45:29.409183Z
false
joncardasis/cocoapods-user-defined-build-types
https://github.com/joncardasis/cocoapods-user-defined-build-types/blob/e34a802bb135ed3549f2b79ac0ac146c645106a7/lib/cocoapods-user-defined-build-types/private_api_hooks.rb
lib/cocoapods-user-defined-build-types/private_api_hooks.rb
require_relative 'podfile_options' module Pod class Podfile class TargetDefinition # [Hash{String, BuildType}] mapping of pod name to preferred build type if specified. @@root_pod_building_options = Hash.new def self.root_pod_building_options @@root_pod_building_options end # ====================== # ==== PATCH METHOD ==== # ====================== swizzled_parse_subspecs = instance_method(:parse_subspecs) define_method(:parse_subspecs) do |name, requirements| # Update hash map of pod target names and association with their preferred linking & packing building_options = @@root_pod_building_options pod_name = Specification.root_name(name) options = requirements.last CocoapodsUserDefinedBuildTypes.verbose_log("Hooked Cocoapods parse_subspecs function to obtain Pod options. #{pod_name}") if options.is_a?(Hash) options.each do |k,v| next if not options.key?(Pod::UserOption.keyword) user_build_type = options.delete(k) if Pod::UserOption.keyword_mapping.key?(user_build_type) build_type = Pod::UserOption.keyword_mapping[user_build_type] building_options[pod_name] = build_type CocoapodsUserDefinedBuildTypes.verbose_log("#{pod_name} build type set to: #{build_type}") else raise Pod::Informative, "#{CocoapodsUserDefinedBuildTypes::PLUGIN_NAME} could not parse a #{Pod::UserOption.keyword} of '#{user_build_type}' on #{pod_name}" end end requirements.pop if options.empty? end # Call old method swizzled_parse_subspecs.bind(self).(name, requirements) end end end end module Pod class Target # @return [BuildTarget] attr_accessor :user_defined_build_type end class Installer # Walk through pod dependencies and assign build_type from root through all transitive dependencies def resolve_all_pod_build_types(pod_targets) root_pod_building_options = Pod::Podfile::TargetDefinition.root_pod_building_options.clone pod_targets.each do |target| next if not root_pod_building_options.key?(target.name) build_type = root_pod_building_options[target.name] dependencies = target.dependent_targets # Cascade build_type down while not dependencies.empty? new_dependencies = [] dependencies.each do |dep_target| dep_target.user_defined_build_type = build_type new_dependencies.push(*dep_target.dependent_targets) end dependencies = new_dependencies end target.user_defined_build_type = build_type end end # ====================== # ==== PATCH METHOD ==== # ====================== # Store old method reference swizzled_analyze = instance_method(:analyze) # Swizzle 'analyze' cocoapods core function to finalize build settings define_method(:analyze) do |analyzer = create_analyzer| if !CocoapodsUserDefinedBuildTypes.plugin_enabled return swizzled_analyze.bind(self).(analyzer) end CocoapodsUserDefinedBuildTypes.verbose_log("patching build types...") # Run original method swizzled_analyze.bind(self).(analyzer) # Set user assigned build types on Target objects resolve_all_pod_build_types(pod_targets) # Update each of @pod_targets private @build_type variable. # Note: @aggregate_targets holds a reference to @pod_targets under it's pod_targets variable. pod_targets.each do |target| next if not target.user_defined_build_type.present? new_build_type = target.user_defined_build_type current_build_type = target.send :build_type CocoapodsUserDefinedBuildTypes.verbose_log("#{target.name}: #{current_build_type} ==> #{new_build_type}") # Override the target's build time for user provided one target.instance_variable_set(:@build_type, new_build_type) # Verify patching status if (target.send :build_type).to_s != new_build_type.to_s raise Pod::Informative, "WARNING: Method injection failed on `build_type` of target #{target.name}. Most likely you have a version of cocoapods which is greater than the latest supported by this plugin (#{CocoapodsUserDefinedBuildTypes::LATEST_SUPPORTED_COCOAPODS_VERSION})" end end CocoapodsUserDefinedBuildTypes.verbose_log("finished patching user defined build types") Pod::UI.puts "#{CocoapodsUserDefinedBuildTypes::PLUGIN_NAME} updated build options" end end end
ruby
MIT
e34a802bb135ed3549f2b79ac0ac146c645106a7
2026-01-04T17:45:29.409183Z
false
joncardasis/cocoapods-user-defined-build-types
https://github.com/joncardasis/cocoapods-user-defined-build-types/blob/e34a802bb135ed3549f2b79ac0ac146c645106a7/lib/cocoapods-user-defined-build-types/podfile_options.rb
lib/cocoapods-user-defined-build-types/podfile_options.rb
is_version_1_9_x = Pod.const_defined?(:BuildType) # CP v1.9.x # Assign BuildType to proper module definition dependent on CP version. BuildType = is_version_1_9_x ? Pod::BuildType : Pod::Target::BuildType module Pod class UserOption def self.keyword :build_type end # [Hash{String, BuildType}] mapping of Podfile keyword to a BuildType def self.keyword_mapping { :dynamic_framework => BuildType.dynamic_framework, :dynamic_library => BuildType.dynamic_library, :static_framework => BuildType.static_framework, :static_library => BuildType.static_library } end end end
ruby
MIT
e34a802bb135ed3549f2b79ac0ac146c645106a7
2026-01-04T17:45:29.409183Z
false
joncardasis/cocoapods-user-defined-build-types
https://github.com/joncardasis/cocoapods-user-defined-build-types/blob/e34a802bb135ed3549f2b79ac0ac146c645106a7/lib/cocoapods-user-defined-build-types/gem_version.rb
lib/cocoapods-user-defined-build-types/gem_version.rb
module CocoapodsUserDefinedBuildTypes VERSION = "0.0.7" end
ruby
MIT
e34a802bb135ed3549f2b79ac0ac146c645106a7
2026-01-04T17:45:29.409183Z
false
kumahq/kuma-website
https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/app/_plugins/hooks/releases_json.rb
app/_plugins/hooks/releases_json.rb
# frozen_string_literal: true Jekyll::Hooks.register :site, :post_write do |site| releases = site.data['versions'] .filter { |v| !v.key?('label') || v['label'] != 'dev' } .map { |v| v['version'] }.to_json File.write "#{site.dest}/releases.json", releases end
ruby
Apache-2.0
7b6c49c772192d2ecf31f70c006229013ad32a56
2026-01-04T17:42:48.724969Z
false
kumahq/kuma-website
https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/app/_plugins/hooks/latest_version.rb
app/_plugins/hooks/latest_version.rb
# frozen_string_literal: true Jekyll::Hooks.register :site, :post_write do |site| latest = site.data['latest_version'] File.write "#{site.dest}/latest_version", latest['version'] end
ruby
Apache-2.0
7b6c49c772192d2ecf31f70c006229013ad32a56
2026-01-04T17:42:48.724969Z
false
kumahq/kuma-website
https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/app/_plugins/blocks/mermaid.rb
app/_plugins/blocks/mermaid.rb
# frozen_string_literal: true module Jekyll class RenderMermaid < Liquid::Block def render(context) text = super mermaid_script = generate_mermaid_script mermaid_pre = "<pre class='mermaid'> #{text} </pre>" "#{mermaid_script}#{mermaid_pre}" end private def generate_mermaid_script <<~SCRIPT <script type='module'> import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.esm.min.mjs'; mermaid.initialize({ startOnLoad: true, theme: 'base', themeVariables: { 'primaryColor': '#fff', 'primaryBorderColor': '#4a86e8', 'primaryTextColor': '#495c64', 'secondaryColor': '#fff', 'secondaryTextColor': '#5096f2', 'edgeLabelBackground': '#fff', 'fontFamily': 'Roboto', 'fontSize': '15px', 'lineColor': '#99b0c0' } }); </script> SCRIPT end end end Liquid::Template.register_tag('mermaid', Jekyll::RenderMermaid)
ruby
Apache-2.0
7b6c49c772192d2ecf31f70c006229013ad32a56
2026-01-04T17:42:48.724969Z
false
kumahq/kuma-website
https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/app/_plugins/blocks/custom_block.rb
app/_plugins/blocks/custom_block.rb
# frozen_string_literal: true module Jekyll class CustomBlock < Liquid::Block alias render_block render def initialize(tag_name, markup, options) super @markup = markup.strip end def render(context) site = context.registers[:site] converter = site.find_converter_instance(::Jekyll::Converters::Markdown) content = converter.convert(render_block(context)) <<~HTML <div class="custom-block #{tag_name}"> <p>#{content}</p> </div> HTML end end end Liquid::Template.register_tag('tip', Jekyll::CustomBlock) Liquid::Template.register_tag('warning', Jekyll::CustomBlock) Liquid::Template.register_tag('danger', Jekyll::CustomBlock)
ruby
Apache-2.0
7b6c49c772192d2ecf31f70c006229013ad32a56
2026-01-04T17:42:48.724969Z
false
kumahq/kuma-website
https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/app/_plugins/tags/tabs/tabs.rb
app/_plugins/tags/tabs/tabs.rb
# frozen_string_literal: true require 'erb' require 'securerandom' module Jekyll module Tabs class TabsBlock < Liquid::Block def initialize(tag_name, markup, tokens) super @class = markup.strip.empty? ? '' : " #{markup.strip}" end def render(context) tabs_id = SecureRandom.uuid environment = context.environments.first environment["tabs-#{tabs_id}"] = {} environment['tabs-stack'] ||= [] environment['tabs-stack'].push(tabs_id) super environment['tabs-stack'].pop ERB.new(self.class.template).result(binding) end def self.template <<~ERB <div class="tabs-component<%= @class %>"> <ul role="tablist" class="tabs-component-tabs"> <% environment['tabs-' + tabs_id].each_with_index do |(hash, _), index| %> <li class="tabs-component-tab<%= index == 0 ? ' is-active' : '' %>" role="presentation"> <a aria-controls="<%= hash.rstrip.gsub(' ', '-') %>" aria-selected="<%= index == 0 %>" href="#<%= hash.rstrip.gsub(' ', '-') %>" class="tabs-component-tab-a" role="tab" data-slug="<%= hash.rstrip.gsub(' ', '-') %>" > <%= hash %> </a> </li> <% end %> </ul> <div class="tabs-component-panels"> <% environment['tabs-' + tabs_id].each_with_index do |(key, value), index| %> <section aria-hidden="<%= index != 0 %>" class="tabs-component-panel<%= index != 0 ? ' hidden' : '' %>" id="<%= key.rstrip.gsub(' ', '-') %>" role="tabpanel" data-panel="<%= key.rstrip.gsub(' ', '-') %>" > <%= value %> </section> <% end %> </div> </div> ERB end end class TabBlock < Liquid::Block alias render_block render def initialize(tag_name, markup, tokens) super raise SyntaxError, "No toggle name given in #{tag_name} tag" if markup == '' @title = markup.strip end def render(context) # Add support for variable titles path = @title.split('.') # 0 is the page scope, 1 is the local scope [0, 1].each do |k| next unless context.scopes[k] ref = context.scopes[k].dig(*path) @title = ref if ref end site = context.registers[:site] converter = site.find_converter_instance(::Jekyll::Converters::Markdown) environment = context.environments.first tabs_id = environment['tabs-stack'].last environment["tabs-#{tabs_id}"][@title] = converter.convert(render_block(context)) end end end end Liquid::Template.register_tag('tab', Jekyll::Tabs::TabBlock) Liquid::Template.register_tag('tabs', Jekyll::Tabs::TabsBlock)
ruby
Apache-2.0
7b6c49c772192d2ecf31f70c006229013ad32a56
2026-01-04T17:42:48.724969Z
false
kumahq/kuma-website
https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/app/_plugins/generators/redirects.rb
app/_plugins/generators/redirects.rb
# frozen_string_literal: true module Jekyll class Redirects < Jekyll::Generator priority :low def generate(site) active_versions = site.data['versions'].filter { |v| !v.key?('label') || v['label'] != 'dev' } # Generate redirects for the latest version latest_release = site.data['latest_version']['release'] kuma_redirects = existing_redirects(latest_release).join("\n") common_redirects = common_redirects(latest_release).join("\n") # Generate redirects for specific versions version_specific_redirects = active_versions.each_with_object([]) do |v, redirects| next unless Gem::Version.correct?(v['version']) vp = v['version'].split('.').map(&:to_i) # Generate redirects for x.y.0, x.y.1, x.y.2 etc # Until we hit the actual version stored in versions.yml (0..vp[2]).each do |idx| current = "#{vp[0]}.#{vp[1]}.#{idx}" redirects << "/docs/#{current}/* /docs/#{v['release']}/:splat 301" redirects << "/install/#{current}/* /install/#{v['release']}/:splat 301" end end.join("\n") # Add all hand-crafted redirects redirects = <<~RDR # Specific version to release #{version_specific_redirects} # _redirects file: #{kuma_redirects} # _common_redirects file: #{common_redirects} RDR write_file(site, '_redirects', redirects) end def write_file(site, path, content) page = PageWithoutAFile.new(site, __dir__, '', path) page.content = content page.data['layout'] = nil site.pages << page end private def existing_redirects(latest_release) @existing_redirects ||= File.readlines( 'app/_redirects', chomp: true ).map { |l| l.gsub('/LATEST_RELEASE/', "/#{latest_release}/") } end def common_redirects(latest_release) @common_redirects ||= File.readlines( 'app/_common_redirects', chomp: true ).map { |l| l.gsub('/LATEST_RELEASE/', "/#{latest_release}/") } end end end
ruby
Apache-2.0
7b6c49c772192d2ecf31f70c006229013ad32a56
2026-01-04T17:42:48.724969Z
false
kumahq/kuma-website
https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/app/_plugins/generators/navigation_links.rb
app/_plugins/generators/navigation_links.rb
# frozen_string_literal: true module Jekyll class NavigationLinks < Jekyll::Generator priority :low def generate(site) site.pages.each_with_index do |page, _index| next unless page.relative_path.start_with? 'docs' next if page.path == 'docs/index.md' next unless page.data.key? 'nav_items' # remove docs/<version>/ prefix and `.md` and the end page_url = page.path.gsub(%r{docs/[^/]+/}, '/').gsub('.md', '/') pages = pages_from_items(page.data['nav_items']) page_index = pages.index { |u| u['url'] == page_url } if page_index page.data['prev'] = pages[page_index - 1] if page_index != 0 page.data['next'] = pages[page_index + 1] if page_index != pages.length - 1 end end end def pages_from_items(items) items.each_with_object([]) do |i, array| if i.key?('url') && URI(i.fetch('url')).fragment.nil? array << { 'url' => i.fetch('url'), 'text' => i.fetch('text'), 'absolute_url' => i.fetch('absolute_url', false) } end array << pages_from_items(i.fetch('items')) if i.key?('items') end.flatten end end end
ruby
Apache-2.0
7b6c49c772192d2ecf31f70c006229013ad32a56
2026-01-04T17:42:48.724969Z
false
kumahq/kuma-website
https://github.com/kumahq/kuma-website/blob/7b6c49c772192d2ecf31f70c006229013ad32a56/app/_plugins/generators/install_pages.rb
app/_plugins/generators/install_pages.rb
# frozen_string_literal: true module Jekyll class InstallPages < Jekyll::Generator priority :low def generate(site) latest_page = site.pages.detect { |p| p.relative_path == 'install/latest.md' } latest_page.data['release'] = site.data['latest_version']['release'] latest_page.data['has_version'] = true site.data['versions'].each do |version| site.pages << InstallPage.new(site, version) end end end class InstallPage < Jekyll::Page def initialize(site, version) super(site, site.source, 'install', 'latest.md') # Override name to be version-specific while keeping content from latest.md @name = "#{version['release']}.md" @basename = version['release'] @data['release'] = version['release'] @data['has_version'] = true end end end
ruby
Apache-2.0
7b6c49c772192d2ecf31f70c006229013ad32a56
2026-01-04T17:42:48.724969Z
false