|
| 1 | +<?php |
| 2 | +declare(strict_types=1); |
| 3 | +namespace TranscriptDock; |
| 4 | + |
| 5 | +final class Client |
| 6 | +{ |
| 7 | + private string $baseUrl; |
| 8 | + |
| 9 | + public function __construct( |
| 10 | + private readonly string $apiKey, |
| 11 | + string $baseUrl = 'https://www.transcriptdock.com', |
| 12 | + private readonly float $timeout = 30, |
| 13 | + ) { |
| 14 | + if (!preg_match('/\A[!-~]+\z/', $apiKey)) { |
| 15 | + throw new \InvalidArgumentException('Provide an API key without whitespace or control characters.'); |
| 16 | + } |
| 17 | + $url = parse_url($baseUrl); |
| 18 | + $host = trim($url['host'] ?? '', '[]'); |
| 19 | + $loopback = $host === 'localhost' || $host === '::1' || |
| 20 | + (filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) && str_starts_with($host, '127.')); |
| 21 | + if (!$url || $host === '' || (($url['scheme'] ?? '') !== 'https' && !(($url['scheme'] ?? '') === 'http' && $loopback)) || |
| 22 | + isset($url['user'], $url['pass']) || isset($url['user']) || isset($url['query']) || isset($url['fragment']) || |
| 23 | + !in_array($url['path'] ?? '', ['', '/'], true) || preg_match('/[\x00-\x20\x7f]/', $baseUrl)) { |
| 24 | + throw new \InvalidArgumentException('Use an HTTPS origin, or loopback HTTP, without credentials, path, query or fragment.'); |
| 25 | + } |
| 26 | + self::positive($timeout); |
| 27 | + $this->baseUrl = rtrim($baseUrl, '/'); |
| 28 | + } |
| 29 | + |
| 30 | + /** Return all API fields as associative arrays, or raw export text. No redirects or retries. */ |
| 31 | + public function request(string $method, string $path, ?array $body = null, array $query = [], ?string $idempotencyKey = null, bool $text = false, ?float $timeout = null): array|string |
| 32 | + { |
| 33 | + $method = strtoupper($method); |
| 34 | + if (!in_array($method, ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'], true)) throw new \InvalidArgumentException('Provide a supported HTTP method.'); |
| 35 | + if (!str_starts_with($path, '/v1/') || preg_match('/[?#\\\\]/', $path) || array_intersect(explode('/', rawurldecode($path)), ['.', '..'])) { |
| 36 | + throw new \InvalidArgumentException('Use a /v1/ path and pass query parameters separately.'); |
| 37 | + } |
| 38 | + $needsKey = $method === 'POST' && (in_array($path, ['/v1/jobs', '/v1/batches', '/v1/video-discoveries', '/v1/language-discoveries'], true) || str_ends_with($path, '/retry')); |
| 39 | + if (($needsKey || $idempotencyKey !== null) && !preg_match('/\A[ -~]{8,128}\z/', $idempotencyKey ?? '')) { |
| 40 | + throw new \InvalidArgumentException('Idempotency keys need 8 to 128 printable ASCII characters.'); |
| 41 | + } |
| 42 | + $seconds = $timeout ?? $this->timeout; |
| 43 | + self::positive($seconds); |
| 44 | + $headers = ['Authorization: Bearer ' . $this->apiKey, 'Accept: application/json', 'User-Agent: transcriptdock-php/0.1.0']; |
| 45 | + if ($idempotencyKey !== null) $headers[] = 'Idempotency-Key: ' . $idempotencyKey; |
| 46 | + $url = $this->baseUrl . $path; |
| 47 | + $query = array_filter($query, fn($v) => $v !== null); |
| 48 | + if ($query) $url .= '?' . http_build_query($query, '', '&', PHP_QUERY_RFC3986); |
| 49 | + $options = [CURLOPT_CUSTOMREQUEST => $method, CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => false, |
| 50 | + CURLOPT_TIMEOUT_MS => max(1, (int) ceil($seconds * 1000)), CURLOPT_CONNECTTIMEOUT_MS => max(1, (int) ceil($seconds * 1000)), |
| 51 | + CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2]; |
| 52 | + if ($body !== null) { |
| 53 | + $options[CURLOPT_POSTFIELDS] = json_encode((object) $body, JSON_THROW_ON_ERROR); |
| 54 | + $headers[] = 'Content-Type: application/json'; |
| 55 | + } |
| 56 | + $options[CURLOPT_HTTPHEADER] = $headers; |
| 57 | + $curl = curl_init($url); |
| 58 | + curl_setopt_array($curl, $options); |
| 59 | + $raw = curl_exec($curl); |
| 60 | + $status = (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE); |
| 61 | + unset($curl); |
| 62 | + if ($raw === false) throw new ApiError('NETWORK_ERROR', 'Could not reach the API. Check the job before retrying a submission.', retryable: true); |
| 63 | + if ($status < 200 || $status >= 300) { |
| 64 | + $envelope = json_decode($raw, true); |
| 65 | + $error = is_array($envelope) && is_array($envelope['error'] ?? null) ? $envelope['error'] : []; |
| 66 | + throw new ApiError($this->redact(is_string($error['code'] ?? null) ? $error['code'] : 'HTTP_ERROR'), |
| 67 | + $this->redact(is_string($error['message'] ?? null) ? $error['message'] : "Request failed with status $status."), $status, |
| 68 | + is_bool($error['retryable'] ?? null) ? $error['retryable'] : ($status === 429 || $status >= 500), |
| 69 | + is_string($envelope['request_id'] ?? null) ? $this->redact($envelope['request_id']) : null, |
| 70 | + is_int($error['retry_after_seconds'] ?? null) ? $error['retry_after_seconds'] : null); |
| 71 | + } |
| 72 | + if ($text) return $raw; |
| 73 | + try { |
| 74 | + $decoded = json_decode($raw, false, 512, JSON_THROW_ON_ERROR); |
| 75 | + } catch (\JsonException) { |
| 76 | + throw new ApiError('INVALID_RESPONSE', 'The API did not return JSON.'); |
| 77 | + } |
| 78 | + if (!$decoded instanceof \stdClass) throw new ApiError('INVALID_RESPONSE', 'The API did not return a JSON object.'); |
| 79 | + return json_decode($raw, true, 512, JSON_THROW_ON_ERROR); |
| 80 | + } |
| 81 | + |
| 82 | + public function capabilities(): array { return $this->request('GET', '/v1/capabilities'); } |
| 83 | + public function createJob(array $body, string $idempotencyKey): array { return $this->request('POST', '/v1/jobs', $body, idempotencyKey: $idempotencyKey); } |
| 84 | + public function getJob(string $id): array { return $this->request('GET', '/v1/jobs/' . self::id($id)); } |
| 85 | + public function getTranscript(string $id): array { return $this->request('GET', '/v1/transcripts/' . self::id($id)); } |
| 86 | + public function exportTranscript(string $id, string $format = 'txt'): string |
| 87 | + { |
| 88 | + if (!in_array($format, ['json', 'txt', 'srt', 'vtt'], true)) throw new \InvalidArgumentException('Choose json, txt, srt or vtt.'); |
| 89 | + return $this->request('GET', '/v1/transcripts/' . self::id($id) . '/export', query: ['format' => $format], text: true); |
| 90 | + } |
| 91 | + public function waitForJob(string $id, float $timeout = 120, float $pollInterval = 3): array |
| 92 | + { |
| 93 | + self::positive($timeout); |
| 94 | + self::positive($pollInterval); |
| 95 | + $deadline = hrtime(true) / 1e9 + $timeout; |
| 96 | + $last = null; |
| 97 | + while (true) { |
| 98 | + $remaining = $deadline - hrtime(true) / 1e9; |
| 99 | + if ($remaining <= 0) throw new JobTimeoutError($last); |
| 100 | + $last = $this->request('GET', '/v1/jobs/' . self::id($id), timeout: min($remaining, $this->timeout)); |
| 101 | + if (in_array($last['status'] ?? '', ['succeeded', 'failed', 'cancelled'], true)) return $last; |
| 102 | + $remaining = $deadline - hrtime(true) / 1e9; |
| 103 | + if ($remaining <= 0) throw new JobTimeoutError($last); |
| 104 | + usleep((int) (min($remaining, $pollInterval) * 1e6)); |
| 105 | + } |
| 106 | + } |
| 107 | + private static function positive(float $value): void |
| 108 | + { |
| 109 | + if (!is_finite($value) || $value <= 0 || $value > 86400) throw new \InvalidArgumentException('Timeout and poll intervals must be positive and at most one day.'); |
| 110 | + } |
| 111 | + private static function id(string $id): string |
| 112 | + { |
| 113 | + if ($id === '' || $id === '.' || $id === '..') throw new \InvalidArgumentException('Provide a nonempty ID.'); |
| 114 | + return rawurlencode($id); |
| 115 | + } |
| 116 | + private function redact(string $value): string |
| 117 | + { |
| 118 | + return preg_replace('/td_live_[A-Za-z0-9_-]+|Bearer\s+\S+/i', '[REDACTED]', str_replace($this->apiKey, '[REDACTED]', $value)); |
| 119 | + } |
| 120 | +} |
0 commit comments