LikeService.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. $ttl = now()->addHours(2);
  13. return Cache::put($key, true, $ttl);
  14. }
  15. public static function remove($profileId, $statusId)
  16. {
  17. $key = self::CACHE_KEY . $profileId . ':' . $statusId;
  18. $ttl = now()->addHours(2);
  19. return Cache::put($key, false, $ttl);
  20. }
  21. public static function liked($profileId, $statusId)
  22. {
  23. $key = self::CACHE_KEY . $profileId . ':' . $statusId;
  24. $ttl = now()->addMinutes(30);
  25. return Cache::remember($key, $ttl, function() use($profileId, $statusId) {
  26. return Like::whereProfileId($profileId)->whereStatusId($statusId)->exists();
  27. });
  28. }
  29. public static function likedBy($status)
  30. {
  31. $empty = [
  32. 'username' => null,
  33. 'others' => false
  34. ];
  35. if(!$status) {
  36. return $empty;
  37. }
  38. if(!$status->likes_count) {
  39. return $empty;
  40. }
  41. $user = request()->user();
  42. if($user) {
  43. $like = Like::whereStatusId($status->id)
  44. ->where('profile_id', '!=', $user->profile_id)
  45. ->first();
  46. } else {
  47. $like = Like::whereStatusId($status->id)
  48. ->first();
  49. }
  50. if(!$like) {
  51. return $empty;
  52. }
  53. $id = $like->profile_id;
  54. $profile = ProfileService::get($id);
  55. $profileUrl = $profile['local'] ? $profile['url'] : '/i/web/profile/_/' . $profile['id'];
  56. $res = [
  57. 'username' => $profile['username'],
  58. 'url' => $profileUrl,
  59. 'others' => $status->likes_count >= 3,
  60. ];
  61. if(request()->user() && request()->user()->profile_id == $status->profile_id) {
  62. $res['total_count'] = ($status->likes_count - 1);
  63. $res['total_count_pretty'] = number_format($res['total_count']);
  64. }
  65. return $res;
  66. }
  67. public static function count($id)
  68. {
  69. return Like::whereStatusId($id)->count();
  70. }
  71. }