Skip to content
This repository has been archived by the owner on Nov 2, 2020. It is now read-only.

Commit

Permalink
perf(Site): Move apps/{libraries->components}/Site
Browse files Browse the repository at this point in the history
1. Move apps/{libraries->components}/Site
2. Fix static Cache Value Behaviour
  • Loading branch information
Rhilip committed Aug 1, 2019
1 parent 4252f8d commit 8620279
Show file tree
Hide file tree
Showing 11 changed files with 137 additions and 136 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
- **UserInfo:** Add Cache Lock of user access_{time,ip} update
- **ban:** Add table `ban_usernames` and `ban_emails`
- **csrf:** Add Csrf Support
- **email:** Use Site::sendEmail to simple email sender
- **email:** Use app()->site->sendEmail to simple email sender
- **system:** can get more system info via class SystemInfoHelper

### Fix
Expand Down
100 changes: 98 additions & 2 deletions apps/components/Site.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@

namespace apps\components;

use apps\models\User;
use apps\libraries\Mailer;
use apps\libraries\Constant;
use Rid\Base\Component;

use apps\models\User;
use Rid\Http\View;
use Rid\Base\Component;
use Rid\Utils\ClassValueCacheUtils;

class Site extends Component
Expand All @@ -23,6 +25,11 @@ class Site extends Component
protected $users = [];
protected $map_username_to_id = [];

const LOG_LEVEL_NORMAL = 'normal';
const LOG_LEVEL_MOD = 'mod';
const LOG_LEVEL_SYSOP = 'sysop';
const LOG_LEVEL_LEADER = 'leader';

public function onRequestBefore()
{
parent::onRequestBefore();
Expand All @@ -31,6 +38,11 @@ public function onRequestBefore()
$this->map_username_to_id = [];
}

protected static function getStaticCacheNameSpace(): string
{
return 'Cache:site';
}

