1
0
mirror of https://gitee.com/koogua/course-tencent-cloud.git synced 2025-07-24 00:41:43 +08:00

优化代码

This commit is contained in:
xiaochong0302 2020-09-10 21:18:56 +08:00
parent 1bf7449eed
commit 8c7453a9ab
38 changed files with 326 additions and 368 deletions

View File

@ -2,8 +2,6 @@
namespace App\Console\Tasks; namespace App\Console\Tasks;
use Phalcon\Cli\Task;
class CleanLogTask extends Task class CleanLogTask extends Task
{ {
@ -165,9 +163,9 @@ class CleanLogTask extends Task
if (strtotime($today) - strtotime($date) >= $keepDays * 86400) { if (strtotime($today) - strtotime($date) >= $keepDays * 86400) {
$deleted = unlink($file); $deleted = unlink($file);
if ($deleted) { if ($deleted) {
echo "Delete {$file} success" . PHP_EOL; echo "delete {$file} success" . PHP_EOL;
} else { } else {
echo "Delete {$file} failed" . PHP_EOL; echo "delete {$file} failed" . PHP_EOL;
} }
} }
} }

View File

@ -2,19 +2,13 @@
namespace App\Console\Tasks; namespace App\Console\Tasks;
use App\Library\Cache\Backend\Redis as RedisCache;
use Phalcon\Cli\Task;
use Phalcon\Config;
class CleanSessionTask extends Task class CleanSessionTask extends Task
{ {
public function mainAction() public function mainAction()
{ {
$config = $this->getConfig(); $config = $this->getConfig();
$cache = $this->getCache(); $cache = $this->getCache();
$redis = $cache->getRedis(); $redis = $cache->getRedis();
$redis->select($config->path('session.db')); $redis->select($config->path('session.db'));
@ -47,24 +41,4 @@ class CleanSessionTask extends Task
return $cache->queryKeys('_PHCR', $limit); return $cache->queryKeys('_PHCR', $limit);
} }
protected function getConfig()
{
/**
* @var Config $config
*/
$config = $this->getDI()->get('config');
return $config;
}
protected function getCache()
{
/**
* @var RedisCache $cache
*/
$cache = $this->getDI()->get('cache');
return $cache;
}
} }

View File

@ -3,7 +3,6 @@
namespace App\Console\Tasks; namespace App\Console\Tasks;
use App\Models\Order as OrderModel; use App\Models\Order as OrderModel;
use Phalcon\Cli\Task;
use Phalcon\Mvc\Model\Resultset; use Phalcon\Mvc\Model\Resultset;
use Phalcon\Mvc\Model\ResultsetInterface; use Phalcon\Mvc\Model\ResultsetInterface;

View File

@ -5,7 +5,6 @@ namespace App\Console\Tasks;
use App\Models\Trade as TradeModel; use App\Models\Trade as TradeModel;
use App\Services\Pay\Alipay as AlipayService; use App\Services\Pay\Alipay as AlipayService;
use App\Services\Pay\Wxpay as WxpayService; use App\Services\Pay\Wxpay as WxpayService;
use Phalcon\Cli\Task;
use Phalcon\Mvc\Model\Resultset; use Phalcon\Mvc\Model\Resultset;
use Phalcon\Mvc\Model\ResultsetInterface; use Phalcon\Mvc\Model\ResultsetInterface;

View File

