PublicTimelineService.php 1.8 KB

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