diff --git a/app/CLI/Cloudflare.php b/app/CLI/Cloudflare.php new file mode 100644 index 0000000..d11e265 --- /dev/null +++ b/app/CLI/Cloudflare.php @@ -0,0 +1,75 @@ +_db = \Config\Database::connect(); + } + private function getAuthModel(): AuthModel + { + return new AuthModel(); + } + private function auth_process(): array + { + $this->getAuthModel()->where('status', DEFAULTS["STATUS"]); + return $this->getAuthModel()->getEntitys(); + } + private function account_process(AuthEntity $auth_entity): array + { + $account = new Account($auth_entity); + return $account->reload(); + } + private function zone_process(AccountEntity $account_entity): array + { + $zone = new Zone($account_entity); + return $zone->reload(); + } + private function record_process(ZoneEntity $zone_entity): array + { + $record = new Record($zone_entity); + return $record->reload(); + } + public function reload(): void + { + //Transaction Start + $this->_db->transStart(); + try { + $auths = $this->auth_process(); + $accounts = []; + foreach ($auths as $auth) { + $accounts = $this->account_process($auth); + } + $zones = []; + foreach ($accounts as $account) { + $zones = $this->zone_process($account); + } + $records = []; + foreach ($zones as $zone) { + $records = $this->record_process($zone); + } + log_message("notice", "Reload 작업을 완료하였습니다."); + $this->_db->transCommit(); + } catch (\Exception $e) { + //Transaction Rollback + $this->_db->transRollback(); + log_message( + "error", + "Reload 작업을 실패하였습니다.\n--------------\n" . + $e->getMessage() . + "\n--------------\n" + ); + } + } +} diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 119cf5b..26349b7 100644 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -12,6 +12,11 @@ $routes->addPlaceholder('uuid', '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4} //1. app/Filters/AuthFilter.php //2. Config/Filters.php -> $aliases = ['authFilter' => AuthFilter::class] $routes->get('/', 'Home::index'); +$routes->group('cli', ['namespace' => 'App\CLI'], function ($routes) { + $routes->group('cloudflare', ['namespace' => 'App\CLI\Cloudflare'], function ($routes) { + $routes->cli('reload', 'Cloudflare::reload'); + }); +}); // $routes->group('admin', ['namespace' => 'App\Controllers\Admin', 'filter' => 'authFilter:manager'], function ($routes) { $routes->group('admin', ['namespace' => 'App\Controllers\Admin'], function ($routes) { $routes->get('/', 'Home::index'); @@ -46,19 +51,13 @@ $routes->group('admin', ['namespace' => 'App\Controllers\Admin'], function ($rou $routes->get('delete/(:num)', 'AuthController::delete/$1'); $routes->get('toggle/(:num)/(:any)', 'AuthController::toggle/$1/$2'); $routes->post('batchjob', 'AuthController::batcjob'); - $routes->get('reload/(:num)', 'AuthController::reload/$1'); - $routes->get('reload', 'AuthController::reload'); - $routes->cli('reload/(:num)', 'AuthController::reload/$1'); - $routes->cli('reload', 'AuthController::reload'); $routes->get('download/(:alpha)', 'AccountController::download/$1'); }); $routes->group('account', function ($routes) { $routes->get('/', 'AccountController::index'); $routes->post('create/(:uuid)', 'AccountController::create'); $routes->get('reload/(:alphanum)', 'AccountController::reload/$1'); - $routes->get('reload', 'AccountController::reload'); - $routes->cli('reload/(:alphanum)', 'AccountController::reload/$1'); - $routes->cli('reload', 'AccountController::reload'); + $routes->get('reload/(:num)', 'AccountController::reload/$1'); $routes->get('download/(:alpha)', 'AccountController::download/$1'); }); $routes->group('zone', function ($routes) { @@ -70,9 +69,6 @@ $routes->group('admin', ['namespace' => 'App\Controllers\Admin'], function ($rou $routes->get('toggle/(:alphanum)/(:any)', 'ZoneController::toggle/$1/$2'); $routes->post('batchjob', 'ZoneController::batcjob'); $routes->get('reload/(:alphanum)', 'ZoneController::reload/$1'); - $routes->get('reload', 'ZoneController::reload'); - $routes->cli('reload/(:alphanum)', 'ZoneController::reload/$1'); - $routes->cli('reload', 'ZoneController::reload'); $routes->get('download/(:alpha)', 'ZoneController::download/$1'); }); $routes->group('record', function ($routes) { @@ -83,6 +79,7 @@ $routes->group('admin', ['namespace' => 'App\Controllers\Admin'], function ($rou $routes->get('sync/(:alphanum)', 'RecordController::sync/$1'); $routes->get('toggle/(:alphanum)/(:any)', 'RecordController::toggle/$1/$2'); $routes->post('batchjob', 'RecordController::batcjob'); + $routes->get('reload/(:alphanum)', 'RecordController::reload/$1'); $routes->get('download/(:alpha)', 'RecordController::download/$1'); }); }); diff --git a/app/Controllers/Admin/Cloudflare/AccountController.php b/app/Controllers/Admin/Cloudflare/AccountController.php index 2d07541..f27955d 100644 --- a/app/Controllers/Admin/Cloudflare/AccountController.php +++ b/app/Controllers/Admin/Cloudflare/AccountController.php @@ -2,18 +2,17 @@ namespace App\Controllers\Admin\Cloudflare; -use App\Libraries\MySocket\Cloudflare\AccountSocket; -use App\Libraries\MySocket\Cloudflare\ZoneSocket; -use App\Models\Cloudflare\AccountModel; -use CodeIgniter\HTTP\DownloadResponse; -use CodeIgniter\HTTP\RedirectResponse; -use CodeIgniter\HTTP\RequestInterface; -use CodeIgniter\HTTP\ResponseInterface; use Psr\Log\LoggerInterface; +use CodeIgniter\HTTP\ResponseInterface; +use CodeIgniter\HTTP\RequestInterface; +use CodeIgniter\HTTP\RedirectResponse; +use CodeIgniter\HTTP\DownloadResponse; +use App\Models\Cloudflare\AccountModel; +use App\Libraries\Cloudflare\Account; class AccountController extends CloudflareController { - private $_mySocket = null; + private $_myLibrary = null; private $_model = null; private $_auth_key = null; public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) @@ -31,12 +30,12 @@ class AccountController extends CloudflareController } return $this->_model; } - final protected function getMySocket(): AccountSocket + final protected function getMyLibrary(): Account { - if ($this->_mySocket === null) { - $this->_mySocket = new AccountSocket($this->_auth_key); + if ($this->_myLibrary === null) { + $this->_myLibrary = new Account($this->_auth_key); } - return $this->_mySocket; + return $this->_myLibrary; } protected function getFormFieldOption(string $field, array $options = []): array { @@ -75,18 +74,19 @@ class AccountController extends CloudflareController $this->batchjob_fields = ['typep', 'status']; return $this->download_procedure($output_type, $uid); } - //Zone Reload By Account - protected function reload_process(mixed $uid = false): void + //reload Account By Auth + protected function reload_process(mixed $uid): void { - if ($uid) { - $this->getModel()->where($this->getModel()::PK, $uid); + $this->_auth_entity = $this->getAuthModel()->getEntityByPK(intval($uid)); + if ($this->_auth_entity === null) { + throw new \Exception("Auth: {$uid} 정보를 찾을수 없습니다."); } + $this->getModel()->where($this->getModel()::PARENT, $this->_auth_entity->getPK()); foreach ($this->getModel()->getEntitys() as $entity) { - $zone_socket = new ZoneSocket($entity); - $zone_socket->reload(); + $this->getMyLibrary()->reload(); } } - public function reload(mixed $uid = false): RedirectResponse + public function reload(int $uid): RedirectResponse { return $this->reload_procedure($uid); } diff --git a/app/Controllers/Admin/Cloudflare/AuthController.php b/app/Controllers/Admin/Cloudflare/AuthController.php index 4c2ef34..fdbbc4d 100644 --- a/app/Controllers/Admin/Cloudflare/AuthController.php +++ b/app/Controllers/Admin/Cloudflare/AuthController.php @@ -2,13 +2,12 @@ namespace App\Controllers\Admin\Cloudflare; -use App\Libraries\MySocket\Cloudflare\AccountSocket; -use App\Models\Cloudflare\AuthModel; -use CodeIgniter\HTTP\DownloadResponse; -use CodeIgniter\HTTP\RedirectResponse; -use CodeIgniter\HTTP\RequestInterface; -use CodeIgniter\HTTP\ResponseInterface; use Psr\Log\LoggerInterface; +use CodeIgniter\HTTP\ResponseInterface; +use CodeIgniter\HTTP\RequestInterface; +use CodeIgniter\HTTP\RedirectResponse; +use CodeIgniter\HTTP\DownloadResponse; +use App\Models\Cloudflare\AuthModel; class AuthController extends CloudflareController { @@ -88,19 +87,4 @@ class AuthController extends CloudflareController $this->batchjob_fields = ['status']; return $this->download_procedure($output_type, $uid); } - //Account Reload by Auth - protected function reload_process(mixed $uid = false): void - { - if ($uid && intval($uid) > 0) { - $this->getModel()->where($this->getModel()::PK, intval($uid)); - } - foreach ($this->getModel()->getEntitys() as $entity) { - $account_socket = new AccountSocket($entity); - $account_socket->reload(); - } - } - public function reload(mixed $uid = false): RedirectResponse - { - return $this->reload_procedure($uid); - } } diff --git a/app/Controllers/Admin/Cloudflare/CloudflareController.php b/app/Controllers/Admin/Cloudflare/CloudflareController.php index ca3e1b1..7ac0786 100644 --- a/app/Controllers/Admin/Cloudflare/CloudflareController.php +++ b/app/Controllers/Admin/Cloudflare/CloudflareController.php @@ -72,8 +72,8 @@ abstract class CloudflareController extends AdminController } } - protected function reload_process(mixed $uid = false): void {} - final protected function reload_procedure(mixed $uid = false): RedirectResponse + protected function reload_process(mixed $uid): void {} + final protected function reload_procedure(mixed $uid): RedirectResponse { //Transaction Start $this->getModel()->transStart(); diff --git a/app/Controllers/Admin/Cloudflare/RecordController.php b/app/Controllers/Admin/Cloudflare/RecordController.php index 44fcb33..a2f8ad1 100644 --- a/app/Controllers/Admin/Cloudflare/RecordController.php +++ b/app/Controllers/Admin/Cloudflare/RecordController.php @@ -2,16 +2,17 @@ namespace App\Controllers\Admin\Cloudflare; -use App\Libraries\MySocket\Cloudflare\RecordSocket; -use App\Models\Cloudflare\RecordModel; -use CodeIgniter\HTTP\DownloadResponse; -use CodeIgniter\HTTP\RedirectResponse; -use CodeIgniter\HTTP\RequestInterface; -use CodeIgniter\HTTP\ResponseInterface; use Psr\Log\LoggerInterface; +use CodeIgniter\HTTP\ResponseInterface; +use CodeIgniter\HTTP\RequestInterface; +use CodeIgniter\HTTP\RedirectResponse; +use CodeIgniter\HTTP\DownloadResponse; +use App\Models\Cloudflare\RecordModel; +use App\Libraries\Cloudflare\Record; class RecordController extends CloudflareController { + private $_myLibrary = null; private $_zone_entity = null; public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) { @@ -28,12 +29,12 @@ class RecordController extends CloudflareController } return $this->_model; } - final protected function getMySocket(): RecordSocket + final protected function getMyLibrary(): Record { - if ($this->_mySocket === null) { - $this->_mySocket = new RecordSocket($this->_zone_entity); + if ($this->_myLibrary === null) { + $this->_myLibrary = new Record($this->_zone_entity); } - return $this->_mySocket; + return $this->_myLibrary; } protected function getFormFieldOption(string $field, array $options = []): array { @@ -105,7 +106,7 @@ class RecordController extends CloudflareController } //Socket처리 foreach ($this->formDatas['hosts'] as $host) { - $entity = $this->getMySocket()->create($host, $this->formDatas['type'], $this->formDatas['content'], $this->formDatas['proxied']); + $entity = $this->getMyLibrary()->create($host, $this->formDatas['type'], $this->formDatas['content'], $this->formDatas['proxied']); log_message("debug", "Record:{$entity->getTitle()} 생성 작업을 완료하였습니다."); } } @@ -128,7 +129,7 @@ class RecordController extends CloudflareController //부모데이터정의 $this->_zone_entity = $this->getZoneModel()->getEntityByPK($this->entity->getParent()); //Socket처리 - $entity = $this->getMySocket()->modify($this->entity, $this->formDatas); + $entity = $this->getMyLibrary()->modify($this->entity, $this->formDatas); log_message("debug", "Record:{$entity->getTitle()} 수정 작업을 완료하였습니다."); } //일괄처리작업 @@ -150,7 +151,7 @@ class RecordController extends CloudflareController //부모데이터정의 $this->_zone_entity = $this->getZoneModel()->getEntityByPK($this->entity->getParent()); //Socket처리 - $this->getMySocket()->sync($this->entity); + $this->getMyLibrary()->sync($this->entity); } public function sync(string $uid): RedirectResponse { @@ -168,7 +169,7 @@ class RecordController extends CloudflareController //부모데이터정의 $this->_zone_entity = $this->getZoneModel()->getEntityByPK($this->formDatas[$this->getModel()::PARENT]); //Cloudflare 삭제 - $this->getMySocket()->delete($this->entity); + $this->getMyLibrary()->delete($this->entity); } // 리스트 public function index(): string @@ -192,4 +193,20 @@ class RecordController extends CloudflareController $this->batchjob_fields = ['proxied']; return $this->download_procedure($output_type, $uid); } + //reload Record By Zone + protected function reload_process(mixed $uid): void + { + $this->_zone_entity = $this->getZoneModel()->getEntityByPK($uid); + if ($this->_zone_entity === null) { + throw new \Exception("Zone: {$uid} 정보를 찾을수 없습니다."); + } + $this->getModel()->where($this->getModel()::PARENT, $this->_zone_entity->getPK()); + foreach ($this->getModel()->getEntitys() as $entity) { + $this->getMyLibrary()->reload(); + } + } + public function reload(string $uid): RedirectResponse + { + return $this->reload_procedure($uid); + } } diff --git a/app/Controllers/Admin/Cloudflare/ZoneController.php b/app/Controllers/Admin/Cloudflare/ZoneController.php index def24c7..d9392fb 100644 --- a/app/Controllers/Admin/Cloudflare/ZoneController.php +++ b/app/Controllers/Admin/Cloudflare/ZoneController.php @@ -2,18 +2,18 @@ namespace App\Controllers\Admin\Cloudflare; -use App\Libraries\MySocket\Cloudflare\RecordSocket; -use App\Libraries\MySocket\Cloudflare\ZoneSocket; -use App\Models\Cloudflare\ZoneModel; -use CodeIgniter\HTTP\DownloadResponse; -use CodeIgniter\HTTP\RedirectResponse; -use CodeIgniter\HTTP\RequestInterface; -use CodeIgniter\HTTP\ResponseInterface; use Psr\Log\LoggerInterface; +use CodeIgniter\HTTP\ResponseInterface; +use CodeIgniter\HTTP\RequestInterface; +use CodeIgniter\HTTP\RedirectResponse; +use CodeIgniter\HTTP\DownloadResponse; +use App\Models\Cloudflare\ZoneModel; +use App\Libraries\Cloudflare\Zone; +use App\Libraries\Cloudflare\Record; class ZoneController extends CloudflareController { - private $_mySocket = null; + private $_myLibrary = null; private $_account_entity = null; private $_model = null; public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) @@ -31,13 +31,13 @@ class ZoneController extends CloudflareController } return $this->_model; } - final protected function getMySocket(): ZoneSocket + final protected function getMyLibrary(): Zone { - if ($this->_mySocket === null) { + if ($this->_myLibrary === null) { - $this->_mySocket = new ZoneSocket($this->_account_entity); + $this->_myLibrary = new Zone($this->_account_entity); } - return $this->_mySocket; + return $this->_myLibrary; } protected function getFormFieldOption(string $field, array $options = []): array { @@ -139,16 +139,16 @@ class ZoneController extends CloudflareController $cnt = 1; $zone_entitys = []; foreach ($this->formDatas['domains'] as $domain) { - $entity = $this->getMySocket()->create($domain); + $entity = $this->getMyLibrary()->create($domain); log_message("debug", "Zone:{$entity->getTitle()} 작업을 완료하였습니다."); $zone_entitys[] = $entity; $cnt++; } //Record생성 foreach ($zone_entitys as $zone_entity) { - $record_socket = new RecordSocket($entity); + $record = new Record($zone_entity); foreach ($this->formDatas['hosts'] as $host) { - $entity = $record_socket->create($host, $this->formDatas['type'], $this->formDatas['content'], $this->formDatas['proxied']); + $entity = $record->create($host, $this->formDatas['type'], $this->formDatas['content'], $this->formDatas['proxied']); log_message("debug", "Record:{$entity->getTitle()} 작업을 완료하였습니다."); } } @@ -172,7 +172,7 @@ class ZoneController extends CloudflareController //부모데이터정의 $this->_account_entity = $this->getAccountModel()->getEntityByPK($this->entity->getParent()); //Socket처리 - $entity = $this->getMySocket()->modify($this->entity, $this->formDatas); + $entity = $this->getMyLibrary()->modify($this->entity, $this->formDatas); log_message("debug", "Zone:{$entity->getTitle()} 수정 작업을 완료하였습니다."); } //일괄처리작업 @@ -194,7 +194,7 @@ class ZoneController extends CloudflareController //부모데이터정의 $this->_account_entity = $this->getAccountModel()->getEntityByPK($this->entity->getParent()); //Socket처리 - $this->getMySocket()->sync($this->entity); + $this->getMyLibrary()->sync($this->entity); } public function sync(string $uid): RedirectResponse { @@ -212,7 +212,7 @@ class ZoneController extends CloudflareController //부모데이터정의 $this->_account_entity = $this->getAccountModel()->getEntityByPK($this->formDatas[$this->getModel()::PARENT]); //Cloudflare 삭제 - $this->getMySocket()->delete($this->entity); + $this->getMyLibrary()->delete($this->entity); } // 리스트 public function index(): string @@ -236,18 +236,19 @@ class ZoneController extends CloudflareController $this->batchjob_fields = ['development_mode', 'ipv6', 'security_level']; return $this->download_procedure($output_type, $uid); } - //reload Record By Zone - protected function reload_process(mixed $uid = false): void + //reload Zone By Account + protected function reload_process(mixed $uid): void { - if ($uid) { - $this->getModel()->where($this->getModel()::PK, $uid); + $this->_account_entity = $this->getAccountModel()->getEntityByPK($uid); + if ($this->_account_entity === null) { + throw new \Exception("Account: {$uid} 정보를 찾을수 없습니다."); } + $this->getModel()->where($this->getModel()::PARENT, $this->_account_entity->getPK()); foreach ($this->getModel()->getEntitys() as $entity) { - $record_socket = new RecordSocket($entity); - $record_socket->reload(); + $this->getMyLibrary()->reload(); } } - public function reload(mixed $uid = false): RedirectResponse + public function reload(string $uid): RedirectResponse { return $this->reload_procedure($uid); } diff --git a/app/Libraries/MySocket/Cloudflare/AccountSocket.php b/app/Libraries/Cloudflare/Account.php similarity index 63% rename from app/Libraries/MySocket/Cloudflare/AccountSocket.php rename to app/Libraries/Cloudflare/Account.php index ab3665b..30e657a 100644 --- a/app/Libraries/MySocket/Cloudflare/AccountSocket.php +++ b/app/Libraries/Cloudflare/Account.php @@ -1,18 +1,15 @@ _auth_entity = $auth_entity; parent::__construct($auth_entity); } @@ -40,29 +37,28 @@ class AccountSocket extends CloudflareSocket public function getArrayByResult($result, array $formDatas = []): array { $formDatas[AccountModel::PK] = $result->id; - $formDatas[AccountModel::PARENT] = $this->_auth_entity->getPK(); + $formDatas[AccountModel::PARENT] = $this->getAuthEntity()->getPK(); $formDatas[AccountModel::TITLE] = $result->name; $formDatas['type'] = $result->type; - $formDatas['status'] = $this->_auth_entity->status; + $formDatas['status'] = $this->getAuthEntity()->status; $formDatas['updated_at'] = date("Y-m-d H:i:s"); $formDatas['created_at'] = $result->created_on; return $formDatas; } - public function reload(): void + public function reload(): array { - log_message("notice", "-----{$this->_auth_entity->getTitle()} 처리 시작-----"); - $entity_uids = []; - $results = $this->reload_procedure("accounts"); - //DB수정 - foreach ($results as $result) { + log_message("notice", "-----{$this->getAuthEntity()->getTitle()} 처리 시작-----"); + $entitys = []; + foreach ($this->reload_procedure("accounts") as $result) { $formDatas = $this->getArrayByResult($result); $entity = $this->getModel()->modify($this->getModel()->getEntity(), $formDatas); - $entity_uids[] = $entity->getPK(); + $entitys[$entity->getPK()] = $entity; } //부모키를 기준으로 CF에 존재하지 않는 데이터 삭제용 - $this->getModel()->where(AccountModel::PARENT, $this->_auth_entity); - $this->getModel()->whereNotIn(AccountModel::PK, $entity_uids); + $this->getModel()->where(AccountModel::PARENT, $this->getAuthEntity()); + $this->getModel()->whereNotIn(AccountModel::PK, array_keys($entitys)); $this->getModel()->delete(); - log_message("notice", "-----{$this->_auth_entity->getTitle()} 처리[" . count($results) . "개] 완료-----"); + log_message("notice", "-----{$this->getAuthEntity()->getTitle()} 처리[" . count($entitys) . "개] 완료-----"); + return $entitys; } } diff --git a/app/Libraries/Cloudflare/Cloudflare.php b/app/Libraries/Cloudflare/Cloudflare.php new file mode 100644 index 0000000..ff7cc36 --- /dev/null +++ b/app/Libraries/Cloudflare/Cloudflare.php @@ -0,0 +1,75 @@ +_auth_entity = $auth_entity; + parent::__construct(); + } + abstract protected function getArrayByResult($result, array $formDatas = []): array; + final public function getMySocket(): CloudflareSocket + { + if ($this->_mySocket === null) { + $this->_mySocket = new CloudflareSocket($this->getAuthEntity()); + } + return $this->_mySocket; + } + final protected function getAuthEntity(): AuthEntity + { + if ($this->_auth_entity === null) { + throw new \Exception(__FUNCTION__ . "에서 인증정보가 없습니다."); + } + return $this->_auth_entity; + } + final protected function getAuthModel(): AuthModel + { + if ($this->_authModel === null) { + $this->_authModel = new AuthModel(); + } + return $this->_authModel; + } + final protected function getAccountModel(): AccountModel + { + if ($this->_accountModel === null) { + $this->_accountModel = new AccountModel(); + } + return $this->_accountModel; + } + final protected function reload_procedure($uri): array + { + $page = 1; //1부터 시작 + $results = []; + do { + $query = [ + 'page' => $page, + 'per_page' => $this->getMySocket()::$_request_perpage_max, + 'match' => 'all', + ]; + $response = $this->getMySocket()->get($uri, $query); + $cf = json_decode($response->getBody()); + if (!$cf->success) { + $message = __FUNCTION__ . "에서 실패:\nresponse:" . var_export($cf, true); + log_message("error", $message); + throw new \Exception($message); + } + $results = array_merge($results, $cf->result); + if (count($cf->result) < $this->getMySocket()::$_request_perpage_max) { + break; + } + $page++; + } while (true); + return $results; + } +} diff --git a/app/Libraries/MySocket/Cloudflare/RecordSocket.php b/app/Libraries/Cloudflare/Record.php similarity index 86% rename from app/Libraries/MySocket/Cloudflare/RecordSocket.php rename to app/Libraries/Cloudflare/Record.php index 43ee0f3..d04537e 100644 --- a/app/Libraries/MySocket/Cloudflare/RecordSocket.php +++ b/app/Libraries/Cloudflare/Record.php @@ -1,13 +1,12 @@ $content, 'proxied' => $proxied === 'on' ? true : false ]; - $cf = $this->post("zones/{$this->_zone_entity->getPK()}/dns_records", $datas); + $cf = $this->getMySocket()->post("zones/{$this->_zone_entity->getPK()}/dns_records", $datas); $cf = json_decode($cf->getBody()); if (!$cf->success) { $message = "Record:" . __FUNCTION__ . "에서 실패:\nrequest:" . var_export($datas, true) . "\nresponse:" . var_export($cf, true); @@ -91,7 +90,7 @@ class RecordSocket extends CloudflareSocket } // 인코딩된 JSON을 확인 // throw new \Exception("Record:" . __FUNCTION__ . "\n" . json_encode($datas, JSON_PRETTY_PRINT) . "\n" . var_export($datas, true)); - $cf = $this->put("zones/{$this->_zone_entity->getPK()}/dns_records/{$entity->getPK()}", $datas); + $cf = $this->getMySocket()->put("zones/{$this->_zone_entity->getPK()}/dns_records/{$entity->getPK()}", $datas); $cf = json_decode($cf->getBody()); if (!$cf->success) { $message = "Record:" . __FUNCTION__ . "에서 실패:\nrequest:" . var_export($datas, true) . "\nresponse:" . var_export($cf, true); @@ -104,7 +103,7 @@ class RecordSocket extends CloudflareSocket } public function delete(RecordEntity $entity): void { - $cf = $this->delete("zones/{$this->_zone_entity->getPK()}/dns_records/{$entity->getPK()}"); + $cf = $this->getMySocket()->delete("zones/{$this->_zone_entity->getPK()}/dns_records/{$entity->getPK()}"); $cf = json_decode($cf->getBody()); if (!$cf->success) { $message = "Record:" . __FUNCTION__ . "에서 실패:\nresponse:" . var_export($cf, true); @@ -118,7 +117,7 @@ class RecordSocket extends CloudflareSocket public function sync(RecordEntity $entity): void { // 기존 Sync형태 - $cf = $this->get("zones/{$this->_zone_entity->getPK()}/dns_records/{$entity->getPK()}"); + $cf = $this->getMySocket()->get("zones/{$this->_zone_entity->getPK()}/dns_records/{$entity->getPK()}"); $cf = json_decode($cf->getBody()); if (!$cf->success) { $message = "Record:" . __FUNCTION__ . "에서 실패:\nresponse:" . var_export($cf, true); @@ -129,7 +128,7 @@ class RecordSocket extends CloudflareSocket log_message("debug", var_export($cf->result, true)); $entity = $this->getModel()->modify($entity, $this->getArrayByResult($cf->result)); //Async형태 - // $promise = $this->getAsync("zones/{$this->_zone_entity->getPK()}/dns_records/{$entity->getPK()}"); + // $promise = $this->getMySocket()getAsync("zones/{$this->_zone_entity->getPK()}/dns_records/{$entity->getPK()}"); // $promise->then( // onFulfilled: function ($response) use ($entity): RecordEntity { // $record = json_decode($response->getBody(), true)['result']; @@ -145,21 +144,20 @@ class RecordSocket extends CloudflareSocket // $promise->wait(); } //Reload - public function reload(): void + public function reload(): array { log_message("notice", "-----{$this->_zone_entity->getTitle()} 처리 시작-----"); - $entity_uids = []; - $results = $this->reload_procedure("zones/{$this->_zone_entity->getPK()}/dns_records"); - //DB수정 - foreach ($results as $result) { + $entitys = []; + foreach ($this->reload_procedure("zones/{$this->_zone_entity->getPK()}/dns_records") as $result) { $formDatas = $this->getArrayByResult($result); $entity = $this->getModel()->modify($this->getModel()->getEntity(), $formDatas); - $entity_uids[] = $entity->getPK(); + $entitys[$entity->getPK()] = $entity; } //부모키를 기준으로 CF에 존재하지 않는 데이터 DB삭제 $this->getModel()->where(RecordModel::PARENT, $this->_zone_entity); - $this->getModel()->whereNotIn(RecordModel::PK, $entity_uids); + $this->getModel()->whereNotIn(RecordModel::PK, array_keys($entitys)); $this->getModel()->delete(); - log_message("notice", "-----{$this->_zone_entity->getTitle()} 처리[" . count($results) . "개] 완료-----"); + log_message("notice", "-----{$this->_zone_entity->getTitle()} 처리[" . count($entitys) . "개] 완료-----"); + return $entitys; } } diff --git a/app/Libraries/MySocket/Cloudflare/ZoneSocket.php b/app/Libraries/Cloudflare/Zone.php similarity index 89% rename from app/Libraries/MySocket/Cloudflare/ZoneSocket.php rename to app/Libraries/Cloudflare/Zone.php index 7b4035c..68c06ac 100644 --- a/app/Libraries/MySocket/Cloudflare/ZoneSocket.php +++ b/app/Libraries/Cloudflare/Zone.php @@ -1,13 +1,13 @@ get('zones/' . $entity->getPK() . '/settings'); + $cf = $this->getMySocket()->get('zones/' . $entity->getPK() . '/settings'); $cf = json_decode($cf->getBody()); if (!$cf->success) { $message = "Zone:" . __FUNCTION__ . "에서 실패:\nresponse:" . var_export($cf, true); @@ -78,7 +78,7 @@ class ZoneSocket extends CloudflareSocket private function setCFSetting(ZoneEntity $entity, string $field, string $value): string { $datas = ['value' => $value]; - $cf = $this->patch('zones/' . $entity->getPK() . '/settings/' . $field, $datas); + $cf = $this->getMySocket()->patch('zones/' . $entity->getPK() . '/settings/' . $field, $datas); $cf = json_decode($cf->getBody()); if (!$cf->success || $cf->result->id !== $field) { $message = "Zone:" . __FUNCTION__ . "에서 실패:\nrequest:" . var_export($datas, true) . "\nresponse:" . var_export($cf, true); @@ -97,7 +97,7 @@ class ZoneSocket extends CloudflareSocket 'name' => $domain, 'jump_start' => $jump_start, ]; - $cf = $this->post('zones/', $datas); + $cf = $this->getMySocket()->post('zones/', $datas); $cf = json_decode($cf->getBody()); if (!$cf->success) { $message = "Zone:" . __FUNCTION__ . "에서 실패:\nrequest:" . var_export($datas, true) . "\nresponse:" . var_export($cf, true); @@ -128,7 +128,7 @@ class ZoneSocket extends CloudflareSocket } public function delete(ZoneEntity $entity): void { - $cf = $this->delete("zones/{$entity->getPK()}"); + $cf = $this->getMySocket()->delete("zones/{$entity->getPK()}"); $cf = json_decode($cf->getBody()); if (!$cf->success) { $message = "Zone:" . __FUNCTION__ . "에서 실패:\nresponse:" . var_export($cf, true); @@ -141,7 +141,7 @@ class ZoneSocket extends CloudflareSocket } public function sync(ZoneEntity $entity): void { - $cf = $this->get("zones/{$entity->getPK()}"); + $cf = $this->getMySocket()->get("zones/{$entity->getPK()}"); $cf = json_decode($cf->getBody()); if (!$cf->success) { $message = "Zone:" . __FUNCTION__ . "에서 실패:\nresponse:" . var_export($cf, true); @@ -155,24 +155,23 @@ class ZoneSocket extends CloudflareSocket $this->getModel()->modify($entity, $formDatas); } //Reload - public function reload(): void + public function reload(): array { log_message("notice", "-----{$this->_account_entity->getTitle()} 처리 시작-----"); - $entity_uids = []; - $results = $this->reload_procedure('zones'); - //DB수정 - foreach ($results as $result) { + $entitys = []; + foreach ($this->reload_procedure('zones') as $result) { $formDatas = $this->getArrayByResult($result); $entity = $this->getModel()->modify($this->getModel()->getEntity(), $formDatas); //추가 셋팅용 $formDatas = $this->getCFSetting($entity); $entity = $this->getModel()->modify($entity, $formDatas); - $entity_uids[] = $entity->getPK(); + $entitys[$entity->getPK()] = $entity; } //부모키를 기준으로 CF에 존재하지 않는 데이터 삭제용 $this->getModel()->where(ZoneModel::PARENT, $this->_account_entity); - $this->getModel()->whereNotIn(ZoneModel::PK, $entity_uids); + $this->getModel()->whereNotIn(ZoneModel::PK, array_keys($entitys)); $this->getModel()->delete(); - log_message("notice", "-----{$this->_account_entity->getTitle()} 처리[" . count($results) . "개] 완료-----"); + log_message("notice", "-----{$this->_account_entity->getTitle()} 처리[" . count($entitys) . "개] 완료-----"); + return $entitys; } } diff --git a/app/Libraries/MySocket/CloudflareSocket.php b/app/Libraries/MySocket/CloudflareSocket.php index c3cff14..124333e 100644 --- a/app/Libraries/MySocket/CloudflareSocket.php +++ b/app/Libraries/MySocket/CloudflareSocket.php @@ -3,35 +3,28 @@ namespace App\Libraries\MySocket; use Psr\Http\Message\ResponseInterface; -use App\Models\Cloudflare\AuthModel; -use App\Models\Cloudflare\AccountModel; use App\Entities\Cloudflare\AuthEntity; -abstract class CloudflareSocket extends MySocket +class CloudflareSocket extends MySocket { private static int $_request = 0; private static int $_request_max = 1000; - private static int $_request_perpage_max = 700; + public static int $_request_perpage_max = 700; private static int $_request_timewait = 60; - private $_authModel = null; - private $_accountModel = null; - private $_auth_entity = null; - protected function __construct(AuthEntity $auth_entity) + public function __construct(AuthEntity $auth_entity) { parent::__construct([ 'base_uri' => 'https://api.cloudflare.com/client/v4/', 'headers' => [ - 'X-Auth-Email' => $this->_auth_entity->getID(), // 인증 토큰 사용 - 'X-Auth-Key' => $this->_auth_entity->getAuthKey(), // 인증 토큰 사용 + 'X-Auth-Email' => $auth_entity->getID(), // 인증 토큰 사용 + 'X-Auth-Key' => $auth_entity->getAuthKey(), // 인증 토큰 사용 'Content-Type' => 'application/json', ] ]); - $this->_auth_entity = $auth_entity; self::$_request_max = getenv("cfmgr.request.max") ?: 1000; self::$_request_perpage_max = getenv("cfmgr.request.perpage.max") ?: 700; self::$_request_timewait = getenv("cfmgr.request.timewait") ?: 60; } - abstract protected function getArrayByResult($result, array $formDatas = []): array; final public function request(string $method, $uri = '', array $options = []): ResponseInterface { @@ -44,43 +37,4 @@ abstract class CloudflareSocket extends MySocket self::$_request++; return parent::request($method, $uri, $options); } - final protected function getAuthModel(): AuthModel - { - if ($this->_authModel === null) { - $this->_authModel = new AuthModel(); - } - return $this->_authModel; - } - final protected function getAccountModel(): AccountModel - { - if ($this->_accountModel === null) { - $this->_accountModel = new AccountModel(); - } - return $this->_accountModel; - } - final protected function reload_procedure($uri): array - { - $page = 1; //1부터 시작 - $results = []; - do { - $query = [ - 'page' => $page, - 'per_page' => self::$_request_perpage_max, - 'match' => 'all', - ]; - $response = $this->getClient()->get($uri, $query); - $cf = json_decode($response->getBody()); - if (!$cf->success) { - $message = __FUNCTION__ . "에서 실패:\nresponse:" . var_export($cf, true); - log_message("error", $message); - throw new \Exception($message); - } - $results = array_merge($results, $cf->result); - if (count($cf->result) < self::$_request_perpage_max) { - break; - } - $page++; - } while (true); - return $results; - } }