100 lines
3.1 KiB
PHP
100 lines
3.1 KiB
PHP
<?php
|
|
|
|
namespace App\Libraries;
|
|
|
|
use GuzzleHttp\Cookie\CookieJar;
|
|
use GuzzleHttp\Client;
|
|
|
|
abstract class MyBaseLibrary
|
|
{
|
|
private $_host = "";
|
|
private $_client = null;
|
|
private $_cookieJar = null;
|
|
protected function __construct(string $host)
|
|
{
|
|
$this->_host = $host;
|
|
}
|
|
|
|
final public function getHost(): string
|
|
{
|
|
return $this->_host;
|
|
}
|
|
|
|
final protected function getClient(): Client
|
|
{
|
|
if ($this->_client === null) {
|
|
$this->_client = new Client(['verify' => false]);
|
|
}
|
|
return $this->_client;
|
|
}
|
|
|
|
final protected function getCookieJar()
|
|
{
|
|
if ($this->_cookieJar === null) {
|
|
$this->_cookieJar = new CookieJar();
|
|
}
|
|
return $this->_cookieJar;
|
|
}
|
|
|
|
final public function getContent(string $url): string
|
|
{
|
|
return $this->getClient()->get($this->gethost() . $url)->getBody();
|
|
}
|
|
|
|
// 로그인 메서드
|
|
final public function login($url, $username, $password)
|
|
{
|
|
try {
|
|
$response = $this->getClient()->post($this->gethost() . $url, [
|
|
'form_params' => [
|
|
'username' => $username,
|
|
'password' => $password,
|
|
],
|
|
'cookies' => $this->getCookieJar(),
|
|
]);
|
|
if ($response->getStatusCode() == 200) {
|
|
log_message("info", "로그인 성공!");
|
|
return true;
|
|
} else {
|
|
log_message("info", "로그인 실패: " . $response->getStatusCode());
|
|
return false;
|
|
}
|
|
} catch (\Exception $e) {
|
|
log_message("error", "파일 다운로드 중 오류 발생: " . $e->getMessage());
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// 파일 다운로드 메서드
|
|
final public function download($url, $path = false)
|
|
{
|
|
try {
|
|
$fileNames = explode('/', $url);
|
|
if (!is_array($fileNames) || !count($fileNames)) {
|
|
throw new \Exception("Download URL Error:" . $url);
|
|
}
|
|
$storagePath = WRITEPATH . "uploads";
|
|
$storagePath .= !$path ? '' : DIRECTORY_SEPARATOR . $path;
|
|
if (!is_dir($storagePath)) {
|
|
if (!mkdir($storagePath)) {
|
|
throw new \Exception("Make Directory Error:" . $storagePath);
|
|
}
|
|
}
|
|
$response = $this->getClient()->get($this->gethost() . $url, [
|
|
'cookies' => $this->getCookieJar(),
|
|
'sink' => $storagePath . DIRECTORY_SEPARATOR . array_pop($fileNames),
|
|
]);
|
|
if ($response->getStatusCode() == 200) {
|
|
log_message("info", "파일이 성공적으로 다운로드되었습니다!");
|
|
return true;
|
|
} else {
|
|
log_message("info", "파일 다운로드 실패: " . $response->getStatusCode());
|
|
return false;
|
|
}
|
|
} catch (\Exception $e) {
|
|
log_message("error", "파일 다운로드 중 오류 발생: " . $e->getMessage());
|
|
return false;
|
|
}
|
|
}
|
|
}
|