|
| 1 | +# frozen_string_literal: true |
| 2 | +require 'net/http' |
| 3 | +require 'json' |
| 4 | +require 'uri' |
| 5 | +require 'ipaddr' |
| 6 | + |
| 7 | +module TranscriptDock |
| 8 | + VERSION = '0.1.0' |
| 9 | + |
| 10 | + class ApiError < StandardError |
| 11 | + attr_reader :code, :status, :retryable, :request_id, :retry_after_seconds |
| 12 | + def initialize(code, message, status: nil, retryable: false, request_id: nil, retry_after_seconds: nil) |
| 13 | + super(message) |
| 14 | + @code, @status, @retryable = code, status, retryable |
| 15 | + @request_id, @retry_after_seconds = request_id, retry_after_seconds |
| 16 | + end |
| 17 | + end |
| 18 | + |
| 19 | + class JobTimeoutError < StandardError |
| 20 | + attr_reader :job |
| 21 | + def initialize(job) |
| 22 | + super('The job is still running. Check it again using its ID.') |
| 23 | + @job = job |
| 24 | + end |
| 25 | + end |
| 26 | + |
| 27 | + class Client |
| 28 | + def initialize(api_key, base_url: 'https://www.transcriptdock.com', timeout: 30) |
| 29 | + raise ArgumentError, 'Provide an API key without whitespace or control characters.' unless api_key.is_a?(String) && api_key.match?(/\A[!-~]+\z/) |
| 30 | + origin = URI.parse(base_url) |
| 31 | + begin |
| 32 | + loopback = origin.hostname == 'localhost' || IPAddr.new(origin.hostname).loopback? |
| 33 | + rescue IPAddr::InvalidAddressError, ArgumentError |
| 34 | + loopback = false |
| 35 | + end |
| 36 | + unless origin.is_a?(URI::HTTP) && origin.hostname && (origin.scheme == 'https' || (origin.scheme == 'http' && loopback)) && origin.userinfo.nil? && origin.query.nil? && origin.fragment.nil? && ['', '/'].include?(origin.path) |
| 37 | + raise ArgumentError, 'Use an HTTPS origin, or loopback HTTP, without credentials, path, query or fragment.' |
| 38 | + end |
| 39 | + @api_key, @base_url = api_key, base_url.sub(%r{/\z}, '') |
| 40 | + @timeout = positive(timeout, 'timeout') |
| 41 | + rescue URI::InvalidURIError |
| 42 | + raise ArgumentError, 'Provide a valid API origin.' |
| 43 | + end |
| 44 | + |
| 45 | + def request(method, path, body: nil, query: {}, idempotency_key: nil, text: false, timeout: @timeout) |
| 46 | + raise ArgumentError, 'Provide a supported HTTP method.' unless method.is_a?(String) && %w[GET POST PUT PATCH DELETE HEAD OPTIONS].include?(method.upcase) |
| 47 | + method = method.upcase |
| 48 | + unless path.is_a?(String) && path.start_with?('/v1/') && !path.match?(/[?#\\]/) && !URI::DEFAULT_PARSER.unescape(path).split('/').any? { |s| ['.', '..'].include?(s) } |
| 49 | + raise ArgumentError, 'Use a /v1/ path and pass query parameters separately.' |
| 50 | + end |
| 51 | + needs_key = method == 'POST' && (%w[/v1/jobs /v1/batches /v1/video-discoveries /v1/language-discoveries].include?(path) || path.end_with?('/retry')) |
| 52 | + if needs_key || !idempotency_key.nil? |
| 53 | + raise ArgumentError, 'Idempotency keys need 8 to 128 printable ASCII characters.' unless idempotency_key.is_a?(String) && idempotency_key.match?(/\A[ -~]{8,128}\z/) |
| 54 | + end |
| 55 | + uri = URI.parse(@base_url + path) |
| 56 | + uri.query = URI.encode_www_form(query.reject { |_, v| v.nil? }) unless query.empty? |
| 57 | + headers = {'Authorization' => "Bearer #{@api_key}", 'Accept' => 'application/json', 'User-Agent' => "transcriptdock-ruby/#{VERSION}"} |
| 58 | + headers['Idempotency-Key'] = idempotency_key if idempotency_key |
| 59 | + headers['Content-Type'] = 'application/json' unless body.nil? |
| 60 | + req = Net::HTTPGenericRequest.new(method, !body.nil?, method != 'HEAD', uri.request_uri, headers) |
| 61 | + req.body = JSON.generate(body) unless body.nil? |
| 62 | + http = Net::HTTP.new(uri.hostname, uri.port, nil) |
| 63 | + http.use_ssl = uri.scheme == 'https' |
| 64 | + http.max_retries = 0 |
| 65 | + http.open_timeout = http.read_timeout = http.write_timeout = positive(timeout, 'timeout') |
| 66 | + begin |
| 67 | + response = http.start { |connection| connection.request(req) } |
| 68 | + rescue IOError, SystemCallError, Timeout::Error, SocketError, OpenSSL::SSL::SSLError |
| 69 | + raise ApiError.new('NETWORK_ERROR', 'Could not reach the API. Check the job before retrying a submission.', retryable: true), cause: nil |
| 70 | + end |
| 71 | + status = response.code.to_i |
| 72 | + if status < 200 || status >= 300 |
| 73 | + begin |
| 74 | + envelope = JSON.parse(response.body) |
| 75 | + rescue JSON::ParserError |
| 76 | + envelope = {} |
| 77 | + end |
| 78 | + envelope = {} unless envelope.is_a?(Hash) |
| 79 | + error = envelope['error'].is_a?(Hash) ? envelope['error'] : {} |
| 80 | + raise ApiError.new(redact(error['code'] || 'HTTP_ERROR'), redact(error['message'] || "Request failed with status #{status}."), status: status, |
| 81 | + retryable: error.fetch('retryable', status == 429 || status >= 500), request_id: envelope['request_id'] && redact(envelope['request_id']), retry_after_seconds: error['retry_after_seconds']) |
| 82 | + end |
| 83 | + return response.body if text |
| 84 | + begin |
| 85 | + result = JSON.parse(response.body) |
| 86 | + rescue JSON::ParserError |
| 87 | + raise ApiError.new('INVALID_RESPONSE', 'The API did not return JSON.'), cause: nil |
| 88 | + end |
| 89 | + raise ApiError.new('INVALID_RESPONSE', 'The API did not return a JSON object.') unless result.is_a?(Hash) |
| 90 | + result |
| 91 | + end |
| 92 | + |
| 93 | + def capabilities = request('GET', '/v1/capabilities') |
| 94 | + def create_job(body, idempotency_key:) = request('POST', '/v1/jobs', body: body, idempotency_key: idempotency_key) |
| 95 | + def get_job(id) = request('GET', "/v1/jobs/#{encode_id(id)}") |
| 96 | + def get_transcript(id) = request('GET', "/v1/transcripts/#{encode_id(id)}") |
| 97 | + def export_transcript(id, format: 'txt') |
| 98 | + raise ArgumentError, 'Choose json, txt, srt or vtt.' unless %w[json txt srt vtt].include?(format) |
| 99 | + request('GET', "/v1/transcripts/#{encode_id(id)}/export", query: {format: format}, text: true) |
| 100 | + end |
| 101 | + |
| 102 | + def wait_for_job(id, timeout: 120, poll_interval: 3) |
| 103 | + deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + positive(timeout, 'timeout') |
| 104 | + positive(poll_interval, 'poll_interval') |
| 105 | + last = nil |
| 106 | + loop do |
| 107 | + remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC) |
| 108 | + raise JobTimeoutError, last if remaining <= 0 |
| 109 | + last = request('GET', "/v1/jobs/#{encode_id(id)}", timeout: [remaining, @timeout].min) |
| 110 | + return last if %w[succeeded failed cancelled].include?(last['status']) |
| 111 | + remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC) |
| 112 | + raise JobTimeoutError, last if remaining <= 0 |
| 113 | + sleep [remaining, poll_interval].min |
| 114 | + end |
| 115 | + end |
| 116 | + |
| 117 | + private |
| 118 | + def positive(value, name) |
| 119 | + raise ArgumentError, "#{name} must be a finite positive number." unless value.is_a?(Numeric) && value.finite? && value > 0 |
| 120 | + value |
| 121 | + end |
| 122 | + def encode_id(id) |
| 123 | + raise ArgumentError, 'Provide a nonempty ID.' unless id.is_a?(String) && !id.empty? && !['.', '..'].include?(id) |
| 124 | + URI.encode_www_form_component(id).gsub('+', '%20') |
| 125 | + end |
| 126 | + def redact(value) |
| 127 | + value.to_s.gsub(@api_key, '[REDACTED]').gsub(/td_live_[A-Za-z0-9_-]+|Bearer\s+\S+/i, '[REDACTED]') |
| 128 | + end |
| 129 | + end |
| 130 | +end |
0 commit comments