add back to top

This commit is contained in:
xiaomlove
2022-04-04 17:26:26 +08:00
parent 9af8e5e442
commit 325c234442
38 changed files with 686 additions and 498 deletions
+6 -4
View File
@@ -12,14 +12,14 @@ class BackupCronjob extends Command
*
* @var string
*/
protected $signature = 'backup:cronjob';
protected $signature = 'backup:cronjob {--force=}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Backup all data cronjob, and upload to Google drive.';
protected $description = 'Backup all data cronjob, and upload to Google drive. options: --force';
/**
* Create a new command instance.
@@ -38,11 +38,13 @@ class BackupCronjob extends Command
*/
public function handle(): int
{
$force = $this->option('force');
$this->info("force: $force");
$rep = new ToolRepository();
$result = $rep->cronjobBackup();
$result = $rep->cronjobBackup($force);
$log = sprintf(
'[%s], %s, result: %s',
nexus()->getRequestId(), __METHOD__, var_export($result, true)
nexus()->getRequestId(), __METHOD__, var_export($result, true)
);
$this->info($log);
do_log($log);
+17 -5
View File
@@ -13,14 +13,14 @@ class ExamUpdateProgress extends Command
*
* @var string
*/
protected $signature = 'exam:update_progress {uid}';
protected $signature = 'exam:update_progress {--uid} {--bulk}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Update exam progress.';
protected $description = 'Update exam progress. options: --uid, --bulk';
/**
* Create a new command instance.
@@ -39,10 +39,22 @@ class ExamUpdateProgress extends Command
*/
public function handle()
{
$uid = $this->argument('uid');
$uid = $this->option('uid');
$bulk = $this->option('bulk');
$examRep = new ExamRepository();
$result = $examRep->updateProgress($uid);
$this->info(nexus()->getRequestId() . ", result: " . var_export($result, true));
$log = "uid: $uid, bulk: $bulk";
$this->info($log);
if (is_numeric($uid) && $uid) {
$log .= ", do updateProgress";
$result = $examRep->updateProgress($uid);
} elseif ($bulk) {
$result = $examRep->updateProgressBulk();
$log .= ", do updateProgressBulk";
} else {
$this->error("specific uid or bulk.");
return 0;
}
$this->info(nexus()->getRequestId() . ", $log, result: " . var_export($result, true));
return 0;
}
}
+16 -9
View File
@@ -70,10 +70,11 @@ class Test extends Command
*/
public function handle()
{
// $searchRep = new SearchRepository();
// $r = $searchRep->deleteIndex();
// $r = $searchRep->createIndex();
// $r = $searchRep->import();
$searchRep = new SearchRepository();
$r = $searchRep->deleteIndex();
$r = $searchRep->createIndex();
$r = $searchRep->import();
dd($r);
//
// $arr = [
// 'cat' => 'category',
@@ -116,12 +117,18 @@ class Test extends Command
// $r = $searchRep->deleteBookmark(1);
// $r = $searchRep->addBookmark(1);
$rep = new AttendanceRepository();
$uid = 1;
$attendance = $rep->getAttendance($uid);
// $rep = new AttendanceRepository();
// $uid = 1;
// $attendance = $rep->getAttendance($uid);
// $r = $rep->migrateAttendanceLogs($uid);
$r = $rep->getContinuousDays($attendance);
dd($r);
// $r = $rep->getContinuousDays($attendance);
// $r = $rep->getContinuousPoints(30);
// $today = Carbon::today();
// $tomorrow = Carbon::tomorrow();
// $yesterday = Carbon::parse('+10 days');
// dd($today->diffInDays($yesterday));
// $r = get_smile(12);
// dd($r);
}
+1
View File
@@ -26,6 +26,7 @@ class Kernel extends ConsoleKernel
{
$schedule->command('exam:assign_cronjob')->everyMinute();
$schedule->command('exam:checkout_cronjob')->everyMinute();
$schedule->command('exam:update_progress --bulk=1')->hourly();
$schedule->command('backup:cronjob')->everyMinute();
$schedule->command('hr:update_status')->everyMinute();
$schedule->command('hr:update_status --ignore_time=1')->hourly();
+2
View File
@@ -21,6 +21,8 @@ class Attendance extends NexusModel
30 => 1000
];
const MAX_RETROACTIVE_DAYS = 30;
public function logs(): \Illuminate\Database\Eloquent\Relations\HasMany
{
+10 -1
View File
@@ -10,13 +10,16 @@ class BonusLogs extends NexusModel
protected $fillable = ['uid', 'business_type', 'old_total_value', 'value', 'new_total_value', 'comment'];
const DEFAULT_BONUS_CANCEL_ONE_HIT_AND_RUN = 10000;
const DEFAULT_BONUS_BUY_ATTENDANCE_CARD = 1000;
const BUSINESS_TYPE_CANCEL_HIT_AND_RUN = 1;
const BUSINESS_TYPE_BUY_MEDAL = 2;
const BUSINESS_TYPE_BUY_ATTENDANCE_CARD = 3;
public static $businessTypes = [
public static array $businessTypes = [
self::BUSINESS_TYPE_CANCEL_HIT_AND_RUN => ['text' => 'Cancel H&R'],
self::BUSINESS_TYPE_BUY_MEDAL => ['text' => 'Buy medal'],
self::BUSINESS_TYPE_BUY_ATTENDANCE_CARD => ['text' => 'Buy attendance card'],
];
public static function getBonusForCancelHitAndRun()
@@ -25,5 +28,11 @@ class BonusLogs extends NexusModel
return $result ?? self::DEFAULT_BONUS_CANCEL_ONE_HIT_AND_RUN;
}
public static function getBonusForBuyAttendanceCard()
{
$result = Setting::get('bonus.attendance_card');
return $result ?? self::DEFAULT_BONUS_BUY_ATTENDANCE_CARD;
}
}
+23 -16
View File
@@ -3,34 +3,41 @@
namespace App\Models;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use Nexus\Database\NexusDB;
class Setting extends NexusModel
{
protected $fillable = ['name', 'value'];
public static function get($name = null)
public static function get($name = null, $default = null)
{
$settings = NexusDB::remember("nexus_settings_in_laravel", 10, function () {
$rows = self::query()->get(['name', 'value']);
$result = [];
foreach ($rows as $row) {
$value = $row->value;
if (!is_null($value)) {
$arr = json_decode($value, true);
if (is_array($arr)) {
$value = $arr;
}
}
Arr::set($result, $row->name, $value);
}
return $result;
return self::getFromDb();
});
if (is_null($name)) {
return $settings;
}
return Arr::get($settings, $name);
return Arr::get($settings, $name, $default);
}
public static function getFromDb($name = null, $default = null)
{
$rows = self::query()->get(['name', 'value']);
$result = [];
foreach ($rows as $row) {
$value = $row->value;
if (!is_null($value)) {
$arr = json_decode($value, true);
if (is_array($arr)) {
$value = $arr;
}
}
Arr::set($result, $row->name, $value);
}
if (is_null($name)) {
return $result;
}
return Arr::get($result, $name, $default);
}
}
+17 -10
View File
@@ -86,7 +86,7 @@ class AttendanceRepository extends BaseRepository
return $query->first();
}
private function getContinuousPoints($days)
public function getContinuousPoints($days)
{
$settings = Setting::get('bonus');
$initial = $settings['attendance_initial'] ?? Attendance::INITIAL_BONUS;
@@ -96,7 +96,7 @@ class AttendanceRepository extends BaseRepository
$points = min($initial + $days * $step, $max);
krsort($extraAwards);
foreach ($extraAwards as $key => $value) {
if ($days >= $key) {
if ($days >= $key - 1) {
$points += $value;
break;
}
@@ -224,11 +224,10 @@ class AttendanceRepository extends BaseRepository
$period = new \DatePeriod($row->added->addDay(1), $interval, $row->days, \DatePeriod::EXCLUDE_START_DATE);
$i = 0;
foreach ($period as $periodValue) {
$insert[] = [
'uid' => $row->uid,
'points' => ($i == 0 ? $row->points : 0),
'date' => $periodValue->format('Y-m-d'),
];
$insert[] = sprintf(
"(%d, %d, '%s')",
$row->uid, $i == 0 ? $row->points : 0, $periodValue->format('Y-m-d')
);
$i++;
}
}
@@ -238,9 +237,13 @@ class AttendanceRepository extends BaseRepository
do_log("no data to insert...", 'info', app()->runningInConsole());
return 0;
}
NexusDB::table($table)->insert($insert);
$sql = sprintf(
"insert into `%s` (`uid`, `points`, `date`) values %s on duplicate key update `points` = values(`points`)",
$table, implode(',', $insert)
);
NexusDB::statement($sql);
$insertCount = count($insert);
do_log("[MIGRATE_ATTENDANCE_LOGS] DONE! insert count: " . $insertCount, 'info', app()->runningInConsole());
do_log("[MIGRATE_ATTENDANCE_LOGS] DONE! insert sql: " . $sql, 'info', app()->runningInConsole());
return $insertCount;
}
@@ -252,7 +255,7 @@ class AttendanceRepository extends BaseRepository
} else {
$start = $attendance->added;
}
$logQuery = $attendance->logs()->where('created_at', '<=', $start)->orderBy('date', 'desc');
$logQuery = $attendance->logs()->where('date', '<=', $start)->orderBy('date', 'desc');
$attendanceLogs = $logQuery->get(['date'])->keyBy('date');
$counts = $attendanceLogs->count();
do_log(sprintf('user: %s, log counts: %s from query: %s', $attendance->uid, $counts, last_query()));
@@ -286,6 +289,10 @@ class AttendanceRepository extends BaseRepository
throw new \LogicException("Haven't attendance yet");
}
$date = Carbon::createFromTimestampMs($timestampMs);
$now = Carbon::now();
if ($date->gte($now) || $now->diffInDays($date) > Attendance::MAX_RETROACTIVE_DAYS) {
throw new \LogicException(sprintf("date: %s can't be retroactive attend", $date->format('Y-m-d')));
}
return NexusDB::transaction(function () use ($user, $attendance, $date) {
if (AttendanceLog::query()->where('uid', $user->id)->where('date', $date->format('Y-m-d'))->exists()) {
throw new \RuntimeException("Already attendance");
+18
View File
@@ -75,6 +75,24 @@ class BonusRepository extends BaseRepository
}
public function consumeToBuyAttendanceCard($uid): bool
{
$user = User::query()->findOrFail($uid);
$requireBonus = BonusLogs::getBonusForBuyAttendanceCard();
NexusDB::transaction(function () use ($user, $requireBonus) {
$comment = nexus_trans('bonus.comment_buy_attendance_card', [
'bonus' => $requireBonus,
], $user->locale);
$comment = addslashes($comment);
do_log("comment: $comment");
$this->consumeUserBonus($user, $requireBonus, BonusLogs::BUSINESS_TYPE_BUY_ATTENDANCE_CARD, "$comment");
User::query()->where('id', $user->id)->increment('attendance_card');
});
return true;
}
private function consumeUserBonus($user, $requireBonus, $logBusinessType, $logComment = '')
{
if ($user->seedbonus < $requireBonus) {
+6 -2
View File
@@ -451,8 +451,12 @@ class ExamRepository extends BaseRepository
return false;
}
if ($examUser->is_done == ExamUser::IS_DONE_YES) {
do_log("examUser: {$examUser->id} is done, won't update progress.");
return false;
/**
* continue update
* @since v1.7.0
*/
// do_log("examUser: {$examUser->id} is done, won't update progress.");
// return false;
}
$exam = $examUser->exam;
if (!$user instanceof User) {
+5 -5
View File
@@ -6,8 +6,8 @@ use App\Models\Setting;
use App\Models\Torrent;
use App\Models\TorrentTag;
use App\Models\User;
use Elastic\Elasticsearch\Client;
use Elastic\Elasticsearch\ClientBuilder;
use Elasticsearch\Client;
use Elasticsearch\ClientBuilder;
use Illuminate\Support\Arr;
use Nexus\Database\NexusDB;
@@ -126,11 +126,11 @@ class SearchRepository extends BaseRepository
{
if (is_null($this->es)) {
$config = nexus_config('nexus.elasticsearch');
$es = ClientBuilder::create()->setHosts($config['hosts']);
$builder = ClientBuilder::create()->setHosts($config['hosts']);
if (!empty($config['ssl_verification'])) {
$es->setSSLVerification($config['ssl_verification']);
$builder->setSSLVerification($config['ssl_verification']);
}
$this->es = $es;
$this->es = $builder->build();
}
return $this->es;
}
+27 -25
View File
@@ -81,10 +81,10 @@ class ToolRepository extends BaseRepository
*
* @return array|false
*/
public function cronjobBackup()
public function cronjobBackup($force = false): bool|array
{
$setting = Setting::get('backup');
if ($setting['enabled'] != 'yes') {
if ($setting['enabled'] != 'yes' && !$force) {
do_log("Backup not enabled.");
return false;
}
@@ -94,23 +94,25 @@ class ToolRepository extends BaseRepository
$settingMinute = (int)$setting['minute'];
$nowHour = (int)$now->format('H');
$nowMinute = (int)$now->format('i');
do_log("Backup frequency: $frequency");
if ($frequency == 'daily') {
if ($settingHour != $nowHour) {
do_log(sprintf('Backup setting hour: %s != now hour: %s', $settingHour, $nowHour));
return false;
do_log("Backup frequency: $frequency, force: " . strval($force));
if (!$force) {
if ($frequency == 'daily') {
if ($settingHour != $nowHour) {
do_log(sprintf('Backup setting hour: %s != now hour: %s', $settingHour, $nowHour));
return false;
}
if ($settingMinute != $nowMinute) {
do_log(sprintf('Backup setting minute: %s != now minute: %s', $settingMinute, $nowMinute));
return false;
}
} elseif ($frequency == 'hourly') {
if ($settingMinute != $nowMinute) {
do_log(sprintf('Backup setting minute: %s != now minute: %s', $settingMinute, $nowMinute));
return false;
}
} else {
throw new \RuntimeException("Unknown backup frequency: $frequency");
}
if ($settingMinute != $nowMinute) {
do_log(sprintf('Backup setting minute: %s != now minute: %s', $settingMinute, $nowMinute));
return false;
}
} elseif ($frequency == 'hourly') {
if ($settingMinute != $nowMinute) {
do_log(sprintf('Backup setting minute: %s != now minute: %s', $settingMinute, $nowMinute));
return false;
}
} else {
throw new \RuntimeException("Unknown backup frequency: $frequency");
}
$backupResult = $this->backupAll();
do_log("Backup all result: " . json_encode($backupResult));
@@ -143,17 +145,17 @@ class ToolRepository extends BaseRepository
$service = new \Google\Service\Drive($client);
$adapter = new \Masbug\Flysystem\GoogleDriveAdapter($service, $folderId);
$filesystem = new \League\Flysystem\Filesystem($adapter, new \League\Flysystem\Config([\League\Flysystem\Config::OPTION_VISIBILITY => \League\Flysystem\Visibility::PRIVATE]));
$filesystem = new \League\Flysystem\Filesystem($adapter);
$localAdapter = new \League\Flysystem\Local\LocalFilesystemAdapter('/');
$localFilesystem = new \League\Flysystem\Filesystem($localAdapter, [\League\Flysystem\Config::OPTION_VISIBILITY => \League\Flysystem\Visibility::PRIVATE]);
$localFilesystem = new \League\Flysystem\Filesystem($localAdapter);
$filename = $backupResult['filename'];
$time = Carbon::now();
$start = Carbon::now();
try {
$filesystem->writeStream(basename($filename), $localFilesystem->readStream($filename), new \League\Flysystem\Config());
$speed = !(float)$time->diffInSeconds() ? 0 :filesize($filename) / (float)$time->diffInSeconds();
$log = 'Elapsed time: '.$time->diffForHumans(null, true);
$filesystem->writeStream(basename($filename), $localFilesystem->readStream($filename));
$speed = !(float)$start->diffInSeconds() ? 0 :filesize($filename) / (float)$start->diffInSeconds();
$log = 'Elapsed time: '.$start->diffForHumans(null, true);
$log .= ', Speed: '. number_format($speed/1024,2) . ' KB/s';
do_log($log);
$backupResult['upload_result'] = 'success: ' .$log;
@@ -174,7 +176,7 @@ class ToolRepository extends BaseRepository
$log = "[SEND_MAIL]";
do_log("$log, to: $to, subject: $subject, body: $body");
$factory = new EsmtpTransportFactory();
$smtp = Setting::get('smtp');
$smtp = Setting::getFromDb('smtp');
$encryption = null;
if (isset($smtp['encryption']) && in_array($smtp['encryption'], ['ssl', 'tls'])) {
$encryption = $smtp['encryption'];