/**
* @param $uid
* @return User|bool return False means this user is not exist
Expand Down Expand Up @@ -141,4 +153,88 @@ protected function loadCurUserFromPasskey()

return $user_id;
}

public function writeLog($msg, $level = self::LOG_LEVEL_NORMAL)
{
app()->pdo->createCommand('INSERT INTO `site_log`(`create_at`,`msg`, `level`) VALUES (CURRENT_TIMESTAMP, :msg, :level)')->bindParams([
'msg' => $msg, 'level' => $level
])->execute();
}

public function sendPM($sender, $receiver, $subject, $msg, $save = 'no', $location = 1)
{
app()->pdo->createCommand('INSERT INTO `messages` (`sender`,`receiver`,`add_at`, `subject`, `msg`, `saved`, `location`) VALUES (:sender,:receiver,`CURRENT_TIMESTAMP`,:subject,:msg,:save,:location)')->bindParams([
'sender' => $sender, 'receiver' => $receiver,
'subject' => $subject, 'msg' => $msg,
'save' => $save, 'location' => $location
])->execute();

app()->redis->hDel(Constant::userContent($receiver), 'unread_message_count', 'inbox_count');
if ($sender != 0) app()->redis->hDel(Constant::userContent($sender), 'outbox_count');
}

public function sendEmail($receivers, $subject, $template, $data = [])
{
$mail_body = (new View(false))->render($template, $data);
$mail_sender = Mailer::newInstanceByConfig('libraries.[mailer]');
$mail_sender->send($receivers, $subject, $mail_body);
}

public static function getQualityTableList()
{
return [
'audio' => 'Audio Codec', // TODO i18n title
'codec' => 'Codec',
'medium' => 'Medium',
'resolution' => 'Resolution'
];
}

public static function ruleCategory(): array
{
return static::getStaticCacheValue('enabled_torrent_category', function () {
return app()->pdo->createCommand('SELECT * FROM `categories` WHERE `id` > 0 ORDER BY `full_path`')->queryAll();
}, 86400);
}

public static function ruleCanUsedCategory(): array
{
return array_filter(static::ruleCategory(), function ($cat) {
return $cat['enabled'] = 1;
});
}

public static function ruleQuality($quality): array
{
if (!in_array($quality, array_keys(self::getQualityTableList()))) throw new \RuntimeException('Unregister quality : ' . $quality);
return static::getStaticCacheValue('enabled_quality_' . $quality, function () use ($quality) {
return app()->pdo->createCommand("SELECT * FROM `quality_$quality` WHERE `id` > 0 AND `enabled` = 1 ORDER BY `sort_index`,`id`")->queryAll();
}, 86400);
}

public static function ruleTeam(): array
{
return static::getStaticCacheValue('enabled_teams', function () {
return app()->pdo->createCommand('SELECT * FROM `teams` WHERE `id` > 0 AND `enabled` = 1 ORDER BY `sort_index`,`id`')->queryAll();
}, 86400);
}

public static function ruleCanUsedTeam(): array
{
return array_filter(static::ruleTeam(), function ($team) {
return app()->site->getCurUser()->getClass(true) >= $team['class_require'];
});
}

public static function rulePinnedTags(): array
{
return static::getStaticCacheValue('pinned_tags', function () {
return app()->pdo->createCommand('SELECT * FROM `tags` WHERE `pinned` = 1 LIMIT 10;')->queryAll();
}, 86400);
}

public static function fetchUserCount(): int
{
return app()->pdo->createCommand("SELECT COUNT(`id`) FROM `users`")->queryScalar();
}
}
111 changes: 0 additions & 111 deletions apps/libraries/Site.php

This file was deleted.

2 changes: 1 addition & 1 deletion apps/models/form/Auth/UserConfirmForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ private function flush_recover()
$this->update_confirm_status();

// Send user email to tell his new password.
Site::sendEmail([$this->email], 'New Password',
app()->site->sendEmail([$this->email], 'New Password',
'email/user_new_password', [
'username' => $this->username,
'password' => $new_password,
Expand Down
2 changes: 1 addition & 1 deletion apps/models/form/Auth/UserRecoverForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public function flush() {
'action' => $this->_action
]);

Site::sendEmail([$this->email], 'Please confirm your action to recover your password',
app()->site->sendEmail([$this->email], 'Please confirm your action to recover your password',
'email/user_recover', [
'username' => $user_info['username'],
'confirm_url' => $confirm_url,
Expand Down
10 changes: 5 additions & 5 deletions apps/models/form/Auth/UserRegisterForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ protected function isRegisterSystemOpen()
protected function isMaxUserReached()
{
if (config('register.check_max_user') &&
Site::fetchUserCount() >= config('base.max_user'))
app()->site::fetchUserCount() >= config('base.max_user'))
$this->buildCallbackFailMsg('MaxUserReached','Max user limit Reached');
}

Expand Down Expand Up @@ -282,7 +282,7 @@ public function flush()
* so that He needn't email (or other way) to confirm his account ,
* and can access the (super)admin panel to change site config .
*/
if (Site::fetchUserCount() == 0) {
if (app()->site::fetchUserCount() == 0) {
$this->status = User::STATUS_CONFIRMED;
$this->class = User::ROLE_STAFFLEADER;
$this->confirm_way = "auto";
Expand Down Expand Up @@ -314,7 +314,7 @@ public function flush()
$invitee = new User($this->invite_by);
$log_text .= '(Invite by ' . $invitee->getUsername() . '(' . $invitee->getId() . ')).';

Site::sendPM(0, $this->invite_by, 'New Invitee Signup Successful', "New Invitee Signup Successful");
app()->site->sendPM(0, $this->invite_by, 'New Invitee Signup Successful', "New Invitee Signup Successful");
}

if ($this->confirm_way == 'email') {
Expand All @@ -327,13 +327,13 @@ public function flush()
'action' => $this->_action
]);

Site::sendEmail([$this->email], 'Please confirm your accent',
app()->site->sendEmail([$this->email], 'Please confirm your accent',
'email/user_register', [
'username' => $this->username,
'confirm_url' => $confirm_url,
]);
}

