Redpack.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. <?php
  2. /**
  3. * 红包
  4. * @author solu
  5. */
  6. class Redpack extends Model {
  7. protected $tableName = 'redpack';
  8. protected $dbKey = 'dw_chat';
  9. const REDIS_PRE_REDPACK_REWARD_LIST = 'mee:redpack_reward_list:';
  10. const REWARD_LIST_TTL = 86400 - 120; // 提前两分钟结束
  11. const MONEY_MIN_AVG = 1;
  12. const TEAM_DEDUCT = 0.02; // 团队提成
  13. const STATUS_PLAYING = 0; // 进行中
  14. const STATUS_FINISH = 1; // 已抢完
  15. const STATUS_TIMEOUT = 2; // 超时关闭
  16. private static function getRewardListKey($trxId) {
  17. return self::REDIS_PRE_REDPACK_REWARD_LIST . $trxId;
  18. }
  19. private function getTokenType($redpack) {
  20. $parts = explode(' ', $redpack['quantity_total']);
  21. $tokenType = strtoupper($parts[1]);
  22. return $tokenType;
  23. }
  24. private function checkValidType($redpack) {
  25. $tokenType = $this->getTokenType($redpack);
  26. if ($redpack['code'] == 'eosio.token' && in_array($tokenType, ['EOS', 'MEETONE'])) {
  27. return true;
  28. }
  29. // 检查是否乱发红包
  30. $parts = explode('-', $redpack['session_id']);
  31. if (count($parts) > 1) {
  32. // 个人转账只能转EOS
  33. return false;
  34. }
  35. $group_id = (int) $redpack['session_id'];
  36. $objGroupEos = new TableHelper('group_eos', 'dw_chat');
  37. $row = $objGroupEos->getRow(compact('group_id'));
  38. if ($row['token_code'] == $redpack['code'] && $row['token'] == $tokenType) {
  39. return true;
  40. } else {
  41. return false;
  42. }
  43. }
  44. /**
  45. * 初始化红包
  46. * @author solu
  47. * @param $redpack Redpack
  48. * @param null $objRedis
  49. * @param $netId
  50. * @return bool
  51. */
  52. public function initReward($redpack, $objRedis = null, $netId = Eos::NET_EOS) {
  53. $trxId = $redpack['transfer_trx_id'];
  54. $total = $redpack['quantity_total_int'];
  55. $num = $redpack['num_total'];
  56. // 检查红包类型是否正确
  57. $flag = $this->checkValidType($redpack);
  58. if (!$flag) {
  59. alermErrorMsg("trxId:{$trxId}, quantity_total:{$redpack['quantity_total']}, num:{$num} 发送的红包类型错误");
  60. return false;
  61. }
  62. !$objRedis && $objRedis = dwRedis::init(Eos::REDIS_SERV);
  63. $key = self::getRewardListKey($trxId);
  64. if (($total/$num) < self::MONEY_MIN_AVG) {
  65. alermErrorMsg("trxId:{$trxId}, total:{$total}, num:{$num} 平均红包金额太小");
  66. return false;
  67. }
  68. $objRedis->del($key);
  69. $total -= $total * self::TEAM_DEDUCT;
  70. $list = self::_makeRandomArr($total, $num);
  71. array_unshift($list, $key);
  72. call_user_func_array([$objRedis, 'lPush'], $list);
  73. $objRedis->expire($key, self::REWARD_LIST_TTL);
  74. $tokenType = $this->getTokenType($redpack);
  75. self::redpackEvent($redpack['session_id'], $redpack['sender'], $trxId, $redpack['memo'], $tokenType, $netId);
  76. return true;
  77. }
  78. private static function redpackEvent($sessionId, $sender, $trxId, $title, $tokenType = 'EOS', $netId = Eos::NET_EOS) {
  79. $objUserBindInfo = new UserBindInfo();
  80. $accountType = Eos::getNetAccount($netId);
  81. $userId = $objUserBindInfo->getUserIdBy($sender, $accountType);
  82. $objSession = new Session();
  83. $se = explode('-', $sessionId);
  84. $data = json_encode(compact('title', 'trxId', 'tokenType'));
  85. $data = Utils::encodeRC4($data);
  86. if (count($se) > 1) {
  87. // 发给个人
  88. $to = 0;
  89. foreach ($se as $_u) {
  90. if ($_u != $userId) {
  91. $to = $_u;
  92. break;
  93. }
  94. }
  95. // 插入一条聊天消息
  96. $ret = $objSession->sendPersonMsg($userId, $sessionId, Session::MSG_TYPE_REDPACK, $data, true);
  97. $nickName = User::getUserNameById($userId);
  98. $eventData = [
  99. 'type' => 'new_redpack',
  100. 'msg_type' => Session::MSG_TYPE_REDPACK,
  101. 'from' => (int) $userId,
  102. 'to' => (int) $to,
  103. 'name' => $nickName,
  104. 'nick_name' => $nickName,
  105. 'hash' => $ret['hash'],
  106. 'content' => $data
  107. // 'content' => Utils::encodeRC4($title),
  108. // 'ext' => compact('trxId'),
  109. ];
  110. ThirdApi::pushPersonEvent($userId, $eventData);
  111. ThirdApi::pushPersonEvent($to, $eventData);
  112. } else {
  113. // 插入一条聊天消息
  114. $ret = $objSession->sendGroupMsg($userId, $sessionId, Session::MSG_TYPE_REDPACK, $data, true);
  115. // 发给群组
  116. $groupId = current($se);
  117. $eventData = [
  118. 'type' => 'new_redpack',
  119. 'msg_type' => Session::MSG_TYPE_REDPACK,
  120. 'group_id' => $groupId,
  121. 'from' => $userId,
  122. 'name' => GroupInfo::getGroupNameById($groupId),
  123. 'nick_name' => User::getUserNameById($userId),
  124. 'hash' => $ret['hash'],
  125. 'content' => $data,
  126. 'userMap' => $ret['userMap'],
  127. // 'content' => Utils::encodeRC4($title),
  128. // 'ext' => compact('trxId'),
  129. ];
  130. ThirdApi::pushGroupEvent($groupId, $eventData);
  131. }
  132. }
  133. private static function _makeRandomArr($money, $num, $min = 1) {
  134. $list = [];
  135. while ($num > 0) {
  136. if ($num == 1) {
  137. $list[] = $money;
  138. break;
  139. } else {
  140. $max = ($money / $num) * 2;
  141. $_tmp = rand($min, $max);
  142. $_tmp <= $min && $_tmp = $min;
  143. $list[] = $_tmp;
  144. $money -= $_tmp;
  145. }
  146. $num--;
  147. }
  148. return $list;
  149. }
  150. /**
  151. * 抢红包
  152. * @author solu
  153. * @param $trxId
  154. * @param $userId
  155. * @return array
  156. * @throws Exception
  157. */
  158. public function grab($trxId, $userId) {
  159. $row = $this->objTable->getRow(['transfer_trx_id' => $trxId]);
  160. if (!$row) {
  161. throw new Exception('miss redpack', CODE_NORMAL_ERROR);
  162. }
  163. $parts = explode('-', $row['session_id']);
  164. // 判断权限
  165. if (count($parts) > 1) { // 私聊
  166. $can = in_array($userId, $parts);
  167. } else {
  168. $c = (new UserGroup())->objTable->getCount(['user_id' => $userId, 'group_id' => $row['session_id'], 'state' => UserGroup::STATE_IN_GROUP]);
  169. $can = $c > 0;
  170. }
  171. if (!$can) {
  172. throw new Exception('no permission', CODE_NO_PERMITION);
  173. }
  174. if (self::STATUS_PLAYING != $row['status']) {
  175. throw new Exception('Too Late', -1001);
  176. }
  177. $netId = (int)$row['net_id'];
  178. $accountType = Eos::getNetAccount($netId);
  179. $objUserBindInfo = new UserBindInfo();
  180. $account = $objUserBindInfo->getAccountByUserId($userId, $accountType);
  181. if (!$account) {
  182. $accountTypeName = Account::getTypeName($accountType);
  183. throw new Exception("not bind {$accountTypeName} account", CODE_NORMAL_ERROR);
  184. }
  185. $objLog = new TableHelper('redpack_log', 'dw_chat');
  186. if ($objLog->getCount(['redpack_trx_id' => $trxId, 'user_id' => $userId])) {
  187. throw new Exception('repeat grab', CODE_NORMAL_ERROR);
  188. }
  189. $key = self::getRewardListKey($trxId);
  190. $objRedis = dwRedis::init(Eos::REDIS_SERV);
  191. $quantity = $objRedis->rPop($key);
  192. if (false === $quantity) {
  193. throw new Exception('Too Late', CODE_NORMAL_ERROR);
  194. }
  195. $tokenType = $this->getTokenType($row);
  196. $strQuantity = Eos::toDisplayFormat($quantity, $tokenType);
  197. $redpackId = $row['id'];
  198. $data = [
  199. 'redpack_id' => $redpackId,
  200. 'redpack_trx_id' => $trxId,
  201. 'player' => $account,
  202. 'quantity' => $strQuantity,
  203. 'quantity_int' => $quantity,
  204. 'create_time' => NOW,
  205. 'user_id' => $userId,
  206. 'net_id' => $netId,
  207. ];
  208. $objLog->addObject($data);
  209. $logId = $objLog->getInsertId();
  210. if (!$logId) {
  211. throw new Exception('log error', CODE_NORMAL_ERROR);
  212. }
  213. $from = $objUserBindInfo->getUserIdBy($row['sender'], $accountType);
  214. $eventData = [
  215. 'type' => 'grab_redpack',
  216. 'from' => (int) $from,
  217. 'to' => (int) $userId,
  218. 'content' => [
  219. 'title' => $row['memo'],
  220. 'redpack_id' => $redpackId,
  221. 'redpack_trx_id' => $trxId,
  222. 'quantity' => $strQuantity,
  223. ],
  224. ];
  225. $objSession = new Session();
  226. $extInfo = $eventData;
  227. $extInfo['event_type'] = $eventData['type'];
  228. unset($extInfo['type']);
  229. try {
  230. if (count($parts) == 1) {
  231. // 抢红包的信息,要发给发红包的人
  232. $groupId = current($parts);
  233. $extInfo['group_id'] = $groupId;
  234. $objSession->sendGroupMsg($userId, $groupId, Session::MSG_TYPE_EVENT, '', false, true, $extInfo);
  235. } else {
  236. $objSession->sendPersonMsg($userId, $row['session_id'], Session::MSG_TYPE_EVENT, '', false, $extInfo);
  237. }
  238. } catch (Exception $e) {
  239. var_log($e->getMessage());
  240. }
  241. Eos::grabRedpack($redpackId, $trxId, $logId, $account, $strQuantity, $netId);
  242. $team = round($row['quantity_total_int'] * self::TEAM_DEDUCT); // 团队提成
  243. $ret = [
  244. 'from' => $from,
  245. 'quantity' => $quantity,
  246. 'type' => 'eos',
  247. 'tokenType' => $this->getTokenType($row),
  248. 'num_total' => $row['num_total'],
  249. 'num_left' => $row['num_left'] - 1,
  250. 'quantity_total' => $row['quantity_total_int'] - $team,
  251. 'quantity_left' => $row['quantity_left_int'] - $quantity,
  252. 'logs' => (new RedpackLog())->getByTrxId($trxId),
  253. ];
  254. return $ret;
  255. }
  256. /**
  257. * 红包详情
  258. * @author solu
  259. * @param $trxId
  260. * @return array
  261. */
  262. public function detail($trxId) {
  263. $row = $this->objTable->getRow(['transfer_trx_id' => $trxId]);
  264. if (!$row) {
  265. return [];
  266. }
  267. $team = round($row['quantity_total_int'] * self::TEAM_DEDUCT); // 团队提成
  268. $ret = [
  269. 'from' => $row['sender_id'],
  270. 'title' => $row['memo'],
  271. 'tokenType' => $this->getTokenType($row),
  272. 'type' => 'EOS',
  273. 'redpack_status' => $row['status'],
  274. 'num_total' => $row['num_total'],
  275. 'num_left' => $row['num_left'],
  276. 'quantity_total' => $row['quantity_total_int'] - $team,
  277. 'quantity_left' => $row['quantity_left_int'],
  278. 'logs' => (new RedpackLog())->getByTrxId($trxId),
  279. ];
  280. return $ret;
  281. }
  282. /**
  283. * 发出的红包
  284. * @author solu
  285. * @param $userId
  286. * @param int $offset
  287. * @param int $size
  288. * @return array
  289. */
  290. public function sendList($userId, $offset = 0, $size = 20) {
  291. if (!$userId) {
  292. return [];
  293. }
  294. $list = $this->objTable->getAll(['sender_id' => $userId], [
  295. '_field' => 'id, session_id, num_total, num_left, quantity_total_int, quantity_left_int, memo as title, status, transfer_trx_id, create_time',
  296. '_sortKey' => 'id DESC',
  297. '_limit' => "{$offset}, {$size}",
  298. ]);
  299. $total_count = 0;
  300. $total_quantity = 0;
  301. if (0 == $offset) {
  302. $row = $this->objTable->getRow(['sender_id' => $userId], [
  303. '_field' => 'sum(quantity_total_int) as total_quantity, count(1) as c',
  304. ]);
  305. $total_count = (int)$row['c'];
  306. $total_quantity = (int)$row['total_quantity'];
  307. }
  308. return [$list, $total_count, $total_quantity];
  309. }
  310. /**
  311. * 收到的红包
  312. * @author solu
  313. * @param $userId
  314. * @param int $offset
  315. * @param int $size
  316. * @return array
  317. */
  318. public function receiveList($userId, $offset = 0, $size = 20) {
  319. if (!$userId) {
  320. return [];
  321. }
  322. $objRedpackLog = new RedpackLog();
  323. $list = $objRedpackLog->objTable->getAll(['user_id' => $userId], [
  324. '_field' => 'id, redpack_trx_id, quantity_int, create_time, status, best',
  325. '_sortKey' => 'id DEsc',
  326. '_limit' => "{$offset}, {$size}",
  327. ]);
  328. $trxIds = array_column($list, 'redpack_trx_id');
  329. $redpacks = $this->objTable->getAll(['transfer_trx_id' => $trxIds], [
  330. '_field' => 'id, transfer_trx_id, sender_id, memo, status',
  331. ]);
  332. $redpacks = arrayFormatKey($redpacks, 'transfer_trx_id');
  333. $senderIds = array_column($redpacks, 'sender_id');
  334. $objUser = new TableHelper('user_info', 'dw_chat');
  335. $users = $objUser->getAll(['user_id' => $senderIds], ['_field' => 'user_id, nick_name, cover_photo']);
  336. $users = arrayFormatKey($users, 'user_id', 'nick_name');
  337. foreach ($list as $k => $v) {
  338. $redpack = $redpacks[$v['redpack_trx_id']];
  339. $senderNick = $users[$redpack['sender_id']];
  340. $v['sender'] = $senderNick;
  341. $v['title'] = $redpack['memo'];
  342. $list[$k] = $v;
  343. }
  344. $total_count = 0;
  345. $best_count = 0;
  346. $total_quantity = 0;
  347. if (0 == $offset) {
  348. $row = $this->objTable->getRow(['sender_id' => $userId], [
  349. '_field' => 'sum(quantity_int) as total_quantity, count(1) as c, sum(best) best_count',
  350. ]);
  351. $total_count = (int)$row['c'];
  352. $total_quantity = (int)$row['total_quantity'];
  353. $best_count = (int)$row['best_count'];
  354. }
  355. return [$list, $total_count, $total_quantity, $best_count];
  356. }
  357. }