[exam] add progress

This commit is contained in:
xiaomlove
2021-04-29 02:52:22 +08:00
parent 1c31f4b22d
commit a1972ea288
4 changed files with 118 additions and 41 deletions
+77 -35
View File
@@ -28,7 +28,7 @@ class ExamRepository extends BaseRepository
{
$this->checkIndexes($params);
$valid = $this->listValid();
if ($valid->isNotEmpty()) {
if ($valid->isNotEmpty() && $params['status'] == Exam::STATUS_ENABLED) {
throw new NexusException("Valid exam already exists.");
}
$exam = Exam::query()->create($params);
@@ -39,7 +39,7 @@ class ExamRepository extends BaseRepository
{
$this->checkIndexes($params);
$valid = $this->listValid($id);
if ($valid->isNotEmpty()) {
if ($valid->isNotEmpty() && $params['status'] == Exam::STATUS_ENABLED) {
throw new NexusException("Valid exam already exists.");
}
$exam = Exam::query()->findOrFail($id);
@@ -197,9 +197,12 @@ class ExamRepository extends BaseRepository
throw new NexusException("No valid exam.");
}
$user = User::query()->findOrFail($uid);
if ($user->exams()->where('status', ExamUser::STATUS_NORMAL)->exists()) {
throw new NexusException("User: $uid already has exam on the way.");
}
$exists = $user->exams()->where('exam_id', $exam->id)->exists();
if ($exists) {
throw new NexusException("Exam: {$exam->id} already assign to user: {$user->id}");
throw new NexusException("Exam: {$exam->id} already assign to user: {$user->id}.");
}
$data = [
'exam_id' => $exam->id,
@@ -230,41 +233,66 @@ class ExamRepository extends BaseRepository
}
public function addProgress(int $examUserId, int $indexId, int $value, int $torrentId)
public function addProgress(int $uid, int $torrentId, array $indexAndValue)
{
$logPrefix = "examUserId: $examUserId, indexId: $indexId, value: $value, torrentId: $torrentId";
$examUser = ExamUser::query()->with(['exam', 'user'])->findOrFail($examUserId);
if ($examUser->status != ExamUser::STATUS_NORMAL) {
throw new \InvalidArgumentException("ExamUser: $examUserId is not normal.");
}
if (!isset(Exam::$indexes[$indexId])) {
throw new \InvalidArgumentException("Invalid index id: $indexId.");
$logPrefix = "uid: $uid, torrentId: $torrentId, indexAndValue: " . json_encode($indexAndValue);
do_log($logPrefix);
$user = User::query()->findOrFail($uid);
$user->checkIsNormal();
$now = Carbon::now()->toDateTimeString();
$examUser = $user->exams()->where('status', ExamUser::STATUS_NORMAL)->orderBy('id', 'desc')->first();
if (!$examUser) {
do_log("no exam is on the way, " . last_query());
return false;
}
$exam = $examUser->exam;
if (!$exam) {
throw new NexusException("exam: {$examUser->exam_id} not exists.");
}
$begin = $examUser->begin ?? $exam->begin;
$end = $examUser->end ?? $exam->end;
if ($now < $begin || $now > $end) {
do_log(sprintf("now: %s, not in exam time range: %s ~ %s", $now, $begin, $end));
return false;
}
$indexes = collect($exam->indexes)->keyBy('index');
if (!$indexes->has($indexId)) {
throw new \InvalidArgumentException(sprintf('Exam: %s does not has index: %s', $exam->id, $indexId));
}
$index = $indexes->get($indexId);
if (!isset($index['checked']) || !$index['checked']) {
throw new \InvalidArgumentException(sprintf('Exam: %s index: %s is not checked', $exam->id, $indexId));
}
do_log("examUser: " . $examUser->toJson() . ", indexes: " . $indexes->toJson());
$torrentFields = ['id', 'visible', 'banned'];
$torrent = Torrent::query()->findOrFail($torrentId, $torrentFields);
$torrent->checkIsNormal($torrentFields);
$user = $examUser->user;
$user->checkIsNormal();
$insert = [];
foreach ($indexAndValue as $indexId => $value) {
if (!$indexes->has($indexId)) {
do_log(sprintf('Exam: %s does not has index: %s.', $exam->id, $indexId));
continue;
}
$indexInfo = $indexes->get($indexId);
if (!isset($indexInfo['checked']) || !$indexInfo['checked']) {
do_log(sprintf('Exam: %s index: %s is not checked.', $exam->id, $indexId));
continue;
}
$insert[] = [
'exam_user_id' => $examUser->id,
'uid' => $user->id,
'exam_id' => $exam->id,
'torrent_id' => $torrentId,
'index' => $indexId,
'value' => $value,
'created_at' => $now,
'updated_at' => $now,
];
}
if (empty($insert)) {
do_log("no progress to insert.");
return false;
}
ExamProgress::query()->insert($insert);
do_log("[addProgress] " . nexus_json_encode($insert));
$data = [
'uid' => $user->id,
'exam_id' => $exam->id,
'torrent_id' => $torrentId,
'index' => $indexId,
'value' => $value,
];
do_log("$logPrefix [addProgress] " . nexus_json_encode($data));
$newProgress = $examUser->progresses()->create($data);
$examProgress = $this->calculateProgress($examUser);
$examProgressFormatted = $this->getProgressFormatted($exam, $examProgress);
$examNotPassed = array_filter($examProgressFormatted, function ($item) {
@@ -274,9 +302,9 @@ class ExamRepository extends BaseRepository
'progress' => $examProgress,
'is_done' => count($examNotPassed) ? ExamUser::IS_DONE_NO : ExamUser::IS_DONE_YES,
];
do_log("$logPrefix [updateProgress] " . nexus_json_encode($update));
do_log("[updateProgress] " . nexus_json_encode($update));
$examUser->update($update);
return $newProgress;
return true;
}
public function getUserExamProgress($uid, $status = null, $with = ['exam', 'user'])
@@ -312,7 +340,7 @@ class ExamRepository extends BaseRepository
private function calculateProgress(ExamUser $examUser)
{
$exam = $examUser->exam;
$logPrefix = ", examUser: " . $examUser->id;
$logPrefix = "examUser: " . $examUser->id;
if ($examUser->begin) {
$logPrefix .= ", begin from examUser: " . $examUser->id;
$begin = $examUser->begin;
@@ -338,11 +366,25 @@ class ExamRepository extends BaseRepository
->where('created_at', '<=', $end)
->selectRaw("`index`, sum(`value`) as sum")
->groupBy(['index'])
->get();
->get()
->pluck('sum', 'index')
->toArray();
$logPrefix .= ", progressSum raw: " . json_encode($progressSum) . ", query: " . last_query();
do_log("$logPrefix, " . last_query() . ", progressSum: " . $progressSum->toJson());
$index = Exam::INDEX_SEED_TIME_AVERAGE;
if (isset($progressSum[$index])) {
$torrentCount = $examUser->progresses()
->where('index', $index)
->selectRaw('count(distinct(torrent_id)) as torrent_count')
->first()
->torrent_count;
$progressSum[$index] = intval($progressSum[$index] / $torrentCount);
$logPrefix .= ", get torrent count: $torrentCount, from query: " . last_query();
}
return $progressSum->pluck('sum', 'index')->toArray();
do_log("$logPrefix, final progressSum: " . json_encode($progressSum));
return $progressSum;
}
+1 -1
View File
@@ -2012,7 +2012,7 @@ function mkprettytime($s) {
}
if ($t["day"])
return $t["day"] . ($lang_functions['text_day'] ?? 'days') . sprintf("%02d:%02d:%02d", $t["hour"], $t["min"], $t["sec"]);
return $t["day"] . ($lang_functions['text_day'] ?? 'day(s)') . sprintf("%02d:%02d:%02d", $t["hour"], $t["min"], $t["sec"]);
if ($t["hour"])
return sprintf("%d:%02d:%02d", $t["hour"], $t["min"], $t["sec"]);
// if ($t["min"])
+2 -2
View File
@@ -534,10 +534,10 @@ function format_datetime($datetime, $format = 'Y-m-d H:i:s')
return $datetime;
}
function nexus_trans($key)
function nexus_trans($key, $replace = [], $locale = null)
{
if (!IN_NEXUS) {
return trans($key);
return trans($key, $replace, $locale);
}
static $translations;
if (is_null($translations)) {
+38 -3
View File
@@ -2,7 +2,7 @@
require_once('../include/bittorrent_announce.php');
require_once('../include/benc.php');
dbconn_announce();
do_log(json_encode($_SERVER));
do_log(nexus_json_encode($_SERVER));
$log = "";
//1. BLOCK ACCESS WITH WEB BROWSERS AND CHEATS!
$agent = $_SERVER["HTTP_USER_AGENT"];
@@ -166,6 +166,7 @@ if (!isset($self))
if(isset($self) && $self['prevts'] > (TIMENOW - $announce_wait))
err('There is a minimum announce time of ' . $announce_wait . ' seconds');
$examIndexData = [];
// current peer_id, or you could say session with tracker not found in table peers
if (!isset($self))
{
@@ -222,15 +223,19 @@ else // continue an existing session
$downthis = $truedownthis = max(0, $downloaded - $self["downloaded"]);
$announcetime = ($self["seeder"] == "yes" ? "seedtime = seedtime + {$self['announcetime']}" : "leechtime = leechtime + {$self['announcetime']}");
$is_cheater = false;
if ($cheaterdet_security){
if ($az['class'] < $nodetect_security && $self['announcetime'] > 10)
{
$is_cheater = check_cheater($userid, $torrent['id'], $upthis, $downthis, $self['announcetime'], $torrent['seeders'], $torrent['leechers']);
}
}
do_log("upthis: $upthis, downthis: $downthis, announcetime: $announcetime, is_cheater: $is_cheater");
if (!$is_cheater) {
$examIndexData[\App\Models\Exam::INDEX_SEED_TIME_AVERAGE] = $self['announcetime'];
}
if (!$is_cheater && ($trueupthis > 0 || $truedownthis > 0))
{
$global_promotion_state = get_global_sp_state();
@@ -240,15 +245,20 @@ else // continue an existing session
{
$USERUPDATESET[] = "uploaded = uploaded + 2*$trueupthis";
$USERUPDATESET[] = "downloaded = downloaded + $truedownthis";
$examIndexData[\App\Models\Exam::INDEX_UPLOADED] = 2 * $trueupthis;
$examIndexData[\App\Models\Exam::INDEX_DOWNLOADED] = $truedownthis;
}
elseif($torrent['sp_state']==4) //2X Free
{
$USERUPDATESET[] = "uploaded = uploaded + 2*$trueupthis";
$examIndexData[\App\Models\Exam::INDEX_UPLOADED] = 2 * $trueupthis;
}
elseif($torrent['sp_state']==6) //2X 50%
{
$USERUPDATESET[] = "uploaded = uploaded + 2*$trueupthis";
$USERUPDATESET[] = "downloaded = downloaded + $truedownthis/2";
$examIndexData[\App\Models\Exam::INDEX_UPLOADED] = 2 * $trueupthis;
$examIndexData[\App\Models\Exam::INDEX_DOWNLOADED] = $truedownthis / 2;
}
else{
if ($torrent['owner'] == $userid && $uploaderdouble_torrent > 0)
@@ -257,21 +267,28 @@ else // continue an existing session
if($torrent['sp_state']==2) //Free
{
$USERUPDATESET[] = "uploaded = uploaded + $upthis";
$examIndexData[\App\Models\Exam::INDEX_UPLOADED] = $upthis;
}
elseif($torrent['sp_state']==5) //50%
{
$USERUPDATESET[] = "uploaded = uploaded + $upthis";
$USERUPDATESET[] = "downloaded = downloaded + $truedownthis/2";
$examIndexData[\App\Models\Exam::INDEX_UPLOADED] = $upthis;
$examIndexData[\App\Models\Exam::INDEX_DOWNLOADED] = $truedownthis / 2;
}
elseif($torrent['sp_state']==7) //30%
{
$USERUPDATESET[] = "uploaded = uploaded + $upthis";
$USERUPDATESET[] = "downloaded = downloaded + $truedownthis*3/10";
$examIndexData[\App\Models\Exam::INDEX_UPLOADED] = $upthis;
$examIndexData[\App\Models\Exam::INDEX_DOWNLOADED] = $truedownthis * 3 / 10;
}
elseif($torrent['sp_state']==1) //Normal
{
$USERUPDATESET[] = "uploaded = uploaded + $upthis";
$USERUPDATESET[] = "downloaded = downloaded + $truedownthis";
$examIndexData[\App\Models\Exam::INDEX_UPLOADED] = $upthis;
$examIndexData[\App\Models\Exam::INDEX_DOWNLOADED] = $truedownthis;
}
}
}
@@ -280,6 +297,7 @@ else // continue an existing session
if ($torrent['owner'] == $userid && $uploaderdouble_torrent > 0)
$upthis = $trueupthis * $uploaderdouble_torrent;
$USERUPDATESET[] = "uploaded = uploaded + $upthis";
$examIndexData[\App\Models\Exam::INDEX_UPLOADED] = $upthis;
}
elseif($global_promotion_state == 3) //2X
{
@@ -288,6 +306,8 @@ else // continue an existing session
else $upthis = 2*$trueupthis;
$USERUPDATESET[] = "uploaded = uploaded + $upthis";
$USERUPDATESET[] = "downloaded = downloaded + $truedownthis";
$examIndexData[\App\Models\Exam::INDEX_UPLOADED] = $upthis;
$examIndexData[\App\Models\Exam::INDEX_DOWNLOADED] = $truedownthis;
}
elseif($global_promotion_state == 4) //2X Free
{
@@ -295,12 +315,15 @@ else // continue an existing session
$upthis = $trueupthis * $uploaderdouble_torrent;
else $upthis = 2*$trueupthis;
$USERUPDATESET[] = "uploaded = uploaded + $upthis";
$examIndexData[\App\Models\Exam::INDEX_UPLOADED] = $upthis;
}
elseif($global_promotion_state == 5){ // 50%
if ($torrent['owner'] == $userid && $uploaderdouble_torrent > 0)
$upthis = $trueupthis * $uploaderdouble_torrent;
$USERUPDATESET[] = "uploaded = uploaded + $upthis";
$USERUPDATESET[] = "downloaded = downloaded + $truedownthis/2";
$examIndexData[\App\Models\Exam::INDEX_UPLOADED] = $upthis;
$examIndexData[\App\Models\Exam::INDEX_DOWNLOADED] = $truedownthis / 2;
}
elseif($global_promotion_state == 6){ //2X 50%
if ($uploaderdouble_torrent > 2 && $torrent['owner'] == $userid && $uploaderdouble_torrent > 0)
@@ -308,12 +331,16 @@ else // continue an existing session
else $upthis = 2*$trueupthis;
$USERUPDATESET[] = "uploaded = uploaded + $upthis";
$USERUPDATESET[] = "downloaded = downloaded + $truedownthis/2";
$examIndexData[\App\Models\Exam::INDEX_UPLOADED] = $upthis;
$examIndexData[\App\Models\Exam::INDEX_DOWNLOADED] = $truedownthis / 2;
}
elseif($global_promotion_state == 7){ //30%
if ($torrent['owner'] == $userid && $uploaderdouble_torrent > 0)
$upthis = $trueupthis * $uploaderdouble_torrent;
$USERUPDATESET[] = "uploaded = uploaded + $upthis";
$USERUPDATESET[] = "downloaded = downloaded + $truedownthis*3/10";
$examIndexData[\App\Models\Exam::INDEX_UPLOADED] = $upthis;
$examIndexData[\App\Models\Exam::INDEX_DOWNLOADED] = $truedownthis * 3 / 10;
}
}
}
@@ -369,7 +396,7 @@ else
if (mysql_affected_rows())
{
$updateset[] = ($seeder == "yes" ? "seeders = seeders + 1" : "leechers = leechers + 1");
$check = @mysql_fetch_row(@sql_query("SELECT COUNT(*) FROM snatched WHERE torrentid = $torrentid AND userid = $userid"));
if (!$check['0'])
sql_query("INSERT INTO snatched (torrentid, userid, ip, port, uploaded, downloaded, to_go, startdat, last_action) VALUES ($torrentid, $userid, ".sqlesc($ip).", $port, $uploaded, $downloaded, $left, $dt, $dt)") or err("SL Err 4");
@@ -392,5 +419,13 @@ if(count($USERUPDATESET) && $userid)
{
sql_query("UPDATE users SET " . join(",", $USERUPDATESET) . " WHERE id = ".$userid);
}
$examRep = new \App\Repositories\ExamRepository();
try {
$examRep->addProgress($userid, $torrentid, $examIndexData);
} catch (\Exception $exception) {
do_log("add exam progress fail: " . $exception->getMessage());
}
benc_resp_raw($resp);
?>