move cleanup: seed bonus and seeding leeching time to job

This commit is contained in:
xiaomlove
2022-10-28 14:17:10 +08:00
parent 410aed39cf
commit a61d1b0900
19 changed files with 404 additions and 110 deletions
+47
View File
@@ -0,0 +1,47 @@
<?php
namespace App\Console\Commands;
use App\Jobs\CalculateSeedBonus;
use App\Jobs\UpdateSeedingLeechingTime;
use Illuminate\Console\Command;
class Cleanup extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'cleanup {--action=} {--begin_uid=} {--end_uid=}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Cleanup async job trigger, options: --begin_uid, --end_uid, --action (seed_bonus, seeding_leeching_time)';
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$action = $this->option('action');
$beginUid = $this->option('begin_uid');
$endUid = $this->option('end_uid');
$this->info("beginUid: $beginUid, endUid: $endUid, action: $action");
if ($action == 'seed_bonus') {
CalculateSeedBonus::dispatch($beginUid, $endUid);
} elseif ($action == 'seeding_leeching_time') {
UpdateSeedingLeechingTime::dispatch($beginUid, $endUid);
} else {
$msg = "Invalid action: $action";
do_log($msg, 'error');
$this->error($msg);
}
return Command::SUCCESS;
}
}
+9
View File
@@ -2,8 +2,10 @@
namespace App\Filament;
use Closure;
use Filament\Resources\Pages\ManageRecords;
use Filament\Tables\Filters\Layout;
use Illuminate\Database\Eloquent\Model;
class PageListSingle extends ManageRecords
{
@@ -13,4 +15,11 @@ class PageListSingle extends ManageRecords
{
return Layout::AboveContent;
}
protected function getTableRecordUrlUsing(): ?Closure
{
return function (Model $record): ?string {
return null;
};
}
}
@@ -4,6 +4,7 @@ namespace App\Filament\Resources\System;
use App\Filament\Resources\System\PluginResource\Pages;
use App\Filament\Resources\System\PluginResource\RelationManagers;
use App\Jobs\ManagePlugin;
use App\Models\Plugin;
use Filament\Forms;
use Filament\Resources\Form;
@@ -52,6 +53,7 @@ class PluginResource extends Resource
Tables\Columns\TextColumn::make('remote_url')->label(__('plugin.labels.remote_url')),
Tables\Columns\TextColumn::make('installed_version')->label(__('plugin.labels.installed_version')),
Tables\Columns\TextColumn::make('statusText')->label(__('label.status')),
Tables\Columns\TextColumn::make('updated_at')->label(__('plugin.labels.updated_at')),
])
->filters([
//
@@ -76,10 +78,11 @@ class PluginResource extends Resource
$actions[] = self::buildInstallAction();
$actions[] = self::buildUpdateAction();
$actions[] = Tables\Actions\DeleteAction::make('delete')
->hidden(fn ($record) => $record->status == Plugin::STATUS_NOT_INSTALLED)
->hidden(fn ($record) => !in_array($record->status, Plugin::$showDeleteBtnStatus))
->using(function ($record) {
$record->update(['status' => Plugin::STATUS_PRE_DELETE]);
});
$record->update(['status' => Plugin::STATUS_PRE_DELETE]);
ManagePlugin::dispatch($record, 'delete');
});
return $actions;
}
@@ -89,9 +92,10 @@ class PluginResource extends Resource
->label(__('plugin.actions.install'))
->icon('heroicon-o-arrow-down')
->requiresConfirmation()
->hidden(fn ($record) => $record->status == Plugin::STATUS_NORMAL)
->hidden(fn ($record) => !in_array($record->status, Plugin::$showInstallBtnStatus))
->action(function ($record) {
$record->update(['status' => Plugin::STATUS_PRE_INSTALL]);
ManagePlugin::dispatch($record, 'install');
})
;
}
@@ -102,9 +106,10 @@ class PluginResource extends Resource
->label(__('plugin.actions.update'))
->icon('heroicon-o-arrow-up')
->requiresConfirmation()
->hidden(fn ($record) => in_array($record->status, [Plugin::STATUS_NOT_INSTALLED, Plugin::STATUS_PRE_UPDATE]))
->hidden(fn ($record) => !in_array($record->status, Plugin::$showUpdateBtnStatus))
->action(function ($record) {
$record->update(['status' => Plugin::STATUS_PRE_UPDATE]);
ManagePlugin::dispatch($record, 'update');
})
;
}
@@ -2,16 +2,15 @@
namespace App\Filament\Resources\System\PluginResource\Pages;
use App\Filament\PageListSingle;
use App\Filament\Resources\System\PluginResource;
use Filament\Pages\Actions;
use Filament\Resources\Pages\ManageRecords;
class ManagePlugins extends ManageRecords
class ManagePlugins extends PageListSingle
{
protected static string $resource = PluginResource::class;
protected ?string $maxContentWidth = 'full';
protected function getActions(): array
{
return [
+91
View File
@@ -0,0 +1,91 @@
<?php
namespace App\Jobs;
use App\Models\Setting;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Nexus\Database\NexusDB;
class CalculateSeedBonus implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
private int $beginUid;
private int $endUid;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(int $beginUid, int $endUid)
{
$this->beginUid = $beginUid;
$this->endUid = $endUid;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$beginTimestamp = time();
$logPrefix = sprintf("[CLEANUP_CLI_CALCULATE_SEED_BONUS], beginUid: %s, endUid: %s", $this->beginUid, $this->endUid);
$sql = sprintf("select userid from peers where userid > %s and userid <= %s and seeder = 'yes' group by userid", $this->beginUid, $this->endUid);
$results = NexusDB::select($sql);
$count = count($results);
do_log("$logPrefix, [GET_UID], sql: $sql, count: " . count($results));
if ($count == 0) {
do_log("$logPrefix, no user...");
return;
}
$haremAdditionFactor = Setting::get('bonus.harem_addition');
$officialAdditionFactor = Setting::get('bonus.official_addition');
$donortimes_bonus = Setting::get('bonus.donortimes');
$autoclean_interval_one = Setting::get('main.autoclean_interval_one');
$sql = sprintf("select %s from users where id in (%s)", implode(',', User::$commonFields), implode(',', array_column($results, 'userid')));
$results = NexusDB::select($sql);
do_log("$logPrefix, [GET_UID_REAL], count: " . count($results));
foreach ($results as $userInfo)
{
$uid = $userInfo['id'];
$isDonor = is_donor($userInfo);
$seedBonusResult = calculate_seed_bonus($uid);
$bonusLog = "[CLEANUP_CALCULATE_SEED_BONUS], user: $uid, seedBonusResult: " . nexus_json_encode($seedBonusResult);
$all_bonus = $seedBonusResult['seed_bonus'];
$bonusLog .= ", all_bonus: $all_bonus";
if ($isDonor) {
$all_bonus = $all_bonus * $donortimes_bonus;
$bonusLog .= ", isDonor, donortimes_bonus: $donortimes_bonus, all_bonus: $all_bonus";
}
if ($officialAdditionFactor > 0) {
$officialAddition = $seedBonusResult['official_bonus'] * $officialAdditionFactor;
$all_bonus += $officialAddition;
$bonusLog .= ", officialAdditionFactor: $officialAdditionFactor, official_bonus: {$seedBonusResult['official_bonus']}, officialAddition: $officialAddition, all_bonus: $all_bonus";
}
if ($haremAdditionFactor > 0) {
$haremBonus = calculate_harem_addition($uid);
$haremAddition = $haremBonus * $haremAdditionFactor;
$all_bonus += $haremAddition;
$bonusLog .= ", haremAdditionFactor: $haremAdditionFactor, haremBonus: $haremBonus, haremAddition: $haremAddition, all_bonus: $all_bonus";
}
$dividend = 3600 / $autoclean_interval_one;
$all_bonus = $all_bonus / $dividend;
$seed_points = $seedBonusResult['seed_points'] / $dividend;
$sql = "update users set seed_points = ifnull(seed_points, 0) + $seed_points, seedbonus = seedbonus + $all_bonus where id = $uid limit 1";
do_log("$bonusLog, query: $sql");
NexusDB::statement($sql);
}
$costTime = time() - $beginTimestamp;
do_log("$logPrefix, [DONE], cost time: $costTime seconds");
}
}
+54
View File
@@ -0,0 +1,54 @@
<?php
namespace App\Jobs;
use App\Models\Plugin;
use App\Repositories\PluginRepository;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class ManagePlugin implements ShouldQueue, ShouldBeUnique
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
private Plugin $plugin;
private string $action;
public int $uniqueFor = 600;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(Plugin $plugin, string $action)
{
$this->plugin = $plugin;
$this->action = $action;
}
public function uniqueId()
{
return $this->plugin->id;
}
/**
* Execute the job.
*
* @return void
*/
public function handle(PluginRepository $pluginRepository)
{
match ($this->action) {
'install' => $pluginRepository->doInstall($this->plugin),
'update' => $pluginRepository->doUpdate($this->plugin),
'delete' => $pluginRepository->doDelete($this->plugin),
default => throw new \InvalidArgumentException("Invalid action: " . $this->action)
};
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Nexus\Database\NexusDB;
class UpdateSeedingLeechingTime implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
private int $beginUid;
private int $endUid;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(int $beginUid, int $endUid)
{
$this->beginUid = $beginUid;
$this->endUid = $endUid;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$beginTimestamp = time();
$logPrefix = sprintf("[CLEANUP_CLI_UPDATE_SEEDING_LEECHING_TIME], beginUid: %s, endUid: %s", $this->beginUid, $this->endUid);
$sql = sprintf("select id from users where id > %s and id <= %s and enabled = 'yes' and status = 'confirmed'", $this->beginUid, $this->endUid);
$results = NexusDB::select($sql);
do_log("$logPrefix, [GET_UID], sql: $sql, count: " . count($results));
foreach ($results as $arr) {
$uid = $arr['id'];
$sql = sprintf('select sum(seedtime) as st, sum(leechtime) as lt from snatched where userid = %s limit 1', $uid);
$row = NexusDB::select($sql);
if (is_numeric($row[0]['st'])) {
$sql = sprintf('update users set seedtime = %s, leechtime = %s where id = %s limit 1', $row[0]['st'], $row[0]['lt'], $uid);
NexusDB::statement($sql);
}
}
$costTime = time() - $beginTimestamp;
do_log("$logPrefix, [DONE], cost time: $costTime seconds");
}
}
+20
View File
@@ -3,11 +3,14 @@
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Support\Arr;
class Plugin extends NexusModel
{
protected $fillable = ['display_name', 'package_name', 'remote_url', 'installed_version', 'status', 'description', 'status_result'];
public $timestamps = true;
const STATUS_NOT_INSTALLED = -1;
const STATUS_NORMAL = 0;
@@ -23,6 +26,23 @@ class Plugin extends NexusModel
const STATUS_DELETING = 102;
const STATUS_DELETE_FAILED = 103;
public static array $showInstallBtnStatus = [
self::STATUS_NOT_INSTALLED,
self::STATUS_INSTALL_FAILED,
];
public static array $showUpdateBtnStatus = [
self::STATUS_NORMAL,
self::STATUS_UPDATE_FAILED,
self::STATUS_DELETE_FAILED,
];
public static array $showDeleteBtnStatus = [
self::STATUS_NORMAL,
self::STATUS_UPDATE_FAILED,
self::STATUS_DELETE_FAILED,
];
public function statusText(): Attribute
{
return new Attribute(
+3
View File
@@ -46,6 +46,7 @@ class PluginRepository extends BaseRepository
public function doInstall(Plugin $plugin)
{
$plugin->update(['status' => Plugin::STATUS_INSTALLING]);
$packageName = $plugin->package_name;
try {
$this->execComposerConfig($plugin);
@@ -72,6 +73,7 @@ class PluginRepository extends BaseRepository
public function doDelete(Plugin $plugin)
{
$plugin->update(['status' => Plugin::STATUS_DELETING]);
$packageName = $plugin->package_name;
$removeSuccess = true;
try {
@@ -101,6 +103,7 @@ class PluginRepository extends BaseRepository
public function doUpdate(Plugin $plugin)
{
$plugin->update(['status' => Plugin::STATUS_UPDATING]);
$packageName = $plugin->package_name;
try {
$output = $this->execComposerUpdate($plugin);
+1 -34
View File
@@ -111,42 +111,8 @@ class SearchBoxRepository extends BaseRepository
*/
public function migrateToModeRelated()
{
$secondIconTable = 'secondicons';
$normalId = Setting::get('main.browsecat');
$specialId = Setting::get('main.specialcat');
$searchBoxList = SearchBox::query()->get();
$tables = array_values(SearchBox::$taxonomies);
foreach ($searchBoxList as $searchBox) {
// if ($searchBox->id == $normalId) {
// //all sub categories add `mode` field
// foreach ($tables as $table) {
// NexusDB::table($table)->update(['mode' => $normalId]);
// do_log("update table $table mode = $normalId");
// }
// //also second icons
// NexusDB::table($secondIconTable)->update(['mode' => $normalId]);
// do_log("update table $secondIconTable mode = $normalId");
// } elseif ($searchBox->id == $specialId && $specialId != $normalId) {
// //copy from normal section
// foreach ($tables as $table) {
// $sql = sprintf(
// "insert into `%s` (name, sort_index, mode) select name, sort_index, '%s' from `%s`",
// $table, $specialId, $table
// );
// NexusDB::statement($sql);
// do_log("copy table $table, $sql");
// }
// $fields = array_keys(SearchBox::$taxonomies);
// $fields = array_merge($fields, ['name', 'class_name', 'image']);
// $fieldStr = implode(', ', $fields);
// $sql = sprintf(
// "insert into `%s` (%s, mode) select %s, '%s' from `%s`",
// $secondIconTable, $fieldStr, $fieldStr, $specialId, $secondIconTable
// );
// NexusDB::statement($sql);
// do_log("copy table $secondIconTable, $sql");
// }
$taxonomies = [];
foreach (SearchBox::$taxonomies as $torrentField => $taxonomyTable) {
$searchBoxField = "show" . $torrentField;
@@ -164,6 +130,7 @@ class SearchBoxRepository extends BaseRepository
if (!empty($taxonomies)) {
$searchBox->update(["extra->" . SearchBox::EXTRA_TAXONOMY_LABELS => $taxonomies]);
}
clear_search_box_cache($searchBox->id);
}
}