| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- <?php
- namespace app\api\controller\user;
- use app\models\coin\UserCoinTransfer;
- use app\models\redis\SystemCarousel;
- use app\models\redis\UserHash;
- use app\models\system\DictCoin;
- use app\Request;
- use crmeb\services\JsonService;
- use think\facade\Config;
- use think\facade\Log;
- use think\facade\Cache;
- /**
- *
- * activities json 配置:
- mining:
- {
- "enabled": 1,
- "symbol": "btc",
- }
- * Class UserNotificationController
- * @package app\api\controller\user
- */
- class UserNotificationController {
- /**
- * 定时请求的状态接口
- * @param Request $request
- */
- public function snapshot(Request $request) {
- $uid = $request->uid();
- // 未读消息
- $unread = UserHash::unread_get($uid);
- // 是否开启挖矿
- $symbol = Config::get('app.mining_symbo');
- $icon = Cache::get($symbol);
- if (!$icon) {
- $icon = DictCoin::where('symbol', $symbol)->value('icon');
- Cache::set($symbol, $icon);
- }
- $defStatus = [
- 'progress'=> 0,
- 'symbol'=>$symbol,
- 'icon'=>$icon,
- 'total'=> 0,
- 'ts' => time(),
- ];
- if ($symbol) {
- $mymining = UserHash::mining_get($uid) ?? $defStatus;
- if ($mymining['progress'] > 0) {
- $mining = $this->calcMining($uid, $mymining);
- UserHash::mining_set($uid, $mining);
- }
- }
- // 跑马灯
- $carousel = SystemCarousel::getFirst(20);
- return app('json')->successful(compact('unread', 'mining', 'carousel'));
- }
- /**
- * 根据上次挖矿状态, 和过去的时长, 计算当前的状态
- * @param $p
- * @return mixed
- */
- protected function calcMining($uid, $p) {
- if ($p['progress'] <= 0) {
- return $p;
- }
- if (!isset($p['ts'])) {
- return $p;
- }
- $now = time();
- $secs_passed = $now - $p['ts'];
- $secs_unit = Config::get('app.mining_sec_unit');
- $reward_unit = Config::get('app.mining_num_per_unit');
- $hours = Config::get('app.mining_time');
- if (count($hours) != 2 || $hours[0] > $hours[1]) {
- Log::warning('app.mining_time config error.');
- return $p;
- }
- $hour = random_int($hours[0], $hours[1]);
- $secs = $hour * 60 * 60;
- //
- if ($secs_passed >= $secs) { // 挖矿结束
- $p['progress'] = 0;
- // 本次个数
- $count = floatval(bcmul(bcdiv($secs, $secs_unit, 8), $reward_unit, 8));
- // save to database
- if (!UserCoinTransfer::addMining($uid, $p['order_id'], $p['symbol'], $count)) {
- Log::error("user<$uid> save transfer failed, amount<$count>");
- }
- $p['total'] += $count;
- return $p;
- }
- $count = floatval(bcmul(bcdiv($secs_passed, $secs_unit, 8), $reward_unit, 8));
- $p['progress'] = $count;
- return $p;
- }
- }
|