seed bonus add log etc

This commit is contained in:
xiaomlove
2025-09-08 03:05:55 +07:00
parent ae08039323
commit 60b5aba518
53 changed files with 720 additions and 131 deletions
+5 -4
View File
@@ -216,8 +216,8 @@ class HitAndRunRepository extends BaseRepository
//check leech time
if (isset($setting['leech_time_minimum']) && $setting['leech_time_minimum'] > 0) {
// $targetLeechTime = $row->snatch->leechtime;
$targetLeechTime = $row->leech_time_no_seeder;//使用自身记录的值
//use diff, other index should do also, update later @todo
$targetLeechTime = $row->snatch->leech_time_no_seeder - $row->leech_time_no_seeder_begin;
$requireLeechTime = bcmul($setting['leech_time_minimum'], 3600);
do_log("$currentLog, targetLeechTime: $targetLeechTime, requireLeechTime: $requireLeechTime");
if ($targetLeechTime >= $requireLeechTime) {
@@ -258,12 +258,13 @@ class HitAndRunRepository extends BaseRepository
private function geReachedMessage(HitAndRun $hitAndRun): array
{
$snatched = $hitAndRun->snatch;
return [
'receiver' => $hitAndRun->uid,
'added' => Carbon::now()->toDateTimeString(),
'subject' => nexus_trans('hr.reached_message_subject', ['hit_and_run_id' => $hitAndRun->id], $hitAndRun->user->locale),
'msg' => nexus_trans('hr.reached_message_content', [
'completed_at' => format_datetime($hitAndRun->snatch->completedat),
'completed_at' => format_datetime($snatched->completedat ?: $snatched->startdat),
'torrent_id' => $hitAndRun->torrent_id,
'torrent_name' => $hitAndRun->torrent->name,
], $hitAndRun->user->locale),
@@ -305,7 +306,7 @@ class HitAndRunRepository extends BaseRepository
do_log(__METHOD__);
$comment = nexus_trans('hr.reached_by_leech_time_comment', [
'now' => Carbon::now()->toDateTimeString(),
'leech_time' => bcdiv($hitAndRun->snatch->leechtime, 3600, 1),
'leech_time' => bcdiv($hitAndRun->snatch->leech_time_no_seeder - $hitAndRun->leech_time_no_seeder_begin, 3600, 1),
'leech_time_minimum' => $setting['leech_time_minimum'],
], $hitAndRun->user->locale);
$update = [
@@ -0,0 +1,169 @@
<?php
namespace App\Repositories;
use App\Models\RequireSeedTorrent;
use App\Models\Setting;
use App\Models\Torrent;
use App\Models\UserRequireSeedTorrent;
use Illuminate\Support\Collection;
use Nexus\Database\NexusDB;
class RequireSeedTorrentRepository extends BaseRepository
{
public function autoAddToListCronjob(): void
{
$logPrefix = "[RequireSeedTorrentRepository.autoAddToListCronjob]";
$enabled = Setting::getIsRequireSeedSectionEnabled();
if (!$enabled) {
do_log("$logPrefix, not enabled");
return;
}
$countMaxAllowed = Setting::getRequireSeedSectionTorrentCountMax();
$countNow = RequireSeedTorrent::query()->count();
if ($countNow >= $countMaxAllowed) {
do_log("$logPrefix, max allowed $countMaxAllowed reached");
return;
}
$count = $countMaxAllowed - $countNow;
$seederMax = Setting::getRequireSeedSectionSeederLte();
$seederMin = Setting::getRequireSeedSectionSeederGte();
$logPrefix .= ", countMaxAllowed: $countMaxAllowed, countNow: $countNow, count: $count, seederMax: $seederMax, seederMin: $seederMin";
$query = Torrent::query()->where('banned', 'no')
->where('seeders', '<=', $seederMax)
->where('seeders', '>=', $seederMin)
;
$tags = Setting::getRequireSeedSectionTags();
if (!empty($tags)) {
$logPrefix .= ", tags: " . implode(',', $tags);
$query->whereHas('torrent_tags', function ($query) use ($tags) {
$query->whereIn('tag_id', $tags);
});
}
$list = $query->leftJoin("require_seed_torrents", "torrents.id", "=", "require_seed_torrents.torrent_id")
->whereNull("require_seed_torrents.id")
->orderBy('torrents.seeders', 'asc')
->orderBy('torrents.times_completed', 'desc')
->orderBy('torrents.hits', 'desc')
->limit($count)
->get(['torrents.id'])
;
$data = [];
$nowStr = now()->toDateTimeString();
$redis = NexusDB::redis();
$cacheKey = self::getTorrentCacheKey();
foreach ($list as $item) {
$data[] = [
'torrent_id' => $item->id,
'created_at' => $nowStr,
'updated_at' => $nowStr,
];
$redis->hset($cacheKey, $item->id, $nowStr);
}
RequireSeedTorrent::query()->insert($data);
do_log("$logPrefix, success inserted: " . count($data));
}
public function autoRemoveFromListCronjob(): void
{
$idArr = RequireSeedTorrent::query()->pluck('torrent_id')->toArray();
if (empty($idArr)) {
do_log("no data to remove");
return;
}
$seederMax = Setting::getRequireSeedSectionSeederLte();
$seederMin = Setting::getRequireSeedSectionSeederGte();
$torrents = Torrent::query()->whereIn('id', $idArr)
->where('seeders', '<', $seederMin)
->get(['id'])
;
if (!empty($torrents)) {
$this->doRemove($torrents);
do_log(sprintf("remove %s seeders < %s", count($torrents), $seederMin));
}
$torrents = Torrent::query()->whereIn('id', $idArr)
->where('seeders', '>', $seederMax)
->get(['id'])
;
if (!empty($torrents)) {
$this->doRemove($torrents);
do_log(sprintf("remove %s seeders > %s", count($torrents), $seederMax));
}
}
public function doRemove(Collection $torrents): void
{
$idArr = [];
$redis = NexusDB::redis();
$promotionState = Setting::getRequireSeedSectionPromotionState();
$ttlInSeconds = 24 * 3600;
foreach ($torrents as $torrent) {
$idArr[] = $torrent->id;
$promotionStateCacheKey = sprintf("%s:%s", Torrent::REQUIRE_SEED_SECTION_PROMOTION_STATE_CACHE_KEY, $torrent->id);
$redis->setex($promotionStateCacheKey, $ttlInSeconds, $promotionState);
//remove torrent from list
$redis->hDel(self::getTorrentCacheKey(), $torrent->id);
//remove all users under torrent
$redis->del(self::getTorrentUserCacheKey($torrent->id));
}
RequireSeedTorrent::query()->whereIn('torrent_id', $idArr)->delete();
UserRequireSeedTorrent::query()->whereIn('torrent_id', $idArr)->delete();
do_log("success removed " . count($idArr));
}
private static function getTorrentCacheKey(): string
{
return Torrent::REQUIRE_SEED_SECTION_TORRENT_ON_LIST_CACHE_KEY;
}
private static function getTorrentUserCacheKey($torrentId): string
{
return sprintf("%s:%s", Torrent::REQUIRE_SEED_SECTION_TORRENT_USER_CACHE_KEY, $torrentId);
}
public static function shouldRecordUser(\Redis $redis, $userId, $torrentId): bool
{
$logPrefix = "userId: $userId, torrentId: $torrentId";
//check enabled or not
if (!Setting::getIsRequireSeedSectionEnabled()) {
do_log("$logPrefix, not enabled", 'debug');
return false;
}
//first, torrent on list
$onListCacheKey = self::getTorrentCacheKey();
if (!$redis->hExists($onListCacheKey, $torrentId)) {
do_log("$logPrefix, torrent not on list: $onListCacheKey", 'debug');
return false;
}
//second, torrent user not exists
$torrentUserCacheKey = self::getTorrentUserCacheKey($torrentId);
if ($redis->hExists($torrentUserCacheKey, $userId)) {
do_log("$logPrefix, user already exists: $torrentUserCacheKey", 'debug');
return false;
}
return true;
}
public static function recordUser(\Redis $redis, $userId, $torrentId, array $snatchedInfo): void
{
$torrentUserCacheKey = self::getTorrentUserCacheKey($torrentId);
$nowStr = now()->toDateTimeString();
$values = [
'user_id' => $userId,
'torrent_id' => $torrentId,
'seed_time_begin' => $snatchedInfo['seedtime'],
'uploaded_begin' => $snatchedInfo['uploaded'],
'created_at' => $nowStr,
];
$uniqueBy = ['user_id', 'torrent_id'];
$update = ['updated_at'];
UserRequireSeedTorrent::query()->upsert($values, $uniqueBy, $update);
$redis->hset($torrentUserCacheKey, $userId, $nowStr);
do_log("success insert user: $userId, torrent: $torrentId");
}
public function autoSettlementCronjob(): void
{
}
}
+17 -4
View File
@@ -123,9 +123,17 @@ class SeedBoxRepository extends BaseRepository
public function delete($id, $uid)
{
$baseQuery = SeedBoxRecord::query()->whereIn('id', Arr::wrap($id))->where('uid', $uid);
$list = $baseQuery->clone()->get();
if ($list->isEmpty()) {
return false;
}
$baseQuery->delete();
$this->clearApprovalCountCache();
publish_model_event("seed_box_record_deleted", $id);
return SeedBoxRecord::query()->whereIn('id', Arr::wrap($id))->where('uid', $uid)->delete();
foreach ($list as $record) {
publish_model_event("seed_box_record_deleted", $record->id, $record->toJson());
}
return true;
}
public function updateStatus(SeedBoxRecord $seedBoxRecord, $status, $reason = '')
@@ -321,8 +329,13 @@ class SeedBoxRepository extends BaseRepository
if (is_null($reader)) {
return 0;
}
$asnObj = $reader->asn($ip);
return $asnObj->autonomousSystemNumber ?? 0;
try {
$asnObj = $reader->asn($ip);
return $asnObj->autonomousSystemNumber ?? 0;
} catch (\Exception $e) {
do_log("ip: $ip, error: " . $e->getMessage(), 'error');
return 0;
}
});
}
+1
View File
@@ -169,6 +169,7 @@ class UploadRepository extends BaseRepository
throw new NexusException(nexus_trans('upload.missing_torrent_file'));
}
if (!$file->isValid()) {
do_log("torrent file is invalid: " . nexus_json_encode($_FILES), 'error');
throw new NexusException("upload torrent file error");
}
$size = $file->getSize();
+7
View File
@@ -2,6 +2,7 @@
namespace App\Repositories;
use App\Enums\ModelEventEnum;
use App\Enums\RedisKeysEnum;
use App\Exceptions\InsufficientPermissionException;
use App\Exceptions\NexusException;
use App\Http\Resources\ExamUserResource;
@@ -252,9 +253,15 @@ class UserRepository extends BaseRepository
do_log("user: $uid, $modCommentText, update: " . nexus_json_encode($update));
$this->clearCache($targetUser);
fire_event("user_enabled", $targetUser);
$this->setEnableLatelyCache($targetUser->id);
return true;
}
private function setEnableLatelyCache(int $userId): void
{
NexusDB::cache_put(User::getUserEnableLatelyCacheKey($userId), now()->toDateTimeString());
}
public function getInviteInfo($id)
{
$user = User::query()->findOrFail($id, ['id']);