DigitalOcean.php 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  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 DigitalOcean implements DNS
  10. {
  11. // 开发依据: https://docs.digitalocean.com/products/networking/dns/how-to/manage-records/
  12. private const API_ENDPOINT = 'https://api.digitalocean.com/v2/domains';
  13. public const KEY = 'digitalocean';
  14. public const LABEL = 'DigitalOcean';
  15. private string $accessToken;
  16. private array $domainInfo;
  17. public function __construct(private readonly string $subdomain)
  18. {
  19. $this->accessToken = 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('DescribeDomains')['domains'] ?? [], 'name');
  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." — DescribeDomains] 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 = ''): array|bool
  39. {
  40. $client = Http::timeout(15)->retry(3, 1000)->withToken($this->accessToken)->baseUrl(self::API_ENDPOINT)->asJson();
  41. $response = match ($action) {
  42. 'DescribeDomains' => $client->get(''),
  43. 'DescribeSubDomainRecords' => $client->get("/{$this->domainInfo['domain']}/records"),
  44. 'CreateDomainRecord' => $client->post("/{$this->domainInfo['domain']}/records", $parameters),
  45. 'UpdateDomainRecord' => $client->patch("/{$this->domainInfo['domain']}/records/$recordId", $parameters),
  46. 'DeleteDomainRecord' => $client->delete("/{$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['message'] ?? '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('CreateDomainRecord', ['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. foreach ($recordIds as $recordId) {
  68. $this->sendRequest('UpdateDomainRecord', ['type' => $type, 'data' => $latest_ip], $recordId);
  69. }
  70. return true;
  71. }
  72. return false;
  73. }
  74. private function getRecordIds(string $type, string $ip): array
  75. {
  76. $response = $this->sendRequest('DescribeSubDomainRecords');
  77. if (isset($response['domain_records'])) {
  78. $records = $response['domain_records'];
  79. if ($ip) {
  80. $records = array_filter($records, function ($record) use ($ip) {
  81. return $record['data'] === $ip && $record['name'] === $this->domainInfo['sub'];
  82. });
  83. } elseif ($type) {
  84. $records = array_filter($records, function ($record) use ($type) {
  85. return $record['type'] === $type && $record['name'] === $this->domainInfo['sub'];
  86. });
  87. } else {
  88. $records = array_filter($records, function ($record) {
  89. return $record['name'] === $this->domainInfo['sub'];
  90. });
  91. }
  92. return array_column($records, 'id');
  93. }
  94. return [];
  95. }
  96. public function destroy(string $type, string $ip): int
  97. {
  98. $recordIds = $this->getRecordIds($type, $ip);
  99. $deletedCount = 0;
  100. foreach ($recordIds as $recordId) {
  101. if ($this->sendRequest('DeleteDomainRecord', [], $recordId)) {
  102. $deletedCount++;
  103. }
  104. }
  105. return $deletedCount;
  106. }
  107. }