2019-04-05 17:23:27 +08:00
|
|
|
<?php
|
|
|
|
|
2019-07-02 22:22:05 +08:00
|
|
|
declare(strict_types=1);
|
|
|
|
|
2019-04-05 17:23:27 +08:00
|
|
|
namespace App\Services;
|
|
|
|
|
|
|
|
use Cache;
|
|
|
|
use Exception;
|
|
|
|
|
|
|
|
class PackageManager
|
|
|
|
{
|
|
|
|
protected $guzzle;
|
|
|
|
protected $path;
|
|
|
|
protected $cacheKey;
|
|
|
|
protected $onProgress;
|
|
|
|
|
|
|
|
public function __construct(\GuzzleHttp\Client $guzzle)
|
|
|
|
{
|
|
|
|
$this->guzzle = $guzzle;
|
|
|
|
$this->onProgress = function ($total, $done) {
|
|
|
|
Cache::put($this->cacheKey, serialize(['total' => $total, 'done' => $done]));
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2019-07-02 22:22:05 +08:00
|
|
|
public function download(string $url, string $path, $shasum = null): self
|
2019-04-05 17:23:27 +08:00
|
|
|
{
|
|
|
|
$this->path = $path;
|
|
|
|
$this->cacheKey = "download_$url";
|
|
|
|
Cache::forget($this->cacheKey);
|
|
|
|
try {
|
|
|
|
$this->guzzle->request('GET', $url, [
|
|
|
|
'sink' => $path,
|
2019-04-19 19:36:36 +08:00
|
|
|
'progress' => $this->onProgress,
|
2019-04-19 23:15:05 +08:00
|
|
|
'verify' => resource_path('misc/ca-bundle.crt'),
|
2019-04-05 17:23:27 +08:00
|
|
|
]);
|
|
|
|
} catch (Exception $e) {
|
|
|
|
throw new Exception(trans('admin.download.errors.download', ['error' => $e->getMessage()]));
|
|
|
|
}
|
|
|
|
|
|
|
|
Cache::forget($this->cacheKey);
|
|
|
|
if (is_string($shasum) && sha1_file($path) != $shasum) {
|
|
|
|
@unlink($path);
|
|
|
|
throw new Exception(trans('admin.download.errors.shasum'));
|
|
|
|
}
|
|
|
|
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
2019-07-02 22:22:05 +08:00
|
|
|
public function extract(string $destination): void
|
2019-04-05 17:23:27 +08:00
|
|
|
{
|
|
|
|
$zip = new \ZipArchive();
|
|
|
|
$resource = $zip->open($this->path);
|
|
|
|
|
|
|
|
if ($resource === true && $zip->extractTo($destination)) {
|
|
|
|
$zip->close();
|
|
|
|
@unlink($this->path);
|
|
|
|
} else {
|
|
|
|
throw new Exception(trans('admin.download.errors.unzip'));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-02 22:22:05 +08:00
|
|
|
public function progress(): float
|
2019-04-05 17:23:27 +08:00
|
|
|
{
|
|
|
|
$progress = unserialize(Cache::get($this->cacheKey));
|
|
|
|
if ($progress['total'] == 0) {
|
|
|
|
return 0;
|
|
|
|
} else {
|
|
|
|
return $progress['done'] / $progress['total'];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|