HomeTimelineService.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\Cache;
  4. use Illuminate\Support\Facades\Redis;
  5. use App\Follower;
  6. use App\Status;
  7. class HomeTimelineService
  8. {
  9. const CACHE_KEY = 'pf:services:timeline:home:';
  10. const FOLLOWER_FEED_POST_LIMIT = 10;
  11. public static function get($id, $start = 0, $stop = 10)
  12. {
  13. if($stop > 100) {
  14. $stop = 100;
  15. }
  16. return Redis::zrevrange(self::CACHE_KEY . $id, $start, $stop);
  17. }
  18. public static function getRankedMaxId($id, $start = null, $limit = 10)
  19. {
  20. if(!$start) {
  21. return [];
  22. }
  23. return array_keys(Redis::zrevrangebyscore(self::CACHE_KEY . $id, $start, '-inf', [
  24. 'withscores' => true,
  25. 'limit' => [1, $limit - 1]
  26. ]));
  27. }
  28. public static function getRankedMinId($id, $end = null, $limit = 10)
  29. {
  30. if(!$end) {
  31. return [];
  32. }
  33. return array_keys(Redis::zrevrangebyscore(self::CACHE_KEY . $id, '+inf', $end, [
  34. 'withscores' => true,
  35. 'limit' => [0, $limit]
  36. ]));
  37. }
  38. public static function add($id, $val)
  39. {
  40. if(self::count($id) >= 400) {
  41. Redis::zpopmin(self::CACHE_KEY . $id);
  42. }
  43. return Redis::zadd(self::CACHE_KEY .$id, $val, $val);
  44. }
  45. public static function rem($id, $val)
  46. {
  47. return Redis::zrem(self::CACHE_KEY . $id, $val);
  48. }
  49. public static function count($id)
  50. {
  51. return Redis::zcard(self::CACHE_KEY . $id);
  52. }
  53. public static function warmCache($id, $force = false, $limit = 100, $returnIds = false)
  54. {
  55. if(self::count($id) == 0 || $force == true) {
  56. Redis::del(self::CACHE_KEY . $id);
  57. $following = Cache::remember('profile:following:'.$id, 1209600, function() use($id) {
  58. $following = Follower::whereProfileId($id)->pluck('following_id');
  59. return $following->push($id)->toArray();
  60. });
  61. $ids = Status::whereIn('profile_id', $following)
  62. ->whereNull(['in_reply_to_id', 'reblog_of_id'])
  63. ->whereIn('type', ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  64. ->whereIn('visibility',['public', 'unlisted', 'private'])
  65. ->orderByDesc('id')
  66. ->limit($limit)
  67. ->pluck('id');
  68. foreach($ids as $pid) {
  69. self::add($id, $pid);
  70. }
  71. return $returnIds ? $ids : 1;
  72. }
  73. return 0;
  74. }
  75. }