@ -5,7 +5,6 @@ namespace App\Console\Tasks;
use App\Models\Course as CourseModel; use App\Models\Course as CourseModel;
use App\Services\Search\CourseDocument; use App\Services\Search\CourseDocument;
use App\Services\Search\CourseSearcher; use App\Services\Search\CourseSearcher;
use Phalcon\Cli\Task;
use Phalcon\Mvc\Model\Resultset; use Phalcon\Mvc\Model\Resultset;
use Phalcon\Mvc\Model\ResultsetInterface; use Phalcon\Mvc\Model\ResultsetInterface;
@ -24,7 +23,7 @@ class CourseIndexTask extends Task
$query = $params[0] ?? null; $query = $params[0] ?? null;
if (!$query) { if (!$query) {
exit("please special a query word" . PHP_EOL); exit('please special a query word' . PHP_EOL);
} }
$result = $this->searchCourses($query); $result = $this->searchCourses($query);
@ -61,11 +60,11 @@ class CourseIndexTask extends Task
$index = $handler->getXS()->getIndex(); $index = $handler->getXS()->getIndex();
echo "start clean index" . PHP_EOL; echo 'start clean index' . PHP_EOL;
$index->clean(); $index->clean();
echo "end clean index" . PHP_EOL; echo 'end clean index' . PHP_EOL;
} }
/** /**
@ -75,9 +74,7 @@ class CourseIndexTask extends Task
{ {
$courses = $this->findCourses(); $courses = $this->findCourses();
if ($courses->count() == 0) { if ($courses->count() == 0) return;
return;
}
$handler = new CourseSearcher(); $handler = new CourseSearcher();
@ -85,7 +82,7 @@ class CourseIndexTask extends Task
$index = $handler->getXS()->getIndex(); $index = $handler->getXS()->getIndex();
echo "start rebuild index" . PHP_EOL; echo 'start rebuild index' . PHP_EOL;
$index->beginRebuild(); $index->beginRebuild();
@ -96,7 +93,7 @@ class CourseIndexTask extends Task
$index->endRebuild(); $index->endRebuild();
echo "end rebuild index" . PHP_EOL; echo 'end rebuild index' . PHP_EOL;
} }
/** /**

View File

@ -74,7 +74,6 @@ class DeliverTask extends Task
$task->update(); $task->update();
$logger->info('Order Process Exception ' . kg_json_encode([ $logger->info('Order Process Exception ' . kg_json_encode([
'line' => $e->getLine(),
'code' => $e->getCode(), 'code' => $e->getCode(),
'message' => $e->getMessage(), 'message' => $e->getMessage(),
'task' => $task->toArray(), 'task' => $task->toArray(),

View File

@ -5,7 +5,6 @@ namespace App\Console\Tasks;
use App\Models\ImGroup as GroupModel; use App\Models\ImGroup as GroupModel;
use App\Services\Search\GroupDocument; use App\Services\Search\GroupDocument;
use App\Services\Search\GroupSearcher; use App\Services\Search\GroupSearcher;
use Phalcon\Cli\Task;
use Phalcon\Mvc\Model\Resultset; use Phalcon\Mvc\Model\Resultset;
use Phalcon\Mvc\Model\ResultsetInterface; use Phalcon\Mvc\Model\ResultsetInterface;
@ -24,7 +23,7 @@ class GroupIndexTask extends Task
$query = $params[0] ?? null; $query = $params[0] ?? null;
if (!$query) { if (!$query) {
exit("please special a query word" . PHP_EOL); exit('please special a query word' . PHP_EOL);
} }
$result = $this->searchGroups($query); $result = $this->searchGroups($query);
@ -61,11 +60,11 @@ class GroupIndexTask extends Task
$index = $handler->getXS()->getIndex(); $index = $handler->getXS()->getIndex();
echo "start clean index" . PHP_EOL; echo 'start clean index' . PHP_EOL;
$index->clean(); $index->clean();
echo "end clean index" . PHP_EOL; echo 'end clean index' . PHP_EOL;
} }
/** /**
@ -75,9 +74,7 @@ class GroupIndexTask extends Task
{ {
$groups = $this->findGroups(); $groups = $this->findGroups();
if ($groups->count() == 0) { if ($groups->count() == 0) return;
return;
}
$handler = new GroupSearcher(); $handler = new GroupSearcher();
@ -85,7 +82,7 @@ class GroupIndexTask extends Task
$index = $handler->getXS()->getIndex(); $index = $handler->getXS()->getIndex();
echo "start rebuild index" . PHP_EOL; echo 'start rebuild index' . PHP_EOL;
$index->beginRebuild(); $index->beginRebuild();
@ -96,7 +93,7 @@ class GroupIndexTask extends Task
$index->endRebuild(); $index->endRebuild();
echo "end rebuild index" . PHP_EOL; echo 'end rebuild index' . PHP_EOL;
} }
/** /**

View File

@ -2,54 +2,42 @@
namespace App\Console\Tasks; namespace App\Console\Tasks;
use App\Library\Cache\Backend\Redis as RedisCache;
use App\Models\CourseUser as CourseUserModel; use App\Models\CourseUser as CourseUserModel;
use App\Repos\Chapter as ChapterRepo; use App\Repos\Chapter as ChapterRepo;
use App\Services\LiveNotify as LiveNotifyService; use App\Services\LiveNotify as LiveNotifyService;
use App\Services\Smser\Live as LiveSmser; use App\Services\Smser\Live as LiveSmser;
use Phalcon\Cli\Task;
class LiveNotifyTask extends Task class LiveNotifyTask extends Task
{ {
/**
* @var RedisCache
*/
protected $cache;
/**
* @var \Redis
*/
protected $redis;
public function mainAction() public function mainAction()
{ {
$this->cache = $this->getDI()->get('cache'); $cache = $this->getCache();
$this->redis = $this->cache->getRedis(); $redis = $cache->getRedis();
$service = new LiveNotifyService(); $service = new LiveNotifyService();
$key = $service->getNotifyKey(); $key = $service->getNotifyKey();
$chapterIds = $this->redis->sMembers($key); $chapterIds = $redis->sMembers($key);
if (!$chapterIds) return; if (!$chapterIds) return;
$sentKey = $service->getSentNotifyKey(); $sentKey = $service->getSentNotifyKey();
$sentChapterIds = $this->redis->sMembers($sentKey); $sentChapterIds = $redis->sMembers($sentKey);
foreach ($chapterIds as $chapterId) { foreach ($chapterIds as $chapterId) {
if (!in_array($chapterId, $sentChapterIds)) { if (!in_array($chapterId, $sentChapterIds)) {
$this->sendNotification($chapterId); $this->sendNotification($chapterId);
} else { } else {
$this->redis->sAdd($sentKey, $chapterId); $redis->sAdd($sentKey, $chapterId);
} }
} }
if ($this->redis->sCard($sentKey) == 1) { if ($redis->sCard($sentKey) == 1) {
$this->redis->expire($sentKey, 86400); $redis->expire($sentKey, 86400);
} }
} }
@ -74,9 +62,6 @@ class LiveNotifyTask extends Task
protected function findTargetUserIds($courseId) protected function findTargetUserIds($courseId)
{ {
/**
* 只给付费和vip用户发通知
*/
$sourceTypes = [ $sourceTypes = [
CourseUserModel::SOURCE_CHARGE, CourseUserModel::SOURCE_CHARGE,
CourseUserModel::SOURCE_VIP, CourseUserModel::SOURCE_VIP,
@ -88,11 +73,11 @@ class LiveNotifyTask extends Task
->inWhere('source_type', $sourceTypes) ->inWhere('source_type', $sourceTypes)
->execute(); ->execute();
if ($rows->count() > 0) { if ($rows->count() == 0) {
return kg_array_column($rows->toArray(), 'user_id'); return [];
} }
return []; return kg_array_column($rows->toArray(), 'user_id');
} }
} }

View File

