DNSimple.php 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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 DNSimple implements DNS
  10. {
  11. // 开发依据: https://developer.dnsimple.com/v2/
  12. private const API_ENDPOINT = 'https://api.dnsimple.com/v2/';
  13. public const KEY = 'dnsimple';
  14. public const LABEL = 'DNSimple';
  15. private string $accountID;
  16. private string $accessToken;
  17. private array $domainInfo;
  18. public function __construct(private readonly string $subdomain)
  19. {
  20. $this->accountID = sysConfig('ddns_key');
  21. $this->accessToken = sysConfig('ddns_secret');
  22. $this->domainInfo = $this->parseDomainInfo();
  23. }
  24. private function parseDomainInfo(): array
  25. {
  26. $domains = Cache::remember('ddns_get_domains', now()->addHour(), function () {
  27. return array_column($this->sendRequest('ListDomains') ?? [], 'name');
  28. });
  29. if ($domains) {
  30. $matched = Arr::first($domains, fn ($domain) => str_contains($this->subdomain, $domain));
  31. }
  32. if (empty($matched)) {
  33. throw new RuntimeException('['.self::LABEL." — ListDomains] The subdomain $this->subdomain does not match any domain in your account.");
  34. }
  35. return [
  36. 'sub' => rtrim(substr($this->subdomain, 0, -strlen($matched)), '.'),
  37. 'domain' => $matched,
  38. ];
  39. }
  40. private function sendRequest(string $action, array $parameters = [], string $recordId = ''): array|bool
  41. {
  42. $client = Http::timeout(15)->retry(3, 1000)->withToken($this->accessToken)->baseUrl(self::API_ENDPOINT.$this->accountID)->asJson();
  43. $response = match ($action) {
  44. 'ListDomains' => $client->get('/domains'),
  45. 'ListZoneRecords' => $client->get("/zones/{$this->domainInfo['domain']}/records", $parameters),
  46. 'CreateZoneRecord' => $client->post("/zones/{$this->domainInfo['domain']}/records", $parameters),
  47. 'UpdateZoneRecord' => $client->patch("/zones/{$this->domainInfo['domain']}/records/$recordId", $parameters),
  48. 'DeleteZoneRecord' => $client->delete("/zones/{$this->domainInfo['domain']}/records/$recordId"),
  49. };
  50. $data = $response->json();
  51. if ($response->successful()) {
  52. return $data['data'] ?? true;
  53. }
  54. if ($data) {
  55. Log::error('['.self::LABEL." — $action] 返回错误信息: ".$data['errors']['base'] ?? $data['message'] ?? 'Unknown error');
  56. } else {
  57. Log::error('['.self::LABEL." — $action] 请求失败");
  58. }
  59. exit(400);
  60. }
  61. public function store(string $ip, string $type): bool
  62. {
  63. return (bool) $this->sendRequest('CreateZoneRecord', ['name' => $this->domainInfo['sub'], 'type' => $type, 'content' => $ip]);
  64. }
  65. public function update(string $latest_ip, string $original_ip, string $type): bool
  66. {
  67. $recordIds = $this->getRecordIds($type, $original_ip);
  68. if ($recordIds) {
  69. $this->sendRequest('UpdateZoneRecord', ['content' => $latest_ip], $recordIds[0]);
  70. return true;
  71. }
  72. return false;
  73. }
  74. private function getRecordIds(string $type, string $ip): array
  75. {
  76. $parameter = ['name' => $this->domainInfo['sub']];
  77. if ($type) {
  78. $parameter['type'] = $type;
  79. }
  80. $records = $this->sendRequest('ListZoneRecords', $parameter);
  81. if ($records) {
  82. if ($ip) {
  83. $records = array_filter($records, static function ($record) use ($ip) {
  84. return $record['content'] === $ip;
  85. });
  86. }
  87. return array_column($records, 'id');
  88. }
  89. return [];
  90. }
  91. public function destroy(string $type, string $ip): int|bool
  92. {
  93. $recordIds = $this->getRecordIds($type, $ip);
  94. $deletedCount = 0;
  95. foreach ($recordIds as $recordId) {
  96. if ($this->sendRequest('DeleteZoneRecord', $recordId)) {
  97. $deletedCount++;
  98. }
  99. }
  100. return $deletedCount;
  101. }
  102. }