Site::writeLog($log_text, Site::LOG_LEVEL_MOD);
app()->site->writeLog($log_text, app()->site::LOG_LEVEL_MOD);
}
}
8 changes: 4 additions & 4 deletions apps/models/form/Links/EditForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,12 @@ public function flush()
{
if ((int) $this->link_id !== 0) { // to edit exist links
app()->pdo->update('links', $this->link_data_diff, [['id', '=', $this->link_id]])->execute();
Site::writeLog('The links data of ' . $this->link_old_data['name'] . '( ' . $this->link_old_data['url'] . ' ) is update by ' .
app()->site->getCurUser()->getUsername() . '(' . app()->site->getCurUser()->getId() . ').', Site::LOG_LEVEL_MOD);
app()->site->writeLog('The links data of ' . $this->link_old_data['name'] . '( ' . $this->link_old_data['url'] . ' ) is update by ' .
app()->site->getCurUser()->getUsername() . '(' . app()->site->getCurUser()->getId() . ').', app()->site::LOG_LEVEL_MOD);
} else { // to new a links
app()->pdo->insert('links', $this->link_new_data)->execute();
Site::writeLog('The links data of ' . $this->link_new_data['name'] . '( ' . $this->link_new_data['url'] . ' ) is update by ' .
app()->site->getCurUser()->getUsername() . '(' . app()->site->getCurUser()->getId() . ').', Site::LOG_LEVEL_MOD);
app()->site->writeLog('The links data of ' . $this->link_new_data['name'] . '( ' . $this->link_new_data['url'] . ' ) is update by ' .
app()->site->getCurUser()->getUsername() . '(' . app()->site->getCurUser()->getId() . ').', app()->site::LOG_LEVEL_MOD);
}
app()->redis->del('Site:links');
}
Expand Down
10 changes: 5 additions & 5 deletions apps/models/form/TorrentUploadForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ public static function inputRules()
{
$categories_id_list = array_map(function ($cat) {
return $cat['id'];
}, Site::ruleCanUsedCategory());
}, app()->site::ruleCanUsedCategory());

$rules = [
'title' => 'required',
Expand Down Expand Up @@ -107,14 +107,14 @@ public static function inputRules()
}

// Add Quality Valid
foreach (Site::getQualityTableList() as $quality => $title) {
foreach (app()->site::getQualityTableList() as $quality => $title) {
$quality_id_list = [0];
// IF enabled this quality field , then load it value list from setting
// Else we just allow the default value 0 to prevent cheating
if (config('torrent_upload.enable_quality_' . $quality)) {
$quality_id_list += array_map(function ($cat) {
return $cat['id'];
}, Site::ruleQuality($quality));
}, app()->site::ruleQuality($quality));
}

$rules[$quality] = [
Expand All @@ -128,7 +128,7 @@ public static function inputRules()
if (config('torrent_upload.enable_teams')) {
$team_id_list += array_map(function ($team) {
return $team['id'];
}, Site::ruleCanUsedTeam());
}, app()->site::ruleCanUsedTeam());
}

$rules['team'] = [
Expand Down Expand Up @@ -308,7 +308,7 @@ public function flush()
throw $e;
}

Site::writeLog("Torrent {$this->id} ({$this->title}) was uploaded by " . ($this->anonymous ? 'Anonymous' : app()->site->getCurUser()->getUsername()));
app()->site->writeLog("Torrent {$this->id} ({$this->title}) was uploaded by " . ($this->anonymous ? 'Anonymous' : app()->site->getCurUser()->getUsername()));
}

// Check and rewrite torrent flags based on site config and user's privilege of upload flags
Expand Down
2 changes: 1 addition & 1 deletion apps/models/form/UserInviteForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ public function flush()
}

if ($invite_status === true) { // TODO use email queue
Site::sendEmail([$this->email], 'Invite To ' . config('base.site_name'),
app()->site->sendEmail([$this->email], 'Invite To ' . config('base.site_name'),
'email/user_invite', [
'username' => $this->username,
'invite_link' => $this->invite_link,
Expand Down
Loading

0 comments on commit 8620279

Please sign in to comment.