ampost 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.
@@ -0,0 +1,130 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ampost
4
+ # `client.media`: the generated `create_upload` and `get_upload`, plus `upload` and `wait_for_upload`.
5
+ class MediaResource < Resources::Media
6
+ MIME_TYPES = {
7
+ "jpg" => "image/jpeg",
8
+ "jpeg" => "image/jpeg",
9
+ "png" => "image/png",
10
+ "webp" => "image/webp",
11
+ "gif" => "image/gif",
12
+ "mp4" => "video/mp4",
13
+ "m4v" => "video/mp4",
14
+ "mov" => "video/quicktime",
15
+ "webm" => "video/webm"
16
+ }.freeze
17
+
18
+ # Large videos take a while to send; the API's per-request timeout would be too short.
19
+ UPLOAD_TIMEOUT = 15 * 60
20
+
21
+ # The MIME type for a file name's extension, or nil.
22
+ #
23
+ # @param file_name [String]
24
+ # @return [String, nil]
25
+ def self.guess_content_type(file_name)
26
+ extension = File.extname(file_name.to_s).delete_prefix(".").downcase
27
+ extension.empty? ? nil : MIME_TYPES[extension]
28
+ end
29
+
30
+ # Uploads one image or video and returns it as a `media` item for `posts.create`:
31
+ #
32
+ # video = client.media.upload("launch.mp4")
33
+ # client.posts.create({ text: "We launched", media: [video], targets: [{ platforms: ["youtube"] }] })
34
+ #
35
+ # Steps: `create_upload`, a PUT of the bytes to the returned `uploadUrl` (straight to storage; your
36
+ # API key is not sent there), then `get_upload` until Ampost has checked the file.
37
+ #
38
+ # @param file [String, Pathname, IO] A path, or an IO (File, StringIO) to read the bytes from.
39
+ # @param file_name [String, nil] Default: the path's name, else `file`.
40
+ # @param content_type [String, nil] MIME type, for example `video/mp4`. Default: guessed from the file name.
41
+ # @param poll_interval [Numeric] Seconds between status checks.
42
+ # @param wait_timeout [Numeric] Seconds to wait for processing before raising MediaUploadError (`timeout`).
43
+ # @param options [Hash] `timeout:`, `max_retries:` and `extra_headers:` for the API calls.
44
+ # @return [Hash] `url`, `type`, `mimeType`, `sizeBytes`, `width`, `height`, `durationSeconds`
45
+ # @raise [Ampost::MediaUploadError]
46
+ def upload(file, file_name: nil, content_type: nil, poll_interval: 2, wait_timeout: 120, **options)
47
+ content, name, mime = read(file, file_name, content_type)
48
+ created = create_upload({ "fileName" => name }, **options)
49
+ response = @client.send_raw(
50
+ created.fetch("method"),
51
+ created.fetch("uploadUrl"),
52
+ headers: created.fetch("headers", {}).merge("x-content-type" => mime),
53
+ body: content,
54
+ timeout: options.fetch(:timeout, UPLOAD_TIMEOUT)
55
+ )
56
+ unless response.success?
57
+ raise MediaUploadError.new(
58
+ "Storage refused the file: HTTP #{response.status} #{response.body.to_s[0, 300]}".strip,
59
+ "upload_rejected",
60
+ created.fetch("id")
61
+ )
62
+ end
63
+
64
+ first_file(wait_for_upload(created.fetch("id"), poll_interval: poll_interval, wait_timeout: wait_timeout, **options))
65
+ end
66
+
67
+ # Polls an upload until it is `completed` and returns it. Raises MediaUploadError when it `failed`
68
+ # or `expired`, or is still pending after `wait_timeout` seconds. Use it after showing
69
+ # `uploadPageUrl` to a user.
70
+ #
71
+ # @return [Hash] the `MediaUpload`
72
+ # @raise [Ampost::MediaUploadError]
73
+ def wait_for_upload(upload_id, poll_interval: 2, wait_timeout: 120, **options)
74
+ deadline = monotonic + wait_timeout
75
+ loop do
76
+ upload = get_upload(upload_id, **options)
77
+ check_status(upload, upload_id)
78
+ return upload if upload["status"] == "completed"
79
+
80
+ if monotonic + poll_interval > deadline
81
+ raise MediaUploadError.new("The upload is still being processed; check it later with get_upload",
82
+ "timeout", upload_id)
83
+ end
84
+
85
+ @client.send(:sleep_for, poll_interval)
86
+ end
87
+ end
88
+
89
+ private
90
+
91
+ def read(file, file_name, content_type)
92
+ name = nil
93
+ if file.is_a?(String) || file.respond_to?(:to_path)
94
+ path = file.respond_to?(:to_path) ? file.to_path : file
95
+ content = File.binread(path)
96
+ name = File.basename(path)
97
+ elsif file.respond_to?(:read)
98
+ content = file.read.to_s.b
99
+ name = File.basename(file.path) if file.respond_to?(:path) && file.path
100
+ else
101
+ raise ArgumentError, "upload takes a file path or an IO, got #{file.class}"
102
+ end
103
+ name = file_name || name || "file"
104
+ mime = content_type || self.class.guess_content_type(name)
105
+ raise Error, "Cannot tell the MIME type of #{name.inspect}: pass content_type:" unless mime
106
+
107
+ [content, name, mime]
108
+ end
109
+
110
+ def check_status(upload, upload_id)
111
+ case upload["status"]
112
+ when "failed"
113
+ raise MediaUploadError.new("The upload failed: #{upload["error"] || "the file was refused"}", "failed", upload_id)
114
+ when "expired"
115
+ raise MediaUploadError.new("The upload expired before a file arrived; create a new one", "expired", upload_id)
116
+ end
117
+ end
118
+
119
+ def first_file(upload)
120
+ file = (upload["files"] || []).first
121
+ raise MediaUploadError.new("The upload completed without a file", "failed", upload["id"]) unless file
122
+
123
+ file.slice("url", "type", "mimeType", "sizeBytes", "width", "height", "durationSeconds")
124
+ end
125
+
126
+ def monotonic
127
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
128
+ end
129
+ end
130
+ end
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ampost
4
+ # One page of a list. `page.data` is this page; `each` (and every Enumerable method) walks every
5
+ # item across pages, fetching the next pages as it goes:
6
+ #
7
+ # page = client.posts.list(status: "failed", limit: 50)
8
+ # page.data # this page's posts
9
+ # page.each { |post| client.posts.retry(post["id"]) } # every failed post
10
+ # client.accounts.list.first(5) # stops fetching after 5 items
11
+ class Page
12
+ include Enumerable
13
+
14
+ # @return [Hash] the raw response: `{"data" => [...], "pagination" => {...}}`
15
+ attr_reader :response
16
+ # @return [Array<Hash>] this page's items
17
+ attr_reader :data
18
+ # @return [Hash] `limit`, `offset`, `total` and `hasMore` as the API sends them
19
+ attr_reader :pagination
20
+
21
+ # @param response [Hash] a list response
22
+ # @param fetch [#call] takes an offset, returns the list response there
23
+ def initialize(response, fetch)
24
+ @response = response
25
+ @data = response.fetch("data")
26
+ @pagination = response.fetch("pagination")
27
+ @fetch = fetch
28
+ end
29
+
30
+ # @return [Integer] items across all pages
31
+ def total
32
+ Integer(@pagination.fetch("total"))
33
+ end
34
+
35
+ # Items on this page (`count` walks every page).
36
+ #
37
+ # @return [Integer]
38
+ def size
39
+ @data.size
40
+ end
41
+ alias length size
42
+
43
+ def next_page?
44
+ @pagination["hasMore"] == true && !@data.empty?
45
+ end
46
+
47
+ # @return [Page]
48
+ # @raise [Ampost::Error] on the last page
49
+ def next_page
50
+ raise Error, "No next page" unless next_page?
51
+
52
+ Page.new(@fetch.call(Integer(@pagination.fetch("offset")) + @data.size), @fetch)
53
+ end
54
+
55
+ # Yields this page and each next page.
56
+ #
57
+ # @return [Enumerator] without a block
58
+ def each_page
59
+ return enum_for(:each_page) unless block_given?
60
+
61
+ page = self
62
+ loop do
63
+ yield page
64
+ break unless page.next_page?
65
+
66
+ page = page.next_page
67
+ end
68
+ self
69
+ end
70
+
71
+ # Yields every item, page after page.
72
+ #
73
+ # @return [Enumerator] without a block
74
+ def each(&block)
75
+ return enum_for(:each) unless block
76
+
77
+ each_page { |page| page.data.each(&block) }
78
+ self
79
+ end
80
+
81
+ def inspect
82
+ "#<#{self.class.name} data=<#{@data.size} items> pagination=#{@pagination.inspect}>"
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "uri"
4
+
5
+ module Ampost
6
+ # Base of the generated resource classes in lib/ampost/generated/resources.rb.
7
+ class Resource
8
+ # @param client [Ampost::Client]
9
+ def initialize(client)
10
+ @client = client
11
+ end
12
+
13
+ def inspect
14
+ "#<#{self.class.name}>"
15
+ end
16
+
17
+ private
18
+
19
+ # Encodes one path parameter.
20
+ def path(value)
21
+ unless value.is_a?(String) && !value.empty?
22
+ raise ArgumentError, "Expected a non-empty String path parameter, got #{value.inspect}"
23
+ end
24
+
25
+ URI.encode_www_form_component(value).gsub("+", "%20")
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "openssl"
5
+ require "uri"
6
+
7
+ module Ampost
8
+ # The HTTP layer under the client. The default, NetHTTP, uses only the standard library; pass your
9
+ # own object with the same `call(request)` to `Ampost::Client.new(transport:)` to change it
10
+ # (instrumentation, a custom HTTP library, tests).
11
+ module Transport
12
+ # One HTTP request. `headers` has the exact names to send; `body` is a String or nil.
13
+ Request = Struct.new(:method, :url, :headers, :body, :timeout, keyword_init: true)
14
+
15
+ # One HTTP response. `headers` has lowercase names.
16
+ Response = Struct.new(:status, :headers, :body, keyword_init: true) do
17
+ def success?
18
+ status >= 200 && status < 300
19
+ end
20
+ end
21
+
22
+ # Net::HTTP, one connection per request (so a client is safe to share between threads). Proxies
23
+ # come from `http_proxy` / `https_proxy` as usual for Net::HTTP.
24
+ class NetHTTP
25
+ # Errors that mean no usable response arrived.
26
+ CONNECTION_ERRORS = [
27
+ SocketError, SystemCallError, IOError, EOFError, OpenSSL::SSL::SSLError, Net::HTTPBadResponse,
28
+ Net::ProtocolError
29
+ ].freeze
30
+
31
+ # @param request [Request]
32
+ # @return [Response]
33
+ # @raise [Ampost::APITimeoutError, Ampost::APIConnectionError] when no response arrives
34
+ def call(request)
35
+ uri = URI(request.url)
36
+ http = Net::HTTP.new(uri.host, uri.port)
37
+ http.use_ssl = uri.scheme == "https"
38
+ http.open_timeout = request.timeout
39
+ http.read_timeout = request.timeout
40
+ http.write_timeout = request.timeout
41
+ http.ssl_timeout = request.timeout if http.use_ssl?
42
+ response = http.start do |connection|
43
+ connection.send_request(request.method, uri.request_uri, request.body, request.headers)
44
+ end
45
+ headers = {}
46
+ response.each_header { |name, value| headers[name] = value }
47
+ body = response.body.to_s.dup.force_encoding(Encoding::UTF_8)
48
+ Response.new(status: response.code.to_i, headers: headers, body: body)
49
+ rescue Net::OpenTimeout, Net::ReadTimeout, Net::WriteTimeout
50
+ raise APITimeoutError, "Request timed out after #{request.timeout} s"
51
+ rescue *CONNECTION_ERRORS => e
52
+ raise APIConnectionError, "Connection error: #{e.message} (#{e.class})"
53
+ end
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ampost
4
+ VERSION = "0.1.0"
5
+ end
data/lib/ampost.rb ADDED
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The official Ruby client for the Ampost API: https://ampost.io/docs?ref=github
4
+ #
5
+ # require "ampost"
6
+ #
7
+ # client = Ampost::Client.new # reads AMPOST_API_KEY
8
+ # client.posts.create({ text: "Hello", targets: [{ platforms: ["bluesky"] }], publishNow: true })
9
+ module Ampost
10
+ end
11
+
12
+ require_relative "ampost/version"
13
+ require_relative "ampost/errors"
14
+ require_relative "ampost/transport"
15
+ require_relative "ampost/page"
16
+ require_relative "ampost/resource"
17
+ require_relative "ampost/generated/resources"
18
+ require_relative "ampost/media"
19
+ require_relative "ampost/client"
metadata ADDED
@@ -0,0 +1,63 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: ampost
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Ampost
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-11-24 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Publish, schedule and track social media posts with one API call. Every
14
+ endpoint of the Ampost REST API, generated from its OpenAPI document, with retries,
15
+ idempotency keys, typed errors, pagination and media upload. No runtime dependencies.
16
+ email:
17
+ - support@ampost.io
18
+ executables: []
19
+ extensions: []
20
+ extra_rdoc_files: []
21
+ files:
22
+ - CHANGELOG.md
23
+ - LICENSE
24
+ - README.md
25
+ - lib/ampost.rb
26
+ - lib/ampost/client.rb
27
+ - lib/ampost/errors.rb
28
+ - lib/ampost/generated/resources.rb
29
+ - lib/ampost/media.rb
30
+ - lib/ampost/page.rb
31
+ - lib/ampost/resource.rb
32
+ - lib/ampost/transport.rb
33
+ - lib/ampost/version.rb
34
+ homepage: https://ampost.io?ref=rubygems
35
+ licenses:
36
+ - MIT
37
+ metadata:
38
+ homepage_uri: https://ampost.io?ref=rubygems
39
+ documentation_uri: https://ampost.io/docs?ref=rubygems
40
+ source_code_uri: https://github.com/ampost-io/ampost-ruby
41
+ changelog_uri: https://github.com/ampost-io/ampost-ruby/blob/main/CHANGELOG.md
42
+ bug_tracker_uri: https://github.com/ampost-io/ampost-ruby/issues
43
+ post_install_message:
44
+ rdoc_options: []
45
+ require_paths:
46
+ - lib
47
+ required_ruby_version: !ruby/object:Gem::Requirement
48
+ requirements:
49
+ - - ">="
50
+ - !ruby/object:Gem::Version
51
+ version: '3.1'
52
+ required_rubygems_version: !ruby/object:Gem::Requirement
53
+ requirements:
54
+ - - ">="
55
+ - !ruby/object:Gem::Version
56
+ version: '0'
57
+ requirements: []
58
+ rubygems_version: 3.5.22
59
+ signing_key:
60
+ specification_version: 4
61
+ summary: 'Official Ruby client for the Ampost API: publish and schedule posts on Instagram,
62
+ Facebook, Threads, X, YouTube, Pinterest, Bluesky, Telegram and Discord'
63
+ test_files: []