@ -2,149 +2,31 @@
namespace App\Console\Tasks; namespace App\Console\Tasks;
use App\Caches\Setting as SettingCache; use App\Caches\IndexFreeCourseList as IndexFreeCourseListCache;
use App\Library\Cache\Backend\Redis as RedisCache; use App\Caches\IndexNewCourseList as IndexNewCourseListCache;
use App\Models\Setting as SettingModel; use App\Caches\IndexVipCourseList as IndexVipCourseListCache;
use Phalcon\Cli\Task;
use Phalcon\Config;
class MaintainTask extends Task class MaintainTask extends Task
{ {
public function mainAction() public function rebuildIndexCourseCacheAction($params)
{ {
$this->resetSettingAction(); $section = $params[0] ?? null;
$this->resetAnnotationAction();
$this->resetMetadataAction();
$this->resetVoltAction();
}
/** if (!$section || $section == 'new_course') {
* 重置设置 $cache = new IndexNewCourseListCache();
* $cache->rebuild();
* @command: php console.php maintain reset_setting
*/
public function resetSettingAction()
{
echo "start reset setting..." . PHP_EOL;
$rows = SettingModel::query()->columns('section')->distinct(true)->execute();
foreach ($rows as $row) {
$cache = new SettingCache();
$cache->rebuild($row->section);
} }
echo "end reset setting..." . PHP_EOL; if (!$section || $section == 'free_course') {
} $cache = new IndexFreeCourseListCache();
$cache->rebuild();
/**
* 重置注解
*
* @command: php console.php maintain reset_annotation
*/
public function resetAnnotationAction()
{
$config = $this->getConfig();
$cache = $this->getCache();
$redis = $cache->getRedis();
$dbIndex = $config->path('annotation.db');
$statsKey = $config->path('annotation.statsKey');
$redis->select($dbIndex);
$keys = $redis->sMembers($statsKey);
echo "start reset annotation..." . PHP_EOL;
if (count($keys) > 0) {
$keys = $this->handlePhKeys($keys);
$redis->del(...$keys);
$redis->del($statsKey);
} }
echo "end reset annotation..." . PHP_EOL; if (!$section || $section == 'vip_course') {
} $cache = new IndexVipCourseListCache();
$cache->rebuild();
/**
* 重置元数据
*
* @command: php console.php maintain reset_metadata
*/
public function resetMetadataAction()
{
$config = $this->getConfig();
$cache = $this->getCache();
$redis = $cache->getRedis();
$dbIndex = $config->path('metadata.db');
$statsKey = $config->path('metadata.statsKey');
$redis->select($dbIndex);
$keys = $redis->sMembers($statsKey);
echo "start reset metadata..." . PHP_EOL;
if (count($keys) > 0) {
$keys = $this->handlePhKeys($keys);
$redis->del(...$keys);
$redis->del($statsKey);
} }
echo "start reset metadata..." . PHP_EOL;
}
/**
* 重置模板
*
* @command: php console.php maintain reset_volt
*/
public function resetVoltAction()
{
echo "start reset volt..." . PHP_EOL;
$dir = cache_path('volt');
foreach (scandir($dir) as $file) {
if (strpos($file, '.php')) {
unlink($dir . '/' . $file);
}
}
echo "end reset volt..." . PHP_EOL;
}
protected function getConfig()
{
/**
* @var Config $config
*/
$config = $this->getDI()->get('config');
return $config;
}
protected function getCache()
{
/**
* @var RedisCache $cache
*/
$cache = $this->getDI()->get('cache');
return $cache;
}
protected function handlePhKeys($keys)
{
return array_map(function ($key) {
return "_PHCR{$key}";
}, $keys);
} }
} }

View File

