add command nexus:update

This commit is contained in:
xiaomlove
2022-05-13 14:40:59 +08:00
parent 5110ef6e7d
commit 6eeac797a4
5 changed files with 178 additions and 24 deletions
+122
View File
@@ -0,0 +1,122 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Nexus\Install\Update;
class NexusUpdate extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'nexus:update';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Update nexusphp after code updated, remember run `composer update` first.';
private $update;
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
$this->update = new Update();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
define('WITH_LARAVEL', true);
require ROOT_PATH . 'nexus/Database/helpers.php';
//Step 1
$step = $this->update->currentStep();
$log = "Step 1, Checking environment...";
$this->doLog($log);
$requirements = $this->update->listRequirementTableRows();
$fails = $requirements['fails'];
if (!empty($fails)) {
foreach ($fails as $value) {
$this->doLog("Error: " . nexus_json_encode($value), 'error');
}
return 0;
}
$this->update->gotoStep(++$step);
//Step 2
$log = "Step 2, get files, cli skip...";
$this->doLog($log);
$this->update->gotoStep(++$step);
//Step 3
$log = "Step 3, update .env, cli skip...";
$this->doLog($log);
$this->update->gotoStep(++$step);
//Step 4
$log = "Step 4, perform update...";
$this->doLog($log);
$settingTableRows = $this->update->listSettingTableRows();
$settings = $settingTableRows['settings'];
$symbolicLinks = $settingTableRows['symbolic_links'];
$fails = $settingTableRows['fails'];
$mysqlInfo = $this->update->getMysqlVersionInfo();
if (!empty($fails)) {
foreach ($fails as $value) {
$this->doLog("Error: " . nexus_json_encode($value), 'error');
}
return 0;
}
if (!$mysqlInfo['match']) {
$this->doLog("Error: MySQL version: {$mysqlInfo['version']} is too low, please use the newest version of 5.7 or above.", 'error');
return 0;
}
$this->doLog("going to createSymbolicLinks...");
$this->update->createSymbolicLinks($symbolicLinks);
$this->doLog("createSymbolicLinks done!");
$this->doLog("going to saveSettings...");
$this->update->saveSettings($settings);
$this->doLog("saveSettings done!");
$this->doLog("going to runExtraQueries...");
$this->update->runExtraQueries();
$this->doLog("runExtraQueries done!");
$this->doLog("going to runMigrate...");
$this->update->runMigrate();
$this->doLog("runMigrate done!");
$this->doLog("going to runExtraMigrate...");
$this->update->runExtraMigrate();
$this->doLog("runExtraMigrate done!");
$this->doLog("All done!");
return 0;
}
private function doLog($log, string $level = 'info')
{
$this->update->doLog($log);
$this->{$level}(sprintf(
'[%s] [%s] %s',
date('Y-m-d H:i:s'), $this->update->currentStep(), $log
));
}
}
+1 -1
View File
@@ -4951,7 +4951,7 @@ function saveSetting($prefix, $nameAndValue, $autoload = 'yes')
$data[] = sprintf("(%s, %s, %s, %s, '%s')", sqlesc("$prefix.$name"), sqlesc($value), sqlesc($datetimeNow), sqlesc($datetimeNow), $autoload); $data[] = sprintf("(%s, %s, %s, %s, '%s')", sqlesc("$prefix.$name"), sqlesc($value), sqlesc($datetimeNow), sqlesc($datetimeNow), $autoload);
} }
$sql .= implode(",", $data) . " on duplicate key update value = values(value)"; $sql .= implode(",", $data) . " on duplicate key update value = values(value)";
sql_query($sql) or sqlerr(__FILE__, __LINE__); \Nexus\Database\NexusDB::statement($sql);
} }
function getFullDirectory($dir) function getFullDirectory($dir)
+18 -1
View File
@@ -2,6 +2,7 @@
namespace Nexus\Database; namespace Nexus\Database;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Capsule\Manager as Capsule; use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Query\Expression; use Illuminate\Database\Query\Expression;
use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Cache;
@@ -262,7 +263,7 @@ class NexusDB
$connection->getDoctrineSchemaManager()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string'); $connection->getDoctrineSchemaManager()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
} }
public static function schema(): \Illuminate\Database\Schema\Builder private static function schema(): \Illuminate\Database\Schema\Builder
{ {
if (IN_NEXUS) { if (IN_NEXUS) {
return Capsule::schema(self::ELOQUENT_CONNECTION_NAME); return Capsule::schema(self::ELOQUENT_CONNECTION_NAME);
@@ -270,6 +271,22 @@ class NexusDB
throw new \RuntimeException('can not call this when not in nexus.'); throw new \RuntimeException('can not call this when not in nexus.');
} }
public static function hasTable($table): bool
{
if (IN_NEXUS) {
return self::schema()->hasTable($table);
}
return Schema::hasTable($table);
}
public static function hasColumn($table, $column): bool
{
if (IN_NEXUS) {
return self::schema()->hasColumn($table, $column);
}
return Schema::hasColumn($table, $column);
}
public static function table($table): \Illuminate\Database\Query\Builder public static function table($table): \Illuminate\Database\Query\Builder
{ {
if (IN_NEXUS) { if (IN_NEXUS) {
+28 -13
View File
@@ -2,6 +2,7 @@
namespace Nexus\Install; namespace Nexus\Install;
use App\Models\Setting;
use App\Models\User; use App\Models\User;
use App\Repositories\UserRepository; use App\Repositories\UserRepository;
use Illuminate\Support\Str; use Illuminate\Support\Str;
@@ -44,7 +45,9 @@ class Install
if (!session_id()) { if (!session_id()) {
session_start(); session_start();
} }
$this->checkLock(); if (!$this->runningInConsole()) {
$this->checkLock();
}
$this->currentStep = min(intval($_REQUEST['step'] ?? 1) ?: 1, count($this->steps) + 1); $this->currentStep = min(intval($_REQUEST['step'] ?? 1) ?: 1, count($this->steps) + 1);
} }
@@ -58,6 +61,11 @@ class Install
return $this->currentStep; return $this->currentStep;
} }
public function runningInConsole(): bool
{
return php_sapi_name() == 'cli';
}
public function canAccessStep($step) public function canAccessStep($step)
{ {
for ($i = 1; $i < $step; $i++) { for ($i = 1; $i < $step; $i++) {
@@ -144,9 +152,10 @@ class Install
{ {
$gdInfo = function_exists('gd_info') ? gd_info() : []; $gdInfo = function_exists('gd_info') ? gd_info() : [];
$tableRows = []; $tableRows = [];
$phpVersionRequire = '>= ' . $this->minimumPhpVersion;
$tableRows[] = [ $tableRows[] = [
'label' => 'PHP version', 'label' => 'PHP version',
'required' => '>= ' . $this->minimumPhpVersion, 'required' => $phpVersionRequire,
'current' => PHP_VERSION, 'current' => PHP_VERSION,
'result' => $this->yesOrNo(version_compare(PHP_VERSION, $this->minimumPhpVersion, '>=')), 'result' => $this->yesOrNo(version_compare(PHP_VERSION, $this->minimumPhpVersion, '>=')),
]; ];
@@ -188,13 +197,13 @@ class Install
]; ];
} }
$fails = array_filter($tableRows, function ($value) use ($phpVersionRequire) {
return in_array($value['required'], ['true', 'enabled', $phpVersionRequire]) && $value['result'] == 'NO';
$fails = array_filter($tableRows, function ($value) {return in_array($value['required'], ['true', 'enabled']) && $value['result'] == 'NO';}); });
$pass = empty($fails); $pass = empty($fails);
return [ return [
'table_rows' => $tableRows, 'table_rows' => $tableRows,
'fails' => $fails,
'pass' => $pass, 'pass' => $pass,
]; ];
} }
@@ -231,7 +240,7 @@ class Install
require $originalConfigFile; require $originalConfigFile;
$settings = require $defaultSettingsFile; $settings = require $defaultSettingsFile;
$settingsFromDb = []; $settingsFromDb = [];
if (NexusDB::schema()->hasTable('settings') && get_row_count('settings') > 0) { if (NexusDB::hasTable('settings') && Setting::query()->count() > 0) {
$settingsFromDb = get_setting(); $settingsFromDb = get_setting();
} }
$this->doLog("settings form db: " . json_encode($settingsFromDb)); $this->doLog("settings form db: " . json_encode($settingsFromDb));
@@ -278,6 +287,7 @@ class Install
'table_rows' => $tableRows, 'table_rows' => $tableRows,
'symbolic_links' => $symbolicLinks, 'symbolic_links' => $symbolicLinks,
'settings' => $settings, 'settings' => $settings,
'fails' => $fails,
'pass' => $pass, 'pass' => $pass,
]; ];
} }
@@ -290,8 +300,13 @@ class Install
public function gotoStep($step) public function gotoStep($step)
{ {
nexus_redirect(getBaseUrl() . "?step=$step"); if ($this->runningInConsole()) {
die(0); $this->currentStep = $step;
} else {
nexus_redirect(getBaseUrl() . "?step=$step");
die(0);
}
} }
public function maxStep() public function maxStep()
@@ -524,7 +539,7 @@ class Install
public function saveSettings($settings) public function saveSettings($settings)
{ {
if (!NexusDB::schema()->hasTable('settings')) { if (!NexusDB::hasTable('settings')) {
$this->runMigrate('database/migrations/2021_06_08_113437_create_settings_table.php'); $this->runMigrate('database/migrations/2021_06_08_113437_create_settings_table.php');
} }
foreach ($settings as $prefix => $group) { foreach ($settings as $prefix => $group) {
@@ -635,9 +650,9 @@ class Install
public function getMysqlVersionInfo(): array public function getMysqlVersionInfo(): array
{ {
$res = mysql_query('select version() as v'); $sql = 'select version() as v';
$result = mysql_fetch_assoc($res); $result = NexusDB::select($sql);
$version = $result['v']; $version = $result[0]['v'];
$match = version_compare($version, '5.7.7', '>='); $match = version_compare($version, '5.7.7', '>=');
return compact('version', 'match'); return compact('version', 'match');
} }
+9 -9
View File
@@ -99,7 +99,7 @@ class Update extends Install
$this->doLog("[ADD CUSTOM FIELD MENU] insert: " . json_encode($insert) . " to table: $table, id: $id"); $this->doLog("[ADD CUSTOM FIELD MENU] insert: " . json_encode($insert) . " to table: $table, id: $id");
} }
//since beta8 //since beta8
if (WITH_LARAVEL && !NexusDB::schema()->hasColumn('categories', 'icon_id')) { if (WITH_LARAVEL && !NexusDB::hasColumn('categories', 'icon_id')) {
$this->doLog('[INIT CATEGORY ICON_ID]'); $this->doLog('[INIT CATEGORY ICON_ID]');
$this->runMigrate('database/migrations/2022_03_08_040415_add_icon_id_to_categories_table.php'); $this->runMigrate('database/migrations/2022_03_08_040415_add_icon_id_to_categories_table.php');
$icon = Icon::query()->orderBy('id', 'asc')->first(); $icon = Icon::query()->orderBy('id', 'asc')->first();
@@ -108,7 +108,7 @@ class Update extends Install
} }
} }
//fix base url, since beta8 //fix base url, since beta8
if (WITH_LARAVEL && NexusDB::schema()->hasTable('settings')) { if (WITH_LARAVEL && NexusDB::hasTable('settings')) {
$settingBasic = get_setting('basic'); $settingBasic = get_setting('basic');
if (isset($settingBasic['BASEURL']) && Str::startsWith($settingBasic['BASEURL'], 'localhost')) { if (isset($settingBasic['BASEURL']) && Str::startsWith($settingBasic['BASEURL'], 'localhost')) {
$this->doLog('[RESET CONFIG basic.BASEURL]'); $this->doLog('[RESET CONFIG basic.BASEURL]');
@@ -137,11 +137,11 @@ class Update extends Install
* attendance change, do migrate * attendance change, do migrate
*/ */
if (WITH_LARAVEL) { if (WITH_LARAVEL) {
if (!NexusDB::schema()->hasTable('attendance')) { if (!NexusDB::hasTable('attendance')) {
//no table yet, no need to migrate //no table yet, no need to migrate
$this->runMigrate('database/migrations/2021_06_08_113437_create_attendance_table.php'); $this->runMigrate('database/migrations/2021_06_08_113437_create_attendance_table.php');
} }
if (!NexusDB::schema()->hasColumn('attendance', 'total_days')) { if (!NexusDB::hasColumn('attendance', 'total_days')) {
$this->runMigrate('database/migrations/2021_06_13_215440_add_total_days_to_attendance_table.php'); $this->runMigrate('database/migrations/2021_06_13_215440_add_total_days_to_attendance_table.php');
$attendanceRep = new AttendanceRepository(); $attendanceRep = new AttendanceRepository();
$count = $attendanceRep->migrateAttendance(); $count = $attendanceRep->migrateAttendance();
@@ -154,7 +154,7 @@ class Update extends Install
* *
* add seed points to user * add seed points to user
*/ */
if (WITH_LARAVEL && !NexusDB::schema()->hasColumn('users', 'seed_points')) { if (WITH_LARAVEL && !NexusDB::hasColumn('users', 'seed_points')) {
$this->runMigrate('database/migrations/2021_06_24_013107_add_seed_points_to_users_table.php'); $this->runMigrate('database/migrations/2021_06_24_013107_add_seed_points_to_users_table.php');
//Don't do this, initial seed points = 0; //Don't do this, initial seed points = 0;
// $result = $this->initSeedPoints(); // $result = $this->initSeedPoints();
@@ -166,7 +166,7 @@ class Update extends Install
* *
* add id to agent_allowed_exception * add id to agent_allowed_exception
*/ */
if (WITH_LARAVEL && !NexusDB::schema()->hasColumn('agent_allowed_exception', 'id')) { if (WITH_LARAVEL && !NexusDB::hasColumn('agent_allowed_exception', 'id')) {
$this->runMigrate('database/migrations/2022_02_25_021356_add_id_to_agent_allowed_exception_table.php'); $this->runMigrate('database/migrations/2022_02_25_021356_add_id_to_agent_allowed_exception_table.php');
$this->doLog("[ADD_ID_TO_AGENT_ALLOWED_EXCEPTION]"); $this->doLog("[ADD_ID_TO_AGENT_ALLOWED_EXCEPTION]");
} }
@@ -176,7 +176,7 @@ class Update extends Install
* *
* init tag * init tag
*/ */
if (WITH_LARAVEL && !NexusDB::schema()->hasTable('tags')) { if (WITH_LARAVEL && !NexusDB::hasTable('tags')) {
$this->runMigrate('database/migrations/2022_03_07_012545_create_tags_table.php'); $this->runMigrate('database/migrations/2022_03_07_012545_create_tags_table.php');
$this->initTag(); $this->initTag();
$this->doLog("[INIT_TAG]"); $this->doLog("[INIT_TAG]");
@@ -205,7 +205,7 @@ class Update extends Install
* *
* add attendance_card to users * add attendance_card to users
*/ */
if (WITH_LARAVEL && !NexusDB::schema()->hasColumn('users', 'attendance_card')) { if (WITH_LARAVEL && !NexusDB::hasColumn('users', 'attendance_card')) {
$this->runMigrate('database/migrations/2022_04_02_163930_create_attendance_logs_table.php'); $this->runMigrate('database/migrations/2022_04_02_163930_create_attendance_logs_table.php');
$this->runMigrate('database/migrations/2022_04_03_041642_add_attendance_card_to_users_table.php'); $this->runMigrate('database/migrations/2022_04_03_041642_add_attendance_card_to_users_table.php');
$rep = new AttendanceRepository(); $rep = new AttendanceRepository();
@@ -232,7 +232,7 @@ class Update extends Install
$this->doLog(__METHOD__ . ", laravel is not available"); $this->doLog(__METHOD__ . ", laravel is not available");
return; return;
} }
if (NexusDB::schema()->hasColumn('torrents', 'tags')) { if (NexusDB::hasColumn('torrents', 'tags')) {
if (Torrent::query()->where('tags', '>', 0)->count() > 0 && TorrentTag::query()->count() == 0) { if (Torrent::query()->where('tags', '>', 0)->count() > 0 && TorrentTag::query()->count() == 0) {
$this->doLog("[MIGRATE_TORRENT_TAG]..."); $this->doLog("[MIGRATE_TORRENT_TAG]...");
$tagRep = new TagRepository(); $tagRep = new TagRepository();