twitterviewer 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: ccba47a25b9e1ad30c7e941c0e0c75da1e3d182f37e3edae457f7b79edc302fe
4
+ data.tar.gz: c9f8f0b30f9f5848af70b43cc021467afe8c8f46b5696d3eb996081d7334371a
5
+ SHA512:
6
+ metadata.gz: c74fd1c59895d225bec2755a8798e9a8e178cde47aef4752090bb1e8e10eaba6d09d645b631e58bebb83f359966768c0032bacf0d78f606cb3ef53bbbc7a4c42
7
+ data.tar.gz: e05e29e40cfe3c2c95be01b67fd14bf7f9237dc1476c2196a0ff92f3702b8eebd1c60807bd5c57b888baabc037905b4808df5122f7748128e15e652da972f1d2
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 TwitterViewer
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 all
13
+ 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 THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,173 @@
1
+ # TwitterViewer for Ruby
2
+
3
+ Official Ruby client for the [TwitterViewer API](https://twitterviewer.ai/docs/api): read public X (Twitter) posts, threads, profiles and replies as JSON, Markdown, text or PDF. All access is read-only. TwitterViewer is an independent service, not the official X API.
4
+
5
+ Requires Ruby 3.1 or later. No runtime dependencies.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ gem install twitterviewer
11
+ ```
12
+
13
+ or in your Gemfile:
14
+
15
+ ```ruby
16
+ gem "twitterviewer"
17
+ ```
18
+
19
+ ## Quickstart
20
+
21
+ The API needs a Plus plan: every call from an account without it fails with `402 LIMIT_REACHED` and `details.reason` = `PLUS_REQUIRED` (API, MCP and CLI access are all part of Plus). Create an API key at <https://twitterviewer.ai/account/api> and export it as `TWITTERVIEWER_API_KEY`.
22
+
23
+ ```ruby
24
+ require "twitterviewer"
25
+
26
+ client = TwitterViewer::Client.new # or Client.new(api_key: "tv_live_...")
27
+
28
+ thread = client.convert("https://x.com/jack/status/20")
29
+
30
+ puts thread.markdown
31
+ puts "charged #{thread.credits.charged}, #{thread.credits.remaining} left"
32
+ ```
33
+
34
+ ## Configuration
35
+
36
+ | Keyword | Default | Meaning |
37
+ | --- | --- | --- |
38
+ | `api_key:` | `TWITTERVIEWER_API_KEY` | Required. |
39
+ | `base_url:` | `TWITTERVIEWER_BASE_URL`, then `https://twitterviewer.ai` | |
40
+ | `timeout:` | `90` | Seconds allowed to connect, and for each read or write, per attempt. |
41
+ | `max_retries:` | `2` | Retries after a transient failure; see [Errors and retries](#errors-and-retries). `0` disables them. |
42
+ | `sleeper:` | `Kernel#sleep` | Called with the seconds to wait between retries. |
43
+
44
+ A client can be shared between threads. The standard `http_proxy` environment variable is honored.
45
+
46
+ ## Methods
47
+
48
+ Responses are frozen objects with snake_case readers (`post.created_at` is a `Time`, `post.reply_count`, and so on).
49
+
50
+ ### Convert
51
+
52
+ The argument is a link to an X post or profile, or an `@handle`. Profile links return recent posts.
53
+
54
+ ```ruby
55
+ # Structured result (POST /api/v1/convert)
56
+ result = client.convert("https://x.com/jack/status/20", scope: :conversation)
57
+ result.posts.each { |post| puts "#{post.author.handle}: #{post.text}" }
58
+
59
+ # The same through GET /api/v1/convert
60
+ profile = client.convert_by_query("@NASA", max: 50, reposts: true)
61
+
62
+ # Only the document body: :markdown (default), :obsidian or :text
63
+ document = client.convert_to_text("@NASA", format: :obsidian, stats: :off)
64
+ document.save("nasa.md")
65
+
66
+ # PDF, rendered by the server
67
+ pdf = client.convert_to_pdf("https://x.com/jack/status/20", paper: :letter)
68
+ pdf.save(pdf.filename || "thread.pdf")
69
+ ```
70
+
71
+ | Option | Values | Server default |
72
+ | --- | --- | --- |
73
+ | `scope:` | `:thread`, `:post`, `:conversation` (post links) | `:thread` |
74
+ | `format:` | depends on the method | |
75
+ | `stats:` | `:all`, `:root`, `:off` | `:all` |
76
+ | `max:` | 1 to 200 (profile links) | 20 |
77
+ | `replies:` | include replies (profile links) | `false` |
78
+ | `reposts:` | include reposts (profile links) | `false` |
79
+ | `paper:` | `:a4`, `:letter` (PDF) | `:a4` |
80
+
81
+ A `TwitterViewer::Document` has `body`, `content_type`, `filename` (PDF), `credits_charged`, `credits_remaining`, `rate_limit_remaining` and `posts_returned` (Markdown and text).
82
+
83
+ ### Replies
84
+
85
+ ```ruby
86
+ result = client.replies("https://x.com/jack/status/20", max: 50)
87
+ result.replies.each { |reply| puts reply.text }
88
+ ```
89
+
90
+ ### Credits
91
+
92
+ ```ruby
93
+ balance = client.credits # costs no credits
94
+ puts balance.total, balance.plan.remaining, balance.purchased.remaining
95
+ ```
96
+
97
+ ### Domain swap
98
+
99
+ The same conversion addressed like an x.com URL. Returns a Markdown `Document` unless `format:` says otherwise.
100
+
101
+ ```ruby
102
+ markdown = client.swap_profile("NASA", max: 10).body
103
+ text = client.swap_post("jack", "20", format: :text).body
104
+ data = client.swap_post("jack", "20", format: :json).to_convert_result
105
+ ```
106
+
107
+ ## Errors and retries
108
+
109
+ Every error raised for a request inherits from `TwitterViewer::Error`.
110
+
111
+ | Class | When |
112
+ | --- | --- |
113
+ | `APIError` | Non-2xx answer. Has `status`, `code`, `retry_after_sec`, `details` (string keys). |
114
+ | `ConnectionError` | No response (DNS, connection, TLS). |
115
+ | `TimeoutError` | A `ConnectionError`: the attempt ran out of time. |
116
+ | `UnexpectedResponseError` | A 2xx body that cannot be read, usually a wrong base URL. |
117
+
118
+ Values that can never work raise `ArgumentError`, and nothing is sent.
119
+
120
+ ```ruby
121
+ begin
122
+ client.replies("https://x.com/jack/status/20")
123
+ rescue TwitterViewer::APIError => e
124
+ raise unless e.code == TwitterViewer::ErrorCode::LIMIT_REACHED
125
+
126
+ puts e.details["reason"] # PLUS_REQUIRED or INSUFFICIENT_CREDITS
127
+ end
128
+ ```
129
+
130
+ Every method is retried the same way, up to `max_retries` times:
131
+
132
+ - **429 and 5xx**, with or without an API error body (gateway error pages included).
133
+ - **Network errors**: failed connections, timeouts and dropped connections.
134
+
135
+ How retrying behaves:
136
+
137
+ - The wait is `retryAfterSec` when the server sends it, otherwise exponential backoff (about 0.5 s, 1 s, 2 s, at most 8 s).
138
+ - While an identical request is still running, the API waits for it; after a minute it answers 503 with `details.reason` = `IN_PROGRESS` and `retryAfterSec`, which is retried like any other 503.
139
+ - 402, other 4xx answers and 501 (`UNSUPPORTED`) are never retried.
140
+ - A wait longer than 120 seconds is not performed; the error is raised with `retry_after_sec` set.
141
+
142
+ Retrying does not cost credits twice: see [Credits](#credits).
143
+
144
+ ## Credits
145
+
146
+ **1 credit = 1 post returned.** A quoted post counts as one more post; author profiles are free. Errors and empty results are free.
147
+
148
+ A repeated request by the same account within 10 minutes returns the first result and is not charged again, so retrying is safe. The same request means:
149
+
150
+ - convert and swap: the same link (case-insensitive) with the same scope, `max`, `replies` and `reposts`. Format and stats do not matter; PDF is tracked separately.
151
+ - replies: the same post id and `max`.
152
+
153
+ If that result was partial (limited by the balance, or a free website preview of a conversion) and the account now has credits, the request is treated as new and charged. Every authenticated request, including `credits`, counts toward the per-minute rate limit. Full rules: <https://twitterviewer.ai/docs/api>.
154
+
155
+ ## Development
156
+
157
+ ```bash
158
+ bundle install
159
+ bundle exec rake # RuboCop and tests
160
+ gem build twitterviewer.gemspec
161
+ ```
162
+
163
+ Integration tests are skipped unless both variables are set (they spend a few credits):
164
+
165
+ ```bash
166
+ TWITTERVIEWER_BASE_URL=http://localhost:3400 TWITTERVIEWER_API_KEY=tv_live_... bundle exec rake test
167
+ ```
168
+
169
+ `openapi.json` is the contract; a test fails when an operation has no method.
170
+
171
+ ## License
172
+
173
+ MIT
@@ -0,0 +1,283 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TwitterViewer
4
+ # Client of the TwitterViewer API. Instances are safe to share between threads.
5
+ #
6
+ # The API needs a Plus plan: without it every call raises APIError with status 402, code LIMIT_REACHED and
7
+ # details["reason"] PLUS_REQUIRED.
8
+ #
9
+ # client = TwitterViewer::Client.new(api_key: "tv_live_...")
10
+ # client.convert("https://x.com/jack/status/20").markdown
11
+ #
12
+ # The convert and swap methods take these keyword options; whatever you leave out is not sent,
13
+ # so the server default applies:
14
+ #
15
+ # scope:: :thread (default), :post or :conversation. Post links only.
16
+ # stats:: :all (default), :root or :off. Engagement numbers in the rendered document.
17
+ # max:: Profile links only: number of recent posts, 1 to 200 (default 20).
18
+ # replies:: Profile links only: include the account's replies.
19
+ # reposts:: Profile links only: include reposts.
20
+ # paper:: :a4 (default) or :letter. PDF only.
21
+ class Client
22
+ DEFAULT_BASE_URL = "https://twitterviewer.ai"
23
+ DEFAULT_TIMEOUT = 90
24
+ DEFAULT_MAX_RETRIES = 2
25
+ # A 429 or 5xx asking to wait longer than this is raised instead of retried.
26
+ MAX_RETRY_AFTER_SEC = 120
27
+
28
+ BASE_BACKOFF_SEC = 0.5
29
+ MAX_BACKOFF_SEC = 8.0
30
+ CONVERT_OPTIONS = %i[scope stats max replies reposts paper].freeze
31
+ MEDIA_TYPES = {
32
+ "markdown" => "text/markdown",
33
+ "obsidian" => "text/markdown",
34
+ "text" => "text/plain",
35
+ "json" => "application/json",
36
+ "pdf" => "application/pdf"
37
+ }.freeze
38
+ NETWORK_ERRORS = [
39
+ SocketError, SystemCallError, IOError, OpenSSL::SSL::SSLError, Net::HTTPBadResponse, Net::ProtocolError
40
+ ].freeze
41
+ private_constant :BASE_BACKOFF_SEC, :MAX_BACKOFF_SEC, :CONVERT_OPTIONS, :MEDIA_TYPES, :NETWORK_ERRORS
42
+
43
+ attr_reader :base_url, :timeout, :max_retries
44
+
45
+ # api_key:: Defaults to the TWITTERVIEWER_API_KEY environment variable.
46
+ # base_url:: Defaults to TWITTERVIEWER_BASE_URL, then https://twitterviewer.ai.
47
+ # timeout:: Seconds allowed to connect, and for each read or write, per attempt.
48
+ # max_retries:: Retries after a 429, 5xx (except 501) or network error. 0 disables them.
49
+ # sleeper:: Called with the number of seconds to wait between retries.
50
+ def initialize(api_key: nil, base_url: nil, timeout: DEFAULT_TIMEOUT, max_retries: DEFAULT_MAX_RETRIES,
51
+ sleeper: ->(seconds) { sleep(seconds) })
52
+ @api_key = (api_key || ENV.fetch("TWITTERVIEWER_API_KEY", nil)).to_s.strip
53
+ raise ArgumentError, "An API key is required: pass api_key: or set TWITTERVIEWER_API_KEY" if @api_key.empty?
54
+ raise ArgumentError, "timeout must be greater than 0" unless timeout.positive?
55
+ raise ArgumentError, "max_retries must be 0 or more" if max_retries.negative?
56
+
57
+ base_url ||= ENV.fetch("TWITTERVIEWER_BASE_URL", nil)
58
+ base_url = DEFAULT_BASE_URL if base_url.to_s.empty?
59
+ @base_url = base_url.sub(%r{/+\z}, "")
60
+ raise ArgumentError, "base_url must start with http:// or https://" unless URI.parse(@base_url).is_a?(URI::HTTP)
61
+
62
+ @timeout = timeout
63
+ @max_retries = max_retries
64
+ @sleeper = sleeper
65
+ end
66
+
67
+ # Hides the API key.
68
+ def inspect
69
+ "#<#{self.class.name} base_url=#{base_url.inspect}>"
70
+ end
71
+
72
+ # Converts a post, thread or profile (POST /api/v1/convert) and returns a ConvertResult.
73
+ # +format+ only changes the markdown field (:obsidian); use #convert_to_pdf for PDF.
74
+ def convert(url, format: nil, **options)
75
+ reject_pdf(format)
76
+ ConvertResult.from_hash(parse_json(post_convert(url, format, "application/json", options)))
77
+ end
78
+
79
+ # The same conversion through GET /api/v1/convert.
80
+ def convert_by_query(url, format: nil, **options)
81
+ reject_pdf(format)
82
+ params = { url: url, **convert_params(format, options) }
83
+ ConvertResult.from_hash(parse_json(get("/api/v1/convert", params, "application/json")))
84
+ end
85
+
86
+ # Converts a link and returns only the document body as a Document.
87
+ # +format+ is :markdown (default), :obsidian or :text.
88
+ def convert_to_text(url, format: :markdown, **options)
89
+ unless %w[markdown obsidian text].include?(format.to_s)
90
+ raise ArgumentError, "convert_to_text accepts format :markdown, :obsidian or :text"
91
+ end
92
+
93
+ document(post_convert(url, format, "text/markdown", options), format)
94
+ end
95
+
96
+ # Converts a link to a PDF rendered by the server and returns a Document.
97
+ def convert_to_pdf(url, **options)
98
+ document(post_convert(url, :pdf, "application/pdf", options), :pdf)
99
+ end
100
+
101
+ # Reads the replies under a post. +max+ is 1 to 100 (default 20).
102
+ def replies(url, max: nil)
103
+ RepliesResult.from_hash(parse_json(get("/api/v1/replies", { url: url, max: max }, "application/json")))
104
+ end
105
+
106
+ # The CreditBalance. Costs no credits.
107
+ def credits
108
+ CreditBalance.from_hash(parse_json(get("/api/v1/credits", {}, "application/json")))
109
+ end
110
+
111
+ # Recent posts of a profile, addressed like on x.com. Returns a Document, Markdown unless +format+
112
+ # is :obsidian, :text, :json or :pdf.
113
+ def swap_profile(handle, format: :markdown, **options)
114
+ swap("/api/v1/swap/#{path_handle(handle)}", format, options)
115
+ end
116
+
117
+ # A post or thread, addressed like on x.com. Same formats as #swap_profile.
118
+ def swap_post(handle, post_id, format: :markdown, **options)
119
+ post_id = post_id.to_s
120
+ raise ArgumentError, "post_id must be the numeric id of a post" unless post_id.match?(/\A\d{1,25}\z/)
121
+
122
+ swap("/api/v1/swap/#{path_handle(handle)}/status/#{post_id}", format, options)
123
+ end
124
+
125
+ private
126
+
127
+ def swap(path, format, options)
128
+ accept = MEDIA_TYPES.fetch(format.to_s) do
129
+ raise ArgumentError, "format must be :markdown, :obsidian, :text, :json or :pdf"
130
+ end
131
+ document(get(path, convert_params(format, options), accept), format)
132
+ end
133
+
134
+ def reject_pdf(format)
135
+ raise ArgumentError, "Use convert_to_pdf to get a PDF" if format.to_s == "pdf"
136
+ end
137
+
138
+ def convert_params(format, options)
139
+ unknown = options.keys - CONVERT_OPTIONS
140
+ raise ArgumentError, "unknown keyword: #{unknown.map(&:inspect).join(', ')}" unless unknown.empty?
141
+
142
+ { format: format, **options }.compact.transform_values { |v| v.is_a?(Symbol) ? v.to_s : v }
143
+ end
144
+
145
+ def path_handle(handle)
146
+ name = handle.to_s.delete_prefix("@")
147
+ return name if name.match?(/\A[A-Za-z0-9_]{1,15}\z/)
148
+
149
+ raise ArgumentError, "handle must be an X username: 1 to 15 letters, digits or underscores"
150
+ end
151
+
152
+ def get(path, params, accept)
153
+ uri = URI.parse(@base_url + path)
154
+ params = params.compact
155
+ uri.query = URI.encode_www_form(params) unless params.empty?
156
+ perform(uri, Net::HTTP::Get.new(uri), accept)
157
+ end
158
+
159
+ def post_convert(url, format, accept, options)
160
+ uri = URI.parse("#{@base_url}/api/v1/convert")
161
+ request = Net::HTTP::Post.new(uri)
162
+ request["content-type"] = "application/json"
163
+ request.body = JSON.generate({ url: url, **convert_params(format, options) })
164
+ perform(uri, request, accept)
165
+ end
166
+
167
+ # Sends the request, retrying 429, 5xx (except 501) and network errors, and returns a 2xx response.
168
+ # Repeating a request is safe: the API returns the first result again without charging it twice.
169
+ def perform(uri, request, accept)
170
+ request["authorization"] = "Bearer #{@api_key}"
171
+ request["accept"] = accept
172
+ request["user-agent"] = "twitterviewer-ruby/#{VERSION}"
173
+
174
+ attempt = 0
175
+ loop do
176
+ begin
177
+ response = transmit(uri, request)
178
+ rescue Timeout::Error, *NETWORK_ERRORS => e
179
+ raise network_error(e) if attempt >= max_retries
180
+
181
+ wait = backoff(attempt)
182
+ else
183
+ return response if response.is_a?(Net::HTTPSuccess)
184
+
185
+ error = api_error(response)
186
+ raise error unless attempt < max_retries && retryable?(error)
187
+
188
+ wait = error.retry_after_sec || backoff(attempt)
189
+ end
190
+ @sleeper.call(wait)
191
+ attempt += 1
192
+ end
193
+ end
194
+
195
+ def transmit(uri, request)
196
+ Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https", open_timeout: timeout,
197
+ read_timeout: timeout, write_timeout: timeout) do |http|
198
+ # Retries are handled here, not by Net::HTTP.
199
+ http.max_retries = 0
200
+ http.request(request)
201
+ end
202
+ end
203
+
204
+ def network_error(error)
205
+ return TimeoutError.new("The request timed out: #{error.message}") if error.is_a?(Timeout::Error)
206
+
207
+ ConnectionError.new("Could not reach the API: #{error.message}")
208
+ end
209
+
210
+ def retryable?(error)
211
+ # 501 means no data source can serve the request, so asking again does not help.
212
+ return false unless error.status == 429 || (error.status >= 500 && error.status != 501)
213
+
214
+ (error.retry_after_sec || 0) <= MAX_RETRY_AFTER_SEC
215
+ end
216
+
217
+ # Exponential backoff with jitter: about 0.5 s, 1 s, 2 s, up to 8 s.
218
+ def backoff(attempt)
219
+ [BASE_BACKOFF_SEC * (2**attempt), MAX_BACKOFF_SEC].min * rand(0.75..1.0)
220
+ end
221
+
222
+ def api_error(response)
223
+ status = response.code.to_i
224
+ body = begin
225
+ JSON.parse(response.body.to_s.dup.force_encoding(Encoding::UTF_8))
226
+ rescue JSON::ParserError
227
+ nil
228
+ end
229
+ error = body.is_a?(Hash) && body["error"].is_a?(Hash) ? body["error"] : {}
230
+ retry_after = error["retryAfterSec"] || integer_header(response, "retry-after")
231
+ APIError.new(
232
+ error["message"] || "The API answered with HTTP #{status}",
233
+ status: status,
234
+ code: error["code"],
235
+ retry_after_sec: retry_after,
236
+ details: error["details"] || {}
237
+ )
238
+ end
239
+
240
+ def parse_json(response)
241
+ data = JSON.parse(response.body.to_s.dup.force_encoding(Encoding::UTF_8))
242
+ return data if data.is_a?(Hash)
243
+
244
+ raise UnexpectedResponseError, "Expected a JSON object from the API; check the base URL"
245
+ rescue JSON::ParserError
246
+ raise UnexpectedResponseError, "Expected a JSON object from the API; check the base URL"
247
+ end
248
+
249
+ def document(response, format)
250
+ expected = MEDIA_TYPES.fetch(format.to_s)
251
+ content_type = response["content-type"].to_s
252
+ unless content_type.downcase.start_with?(expected)
253
+ raise UnexpectedResponseError,
254
+ "Expected #{expected} from the API, got #{content_type.inspect}; check the base URL"
255
+ end
256
+
257
+ body = response.body.to_s.dup
258
+ body.force_encoding(expected == "application/pdf" ? Encoding::BINARY : Encoding::UTF_8)
259
+ Document.new(
260
+ body: body.freeze,
261
+ content_type: content_type,
262
+ filename: filename(response["content-disposition"].to_s),
263
+ credits_charged: integer_header(response, "x-credits-charged"),
264
+ credits_remaining: integer_header(response, "x-credits-remaining"),
265
+ rate_limit_remaining: integer_header(response, "x-ratelimit-remaining"),
266
+ posts_returned: integer_header(response, "x-posts-returned")
267
+ )
268
+ end
269
+
270
+ # Prefers the UTF-8 name (RFC 5987 filename*) over the ASCII fallback. Never returns a path.
271
+ def filename(disposition)
272
+ encoded = disposition[/filename\*=UTF-8''([^;\s]+)/i, 1]
273
+ name = encoded && URI.decode_www_form_component(encoded.gsub("+", "%2B"))
274
+ name = disposition[/filename="([^"]*)"/i, 1] unless name&.valid_encoding?
275
+ name&.gsub(%r{[/\\\0]}, "-")
276
+ end
277
+
278
+ def integer_header(response, name)
279
+ value = response[name]
280
+ value.to_i if value&.match?(/\A\d+\z/)
281
+ end
282
+ end
283
+ end
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TwitterViewer
4
+ # A raw response body (Markdown, plain text, PDF or JSON) with the metadata sent in the response headers.
5
+ class Document
6
+ # body:: Text in UTF-8, or the binary PDF.
7
+ # content_type:: Content type of the body.
8
+ # filename:: Suggested file name in UTF-8, PDF only. Contains no path separators.
9
+ # credits_charged:: Credits charged by this call.
10
+ # credits_remaining:: Credits left.
11
+ # rate_limit_remaining:: Requests left in this minute; nil for accounts without a limit.
12
+ # posts_returned:: Posts in the document, quoted posts included; Markdown and text only.
13
+ attr_reader :body, :content_type, :filename, :credits_charged, :credits_remaining, :rate_limit_remaining,
14
+ :posts_returned
15
+
16
+ def initialize(body:, content_type:, filename: nil, credits_charged: nil, credits_remaining: nil,
17
+ rate_limit_remaining: nil, posts_returned: nil)
18
+ @body = body
19
+ @content_type = content_type
20
+ @filename = filename
21
+ @credits_charged = credits_charged
22
+ @credits_remaining = credits_remaining
23
+ @rate_limit_remaining = rate_limit_remaining
24
+ @posts_returned = posts_returned
25
+ freeze
26
+ end
27
+
28
+ # Writes the body to +path+ in binary mode.
29
+ def save(path)
30
+ File.binwrite(path, body)
31
+ end
32
+
33
+ # Parses the body of a swap call made with <tt>format: :json</tt>.
34
+ def to_convert_result
35
+ ConvertResult.from_hash(JSON.parse(body))
36
+ rescue JSON::ParserError
37
+ raise UnexpectedResponseError, "The document is not JSON; request format: :json to get a conversion result"
38
+ end
39
+
40
+ def to_s
41
+ body
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TwitterViewer
4
+ # Base class of every error raised by this library. Invalid arguments raise ArgumentError instead.
5
+ class Error < StandardError; end
6
+
7
+ # Every error code the service defines. Compare against APIError#code.
8
+ module ErrorCode
9
+ ALL = [
10
+ INVALID_INPUT = "INVALID_INPUT",
11
+ UNAUTHORIZED = "UNAUTHORIZED",
12
+ FORBIDDEN = "FORBIDDEN",
13
+ NOT_FOUND = "NOT_FOUND",
14
+ PROTECTED = "PROTECTED",
15
+ SUSPENDED = "SUSPENDED",
16
+ CONFLICT = "CONFLICT",
17
+ LIMIT_REACHED = "LIMIT_REACHED",
18
+ RATE_LIMITED = "RATE_LIMITED",
19
+ UPSTREAM = "UPSTREAM",
20
+ UNSUPPORTED = "UNSUPPORTED",
21
+ INTERNAL = "INTERNAL",
22
+ TURNSTILE_FAILED = "TURNSTILE_FAILED",
23
+ HUMAN_CHECK_REQUIRED = "HUMAN_CHECK_REQUIRED",
24
+ INVALID_OR_EXPIRED_TOKEN = "INVALID_OR_EXPIRED_TOKEN",
25
+ EMAIL_SEND_FAILED = "EMAIL_SEND_FAILED",
26
+ EMAIL_NOT_CONFIGURED = "EMAIL_NOT_CONFIGURED",
27
+ EMAIL_BLOCKED = "EMAIL_BLOCKED",
28
+ SERVICE_UNAVAILABLE = "SERVICE_UNAVAILABLE"
29
+ ].freeze
30
+ end
31
+
32
+ # The API answered with a non-2xx status.
33
+ class APIError < Error
34
+ # HTTP status.
35
+ attr_reader :status
36
+ # One of the ErrorCode values; nil when the body is not an API error (for example a gateway error page).
37
+ attr_reader :code
38
+ # Seconds to wait before trying again, when the server says so.
39
+ attr_reader :retry_after_sec
40
+ # Extra data with string keys, such as "reason", "required" and "balance" on a 402.
41
+ attr_reader :details
42
+
43
+ def initialize(message, status:, code: nil, retry_after_sec: nil, details: {})
44
+ super(message)
45
+ @status = status
46
+ @code = code
47
+ @retry_after_sec = retry_after_sec
48
+ @details = details
49
+ end
50
+ end
51
+
52
+ # No response was received: DNS, connection or TLS failure. The original exception is available as #cause.
53
+ class ConnectionError < Error; end
54
+
55
+ # The request ran longer than the client's timeout.
56
+ class TimeoutError < ConnectionError; end
57
+
58
+ # A successful status came with a body this library cannot read, which usually means the base URL is wrong.
59
+ class UnexpectedResponseError < Error; end
60
+ end
@@ -0,0 +1,250 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TwitterViewer
4
+ # Immutable value object built from an API response. Attributes use snake_case; unknown fields are ignored,
5
+ # so new API fields do not break older clients.
6
+ class Model
7
+ class << self
8
+ def attributes
9
+ @attributes ||= superclass.respond_to?(:attributes) ? superclass.attributes.dup : {}
10
+ end
11
+
12
+ # Builds an instance from a decoded JSON object.
13
+ def from_hash(hash)
14
+ raise UnexpectedResponseError, "Unexpected API response: #{name} is not an object" unless hash.is_a?(Hash)
15
+
16
+ new(attributes.to_h { |attr, options| [attr, read(hash, options)] })
17
+ end
18
+
19
+ private
20
+
21
+ # type: a Model class, :time, or nil for plain JSON values. A missing required field raises.
22
+ def attribute(attr, type = nil, key: nil, list: false, optional: false)
23
+ key ||= attr.to_s.gsub(/_([a-z])/) { Regexp.last_match(1).upcase }
24
+ attributes[attr] = { key: key, type: type, list: list, optional: optional }.freeze
25
+ attr_reader attr
26
+ end
27
+
28
+ def read(hash, options)
29
+ key = options[:key]
30
+ raise UnexpectedResponseError, "Unexpected API response: #{name}.#{key} is missing" unless
31
+ options[:optional] || hash.key?(key)
32
+
33
+ value = hash[key]
34
+ return value if value.nil?
35
+ return value.map { |item| cast(item, options[:type]) }.freeze if options[:list]
36
+
37
+ cast(value, options[:type])
38
+ end
39
+
40
+ def cast(value, type)
41
+ case type
42
+ when nil then value
43
+ when :time then Time.iso8601(value)
44
+ when :self then from_hash(value)
45
+ else type.from_hash(value)
46
+ end
47
+ rescue ArgumentError, TypeError
48
+ raise UnexpectedResponseError, "Unexpected API response: invalid value #{value.inspect}"
49
+ end
50
+ end
51
+
52
+ def initialize(values)
53
+ values.each { |attr, value| instance_variable_set(:"@#{attr}", value) }
54
+ freeze
55
+ end
56
+
57
+ def to_h
58
+ self.class.attributes.keys.to_h { |attr| [attr, public_send(attr)] }
59
+ end
60
+
61
+ def ==(other)
62
+ other.class == self.class && other.to_h == to_h
63
+ end
64
+ alias eql? ==
65
+
66
+ def hash
67
+ [self.class, to_h].hash
68
+ end
69
+
70
+ def inspect
71
+ "#<#{self.class.name} #{to_h.map { |k, v| "#{k}=#{v.inspect}" }.join(' ')}>"
72
+ end
73
+ end
74
+
75
+ # The short form of an X account.
76
+ class UserLite < Model
77
+ # Returns a User when the object carries the full profile.
78
+ def self.from_hash(hash)
79
+ return User.from_hash(hash) if equal?(UserLite) && hash.is_a?(Hash) && hash.key?("followers") && hash.key?("bio")
80
+
81
+ super
82
+ end
83
+
84
+ attribute :id
85
+ attribute :handle
86
+ attribute :name
87
+ attribute :avatar_url
88
+ attribute :verified
89
+ # "blue", "business", "government" or nil.
90
+ attribute :verified_type
91
+ attribute :protected
92
+ end
93
+
94
+ # The full profile of an X account.
95
+ class User < UserLite
96
+ attribute :banner_url
97
+ attribute :bio
98
+ attribute :location
99
+ attribute :website
100
+ attribute :followers
101
+ attribute :following
102
+ attribute :posts_count
103
+ attribute :likes_count
104
+ attribute :media_count
105
+ attribute :created_at, :time
106
+ attribute :pinned_tweet_ids
107
+ end
108
+
109
+ # One rendition of a video or GIF.
110
+ class VideoVariant < Model
111
+ attribute :url
112
+ attribute :content_type
113
+ attribute :bitrate
114
+ attribute :width
115
+ attribute :height
116
+ end
117
+
118
+ # A photo, video or GIF attached to a post.
119
+ class Media < Model
120
+ attribute :id
121
+ # "photo", "video" or "gif".
122
+ attribute :kind
123
+ # Photo address; cover image for video and GIF.
124
+ attribute :url
125
+ attribute :width
126
+ attribute :height
127
+ attribute :alt_text
128
+ attribute :duration_ms
129
+ attribute :variants, VideoVariant, list: true
130
+ end
131
+
132
+ # A long-form X article.
133
+ class Article < Model
134
+ attribute :id
135
+ attribute :title
136
+ attribute :markdown
137
+ attribute :cover_url
138
+ attribute :url
139
+ end
140
+
141
+ # One choice of a poll.
142
+ class PollOption < Model
143
+ attribute :label
144
+ attribute :votes
145
+ end
146
+
147
+ # A poll attached to a post.
148
+ class Poll < Model
149
+ attribute :options, PollOption, list: true
150
+ attribute :total_votes
151
+ attribute :ends_at, :time
152
+ attribute :ended
153
+ end
154
+
155
+ # A link preview card.
156
+ class Card < Model
157
+ attribute :url
158
+ attribute :title
159
+ attribute :description
160
+ attribute :domain
161
+ attribute :image_url
162
+ end
163
+
164
+ # The post a reply answers.
165
+ class ReplyTarget < Model
166
+ attribute :tweet_id
167
+ attribute :handle
168
+ end
169
+
170
+ # A post on X.
171
+ class Tweet < Model
172
+ attribute :id
173
+ attribute :url
174
+ attribute :author, UserLite
175
+ attribute :text
176
+ attribute :lang
177
+ attribute :created_at, :time
178
+ attribute :reply_count
179
+ attribute :repost_count
180
+ attribute :like_count
181
+ attribute :quote_count
182
+ attribute :bookmark_count
183
+ attribute :view_count
184
+ attribute :media, Media, list: true
185
+ attribute :quoted, :self
186
+ attribute :reposted_by, UserLite
187
+ attribute :in_reply_to, ReplyTarget
188
+ attribute :conversation_id
189
+ attribute :pinned
190
+ attribute :article, Article, optional: true
191
+ attribute :poll, Poll, optional: true
192
+ attribute :card, Card, optional: true
193
+ attribute :community_note, optional: true
194
+ attribute :sensitive, optional: true
195
+ end
196
+
197
+ # Credits used by one call. 1 credit = 1 post returned.
198
+ class Billing < Model
199
+ attribute :charged
200
+ # Credits left; a very large fixed number for unlimited accounts.
201
+ attribute :remaining
202
+ end
203
+
204
+ # A converted post, thread, conversation or profile.
205
+ class ConvertResult < Model
206
+ # "post", "thread", "conversation" or "profile".
207
+ attribute :kind
208
+ attribute :title
209
+ attribute :source_url
210
+ # A User when the full profile is available, otherwise a UserLite.
211
+ attribute :author, UserLite
212
+ attribute :markdown
213
+ attribute :text
214
+ attribute :posts, Tweet, list: true
215
+ # Filled only for the conversation scope.
216
+ attribute :replies, Tweet, list: true
217
+ attribute :posts_returned
218
+ attribute :word_count
219
+ attribute :credits, Billing
220
+ end
221
+
222
+ # Replies under a post.
223
+ class RepliesResult < Model
224
+ attribute :source_url
225
+ attribute :replies, Tweet, list: true
226
+ # Number of replies. Quoted posts are not counted here but are charged.
227
+ attribute :posts_returned
228
+ attribute :credits, Billing
229
+ end
230
+
231
+ # This month's subscription credits.
232
+ class PlanCredits < Model
233
+ attribute :remaining
234
+ attribute :granted
235
+ attribute :expires_at, :time
236
+ end
237
+
238
+ # Credits that never expire, including the sign-up credits.
239
+ class PurchasedCredits < Model
240
+ attribute :remaining
241
+ end
242
+
243
+ # Credit balance by source.
244
+ class CreditBalance < Model
245
+ attribute :total
246
+ attribute :unlimited
247
+ attribute :plan, PlanCredits
248
+ attribute :purchased, PurchasedCredits
249
+ end
250
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TwitterViewer
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "net/http"
5
+ require "openssl"
6
+ require "time"
7
+ require "uri"
8
+
9
+ require_relative "twitterviewer/version"
10
+ require_relative "twitterviewer/errors"
11
+ require_relative "twitterviewer/models"
12
+ require_relative "twitterviewer/document"
13
+ require_relative "twitterviewer/client"
14
+
15
+ # Client library for the TwitterViewer API (https://twitterviewer.ai/docs/api).
16
+ module TwitterViewer
17
+ end
metadata ADDED
@@ -0,0 +1,54 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: twitterviewer
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - TwitterViewer
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: Read public X (Twitter) posts, threads, profiles and replies as JSON,
13
+ Markdown, text or PDF. Uses only the Ruby standard library.
14
+ email:
15
+ - support@twitterviewer.ai
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - LICENSE
21
+ - README.md
22
+ - lib/twitterviewer.rb
23
+ - lib/twitterviewer/client.rb
24
+ - lib/twitterviewer/document.rb
25
+ - lib/twitterviewer/errors.rb
26
+ - lib/twitterviewer/models.rb
27
+ - lib/twitterviewer/version.rb
28
+ homepage: https://twitterviewer.ai
29
+ licenses:
30
+ - MIT
31
+ metadata:
32
+ homepage_uri: https://twitterviewer.ai
33
+ source_code_uri: https://github.com/TwitterViewer/twitterviewer-ruby
34
+ bug_tracker_uri: https://github.com/TwitterViewer/twitterviewer-ruby/issues
35
+ documentation_uri: https://twitterviewer.ai/docs/api
36
+ rubygems_mfa_required: 'true'
37
+ rdoc_options: []
38
+ require_paths:
39
+ - lib
40
+ required_ruby_version: !ruby/object:Gem::Requirement
41
+ requirements:
42
+ - - ">="
43
+ - !ruby/object:Gem::Version
44
+ version: '3.1'
45
+ required_rubygems_version: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - ">="
48
+ - !ruby/object:Gem::Version
49
+ version: '0'
50
+ requirements: []
51
+ rubygems_version: 3.6.9
52
+ specification_version: 4
53
+ summary: Official Ruby client for the TwitterViewer API.
54
+ test_files: []