opf 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 731442c9df097ae3a58ededf90d0d9e3d76a74f61fef679e3528ac32ed54b8ea
4
+ data.tar.gz: cde4c1fe0d2324f469c14e22620353e1dbd03e7bf793dcc98df9fdc72b5cb62e
5
+ SHA512:
6
+ metadata.gz: 1113c851bf4373d1d483a50246e24d49047278267a0b5cd84fc7e1454ee8d4d665556a7ea27794722377bb4fa5fddb49f28241bf0d99ab512fc359ceb9706f1d
7
+ data.tar.gz: 664c47d1dd6464313f14c3cf8cc79b6e437aa2ee68f380aac2f8c5593e0cf64e83a323dc8ea18c6425dbae68e4ac9f221da7298d586f61774c1c872ba39a9b13
data/.envrc ADDED
@@ -0,0 +1 @@
1
+ use flake
data/.gitignore ADDED
@@ -0,0 +1,15 @@
1
+ # Nix
2
+ .nix-gems/
3
+ .direnv/
4
+
5
+ # Bundler / RubyGems
6
+ /.bundle/
7
+ /pkg/
8
+ /tmp/
9
+
10
+ # Docs and coverage
11
+ /.yardoc
12
+ /_yardoc/
13
+ /coverage/
14
+ /doc/
15
+ /spec/reports/
data/CHANGELOG.md ADDED
@@ -0,0 +1,10 @@
1
+ ## [Unreleased]
2
+
3
+ ### Added
4
+
5
+ - `Opf.fetch(url)`: fetches a page and returns an `Opf::Page` with `title`, `description`, `images` (plus `image` shortcut) and `favicon`, resolved from OpenGraph tags with HTML fallbacks
6
+ - Typed errors: `Opf::InvalidURLError` and `Opf::FetchError`
7
+
8
+ ## [0.1.0] - 2026-10-11
9
+
10
+ - Initial release
@@ -0,0 +1,10 @@
1
+ # Code of Conduct
2
+
3
+ "opf" follows [The Ruby Community Conduct Guideline](https://www.ruby-lang.org/en/conduct) in all "collaborative space", which is defined as community communications channels (such as mailing lists, submitted patches, commit comments, etc.):
4
+
5
+ * Participants will be tolerant of opposing views.
6
+ * Participants must ensure that their language and actions are free of personal attacks and disparaging personal remarks.
7
+ * When interpreting the words and actions of others, participants should always assume good intentions.
8
+ * Behaviour which can be reasonably considered harassment will not be tolerated.
9
+
10
+ If you have any concerns about behaviour within this project, please contact us at [santiago.fgonz@gmail.com](mailto:santiago.fgonz@gmail.com).
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 iagus
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,51 @@
1
+ # Opf
2
+
3
+ Opf fetches OpenGraph metadata — title, description and images — plus the site favicon, from user-provided URLs. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ ## Installation
6
+
7
+ TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org.
8
+
9
+ Install the gem and add to the application's Gemfile by executing:
10
+
11
+ ```bash
12
+ bundle add UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
13
+ ```
14
+
15
+ If bundler is not being used to manage dependencies, install the gem by executing:
16
+
17
+ ```bash
18
+ gem install UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
19
+ ```
20
+
21
+ ## Usage
22
+
23
+ ```ruby
24
+ require "opf"
25
+
26
+ page = Opf.fetch("https://ogp.me")
27
+
28
+ page.title # => og:title (falls back to the HTML <title>)
29
+ page.description # => og:description (falls back to <meta name="description">)
30
+ page.images # => every declared og:image URL
31
+ page.image # => the primary image (first og:image)
32
+ page.favicon # => the site's favicon URL
33
+ page.url # => final URL after following redirects
34
+ ```
35
+
36
+ `Opf.fetch` raises typed errors on failure:
37
+
38
+ - `Opf::InvalidURLError` — malformed URLs or non http/https schemes
39
+ - `Opf::FetchError` — network failures, redirect loops, error statuses or non HTML responses
40
+
41
+ Pages lacking OpenGraph tags simply return `nil`/`[]` for the missing fields.
42
+
43
+ ## Development
44
+
45
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
46
+
47
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
48
+
49
+ ## License
50
+
51
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "minitest/test_task"
5
+
6
+ Minitest::TestTask.create
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[test rubocop]
data/flake.lock ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "nodes": {
3
+ "nixpkgs": {
4
+ "locked": {
5
+ "lastModified": 1791662279,
6
+ "narHash": "sha256-xI8L+UwJLIg75yVJwLPsY+AUEP1teCT3FyuvodyJu2Y=",
7
+ "owner": "NixOS",
8
+ "repo": "nixpkgs",
9
+ "rev": "6fcc160353f63555b560f25588925133c8f61f2a",
10
+ "type": "github"
11
+ },
12
+ "original": {
13
+ "owner": "NixOS",
14
+ "ref": "nixos-26.05",
15
+ "repo": "nixpkgs",
16
+ "type": "github"
17
+ }
18
+ },
19
+ "root": {
20
+ "inputs": {
21
+ "nixpkgs": "nixpkgs"
22
+ }
23
+ }
24
+ },
25
+ "root": "root",
26
+ "version": 7
27
+ }
data/flake.nix ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ description = "Development environment for the opf Ruby gem";
3
+
4
+ inputs = {
5
+ nixpkgs.url = "github:NixOS/nixpkgs/nixos-26.05";
6
+ };
7
+
8
+ outputs =
9
+ { self, nixpkgs }:
10
+ let
11
+ systems = [
12
+ "x86_64-linux"
13
+ "aarch64-linux"
14
+ "x86_64-darwin"
15
+ "aarch64-darwin"
16
+ ];
17
+ forAllSystems = nixpkgs.lib.genAttrs systems;
18
+ in
19
+ {
20
+ devShells = forAllSystems (
21
+ system:
22
+ let
23
+ pkgs = nixpkgs.legacyPackages.${system};
24
+ in
25
+ {
26
+ default = pkgs.mkShell {
27
+ packages = [
28
+ pkgs.ruby_4_0
29
+ ];
30
+
31
+ # The nix-provided Ruby is read-only; install gems into a
32
+ # project-local directory so bundler works out of the box.
33
+ shellHook = ''
34
+ export GEM_HOME="$PWD/.nix-gems"
35
+ export GEM_PATH="$GEM_HOME"
36
+ export PATH="$GEM_HOME/bin:$PATH"
37
+ '';
38
+ };
39
+ }
40
+ );
41
+ };
42
+ }
@@ -0,0 +1,102 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "openssl"
5
+ require "uri"
6
+
7
+ module Opf
8
+ # Fetches an HTML document over HTTP(S), following redirects.
9
+ #
10
+ # Only `text/html` documents are accepted. All failure modes raise
11
+ # Opf::InvalidURLError or Opf::FetchError.
12
+ class Fetcher
13
+ MAX_REDIRECTS = 5
14
+ OPEN_TIMEOUT = 5
15
+ READ_TIMEOUT = 5
16
+ USER_AGENT = "Opf/#{Opf::VERSION}".freeze
17
+ HTML_MIME_TYPES = %w[text/html application/xhtml+xml].freeze
18
+
19
+ NETWORK_ERRORS = [
20
+ SocketError, # DNS failures
21
+ SystemCallError, # Errno::ECONNREFUSED and friends
22
+ Timeout::Error, # Net::OpenTimeout / Net::ReadTimeout
23
+ OpenSSL::SSL::SSLError, # TLS negotiation failures
24
+ EOFError, # connection dropped mid response
25
+ Net::ProtocolError # malformed HTTP responses
26
+ ].freeze
27
+
28
+ # The result of a successful fetch: the final URL (after redirects) and
29
+ # the raw HTML body.
30
+ Response = Data.define(:url, :body)
31
+
32
+ def self.call(url)
33
+ new.call(url)
34
+ end
35
+
36
+ def call(url)
37
+ uri = parse_uri(url)
38
+ redirects = 0
39
+
40
+ loop do
41
+ response = request(uri)
42
+ return success_response(uri, response) if response.is_a?(Net::HTTPSuccess)
43
+
44
+ uri = follow_redirect(uri, response, redirects += 1)
45
+ end
46
+ end
47
+
48
+ private
49
+
50
+ def parse_uri(url)
51
+ uri = URI.parse(url.to_s)
52
+ return uri if http_uri?(uri)
53
+
54
+ raise InvalidURLError, "only http(s) URLs are supported: #{url.inspect}"
55
+ rescue URI::InvalidURIError => e
56
+ raise InvalidURLError, "invalid URL #{url.inspect}: #{e.message}"
57
+ end
58
+
59
+ def http_uri?(uri)
60
+ uri.is_a?(URI::HTTP) && !uri.host.to_s.empty?
61
+ end
62
+
63
+ def request(uri)
64
+ Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https",
65
+ open_timeout: OPEN_TIMEOUT, read_timeout: READ_TIMEOUT) do |http|
66
+ http.request_get(uri.request_uri, "User-Agent" => USER_AGENT, "Accept" => HTML_MIME_TYPES.join(", "))
67
+ end
68
+ rescue *NETWORK_ERRORS => e
69
+ raise FetchError, "request to #{uri} failed: #{e.message}"
70
+ end
71
+
72
+ def follow_redirect(uri, response, count)
73
+ raise FetchError, "giving up after #{MAX_REDIRECTS} redirects" if count > MAX_REDIRECTS
74
+
75
+ unless response.is_a?(Net::HTTPRedirection)
76
+ raise FetchError, "request to #{uri} failed with status #{response.code}"
77
+ end
78
+
79
+ redirect_uri(uri, response)
80
+ end
81
+
82
+ def redirect_uri(uri, response)
83
+ location = response["location"].to_s
84
+ raise FetchError, "redirect from #{uri} lacked a Location header" if location.empty?
85
+
86
+ redirected = URI.join(uri, location)
87
+ return redirected if http_uri?(redirected)
88
+
89
+ raise FetchError, "redirect from #{uri} points to an invalid URL: #{location.inspect}"
90
+ rescue URI::InvalidURIError => e
91
+ raise FetchError, "redirect from #{uri} points to an invalid URL: #{e.message}"
92
+ end
93
+
94
+ def success_response(uri, response)
95
+ mime_type = response["content-type"].to_s.split(";").first.to_s.strip
96
+ return Response.new(url: uri.to_s, body: response.body.to_s) if HTML_MIME_TYPES.include?(mime_type)
97
+
98
+ raise FetchError,
99
+ "expected an HTML document from #{uri}, got: #{mime_type.empty? ? "no Content-Type" : mime_type}"
100
+ end
101
+ end
102
+ end
data/lib/opf/page.rb ADDED
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Opf
4
+ # Immutable value object with everything we managed to learn about a page:
5
+ # its final URL, title, description, every declared OpenGraph image and the
6
+ # favicon URL.
7
+ Page = Data.define(:url, :title, :description, :images, :favicon) do
8
+ # The primary image: the first og:image declared by the page.
9
+ def image
10
+ images&.first
11
+ end
12
+ end
13
+ end
data/lib/opf/parser.rb ADDED
@@ -0,0 +1,92 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "nokogiri"
4
+ require "uri"
5
+
6
+ module Opf
7
+ # Extracts metadata from a fetched HTML document: OpenGraph tags with plain
8
+ # HTML fallbacks, plus the site's favicon.
9
+ class Parser
10
+ IMAGE_PROPERTIES = %w[og:image og:image:secure_url og:image:url].freeze
11
+
12
+ def self.call(url:, body:)
13
+ new(url: url, body: body).call
14
+ end
15
+
16
+ def initialize(url:, body:)
17
+ @url = url
18
+ @body = body
19
+ end
20
+
21
+ def call
22
+ Page.new(
23
+ url: @url,
24
+ title: open_graph("og:title") || html_title,
25
+ description: open_graph("og:description") || html_description,
26
+ images: images,
27
+ favicon: favicon
28
+ )
29
+ end
30
+
31
+ private
32
+
33
+ def doc
34
+ @doc ||= Nokogiri::HTML(@body)
35
+ end
36
+
37
+ # Some sites wrongly use a `name` attribute for OpenGraph tags, so both
38
+ # spellings are accepted.
39
+ def open_graph(property)
40
+ tag = doc.at_css(%(meta[property="#{property}"]), %(meta[name="#{property}"]))
41
+ content = tag&.[]("content").to_s.strip
42
+ content.empty? ? nil : content
43
+ end
44
+
45
+ def html_title
46
+ title = doc.at_css("title")&.text.to_s.strip
47
+ title.empty? ? nil : title
48
+ end
49
+
50
+ def html_description
51
+ tag = doc.at_css('meta[name="description"]')
52
+ content = tag&.[]("content").to_s.strip
53
+ content.empty? ? nil : content
54
+ end
55
+
56
+ def images
57
+ doc.css(image_selector).filter_map { |tag| tag["content"] }.map(&:strip).reject(&:empty?).uniq
58
+ end
59
+
60
+ def image_selector
61
+ IMAGE_PROPERTIES
62
+ .flat_map { |property| [%(meta[property="#{property}"]), %(meta[name="#{property}"])] }.join(", ")
63
+ end
64
+
65
+ # The site's favicon: a declared <link rel="icon">, then the legacy
66
+ # "shortcut icon" spelling, and finally the conventional /favicon.ico,
67
+ # which is returned unverified.
68
+ def favicon
69
+ resolve(declared_favicon || "/favicon.ico")
70
+ end
71
+
72
+ def declared_favicon
73
+ links = doc.css("link[href]")
74
+ link = links.find { rel_tokens(_1) == ["icon"] } ||
75
+ links.find { rel_tokens(_1) == %w[icon shortcut] }
76
+ href = link&.[]("href").to_s.strip
77
+ href.empty? || href.start_with?("data:") ? nil : href
78
+ end
79
+
80
+ def rel_tokens(link)
81
+ link["rel"].to_s.downcase.split.sort
82
+ end
83
+
84
+ # Relative hrefs are common for favicons; they resolve against the final
85
+ # (post-redirect) page URL.
86
+ def resolve(href)
87
+ URI.join(@url, href).to_s
88
+ rescue URI::InvalidURIError
89
+ nil
90
+ end
91
+ end
92
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Opf
4
+ VERSION = "0.1.0"
5
+ end
data/lib/opf.rb ADDED
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "opf/version"
4
+ require_relative "opf/page"
5
+ require_relative "opf/fetcher"
6
+ require_relative "opf/parser"
7
+
8
+ # Fetches OpenGraph metadata (title, description, images) and the favicon
9
+ # from user-provided URLs.
10
+ module Opf
11
+ class Error < StandardError; end
12
+
13
+ # Raised when the provided URL cannot be used (missing host, non
14
+ # http/https scheme, malformed URI, ...).
15
+ class InvalidURLError < Error; end
16
+
17
+ # Raised when the URL could not be fetched: network failure, too many
18
+ # redirects, unsuccessful status code or a non HTML response.
19
+ class FetchError < Error; end
20
+
21
+ # Fetches OpenGraph information for the given URL and returns an Opf::Page.
22
+ #
23
+ # page = Opf.fetch("https://example.com")
24
+ # page.title #=> "Example Domain"
25
+ # page.image #=> "https://example.com/og.png"
26
+ #
27
+ # Raises Opf::InvalidURLError or Opf::FetchError on failure.
28
+ def self.fetch(url)
29
+ response = Fetcher.call(url)
30
+ Parser.call(url: response.url, body: response.body)
31
+ end
32
+ end
data/sig/opf.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module Opf
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,75 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: opf
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - iagus
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 1980-01-01 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: nokogiri
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '1.19'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: '1.19'
26
+ description: Opf fetches OpenGraph metadata (title, description, images) and the favicon
27
+ URL from user-provided URLs, raising typed errors for invalid URLs or failed fetches.
28
+ email:
29
+ - iagus.widget524@passinbox.com
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - ".envrc"
35
+ - ".gitignore"
36
+ - CHANGELOG.md
37
+ - CODE_OF_CONDUCT.md
38
+ - LICENSE.txt
39
+ - README.md
40
+ - Rakefile
41
+ - flake.lock
42
+ - flake.nix
43
+ - lib/opf.rb
44
+ - lib/opf/fetcher.rb
45
+ - lib/opf/page.rb
46
+ - lib/opf/parser.rb
47
+ - lib/opf/version.rb
48
+ - sig/opf.rbs
49
+ homepage: https://github.com/iagus/opf
50
+ licenses:
51
+ - MIT
52
+ metadata:
53
+ allowed_push_host: https://rubygems.org
54
+ homepage_uri: https://github.com/iagus/opf
55
+ source_code_uri: https://rubygems.org
56
+ changelog_uri: https://rubygems.org
57
+ rubygems_mfa_required: 'true'
58
+ rdoc_options: []
59
+ require_paths:
60
+ - lib
61
+ required_ruby_version: !ruby/object:Gem::Requirement
62
+ requirements:
63
+ - - ">="
64
+ - !ruby/object:Gem::Version
65
+ version: 3.2.0
66
+ required_rubygems_version: !ruby/object:Gem::Requirement
67
+ requirements:
68
+ - - ">="
69
+ - !ruby/object:Gem::Version
70
+ version: '0'
71
+ requirements: []
72
+ rubygems_version: 3.7.2
73
+ specification_version: 4
74
+ summary: Fetch OpenGraph metadata (title, description, images) and favicons from URLs.
75
+ test_files: []