LikeService.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace App\Services;
  3. use App\Util\ActivityPub\Helpers;
  4. use Illuminate\Support\Facades\Cache;
  5. use Illuminate\Support\Facades\Redis;
  6. use App\Like;
  7. class LikeService {
  8. const CACHE_KEY = 'pf:services:likes:ids:';
  9. public static function add($profileId, $statusId)
  10. {
  11. $key = self::CACHE_KEY . $profileId . ':' . $statusId;
  12. Cache::increment('pf:services:likes:count:'.$statusId);
  13. Cache::forget('pf:services:likes:liked_by:'.$statusId);
  14. return Cache::put($key, true, 86400);
  15. }
  16. public static function remove($profileId, $statusId)
  17. {
  18. $key = self::CACHE_KEY . $profileId . ':' . $statusId;
  19. Cache::decrement('pf:services:likes:count:'.$statusId);
  20. Cache::forget('pf:services:likes:liked_by:'.$statusId);
  21. return Cache::put($key, false, 86400);
  22. }
  23. public static function liked($profileId, $statusId)
  24. {
  25. $key = self::CACHE_KEY . $profileId . ':' . $statusId;
  26. return Cache::remember($key, 86400, function() use($profileId, $statusId) {
  27. return Like::whereProfileId($profileId)->whereStatusId($statusId)->exists();
  28. });
  29. }
  30. public static function likedBy($status)
  31. {
  32. $empty = [
  33. 'username' => null,
  34. 'others' => false
  35. ];
  36. if(!$status) {
  37. return $empty;
  38. }
  39. $res = Cache::remember('pf:services:likes:liked_by:' . $status->id, 86400, function() use($status, $empty) {
  40. $like = Like::whereStatusId($status->id)->first();
  41. if(!$like) {
  42. return $empty;
  43. }
  44. $id = $like->profile_id;
  45. $profile = ProfileService::get($id);
  46. $profileUrl = "/i/web/profile/{$profile['id']}";
  47. $res = [
  48. 'id' => (string) $profile['id'],
  49. 'username' => $profile['username'],
  50. 'url' => $profileUrl,
  51. 'others' => $status->likes_count >= 3,
  52. ];
  53. return $res;
  54. });
  55. if(!isset($res['id']) || !isset($res['url'])) {
  56. return $empty;
  57. }
  58. $res['total_count'] = ($status->likes_count - 1);
  59. $res['total_count_pretty'] = number_format($res['total_count']);
  60. return $res;
  61. }
  62. public static function count($id)
  63. {
  64. return Cache::get('pf:services:likes:count:'.$id, 0);
  65. }
  66. }