public function download(Request $request) { $action = $request->input('action'); if (!$this->newVersionAvailable()) { return; } $release_url = $this->getReleaseInfo($this->latestVersion)['release_url']; $file_size = Utils::getRemoteFileSize($release_url); $tmp_path = session('tmp_path'); switch ($action) { case 'prepare-download': $update_cache = storage_path('update_cache'); if (!is_dir($update_cache)) { if (false === mkdir($update_cache)) { exit('创建下载缓存文件夹失败,请检查目录权限。'); } } $tmp_path = $update_cache . "/update_" . time() . ".zip"; session(['tmp_path' => $tmp_path]); return json(compact('release_url', 'tmp_path', 'file_size')); break; case 'start-download': if (!session()->has('tmp_path')) { return "No temp path is set."; } try { Utils::download($release_url, $tmp_path); } catch (\Exception $e) { Storage::remove($tmp_path); exit('发生错误:' . $e->getMessage()); } return json(compact('tmp_path')); break; case 'get-file-size': if (!session()->has('tmp_path')) { return "No temp path is set."; } if (file_exists($tmp_path)) { return json(['size' => filesize($tmp_path)]); } break; case 'extract': if (!file_exists($tmp_path)) { exit('No file available'); } $extract_dir = storage_path("update_cache/{$this->latestVersion}"); $zip = new ZipArchive(); $res = $zip->open($tmp_path); if ($res === true) { Log::info("[ZipArchive] Extracting file {$tmp_path}"); try { $zip->extractTo($extract_dir); } catch (\Exception $e) { exit('发生错误:' . $e->getMessage()); } } else { exit('更新包解压缩失败。错误代码:' . $res); } $zip->close(); if (Storage::copyDir($extract_dir, base_path()) !== true) { Storage::removeDir(storage_path('update_cache')); exit('无法覆盖文件。'); } else { Log::info("[Extracter] Covering files"); Storage::removeDir(storage_path('update_cache')); Log::info("[Extracter] Cleaning cache"); } return json('更新完成', 0); break; default: # code... break; } }