KeepContinueReadV2.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: z-yang
  5. * Date: 2019/8/20
  6. * Time: 14:00
  7. */
  8. namespace App\Console\Commands\SmartPush;
  9. use Illuminate\Console\Command;
  10. use DB;
  11. use Redis;
  12. use GuzzleHttp\Client;
  13. use App\Http\Controllers\WechatController;
  14. use GuzzleHttp\Psr7\Request as GuzzleRequest;
  15. use GuzzleHttp\Pool;
  16. use Hashids;
  17. class KeepContinueReadV2 extends Command
  18. {
  19. /**
  20. * The name and signature of the console command.
  21. *
  22. * @var string
  23. */
  24. protected $signature = 'SmartPush:KeepContinueReadV2';
  25. /**
  26. * The console command description.
  27. *
  28. * @var string
  29. */
  30. protected $description = '持续阅读推送';
  31. /**
  32. * Create a new command instance.
  33. *
  34. * @return void
  35. */
  36. public function __construct()
  37. {
  38. parent::__construct();
  39. }
  40. /**
  41. * Execute the console command.
  42. *
  43. * @return mixed
  44. */
  45. public function handle()
  46. {
  47. $this->send();
  48. }
  49. private function generateRequest()
  50. {
  51. $switch_array = [];
  52. $now_hour = date('G');
  53. $temp = 0;
  54. $info = DB::connection('api_mysql')->table('custom_msg_switchs')->where('custom_category','continue_read')->first();
  55. if(!$info) return ;
  56. $default_status = $info->default_switch_status;
  57. while (true){
  58. $user = DB::connection('api_mysql')->table('temp_force_subscribe_users')
  59. ->select('id','uid','distribution_channel_id','openid','appid')
  60. ->where('id','>',$temp)
  61. //->whereIn('id',[3032288,3042985])
  62. ->where('last_interactive_time','>',date('Y-m-d H:i:s',time()-86400*2))
  63. ->orderBy('id')
  64. ->limit(1000)
  65. ->get();
  66. if(!$user) break;
  67. foreach ($user as $item){
  68. if(isInnerSites($item->distribution_channel_id)) continue;
  69. //if(!in_array($item->distribution_channel_id,[70])) continue;
  70. //\Log::info( '---------------------------start--start-------------------------------------------' );
  71. //\Log::info('$item->distribution_channel_id is :'.$item->distribution_channel_id );
  72. //\Log::info( '$item->id is :'.$item->id );
  73. if(!isset($switch_array[$item->distribution_channel_id])){
  74. $switch = DB::connection('api_mysql')->table('custom_msg_switchs_msgs')
  75. ->where('distribution_channel_id',$item->distribution_channel_id)
  76. ->where('custom_category','continue_read')
  77. ->select('status')
  78. ->first();
  79. if($switch){
  80. $switch_array[$item->distribution_channel_id] = $switch->status;
  81. }else{
  82. $switch_array[$item->distribution_channel_id] = $default_status;
  83. }
  84. }
  85. $switch_status = $switch_array[$item->distribution_channel_id];
  86. //if(!in_array($item->distribution_channel_id,[5,123,14,13,8])) continue;
  87. if($switch_status != 1) continue;
  88. //\Log::info( '$item->distribution_channel_id in is :'.$item->distribution_channel_id );
  89. //$data = ['first'=>[],'seconds'=>[]];
  90. $read_info = $this->getReadRecord($item->uid);
  91. if(empty($read_info['first'])){
  92. continue;
  93. }
  94. //获取本次发送的时间间隔
  95. $this_push_hour = Redis::hget('book_read:'.$item->uid,'next_push_hour');
  96. //上次发送时间
  97. $prev_send_info = DB::connection('api_mysql')->table('custom_push_keep_continue')->where('uid',$item->uid)->select('send_time')->orderBy('id','desc')->first();
  98. $diff = $this_push_hour?$this_push_hour:8;
  99. if($diff == 8){
  100. if((time()-$read_info['time']) > 3600*8){
  101. $send_hour = $now_hour;
  102. }else{
  103. $send_hour = -1;
  104. }
  105. }else{
  106. if($prev_send_info){
  107. //$send_hour = date('G',strtotime($prev_send_info->send_time)+$diff*3600);
  108. if((time()-strtotime($prev_send_info->send_time)) >$diff*3600){
  109. $send_hour = $now_hour;
  110. }else{
  111. $send_hour = -1;
  112. }
  113. }else{
  114. $send_hour = $now_hour;
  115. }
  116. }
  117. $domain = sprintf('https://site%s.%s.com',encodeDistributionChannelId($item->distribution_channel_id),
  118. env('CUSTOM_HOST'));
  119. if($send_hour != $now_hour ) continue;
  120. $openid = $item->openid;
  121. $appid = $item->appid;
  122. $user_info = DB::connection('api_mysql')->table('users')->where('id',$item->uid)->select('nickname')->first();
  123. $nickname = '读者';
  124. if($user_info && $user_info->nickname)$nickname = $user_info->nickname;
  125. //$content_format = "您看的小说有更新\r\n\r\n<a href='%s'>《%s》剧情已更新,点击继续阅读</a> \r\n\r\n记得点击菜单栏签到领书币哦";
  126. $content_format = "@%s 为您推荐上次未看完的小说\r\n\r\n点击<a href='%s'>继续阅读</a>❤\r\n\r\n";
  127. /*$content = sprintf($content_format,
  128. sprintf($continueReadUrlFormat,
  129. encodeDistributionChannelId($item->distribution_channel_id),
  130. env('CUSTOM_HOST'),
  131. $read_info['url']
  132. ),
  133. $read_info['book_name']
  134. )*/;
  135. $content = sprintf($content_format,$nickname,$domain.$read_info['first']['url']);
  136. if(!empty($read_info['seconds'])){
  137. $content .= "历史阅读记录:\r\n\r\n";
  138. foreach ($read_info['seconds'] as $record_item){
  139. $content .= sprintf(" 🌳 <a href='%s'>%s</a>\r\n",$domain.$record_item['url'],$record_item['book_name']);
  140. }
  141. }
  142. $content .= "\r\n为了方便下次阅读,请<a href='http://cdn-pro.18yuedu.com/h5/top.html'>置顶公众号</a>";
  143. $access_token = $this->getAccessToken($appid);
  144. if(!$access_token)continue;
  145. $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$access_token;
  146. $request = new GuzzleRequest('post',$url,[],\GuzzleHttp\json_encode([
  147. 'touser'=>$openid,
  148. 'msgtype'=>'text',
  149. 'text'=>['content'=>$content]
  150. ],JSON_UNESCAPED_UNICODE));
  151. DB::connection('api_mysql')->table('custom_push_keep_continue')->insert([
  152. 'uid'=>$item->uid,
  153. 'time_diff'=>$diff,
  154. 'send_time'=>date('Y-m-d H:i:s'),
  155. 'day'=>date('Y-m-d'),
  156. 'created_at'=>date('Y-m-d H:i:s'),
  157. 'updated_at'=>date('Y-m-d H:i:s')
  158. ]);
  159. if($diff == 8){
  160. $next = 24;
  161. }else{
  162. $next = 24;
  163. }
  164. Redis::hset('book_read:'.$item->uid,'next_push_hour',$next);
  165. //\Log::info( '----------------------------end-end-end-------------------------------------------' );
  166. yield $request;
  167. }
  168. $temp = $item->id;
  169. }
  170. }
  171. private function getFirstReadRecord($uid){
  172. //Redis::hget('book_base:' . $uid, 'last_read', "{$bid}_{$cid}_{$book_name}_{$chapter_name}_" . time());
  173. $record = Redis::hget('book_read:' . $uid, 'last_read');
  174. if($record){
  175. $record_arr = explode('_',$record);
  176. $bid = $record_arr[0];
  177. $book_name = $this->bid2BookName($bid);
  178. //$hash = new Hashids('D6M97LIvpp4qWuz3nKzqi6yYN4GAA61b',32,'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890');
  179. $bid = $hash->encode($bid);
  180. $cid = $record_arr[1];
  181. $time = $record_arr[2];
  182. $res = [
  183. 'url' => '/reader?bid='.$bid.'&cid='.$cid.'&fromtype=continue_read',
  184. 'book_name'=>$book_name,
  185. 'bid'=>$bid,
  186. 'time'=>$time
  187. ];
  188. return $res;
  189. }
  190. return [];
  191. }
  192. private function getReadRecord($uid){
  193. //$hash = new Hashids('D6M97LIvpp4qWuz3nKzqi6yYN4GAA61b',32,'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890');
  194. $records = Redis::hgetall('book_read:' . $uid);
  195. $data = ['first'=>[],'seconds'=>[],'time'=>''];
  196. foreach ($records as $k=>$item){
  197. if($k == 'last_read'){
  198. $record_arr = explode('_',$item);
  199. $bid = $record_arr[0];
  200. //$book_name = $this->bid2BookName($bid);
  201. $bid = Hashids::encode($bid);
  202. $cid = $record_arr[1];
  203. $time = $record_arr[2];
  204. $data['first'] = [
  205. 'url' => '/reader?bid='.$bid.'&cid='.$cid.'&fromtype=continue_read',
  206. 'book_name'=>'',
  207. ];
  208. $data['time'] = $time;
  209. continue;
  210. }
  211. if(!is_numeric($k)) continue;
  212. $record = explode('_', $item);
  213. $latest_read_cid = $record[0];
  214. $book_name = self::bid2BookName($k);
  215. $latest_read_time = $record[count($record) - 1];
  216. $data['seconds'][] =[
  217. 'url' => '/reader?bid='.Hashids::encode($k).'&cid='.$latest_read_cid.'&fromtype=continue_read',
  218. 'book_name'=>$book_name,
  219. 'time'=>$latest_read_time
  220. ];
  221. }
  222. $temp = $data['seconds'];
  223. if($temp){
  224. usort($temp, function ($a, $b) {
  225. if ($a['time'] >= $b['time']) return -1;
  226. return 1;
  227. });
  228. }
  229. $temp_res = [];
  230. foreach ($temp as $k=>$it){
  231. $temp_res[] = $it;
  232. if($k>=2) break;
  233. }
  234. $data['seconds'] = $temp_res;
  235. return $data;
  236. }
  237. private function bid2BookName($bid){
  238. $book_name = null;
  239. if(is_null($book_name)){
  240. $book_key = 'wap:string:book:'.$bid;
  241. $book_name = Redis::get($book_key);
  242. Redis::EXPIRE($book_key,3600);
  243. if(!$book_name){
  244. $book_name = '';
  245. $book_info = DB::connection('api_mysql')->table('book_configs')->where('bid',$bid)->select('book_name')->first();
  246. //$book_info = BookConfigService::getBookById($bid);
  247. if($book_info && isset($book_info->book_name)){
  248. $book_name = $book_info->book_name;
  249. Redis::setex($book_key,3600,$book_name);
  250. }
  251. }
  252. }
  253. return $book_name;
  254. }
  255. private function getAccessToken($appid){
  256. try{
  257. $WechatController = new WechatController($appid);
  258. $accessToken = $WechatController->app->access_token; // EasyWeChat\Core\AccessToken 实例
  259. $token = $accessToken->getToken(); // token 字符串
  260. return $token;
  261. }catch(\Exception $e){
  262. \Log::error($e->getMessage());
  263. }
  264. return '';
  265. }
  266. private function send(){
  267. $client = new Client();
  268. $requests = $this->generateRequest();
  269. $pool = new Pool($client, $requests, [
  270. 'concurrency' => 5,
  271. 'fulfilled' => function ($response, $index) {
  272. },
  273. 'rejected' => function ($reason, $index) {
  274. },
  275. ]);
  276. $promise = $pool->promise();
  277. $promise->wait();
  278. }
  279. }