PushService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. <?php
  2. namespace App\Modules\Push\Services;
  3. use App\Cache\Lock\LockCache;
  4. use App\Libs\Push\VPush\VPush;
  5. use Exception;
  6. use App\Cache\Push\PushCache;
  7. use App\Consts\PushConst;
  8. use App\Libs\Push\OPPOPush\OPPOPushCommon;
  9. use App\Libs\Push\XMPush\MiPushCommon;
  10. use App\Libs\Push\HuaWei\HwPushCommon;
  11. use App\Modules\Push\Models\QappPushApp;
  12. use App\Modules\Push\Models\QappPushTask;
  13. use App\Modules\Push\Models\QappPushTaskLogs;
  14. use App\Modules\Push\Models\QappPushTaskUsers;
  15. use App\Modules\Push\Models\QappPushUser;
  16. use App\Modules\User\Models\QappPackage;
  17. use GuzzleHttp\Exception\GuzzleException;
  18. class PushService
  19. {
  20. /**
  21. * 设置用户reg_id
  22. * @param $uid
  23. * @param string $regId
  24. * @param string $provider
  25. * @param string $package
  26. * @return bool
  27. */
  28. public static function setUserRegId($uid, string $regId, string $provider, string $package): bool
  29. {
  30. // push服务商(转小写)
  31. $provider = strtolower($provider);
  32. if (empty($uid) || empty($regId) || empty($package) || empty($provider)) {
  33. return false;
  34. }
  35. //myLog('push')->info('setUserRegId', compact('uid', 'regId', 'provider', 'package'));
  36. // 获取缓存
  37. $userCacheRegId = PushCache::getUserPushRegId($uid);
  38. if ($regId === $userCacheRegId) {
  39. return true;
  40. }
  41. // 加锁
  42. $token = md5($provider . ':' . $regId);
  43. $lock = LockCache::getLock($token, 3);
  44. if (!$lock) {
  45. return false;
  46. }
  47. //myLog('push')->info('setUserRegId', compact('uid', 'regId', 'provider', 'token', 'lock'));
  48. // 获取包信息
  49. $packageInfo = QappPackage::getPackageByPackage($package);
  50. $packageId = getProp($packageInfo, 'id');
  51. $channelId = getProp($packageInfo, 'channel_id');
  52. $company = getProp($packageInfo, 'company');
  53. //myLog('push')->info('setUserRegId', compact('packageId', 'channelId', 'company'));
  54. if (empty($packageId)) {
  55. return false;
  56. }
  57. // 获取app信息
  58. $pushApp = QappPushApp::getPushAppByPackageIdAndProvider($packageId, $provider);
  59. $pushAppId = getProp($pushApp, 'app_id');
  60. //myLog('push')->info('setUserRegId', compact('pushAppId'));
  61. if (!$pushAppId) {
  62. return false;
  63. }
  64. // 设置
  65. $pushUser = QappPushUser::getPushUserByUid($uid);
  66. $pushUserRegId = (string)getProp($pushUser, 'reg_id');
  67. // myLog('push')->info('setUserRegId', compact('pushUserRegId','uid','regId'));
  68. if ($pushUserRegId === $regId) {
  69. PushCache::setUserPushRegId($uid, $regId);
  70. return true;
  71. }
  72. // 初始化用户Push信息
  73. if (!$pushUser) {
  74. // 初始化push_users
  75. QappPushUser::initPushUser($uid, $regId, $pushAppId, $provider, $channelId);
  76. # 推送相关变量
  77. $topic = PushConst::TOPIC_ALL;
  78. $appId = getProp($pushApp, 'app_id');
  79. $appSecret = getProp($pushApp, 'app_secret');
  80. $appKey = getProp($pushApp, 'app_key');
  81. $masterSecret = getProp($pushApp, 'master_secret');
  82. // 针对华为用户需要主动订阅topic,方便后续全量推送
  83. if ($provider === PushConst::PROVIDER_HW) {
  84. $client = new HwPushCommon($pushAppId, $appSecret);
  85. $client->subscribeTopic($topic, [$regId]);
  86. }
  87. // 针对OPPO用户需要主动订阅topic,方便后续全量推送
  88. if ($provider === PushConst::PROVIDER_OPPO) {
  89. $client = new OPPOPushCommon($appKey, $masterSecret);
  90. $client->subscribeTags($regId, $topic);
  91. }
  92. // 针对VIVO用户需要主动订阅topic,方便后续全量推送
  93. if ($provider === PushConst::PROVIDER_OPPO) {
  94. $client = new VPush($appId, $appKey, $appSecret);
  95. $client->addTagForUsers($topic, [$regId]);
  96. }
  97. }
  98. // 更新用户数据库中reg_id
  99. $result = QappPushUser::setUserRegId($uid, $regId);
  100. if ($result) {
  101. // 更新缓存
  102. PushCache::setUserPushRegId($uid, $regId);
  103. // myLog('push')->info('updateUserRegId', compact('uid','regId'));
  104. }
  105. // 释放锁
  106. // LockCache::releaseLock($token);
  107. return $result;
  108. }
  109. /**
  110. * 推送消息
  111. * @param $taskId
  112. * @return bool
  113. * @throws GuzzleException
  114. */
  115. public static function pushMessageByTaskId($taskId): bool
  116. {
  117. if (empty($taskId)) {
  118. return false;
  119. }
  120. // 获取任务数据,判断任务状态及发送时间
  121. $pushTask = QappPushTask::getPushTaskById($taskId);
  122. if (
  123. (int)getProp($pushTask, 'status') !== PushConst::STATUS_TODO ||
  124. (int)getProp($pushTask, 'select_user_status') !== PushConst::SELECT_USER_OK ||
  125. getProp($pushTask, 'push_time') > date('Y-m-d H:i:s')
  126. ) {
  127. return false;
  128. }
  129. // 获取全部子任务,判断子任务是否有效
  130. $subTasks = QappPushTaskLogs::getPushTaskLogsByTaskId($taskId);
  131. if (!$subTasks) {
  132. // 更新主任务失败状态及原因
  133. QappPushTask::updateMainTaskStatus($taskId, PushConst::STATUS_FAIL, '无有效子任务');
  134. return false;
  135. }
  136. // 获取推送应用信息
  137. $pushAppIds = array_column($subTasks, 'app_id');
  138. $pushApps = QappPushApp::getPushAppByAppIds($pushAppIds);
  139. if (!$pushApps) {
  140. // 更新主任务失败状态及原因
  141. QappPushTask::updateMainTaskStatus($taskId, PushConst::STATUS_FAIL, '无有效推送APP');
  142. return false;
  143. }
  144. // 更新主任务状态为开始状态
  145. QappPushTask::updateMainTaskStatus($taskId, PushConst::STATUS_DOING, '无有效推送APP');
  146. // 全量发送走标签,否则走批量
  147. $pushFilter = getProp($pushTask, 'push_filter');
  148. if (in_array($pushFilter, [PushConst::FILTER_ALL_USERS, PushConst::FILTER_ALL_SUB_USERS])) {
  149. $result = self::pushMessageToAll($pushTask, $subTasks, $pushApps);
  150. } else {
  151. $result = self::pushMessageToUsers($pushTask, $subTasks, $pushApps);
  152. }
  153. // 更新主任务最终状态(成功/失败)
  154. $status = $result ? PushConst::STATUS_SUCCESS : PushConst::STATUS_FAIL;
  155. QappPushTask::updateMainTaskStatus($taskId, $status, $result);
  156. return $result;
  157. }
  158. /**
  159. * 全部发送
  160. * @param $pushTask
  161. * @param $subTasks
  162. * @param $pushApps
  163. * @return bool
  164. * @throws GuzzleException
  165. */
  166. private static function pushMessageToAll($pushTask, $subTasks, $pushApps): bool
  167. {
  168. if (empty($pushTask) || empty($subTasks) || empty($pushApps)) {
  169. return false;
  170. }
  171. // 推送结果、推送内容
  172. $pushResult = true;
  173. $title = getProp($pushTask, 'title');
  174. $content = getProp($pushTask, 'content');
  175. $url = getProp($pushTask, 'url');
  176. myLog('push')->info('1', compact('title', 'content'));
  177. // 循环群发
  178. foreach ($subTasks as $subTask) {
  179. $appId = getProp($subTask, 'app_id');
  180. $subTaskId = getProp($subTask, 'id');
  181. $pushApp = collect($pushApps)->firstWhere('app_id', $appId);
  182. if (empty($pushApp)) {
  183. continue;
  184. }
  185. // push app相关
  186. $provider = getProp($pushApp, 'provider');
  187. $package = getProp($pushApp, 'package');
  188. $appId = getProp($pushApp, 'app_id');
  189. $appSecret = getProp($pushApp, 'app_secret');
  190. $appKey = getProp($pushApp, 'app_key');
  191. $masterSecret = getProp($pushApp, 'master_secret');
  192. $topic = PushConst::TOPIC_ALL;
  193. $content = self::contentFormat($content, $provider);
  194. // 更新开始状态
  195. QappPushTaskLogs::updateSubTaskStatus($subTaskId, PushConst::STATUS_DOING);
  196. $result = [];
  197. try {
  198. // 针对渠道做不同处理
  199. switch ($provider) {
  200. // 华为
  201. case PushConst::PROVIDER_HW:
  202. // 开发状态还是生产状态
  203. $target = env('APP_ENV') === 'production' ? 2 : 1;
  204. // 设置相关配置
  205. $client = new HwPushCommon($appId, $appSecret);
  206. $client->setFastAppTarget($target);
  207. $client->setTopic($topic);
  208. $client->setBigTag('Task_' . getProp($pushTask, 'id'));
  209. // 推送
  210. $result = $client->sendPushMessage($title, $content, $url);
  211. break;
  212. // 小米
  213. case PushConst::PROVIDER_MI:
  214. $client = new MiPushCommon($package, $appSecret);
  215. $result = $client->sendMessageToAll($title, $content, $url);
  216. break;
  217. // OPPO
  218. case PushConst::PROVIDER_OPPO:
  219. $client = new OPPOPushCommon($appKey, $masterSecret);
  220. $messageId = $client->getMessageId($title, $content, $url);
  221. $result = $client->broadCastAll($messageId, $topic);
  222. break;
  223. // VIVO
  224. case PushConst::PROVIDER_VIVO:
  225. $client = new VPush($appId, $appKey, $appSecret);
  226. $client->setPushData($title, $content, $url);
  227. // $result = $client->sendAll();
  228. $result = $client->tagPush($topic);
  229. break;
  230. }
  231. } catch (Exception $e) {
  232. myLog('push')->info('pushMessageToAll', [$provider, $result, $e->getMessage()]);
  233. // 最终结果
  234. $pushResult = 0 && $pushResult;
  235. // 更新子任务失败状态
  236. QappPushTaskLogs::updateSubTaskStatus($subTaskId, PushConst::STATUS_FAIL, $result);
  237. continue;
  238. }
  239. // 更新成功状态
  240. QappPushTaskLogs::updateSubTaskStatus($subTaskId, PushConst::STATUS_SUCCESS, $result);
  241. }
  242. return $pushResult;
  243. }
  244. /**
  245. * @param $pushTask
  246. * @param $subTasks
  247. * @param $pushApps
  248. * @return bool
  249. * @throws GuzzleException
  250. */
  251. private static function pushMessageToUsers($pushTask, $subTasks, $pushApps)
  252. {
  253. // 获取需要推送的人
  254. $taskId = getProp($pushTask, 'id');
  255. $taskUsers = QappPushTaskUsers::getTaskUsers($taskId);
  256. if (!$taskUsers) {
  257. // 更新主任务失败状态及原因
  258. QappPushTask::updateMainTaskStatus($taskId, PushConst::STATUS_FAIL, '未设置推送用户');
  259. return false;
  260. }
  261. // 推送结果、推送内容
  262. $pushResult = true;
  263. $title = getProp($pushTask, 'title');
  264. $content = getProp($pushTask, 'content');
  265. $url = getProp($pushTask, 'url');
  266. // 推送
  267. foreach ($subTasks as $subTask) {
  268. $subTaskId = getProp($subTask, 'id');
  269. $appId = getProp($subTask, 'app_id');
  270. $pushApp = collect($pushApps)->firstWhere('app_id', $appId);
  271. $uids = collect($taskUsers)->where('app_id', $appId)->pluck('uid');
  272. $users = QappPushUser::getPushUserByUids($uids);
  273. $regIds = array_column($users, 'reg_id');
  274. // push app相关
  275. $provider = getProp($pushApp, 'provider');
  276. $package = getProp($pushApp, 'package');
  277. $appId = getProp($pushApp, 'app_id');
  278. $appSecret = getProp($pushApp, 'app_secret');
  279. $appKey = getProp($pushApp, 'app_key');
  280. $masterSecret = getProp($pushApp, 'master_secret');
  281. $content = self::contentFormat($content, $provider);
  282. // 更新开始状态
  283. QappPushTaskLogs::updateSubTaskStatus($subTaskId, PushConst::STATUS_DOING);
  284. // 循环批量
  285. $result = [];
  286. $regIdArr = array_chunk($regIds, 1000);
  287. try {
  288. switch ($provider) {
  289. // 华为
  290. case PushConst::PROVIDER_HW:
  291. // 初始化huawei推送
  292. $client = new HwPushCommon($appId, $appSecret);
  293. // 循环推送
  294. $i = 0;
  295. foreach ($regIdArr as $regIdList) {
  296. $client->setToken($regIdList);
  297. $result = $client->sendPushMessage($title, $content, $url);
  298. // 一般的应用默认消息流控是针对单个应用3000QPS(每秒不能超过3000个token数)
  299. $i++;
  300. if ($i % 3 === 0) {
  301. sleep(1);
  302. }
  303. }
  304. break;
  305. // 小米
  306. case PushConst::PROVIDER_MI:
  307. // 初始化小米推送
  308. $client = new MiPushCommon($package, $appSecret);
  309. // 循环推送
  310. $i = 0;
  311. foreach ($regIdArr as $regIdList) {
  312. $client->setRegArr($regIdList);
  313. $result = $client->sendMessage($title, $content, $url);
  314. // 一般的应用默认消息流控是针对单个应用3000QPS(每秒不能超过3000个token数)
  315. $i++;
  316. if ($i % 3 === 0) {
  317. sleep(1);
  318. }
  319. }
  320. break;
  321. // OPPO
  322. case PushConst::PROVIDER_OPPO:
  323. // 初始化oppo推送
  324. $client = new OPPOPushCommon($appKey, $masterSecret);
  325. $messageId = $client->getMessageId($title, $content, $url);
  326. // 循环推送
  327. $i = 0;
  328. foreach ($regIdArr as $regIdList) {
  329. $client->setRegArr($regIdList);
  330. $result = $client->broadCastRegIds($messageId);
  331. // 一般的应用默认消息流控是针对单个应用3000QPS(每秒不能超过3000个token数)
  332. $i++;
  333. if ($i % 3 === 0) {
  334. sleep(1);
  335. }
  336. }
  337. break;
  338. // VIVO
  339. case PushConst::PROVIDER_VIVO:
  340. // 初始化oppo推送
  341. $client = new VPush($appId, $appKey, $appSecret);
  342. // 循环推送
  343. $i = 0;
  344. foreach ($regIdArr as $regIdList) {
  345. // 设置相关推送数据,保存消息内容
  346. $client->setPushData($title, $content, $url, $regIdList);
  347. $client->saveListPayload();
  348. $result = $client->sendMessage();
  349. // 一般的应用默认消息流控是针对单个应用3000QPS(每秒不能超过3000个token数)
  350. $i++;
  351. if ($i % 3 === 0) {
  352. sleep(1);
  353. }
  354. }
  355. }
  356. } catch (Exception $e) {
  357. // 最终结果
  358. $pushResult = 0 && $pushResult;
  359. // 更新子任务失败状态
  360. QappPushTaskLogs::updateSubTaskStatus($subTaskId, PushConst::STATUS_FAIL, $result);
  361. continue;
  362. }
  363. // 更新成功状态
  364. QappPushTaskLogs::updateSubTaskStatus($subTaskId, PushConst::STATUS_SUCCESS, $result);
  365. }
  366. return $pushResult;
  367. }
  368. private static function contentFormat(string $content, string $provider): string
  369. {
  370. return str_replace('{device}', PushMessageService::providers[$provider], $content);
  371. }
  372. }