@ -111,7 +111,6 @@ class RefundTask extends Task
$task->update(); $task->update();
$logger->info('Refund Task Exception ' . kg_json_encode([ $logger->info('Refund Task Exception ' . kg_json_encode([
'line' => $e->getLine(),
'code' => $e->getCode(), 'code' => $e->getCode(),
'message' => $e->getMessage(), 'message' => $e->getMessage(),
'task' => $task->toArray(), 'task' => $task->toArray(),

View File

@ -3,7 +3,6 @@
namespace App\Console\Tasks; namespace App\Console\Tasks;
use App\Models\User as UserModel; use App\Models\User as UserModel;
use Phalcon\Cli\Task;
use Phalcon\Mvc\Model\Resultset; use Phalcon\Mvc\Model\Resultset;
use Phalcon\Mvc\Model\ResultsetInterface; use Phalcon\Mvc\Model\ResultsetInterface;

View File

@ -51,7 +51,7 @@ class SiteMapTask extends Task
$settings = $service->getSectionSettings('site'); $settings = $service->getSectionSettings('site');
return $settings['base_url'] ?? ''; return $settings['url'] ?? '';
} }
protected function addIndex() protected function addIndex()
@ -62,7 +62,7 @@ class SiteMapTask extends Task
protected function addCourses() protected function addCourses()
{ {
/** /**
* @var Resultset $courses * @var Resultset|CourseModel[] $courses
*/ */
$courses = CourseModel::query()->where('published = 1')->execute(); $courses = CourseModel::query()->where('published = 1')->execute();

View File

@ -2,7 +2,6 @@
namespace App\Console\Tasks; namespace App\Console\Tasks;
use App\Library\Cache\Backend\Redis as RedisCache;
use App\Repos\Course as CourseRepo; use App\Repos\Course as CourseRepo;
use App\Services\Search\CourseDocument; use App\Services\Search\CourseDocument;
use App\Services\Search\CourseSearcher; use App\Services\Search\CourseSearcher;
@ -11,30 +10,15 @@ use App\Services\Syncer\CourseIndex as CourseIndexSyncer;
class SyncCourseIndexTask extends Task class SyncCourseIndexTask extends Task
{ {
/**
* @var RedisCache
*/
protected $cache;
/**
* @var \Redis
*/
protected $redis;
public function mainAction() public function mainAction()
{ {
$this->cache = $this->getDI()->get('cache'); $cache = $this->getCache();
$this->redis = $this->cache->getRedis(); $redis = $cache->getRedis();
$this->rebuild();
}
protected function rebuild()
{
$key = $this->getSyncKey(); $key = $this->getSyncKey();
$courseIds = $this->redis->sRandMember($key, 1000); $courseIds = $redis->sRandMember($key, 1000);
if (!$courseIds) return; if (!$courseIds) return;
@ -42,9 +26,7 @@ class SyncCourseIndexTask extends Task
$courses = $courseRepo->findByIds($courseIds); $courses = $courseRepo->findByIds($courseIds);
if ($courses->count() == 0) { if ($courses->count() == 0) return;
return;
}
$document = new CourseDocument(); $document = new CourseDocument();
@ -67,7 +49,7 @@ class SyncCourseIndexTask extends Task
$index->closeBuffer(); $index->closeBuffer();
$this->redis->sRem($key, ...$courseIds); $redis->sRem($key, ...$courseIds);
} }
protected function getSyncKey() protected function getSyncKey()

View File

@ -2,7 +2,6 @@
namespace App\Console\Tasks; namespace App\Console\Tasks;
use App\Library\Cache\Backend\Redis as RedisCache;
use App\Repos\ImGroup as GroupRepo; use App\Repos\ImGroup as GroupRepo;
use App\Services\Search\GroupDocument; use App\Services\Search\GroupDocument;
use App\Services\Search\GroupSearcher; use App\Services\Search\GroupSearcher;
@ -11,30 +10,15 @@ use App\Services\Syncer\GroupIndex as GroupIndexSyncer;
class SyncGroupIndexTask extends Task class SyncGroupIndexTask extends Task
{ {
/**
* @var RedisCache
*/
protected $cache;
/**
* @var \Redis
*/
protected $redis;
public function mainAction() public function mainAction()
{ {
$this->cache = $this->getDI()->get('cache'); $cache = $this->getCache();
$this->redis = $this->cache->getRedis(); $redis = $cache->getRedis();
$this->rebuild();
}
protected function rebuild()
{
$key = $this->getSyncKey(); $key = $this->getSyncKey();
$groupIds = $this->redis->sRandMember($key, 1000); $groupIds = $redis->sRandMember($key, 1000);
if (!$groupIds) return; if (!$groupIds) return;
@ -42,9 +26,7 @@ class SyncGroupIndexTask extends Task
$groups = $groupRepo->findByIds($groupIds); $groups = $groupRepo->findByIds($groupIds);
if ($groups->count() == 0) { if ($groups->count() == 0) return;
return;
}
$document = new GroupDocument(); $document = new GroupDocument();
@ -67,7 +49,7 @@ class SyncGroupIndexTask extends Task
$index->closeBuffer(); $index->closeBuffer();
$this->redis->sRem($key, ...$groupIds); $redis->sRem($key, ...$groupIds);
} }
protected function getSyncKey() protected function getSyncKey()

View File

@ -2,7 +2,6 @@
namespace App\Console\Tasks; namespace App\Console\Tasks;
use App\Library\Cache\Backend\Redis as RedisCache;
use App\Models\Course as CourseModel; use App\Models\Course as CourseModel;
use App\Models\Learning as LearningModel; use App\Models\Learning as LearningModel;
use App\Repos\Chapter as ChapterRepo; use App\Repos\Chapter as ChapterRepo;
@ -11,32 +10,21 @@ use App\Repos\Course as CourseRepo;
use App\Repos\CourseUser as CourseUserRepo; use App\Repos\CourseUser as CourseUserRepo;
use App\Repos\Learning as LearningRepo; use App\Repos\Learning as LearningRepo;
use App\Services\Syncer\Learning as LearningSyncer; use App\Services\Syncer\Learning as LearningSyncer;
use Phalcon\Cli\Task;
class SyncLearningTask extends Task class SyncLearningTask extends Task
{ {
/**
* @var RedisCache
*/
protected $cache;
/**
* @var \Redis
*/
protected $redis;
public function mainAction() public function mainAction()
{ {
$this->cache = $this->getDI()->get('cache'); $cache = $this->getCache();
$this->redis = $this->cache->getRedis(); $redis = $cache->getRedis();
$syncer = new LearningSyncer(); $syncer = new LearningSyncer();
$syncKey = $syncer->getSyncKey(); $syncKey = $syncer->getSyncKey();
$requestIds = $this->redis->sMembers($syncKey); $requestIds = $redis->sMembers($syncKey);
if (!$requestIds) return; if (!$requestIds) return;
@ -46,7 +34,7 @@ class SyncLearningTask extends Task
$this->handleLearning($itemKey); $this->handleLearning($itemKey);
$this->redis->sRem($syncKey, $requestId); $redis->sRem($syncKey, $requestId);
} }
} }
@ -153,15 +141,11 @@ class SyncLearningTask extends Task
$courseLessons = $courseRepo->findLessons($learning->course_id); $courseLessons = $courseRepo->findLessons($learning->course_id);
if ($courseLessons->count() == 0) { if ($courseLessons->count() == 0) return;
return;
}
$userLearnings = $courseRepo->findUserLearnings($learning->course_id, $learning->user_id, $learning->plan_id); $userLearnings = $courseRepo->findUserLearnings($learning->course_id, $learning->user_id, $learning->plan_id);
if ($userLearnings->count() == 0) { if ($userLearnings->count() == 0) return;
return;
}
$consumedUserLearnings = []; $consumedUserLearnings = [];
@ -171,9 +155,7 @@ class SyncLearningTask extends Task
} }
} }
if (count($consumedUserLearnings) == 0) { if (count($consumedUserLearnings) == 0) return;
return;
}
$duration = 0; $duration = 0;

View File

@ -2,7 +2,6 @@
namespace App\Console\Tasks; namespace App\Console\Tasks;
use App\Library\Cache\Backend\Redis as RedisCache;
use App\Repos\User as UserRepo; use App\Repos\User as UserRepo;
use App\Services\Search\UserDocument; use App\Services\Search\UserDocument;
use App\Services\Search\UserSearcher; use App\Services\Search\UserSearcher;
@ -11,30 +10,15 @@ use App\Services\Syncer\UserIndex as UserIndexSyncer;
class SyncUserIndexTask extends Task class SyncUserIndexTask extends Task
{ {
/**
* @var RedisCache
*/
protected $cache;
/**
* @var \Redis
*/
protected $redis;
public function mainAction() public function mainAction()
{ {
$this->cache = $this->getDI()->get('cache'); $cache = $this->getCache();
$this->redis = $this->cache->getRedis(); $redis = $cache->getRedis();
$this->rebuild();
}
protected function rebuild()
{
$key = $this->getSyncKey(); $key = $this->getSyncKey();
$userIds = $this->redis->sRandMember($key, 1000); $userIds = $redis->sRandMember($key, 1000);
if (!$userIds) return; if (!$userIds) return;
@ -42,9 +26,7 @@ class SyncUserIndexTask extends Task
$users = $userRepo->findByIds($userIds); $users = $userRepo->findByIds($userIds);
if ($users->count() == 0) { if ($users->count() == 0) return;
return;
}
$document = new UserDocument(); $document = new UserDocument();
@ -67,7 +49,7 @@ class SyncUserIndexTask extends Task
$index->closeBuffer(); $index->closeBuffer();
$this->redis->sRem($key, ...$userIds); $redis->sRem($key, ...$userIds);
} }
protected function getSyncKey() protected function getSyncKey()

View File

@ -2,14 +2,38 @@
namespace App\Console\Tasks; namespace App\Console\Tasks;
use App\Library\Logger; use App\Library\Cache\Backend\Redis as RedisCache;
use App\Library\Logger as AppLogger;
use Phalcon\Config as PhConfig;
use Phalcon\Logger\Adapter\File as PhLogger;
class Task extends \Phalcon\Cli\Task class Task extends \Phalcon\Cli\Task
{ {
/**
* @return PhConfig
*/
public function getConfig()
{
return $this->getDI()->get('config');
}
/**
* @return RedisCache
*/
public function getCache()
{
return $this->getDI()->get('cache');
}
/**
* @param null $channel
* @return PhLogger
*/
public function getLogger($channel = null) public function getLogger($channel = null)
{ {
$logger = new Logger(); $logger = new AppLogger();
return $logger->getInstance($channel); return $logger->getInstance($channel);
} }

View File

@ -3,7 +3,6 @@
namespace App\Console\Tasks; namespace App\Console\Tasks;
use App\Models\User as UserModel; use App\Models\User as UserModel;
use Phalcon\Cli\Task;
use Phalcon\Mvc\Model\Resultset; use Phalcon\Mvc\Model\Resultset;
use Phalcon\Mvc\Model\ResultsetInterface; use Phalcon\Mvc\Model\ResultsetInterface;
@ -14,13 +13,10 @@ class UnlockUserTask extends Task
{ {
$users = $this->findUsers(); $users = $this->findUsers();
if ($users->count() == 0) { if ($users->count() == 0) return;
return;
}
foreach ($users as $user) { foreach ($users as $user) {
$user->locked = 0; $user->update(['locked' => 0]);
$user->update();
} }
} }

View File

@ -0,0 +1,127 @@
<?php
namespace App\Console\Tasks;
use App\Caches\Setting as SettingCache;
use App\Models\Setting as SettingModel;
class UpgradeTask extends Task
{
public function mainAction()
{
$this->resetSettingAction();
$this->resetAnnotationAction();
$this->resetMetadataAction();
$this->resetVoltAction();
}
/**
* 重置系统设置
*
* @command: php console.php upgrade reset_setting
*/
public function resetSettingAction()
{
echo "start reset setting..." . PHP_EOL;
$rows = SettingModel::query()->columns('section')->distinct(true)->execute();
foreach ($rows as $row) {
$cache = new SettingCache();
$cache->rebuild($row->section);
}
echo "end reset setting..." . PHP_EOL;
}
/**
* 重置注解
*
* @command: php console.php upgrade reset_annotation
*/
public function resetAnnotationAction()
{
$config = $this->getConfig();
$cache = $this->getCache();
$redis = $cache->getRedis();
$dbIndex = $config->path('annotation.db');
$statsKey = $config->path('annotation.statsKey');
$redis->select($dbIndex);
$keys = $redis->sMembers($statsKey);
echo "start reset annotation..." . PHP_EOL;
if (count($keys) > 0) {
$keys = $this->handlePhKeys($keys);
$redis->del(...$keys);
$redis->del($statsKey);
}
echo "end reset annotation..." . PHP_EOL;
}
/**
* 重置元数据
*
* @command: php console.php upgrade reset_metadata
*/
public function resetMetadataAction()
{
$config = $this->getConfig();
$cache = $this->getCache();
$redis = $cache->getRedis();
$dbIndex = $config->path('metadata.db');
$statsKey = $config->path('metadata.statsKey');
$redis->select($dbIndex);
$keys = $redis->sMembers($statsKey);
echo "start reset metadata..." . PHP_EOL;
if (count($keys) > 0) {
$keys = $this->handlePhKeys($keys);
$redis->del(...$keys);
$redis->del($statsKey);
}
echo "start reset metadata..." . PHP_EOL;
}
/**
* 重置模板
*
* @command: php console.php upgrade reset_volt
*/
public function resetVoltAction()
{
echo "start reset volt..." . PHP_EOL;
$dir = cache_path('volt');
foreach (scandir($dir) as $file) {
if (strpos($file, '.php')) {
unlink($dir . '/' . $file);
}
}
echo "end reset volt..." . PHP_EOL;
}
protected function handlePhKeys($keys)
{
return array_map(function ($key) {
return "_PHCR{$key}";
}, $keys);
}
}

View File

@ -5,7 +5,6 @@ namespace App\Console\Tasks;
use App\Models\User as UserModel; use App\Models\User as UserModel;
use App\Services\Search\UserDocument; use App\Services\Search\UserDocument;
use App\Services\Search\UserSearcher; use App\Services\Search\UserSearcher;
use Phalcon\Cli\Task;
use Phalcon\Mvc\Model\Resultset; use Phalcon\Mvc\Model\Resultset;
use Phalcon\Mvc\Model\ResultsetInterface; use Phalcon\Mvc\Model\ResultsetInterface;
@ -24,7 +23,7 @@ class UserIndexTask extends Task
$query = $params[0] ?? null; $query = $params[0] ?? null;
if (!$query) { if (!$query) {
exit("please special a query word" . PHP_EOL); exit('please special a query word' . PHP_EOL);
} }
$result = $this->searchUsers($query); $result = $this->searchUsers($query);
@ -61,11 +60,11 @@ class UserIndexTask extends Task
$index = $handler->getXS()->getIndex(); $index = $handler->getXS()->getIndex();
echo "start clean index" . PHP_EOL; echo 'start clean index' . PHP_EOL;
$index->clean(); $index->clean();
echo "end clean index" . PHP_EOL; echo 'end clean index' . PHP_EOL;
} }
/** /**
@ -75,9 +74,7 @@ class UserIndexTask extends Task
{ {
$users = $this->findUsers(); $users = $this->findUsers();
if ($users->count() == 0) { if ($users->count() == 0) return;
return;
}
$handler = new UserSearcher(); $handler = new UserSearcher();
@ -85,7 +82,7 @@ class UserIndexTask extends Task
$index = $handler->getXS()->getIndex(); $index = $handler->getXS()->getIndex();
echo "start rebuild index" . PHP_EOL; echo 'start rebuild index' . PHP_EOL;
$index->beginRebuild(); $index->beginRebuild();
@ -96,7 +93,7 @@ class UserIndexTask extends Task
$index->endRebuild(); $index->endRebuild();
echo "end rebuild index" . PHP_EOL; echo 'end rebuild index' . PHP_EOL;
} }
/** /**

View File

@ -6,7 +6,6 @@ use App\Models\Chapter as ChapterModel;
use App\Repos\Chapter as ChapterRepo; use App\Repos\Chapter as ChapterRepo;
use App\Services\CourseStat as CourseStatService; use App\Services\CourseStat as CourseStatService;
use App\Services\Vod as VodService; use App\Services\Vod as VodService;
use Phalcon\Cli\Task;
class VodEventTask extends Task class VodEventTask extends Task
{ {

View File

@ -10,6 +10,7 @@ use App\Models\User as UserModel;
use App\Services\Auth\Desktop as DesktopAuth; use App\Services\Auth\Desktop as DesktopAuth;
use App\Traits\Response as ResponseTrait; use App\Traits\Response as ResponseTrait;
use App\Traits\Security as SecurityTrait; use App\Traits\Security as SecurityTrait;
use Phalcon\Config;
use Phalcon\Mvc\Dispatcher; use Phalcon\Mvc\Dispatcher;
class Controller extends \Phalcon\Mvc\Controller class Controller extends \Phalcon\Mvc\Controller
@ -120,13 +121,32 @@ class Controller extends \Phalcon\Mvc\Controller
{ {
$cache = new SettingCache(); $cache = new SettingCache();
$websocket = $this->getConfig()->get('websocket');
/**
* ssl通过nginx转发实现
*/
if ($this->request->isSecure()) {
$websocket->connect_url = sprintf('wss://%s/wss', $this->request->getHttpHost());
} else {
$websocket->connect_url = sprintf('ws://%s', $websocket->connect_address);
}
return [ return [
'main' => $cache->get('im.main'), 'main' => $cache->get('im.main'),
'cs' => $cache->get('im.cs'), 'cs' => $cache->get('im.cs'),
'websocket' => $this->config->websocket, 'websocket' => $websocket,
]; ];
} }
/**
* @return Config
*/
protected function getConfig()
{
return $this->getDI()->get('config');
}
protected function checkSiteStatus() protected function checkSiteStatus()
{ {
if ($this->siteInfo['enabled'] == 0) { if ($this->siteInfo['enabled'] == 0) {

View File

@ -21,7 +21,7 @@ class SearchController extends Controller
public function indexAction() public function indexAction()
{ {
$query = $this->request->get('query', ['trim', 'string']); $query = $this->request->get('query', ['trim', 'string']);
$type = $this->request->get('type', ['trim'], 'course'); $type = $this->request->get('type', ['trim', 'string'], 'course');
if (empty($query)) { if (empty($query)) {
return $this->response->redirect(['for' => 'desktop.course.list']); return $this->response->redirect(['for' => 'desktop.course.list']);
@ -31,9 +31,9 @@ class SearchController extends Controller
$service = $this->getSearchService($type); $service = $this->getSearchService($type);
$hotQueries = $service->hotQuery(); $hotQueries = $service->getHotQuery();
$relatedQueries = $service->relatedQuery($query); $relatedQueries = $service->getRelatedQuery($query);
$pager = $service->search(); $pager = $service->search();

View File

@ -341,9 +341,9 @@ class Im extends Service
protected function getRegisterAddress() protected function getRegisterAddress()
{ {
$config = $this->getDI()->get('config'); $config = $this->getConfig();
return $config->websocket->register_address; return $config->path('websocket.register_address');
} }
} }

View File

@ -15,7 +15,7 @@ class Live extends Service
{ {
$redis = $this->getRedis(); $redis = $this->getRedis();
$key = $this->getRedisListKey($id); $key = $this->getRecentChatKey($id);
$redis->expire($key, 3 * 3600); $redis->expire($key, 3 * 3600);
@ -132,12 +132,12 @@ class Live extends Service
protected function getRegisterAddress() protected function getRegisterAddress()
{ {
$config = $this->getDI()->get('config'); $config = $this->getConfig();
return $config->websocket->register_address; return $config->path('websocket.register_address');
} }
protected function getRedisListKey($id) protected function getRecentChatKey($id)
{ {
return "live_recent_chat:{$id}"; return "live_recent_chat:{$id}";
} }

View File

@ -21,7 +21,8 @@
enabled: '{{ im_info.cs.enabled }}' enabled: '{{ im_info.cs.enabled }}'
}, },
websocket: { websocket: {
url: '{{ im_info.websocket.url }}' connect_url: '{{ im_info.websocket.connect_url }}',
ping_interval: '{{ im_info.websocket.ping_interval }}'
} }
}; };

View File

@ -3,7 +3,7 @@
namespace App\Library; namespace App\Library;
use Phalcon\Di; use Phalcon\Di;
use Phalcon\Logger as PhalconLogger; use Phalcon\Logger as PhLogger;
use Phalcon\Logger\Adapter\File as FileLogger; use Phalcon\Logger\Adapter\File as FileLogger;
class Logger class Logger
@ -23,7 +23,7 @@ class Logger
$path = log_path($filename); $path = log_path($filename);
$level = $config->env != ENV_DEV ? $config->log->level : PhalconLogger::DEBUG; $level = $config->env != ENV_DEV ? $config->log->level : PhLogger::DEBUG;
$logger = new FileLogger($path); $logger = new FileLogger($path);

View File

@ -4,10 +4,9 @@ namespace App\Services\Frontend\Search;
use App\Library\Paginator\Adapter\XunSearch as XunSearchPaginator; use App\Library\Paginator\Adapter\XunSearch as XunSearchPaginator;
use App\Library\Paginator\Query as PagerQuery; use App\Library\Paginator\Query as PagerQuery;
use App\Services\Frontend\Service as FrontendService;
use App\Services\Search\CourseSearcher as CourseSearcherService; use App\Services\Search\CourseSearcher as CourseSearcherService;
class Course extends FrontendService class Course extends Handler
{ {
public function search() public function search()
@ -33,14 +32,14 @@ class Course extends FrontendService
return $this->handleCourses($pager); return $this->handleCourses($pager);
} }
public function hotQuery($limit = 10, $type = 'total') public function getHotQuery($limit = 10, $type = 'total')
{ {
$searcher = new CourseSearcherService(); $searcher = new CourseSearcherService();
return $searcher->getHotQuery($limit, $type); return $searcher->getHotQuery($limit, $type);
} }
public function relatedQuery($query, $limit = 10) public function getRelatedQuery($query, $limit = 10)
{ {
$searcher = new CourseSearcherService(); $searcher = new CourseSearcherService();

View File

@ -4,10 +4,9 @@ namespace App\Services\Frontend\Search;
use App\Library\Paginator\Adapter\XunSearch as XunSearchPaginator; use App\Library\Paginator\Adapter\XunSearch as XunSearchPaginator;
use App\Library\Paginator\Query as PagerQuery; use App\Library\Paginator\Query as PagerQuery;
use App\Services\Frontend\Service as FrontendService;
use App\Services\Search\GroupSearcher as GroupSearcherService; use App\Services\Search\GroupSearcher as GroupSearcherService;
class Group extends FrontendService class Group extends Handler
{ {
public function search() public function search()
@ -33,14 +32,14 @@ class Group extends FrontendService
return $this->handleGroups($pager); return $this->handleGroups($pager);
} }
public function hotQuery($limit = 10, $type = 'total') public function getHotQuery($limit = 10, $type = 'total')
{ {
$searcher = new GroupSearcherService(); $searcher = new GroupSearcherService();
return $searcher->getHotQuery($limit, $type); return $searcher->getHotQuery($limit, $type);
} }
public function relatedQuery($query, $limit = 10) public function getRelatedQuery($query, $limit = 10)
{ {
$searcher = new GroupSearcherService(); $searcher = new GroupSearcherService();

View File

@ -0,0 +1,16 @@
<?php
namespace App\Services\Frontend\Search;
use App\Services\Frontend\Service as FrontendService;
abstract class Handler extends FrontendService
{
abstract function search();
abstract function getHotQuery($limit, $type);
abstract function getRelatedQuery($query, $limit);
}

View File

@ -4,10 +4,9 @@ namespace App\Services\Frontend\Search;
use App\Library\Paginator\Adapter\XunSearch as XunSearchPaginator; use App\Library\Paginator\Adapter\XunSearch as XunSearchPaginator;
use App\Library\Paginator\Query as PagerQuery; use App\Library\Paginator\Query as PagerQuery;
use App\Services\Frontend\Service as FrontendService;
use App\Services\Search\UserSearcher as UserSearcherService; use App\Services\Search\UserSearcher as UserSearcherService;
class User extends FrontendService class User extends Handler
{ {
public function search() public function search()
@ -33,14 +32,14 @@ class User extends FrontendService
return $this->handleUsers($pager); return $this->handleUsers($pager);
} }
public function hotQuery($limit = 10, $type = 'total') public function getHotQuery($limit = 10, $type = 'total')
{ {
$searcher = new UserSearcherService(); $searcher = new UserSearcherService();
return $searcher->getHotQuery($limit, $type); return $searcher->getHotQuery($limit, $type);
} }
public function relatedQuery($query, $limit = 10) public function getRelatedQuery($query, $limit = 10)
{ {
$searcher = new UserSearcherService(); $searcher = new UserSearcherService();

View File

@ -3,9 +3,11 @@
namespace App\Services; namespace App\Services;
use App\Caches\Setting as SettingCache; use App\Caches\Setting as SettingCache;
use App\Library\Cache\Backend\Redis as RedisCache;
use App\Library\Logger as AppLogger; use App\Library\Logger as AppLogger;
use App\Traits\Auth as AuthTrait; use App\Traits\Auth as AuthTrait;
use Phalcon\Logger\Adapter\File as FileLogger; use Phalcon\Config as PhConfig;
use Phalcon\Logger\Adapter\File as PhLogger;
use Phalcon\Mvc\User\Component; use Phalcon\Mvc\User\Component;
class Service extends Component class Service extends Component
@ -13,11 +15,27 @@ class Service extends Component
use AuthTrait; use AuthTrait;
/**
* @return PhConfig
*/
public function getConfig()
{
return $this->getDI()->get('config');
}
/**
* @return RedisCache
*/
public function getCache()
{
return $this->getDI()->get('cache');
}
/** /**
* 获取Logger * 获取Logger
* *
* @param string $channel * @param string $channel
* @return FileLogger * @return PhLogger
*/ */
public function getLogger($channel = null) public function getLogger($channel = null)
{ {

View File

@ -163,12 +163,17 @@ $config['throttle']['lifetime'] = 60;
$config['throttle']['rate_limit'] = 60; $config['throttle']['rate_limit'] = 60;
/** /**
* 客户端连接地址外部可访问的ip或域名 * 客户端ping服务端间隔
*/ */
$config['websocket']['url'] = 'ws://127.0.0.1:8282'; $config['websocket']['ping_interval'] = 50;
/** /**
* gateway和worker注册地址内部访问 * 客户端连接地址外部可访问的域名或ip带端口号
*/
$config['websocket']['connect_address'] = 'your_domain.com:8282';
/**
* gateway和worker注册地址带端口号
*/ */
$config['websocket']['register_address'] = '127.0.0.1:1238'; $config['websocket']['register_address'] = '127.0.0.1:1238';

View File

@ -3,7 +3,7 @@ layui.use(['jquery', 'form', 'helper'], function () {
var $ = layui.jquery; var $ = layui.jquery;
var form = layui.form; var form = layui.form;
var helper = layui.helper; var helper = layui.helper;
var socket = new WebSocket(window.im.websocket.url); var socket = new WebSocket(window.im.websocket.connect_url);
var bindUserUrl = $('input[name="bind_user_url"]').val(); var bindUserUrl = $('input[name="bind_user_url"]').val();
var liveStatsUrl = $('input[name="live_stats_url"]').val(); var liveStatsUrl = $('input[name="live_stats_url"]').val();
var $chatContent = $('input[name=content]'); var $chatContent = $('input[name=content]');
@ -13,7 +13,7 @@ layui.use(['jquery', 'form', 'helper'], function () {
console.log('socket connect success'); console.log('socket connect success');
setInterval(function () { setInterval(function () {
socket.send('ping'); socket.send('ping');
}, 30000); }, 1000 * parseInt(window.im.websocket.ping_interval));
}; };
socket.onclose = function () { socket.onclose = function () {

View File

@ -16,10 +16,13 @@ layui.use(['jquery', 'layim'], function () {
welcome: $('input[name="cs_user.welcome"]').val() welcome: $('input[name="cs_user.welcome"]').val()
}; };
var socket = new WebSocket(window.im.websocket.url); var socket = new WebSocket(window.im.websocket.connect_url);
socket.onopen = function () { socket.onopen = function () {
console.log('socket connect success'); console.log('socket connect success');
setInterval(function () {
socket.send('ping');
}, 1000 * parseInt(window.im.websocket.ping_interval));
}; };
socket.onclose = function () { socket.onclose = function () {
@ -33,9 +36,7 @@ layui.use(['jquery', 'layim'], function () {
socket.onmessage = function (e) { socket.onmessage = function (e) {
var data = JSON.parse(e.data); var data = JSON.parse(e.data);
console.log(data); console.log(data);
if (data.type === 'ping') { if (data.type === 'bind_user') {
socket.send('pong...');
} else if (data.type === 'bind_user') {
bindUser(data); bindUser(data);
} else if (data.type === 'show_chat_msg') { } else if (data.type === 'show_chat_msg') {
showChatMessage(data); showChatMessage(data);
@ -48,18 +49,18 @@ layui.use(['jquery', 'layim'], function () {
id: me.id, id: me.id,
username: me.name, username: me.name,
avatar: me.avatar, avatar: me.avatar,
status: 'online', status: 'online'
} }
}, },
brief: true, brief: true,
maxLength: 1000, maxLength: window.im.main.msg_max_length
}); });
layim.chat({ layim.chat({
id: csUser.id, id: csUser.id,
name: csUser.name, name: csUser.name,
avatar: csUser.avatar, avatar: csUser.avatar,
type: 'friend', type: 'friend'
}); });
layim.on('sendMessage', function (res) { layim.on('sendMessage', function (res) {
@ -95,7 +96,7 @@ layui.use(['jquery', 'layim'], function () {
avatar: csUser.avatar, avatar: csUser.avatar,
content: csUser.welcome, content: csUser.welcome,
timestamp: new Date().getTime(), timestamp: new Date().getTime(),
type: 'friend', type: 'friend'
}); });
} }

View File

@ -2,13 +2,14 @@ layui.use(['jquery', 'layim'], function () {
var $ = layui.jquery; var $ = layui.jquery;
var layim = layui.layim; var layim = layui.layim;
var socket = new WebSocket(window.im.websocket.url); var socket = new WebSocket(window.im.websocket.connect_url);
socket.onopen = function () { socket.onopen = function () {
console.log('socket connect success'); console.log('socket connect success');
setInterval(function () { setInterval(function () {
socket.send('ping'); socket.send('ping');
}, 30000); console.log('ping...');
}, 1000 * parseInt(window.im.websocket.ping_interval));
}; };
socket.onclose = function () { socket.onclose = function () {

View File

@ -23,7 +23,7 @@ require_once dirname(__DIR__) . '/vendor/autoload.php';
$worker = new BusinessWorker(); $worker = new BusinessWorker();
// worker名称 // worker名称
$worker->name = 'ChatBusinessWorker'; $worker->name = 'ImBusinessWorker';
// businessWorker进程数量 // businessWorker进程数量
$worker->count = 4; $worker->count = 4;

View File

@ -23,7 +23,7 @@ require_once dirname(__DIR__) . '/vendor/autoload.php';
$gateway = new Gateway("websocket://0.0.0.0:8282"); $gateway = new Gateway("websocket://0.0.0.0:8282");
// gateway名称status方便查看 // gateway名称status方便查看
$gateway->name = 'ChatGateway'; $gateway->name = 'ImGateway';
// gateway进程数 // gateway进程数
$gateway->count = 4; $gateway->count = 4;