Vultr.php 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. <?php
  2. namespace App\Utils\DDNS;
  3. use App\Utils\Library\Templates\DNS;
  4. use Arr;
  5. use Cache;
  6. use Http;
  7. use Log;
  8. use RuntimeException;
  9. class Vultr implements DNS
  10. {
  11. // 开发依据: https://www.vultr.com/api/#tag/dns
  12. private const API_ENDPOINT = 'https://api.vultr.com/v2/';
  13. public const KEY = 'vultr';
  14. public const LABEL = 'Vultr';
  15. private string $apiKey;
  16. private array $domainInfo;
  17. public function __construct(private readonly string $subdomain)
  18. {
  19. $this->apiKey = sysConfig('ddns_secret');
  20. $this->domainInfo = $this->parseDomainInfo();
  21. }
  22. private function parseDomainInfo(): array
  23. {
  24. $domains = Cache::remember('ddns_get_domains', now()->addHour(), function () {
  25. return array_column($this->sendRequest('ListDNSDomains')['domains'] ?? [], 'domain');
  26. });
  27. if ($domains) {
  28. $matched = Arr::first($domains, fn ($domain) => str_contains($this->subdomain, $domain));
  29. }
  30. if (empty($matched)) {
  31. throw new RuntimeException('['.self::LABEL." — ListDNSDomains] The subdomain $this->subdomain does not match any domain in your account.");
  32. }
  33. return [
  34. 'sub' => rtrim(substr($this->subdomain, 0, -strlen($matched)), '.'),
  35. 'domain' => $matched,
  36. ];
  37. }
  38. private function sendRequest(string $action, array $parameters = [], string $recordId = ''): bool|array
  39. {
  40. $client = Http::timeout(15)->retry(3, 1000)->withHeader('Authorization', "Bearer $this->apiKey")->baseUrl(self::API_ENDPOINT)->asJson();
  41. $response = match ($action) {
  42. 'ListDNSDomains' => $client->get('/domains'),
  43. 'ListRecords' => $client->get("/domains/{$this->domainInfo['domain']}/records", $parameters),
  44. 'CreateRecord' => $client->post("/domains/{$this->domainInfo['domain']}/records", $parameters),
  45. 'UpdateRecord' => $client->patch("/domains/{$this->domainInfo['domain']}/records/$recordId", $parameters),
  46. 'DeleteRecord' => $client->delete("/domains/{$this->domainInfo['domain']}/records/$recordId"),
  47. };
  48. $data = $response->json();
  49. if ($response->successful()) {
  50. return $data ?? true;
  51. }
  52. if ($data) {
  53. Log::error('['.self::LABEL." — $action] 返回错误信息: ".$data['error'] ?? 'Unknown error');
  54. } else {
  55. Log::error('['.self::LABEL." — $action] 请求失败");
  56. }
  57. exit(400);
  58. }
  59. public function store(string $ip, string $type): bool
  60. {
  61. return (bool) $this->sendRequest('CreateRecord', ['name' => $this->domainInfo['sub'], 'type' => $type, 'data' => $ip]);
  62. }
  63. public function update(string $latest_ip, string $original_ip, string $type): bool
  64. {
  65. $recordIds = $this->getRecordIds($type, $original_ip);
  66. if ($recordIds) {
  67. $this->sendRequest('UpdateRecord', ['data' => $latest_ip], $recordIds[0]);
  68. return true;
  69. }
  70. return false;
  71. }
  72. private function getRecordIds(string $type, string $ip): array
  73. {
  74. $response = $this->sendRequest('ListRecords');
  75. if (isset($response['records'])) {
  76. $records = $response['records'];
  77. if ($ip) {
  78. $records = array_filter($records, function ($record) use ($ip) {
  79. return $record['data'] === $ip && $record['name'] === $this->domainInfo['sub'];
  80. });
  81. } elseif ($type) {
  82. $records = array_filter($records, function ($record) use ($type) {
  83. return $record['type'] === $type && $record['name'] === $this->domainInfo['sub'];
  84. });
  85. } else {
  86. $records = array_filter($records, function ($record) {
  87. return $record['name'] === $this->domainInfo['sub'];
  88. });
  89. }
  90. return array_column($records, 'id');
  91. }
  92. return [];
  93. }
  94. public function destroy(string $type, string $ip): int|bool
  95. {
  96. $recordIds = $this->getRecordIds($type, $ip);
  97. $deletedCount = 0;
  98. foreach ($recordIds as $recordId) {
  99. if ($this->sendRequest('DeleteRecord', $recordId)) {
  100. $deletedCount++;
  101. }
  102. }
  103. return $deletedCount;
  104. }
  105. }