94 lines
2.8 KiB
PHP
94 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Libraries;
|
|
|
|
use GuzzleHttp\Cookie\CookieJar;
|
|
use GuzzleHttp\Client;
|
|
|
|
abstract class WebBaseLibrary
|
|
{
|
|
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;
|
|
}
|
|
|
|
// 로그인 메서드
|
|
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;
|
|
}
|
|
}
|
|
|
|
// 파일 다운로드 메서드
|
|
public function download($url, $addPath = false)
|
|
{
|
|
try {
|
|
$fullPath = WRITEPATH . "uploads";
|
|
$fullPath .= !$addPath ? '' : DIRECTORY_SEPARATOR . $addPath;
|
|
if (!is_dir($fullPath)) {
|
|
mkdir($fullPath);
|
|
}
|
|
$temps = explode('/', $url);
|
|
if (!is_array($temps) || !count($temps)) {
|
|
throw new \Exception("URL error:" . var_dump($temps, true));
|
|
}
|
|
$file = $fullPath . DIRECTORY_SEPARATOR . array_pop($temps);
|
|
$response = $this->getClient()->get($this->gethost() . $url, [
|
|
'cookies' => $this->getCookieJar(),
|
|
'sink' => $file,
|
|
]);
|
|
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;
|
|
}
|
|
}
|
|
}
|