pixelfed/app/Services/LikeService.php

82 lines
2.0 KiB
PHP
Raw Normal View History

2021-05-01 21:51:02 +00:00
<?php
namespace App\Services;
use App\Util\ActivityPub\Helpers;
2021-07-02 07:31:45 +00:00
use Illuminate\Support\Facades\Cache;
2021-05-01 21:51:02 +00:00
use Illuminate\Support\Facades\Redis;
use App\Like;
class LikeService {
const CACHE_KEY = 'pf:services:likes:ids:';
2021-07-02 07:31:45 +00:00
public static function add($profileId, $statusId)
2021-05-01 21:51:02 +00:00
{
2021-07-02 07:31:45 +00:00
$key = self::CACHE_KEY . $profileId . ':' . $statusId;
Cache::increment('pf:services:likes:count:'.$statusId);
Cache::forget('pf:services:likes:liked_by:'.$statusId);
return Cache::put($key, true, 86400);
2021-05-01 21:51:02 +00:00
}
2021-07-02 07:31:45 +00:00
public static function remove($profileId, $statusId)
2021-05-01 21:51:02 +00:00
{
2021-07-02 07:31:45 +00:00
$key = self::CACHE_KEY . $profileId . ':' . $statusId;
Cache::decrement('pf:services:likes:count:'.$statusId);
Cache::forget('pf:services:likes:liked_by:'.$statusId);
return Cache::put($key, false, 86400);
2021-05-01 21:51:02 +00:00
}
public static function liked($profileId, $statusId)
{
2021-07-02 07:31:45 +00:00
$key = self::CACHE_KEY . $profileId . ':' . $statusId;
return Cache::remember($key, 86400, function() use($profileId, $statusId) {
2021-07-02 07:31:45 +00:00
return Like::whereProfileId($profileId)->whereStatusId($statusId)->exists();
});
2021-05-01 21:51:02 +00:00
}
public static function likedBy($status)
{
2021-05-03 23:55:06 +00:00
$empty = [
'username' => null,
'others' => false
];
if(!$status) {
return $empty;
}
$res = Cache::remember('pf:services:likes:liked_by:' . $status->id, 86400, function() use($status, $empty) {
$like = Like::whereStatusId($status->id)->first();
if(!$like) {
return $empty;
}
$id = $like->profile_id;
$profile = ProfileService::get($id);
$profileUrl = "/i/web/profile/{$profile['id']}";
$res = [
'id' => (string) $profile['id'],
'username' => $profile['username'],
'url' => $profileUrl,
'others' => $status->likes_count >= 3,
];
return $res;
});
2021-05-03 23:55:06 +00:00
if(!isset($res['id']) || !isset($res['url'])) {
2021-05-03 23:55:06 +00:00
return $empty;
}
$res['total_count'] = ($status->likes_count - 1);
$res['total_count_pretty'] = number_format($res['total_count']);
return $res;
2021-05-01 21:51:02 +00:00
}
2021-08-31 06:37:40 +00:00
public static function count($id)
{
return Cache::get('pf:services:likes:count:'.$id, 0);
2021-08-31 06:37:40 +00:00
}
2021-05-01 21:51:02 +00:00
}