Baidu.php 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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 Baidu implements DNS
  10. {
  11. // 开发依据: https://cloud.baidu.com/doc/DNS/index.html
  12. private const API_ENDPOINT = 'https://dns.baidubce.com';
  13. public const KEY = 'baidu';
  14. public const LABEL = 'Baidu AI Cloud | 百度智能云';
  15. private string $accessKey;
  16. private string $secretKey;
  17. private array $domainInfo;
  18. public function __construct(private readonly string $subdomain)
  19. {
  20. $this->accessKey = sysConfig('ddns_key');
  21. $this->secretKey = 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('DescribeDomains')['zones'] ?? [], '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." — DescribeDomains] 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 = null): array
  41. {
  42. $date = gmdate("Y-m-d\TH:i:s\Z");
  43. $client = Http::timeout(15)->withHeaders(['Host' => 'dns.baidubce.com', 'x-bce-date' => $date, 'Content-Type' => 'application/json; charset=utf-8'])->baseUrl(self::API_ENDPOINT);
  44. $path = match ($action) {
  45. 'DescribeDomains' => '/v1/dns/zone',
  46. 'DescribeSubDomainRecords', 'AddDomainRecord' => "/v1/dns/zone/{$this->domainInfo['domain']}/record",
  47. 'UpdateDomainRecord', 'DeleteDomainRecord' => "/v1/dns/zone/{$this->domainInfo['domain']}/record/$recordId",
  48. };
  49. $method = match ($action) {
  50. 'DescribeDomains', 'DescribeSubDomainRecords' => 'GET',
  51. 'AddDomainRecord' => 'POST',
  52. 'UpdateDomainRecord' => 'PUT',
  53. 'DeleteDomainRecord' => 'DELETE',
  54. };
  55. $client->withHeader('Authorization', $this->generateSignature($parameters, $method, $path, $date));
  56. $response = match ($method) {
  57. 'GET' => $client->get($path, $parameters),
  58. 'POST' => $client->post($path, $parameters),
  59. 'PUT' => $client->put($path, $parameters),
  60. 'DELETE' => $client->delete($path, $parameters),
  61. };
  62. $data = $response->json();
  63. if ($response->successful()) {
  64. return $data ?? [];
  65. }
  66. if ($data) {
  67. Log::error('['.self::LABEL." — $action] 返回错误信息: ".$data['message'] ?? 'Unknown error');
  68. } else {
  69. Log::error('['.self::LABEL." — $action] 请求失败");
  70. }
  71. exit(400);
  72. }
  73. private function generateSignature(array $parameters, string $httpMethod, string $path, string $date): string
  74. { // 签名
  75. $authStringPrefix = "bce-auth-v1/$this->accessKey/$date/1800";
  76. $signingKey = hash_hmac('sha256', $authStringPrefix, $this->secretKey);
  77. $canonicalRequest = "$httpMethod\n$path\n".http_build_query($parameters)."\nhost:dns.baidubce.com\nx-bce-date:".rawurlencode($date);
  78. $signature = hash_hmac('sha256', $canonicalRequest, $signingKey);
  79. return "$authStringPrefix/host;x-bce-date/$signature";
  80. }
  81. public function store(string $ip, string $type): bool
  82. {
  83. return $this->sendRequest('AddDomainRecord', [
  84. 'rr' => $this->domainInfo['sub'],
  85. 'type' => $type,
  86. 'value' => $ip,
  87. ]) === [];
  88. }
  89. public function update(string $latest_ip, string $original_ip, string $type): bool
  90. {
  91. $recordIds = $this->getRecordIds($type, $original_ip);
  92. if ($recordIds) {
  93. return $this->sendRequest('UpdateDomainRecord', [
  94. 'rr' => $this->domainInfo['sub'],
  95. 'type' => $type,
  96. 'value' => $latest_ip,
  97. ], $recordIds[0]) === [];
  98. }
  99. return false;
  100. }
  101. private function getRecordIds(string $type, string $ip): array
  102. {
  103. $parameters = ['rr' => $this->domainInfo['sub']];
  104. $response = $this->sendRequest('DescribeSubDomainRecords', $parameters);
  105. if (isset($response['records'])) {
  106. $records = $response['records'];
  107. if ($ip) {
  108. $records = array_filter($records, static function ($record) use ($ip) {
  109. return $record['value'] === $ip;
  110. });
  111. } elseif ($type) {
  112. $records = array_filter($records, static function ($record) use ($type) {
  113. return $record['type'] === $type;
  114. });
  115. }
  116. return array_column($records, 'id');
  117. }
  118. return [];
  119. }
  120. public function destroy(string $type, string $ip): int
  121. {
  122. $recordIds = $this->getRecordIds($type, $ip);
  123. $deletedCount = 0;
  124. foreach ($recordIds as $recordId) {
  125. if ($this->sendRequest('DeleteDomainRecord', [], $recordId) === []) {
  126. $deletedCount++;
  127. }
  128. }
  129. return $deletedCount;
  130. }
  131. }