1
0

GroupFeedService.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. namespace App\Services\Groups;
  3. use App\Profile;
  4. use App\Models\Group;
  5. use App\Models\GroupCategory;
  6. use App\Models\GroupMember;
  7. use App\Models\GroupPost;
  8. use App\Models\GroupInteraction;
  9. use App\Models\GroupLimit;
  10. use App\Util\ActivityPub\Helpers;
  11. use Cache;
  12. use Purify;
  13. use Illuminate\Support\Facades\Redis;
  14. class GroupFeedService
  15. {
  16. const CACHE_KEY = 'pf:services:groups:feed:';
  17. const FEED_LIMIT = 400;
  18. public static function get($gid, $start = 0, $stop = 10)
  19. {
  20. if($stop > 100) {
  21. $stop = 100;
  22. }
  23. return Redis::zrevrange(self::CACHE_KEY . $gid, $start, $stop);
  24. }
  25. public static function getRankedMaxId($gid, $start = null, $limit = 10)
  26. {
  27. if(!$start) {
  28. return [];
  29. }
  30. return array_keys(Redis::zrevrangebyscore(self::CACHE_KEY . $gid, $start, '-inf', [
  31. 'withscores' => true,
  32. 'limit' => [1, $limit]
  33. ]));
  34. }
  35. public static function getRankedMinId($gid, $end = null, $limit = 10)
  36. {
  37. if(!$end) {
  38. return [];
  39. }
  40. return array_keys(Redis::zrevrangebyscore(self::CACHE_KEY . $gid, '+inf', $end, [
  41. 'withscores' => true,
  42. 'limit' => [0, $limit]
  43. ]));
  44. }
  45. public static function add($gid, $val)
  46. {
  47. if(self::count($gid) > self::FEED_LIMIT) {
  48. if(config('database.redis.client') === 'phpredis') {
  49. Redis::zpopmin(self::CACHE_KEY . $gid);
  50. }
  51. }
  52. return Redis::zadd(self::CACHE_KEY . $gid, $val, $val);
  53. }
  54. public static function rem($gid, $val)
  55. {
  56. return Redis::zrem(self::CACHE_KEY . $gid, $val);
  57. }
  58. public static function del($gid, $val)
  59. {
  60. return self::rem($gid, $val);
  61. }
  62. public static function count($gid)
  63. {
  64. return Redis::zcard(self::CACHE_KEY . $gid);
  65. }
  66. public static function warmCache($gid, $force = false, $limit = 100)
  67. {
  68. if(self::count($gid) == 0 || $force == true) {
  69. Redis::del(self::CACHE_KEY . $gid);
  70. $ids = GroupPost::whereGroupId($gid)
  71. ->orderByDesc('id')
  72. ->limit($limit)
  73. ->pluck('id');
  74. foreach($ids as $id) {
  75. self::add($gid, $id);
  76. }
  77. return 1;
  78. }
  79. }
  80. }