Files
ulthon_information/app/index/controller/Post.php
2023-11-20 09:09:39 +08:00

112 lines
2.7 KiB
PHP

<?php
declare(strict_types=1);
namespace app\index\controller;
use app\model\Post as ModelPost;
use app\model\PostVisit;
use DeviceDetector\DeviceDetector;
use think\facade\Cache;
use think\facade\Db;
use think\facade\View;
use think\model\Relation;
class Post extends Common
{
public function initialize()
{
if ($this->request->action() != 'markVisit') {
parent::initialize();
}
}
/**
* 显示指定的资源.
*
* @param int $id
* @return \think\Response
*/
public function read($uid)
{
//
$cache_key = 'post_' . $uid;
$model_post = Cache::get($cache_key);
if (empty($model_post)) {
$model_post = ModelPost::with([
'comments' => function (Relation $query) {
$query->order('id asc');
},
])->where('uid', $uid)->find();
if (empty($model_post)) {
return $this->error('链接已失效', '/', 404);
}
Cache::set($cache_key, $model_post, 600);
}
$model_post->hits = Db::raw('hits + 1');
$model_post->save();
$list_last_visit = PostVisit::where('post_id', $model_post->id)
->order('id desc')
->group('ip,uid')
->limit(12)
->cache(60)
->select();
View::assign('post', $model_post);
View::assign('list_last_visit', $list_last_visit);
$model_visit = $this->recordVisit($model_post->id);
View::assign('model_visit', $model_visit);
return View::fetch();
}
public function recordVisit($post_id)
{
$model_visit = new PostVisit();
$model_visit->uid = $this->userinfo['uid'] ?? '';
$model_visit->post_id = $post_id;
$model_visit->avatar = $this->userinfo['avatar'] ?? '';
$model_visit->nickname = $this->userinfo['nickname'] ?? '';
$model_visit->ip = $this->request->ip();
$user_agent = $this->request->header('user-agent');
$dd = new DeviceDetector($user_agent);
$cache = Cache::instance();
$dd->setCache(
new \DeviceDetector\Cache\PSR16Bridge($cache)
);
$dd->parse();
$model_visit->client_bot = $dd->getBot() ?: '';
$model_visit->client = $dd->getClient();
$model_visit->client_os = $dd->getOs();
$model_visit->client_device_name = $dd->getDeviceName();
$model_visit->client_brand_name = $dd->getBrandName();
$model_visit->client_model = $dd->getModel();
$model_visit->save();
return $model_visit;
}
public function markVisit($visit_id)
{
PostVisit::where('id', $visit_id)->update(['is_js_run' => 1]);
return json_message();
}
}