pixelfed/app/Services/FollowerService.php

71 lines
1.7 KiB
PHP
Raw Normal View History

2019-02-14 21:24:34 +00:00
<?php
namespace App\Services;
use Redis;
use App\{
Follower,
Profile
};
class FollowerService {
protected $profile;
2019-12-05 02:47:00 +00:00
static $follower_prefix = 'px:profile:followers-v1.3:';
static $following_prefix = 'px:profile:following-v1.3:';
2019-02-14 21:24:34 +00:00
public static function build()
{
return new self();
}
public function profile(Profile $profile)
{
$this->profile = $profile;
2019-12-05 02:47:00 +00:00
self::$follower_prefix .= $profile->id;
self::$following_prefix .= $profile->id;
2019-02-14 21:24:34 +00:00
return $this;
}
2019-12-05 02:47:00 +00:00
public function followers($limit = 100, $offset = 1)
2019-02-14 21:24:34 +00:00
{
2019-12-05 02:47:00 +00:00
if(Redis::zcard(self::$follower_prefix) == 0) {
$followers = $this->profile->followers()->pluck('profile_id');
2019-02-14 21:24:34 +00:00
$followers->map(function($i) {
2019-12-05 02:47:00 +00:00
Redis::zadd(self::$follower_prefix, $i, $i);
2019-02-14 21:24:34 +00:00
});
2019-12-05 02:47:00 +00:00
return Redis::zrevrange(self::$follower_prefix, $offset, $limit);
2019-02-14 21:24:34 +00:00
} else {
2019-12-05 02:47:00 +00:00
return Redis::zrevrange(self::$follower_prefix, $offset, $limit);
2019-02-14 21:24:34 +00:00
}
}
2019-12-05 02:47:00 +00:00
public function following($limit = 100, $offset = 1)
2019-02-14 21:24:34 +00:00
{
2019-12-05 02:47:00 +00:00
if(Redis::zcard(self::$following_prefix) == 0) {
$following = $this->profile->following()->pluck('following_id');
2019-02-14 21:24:34 +00:00
$following->map(function($i) {
2019-12-05 02:47:00 +00:00
Redis::zadd(self::$following_prefix, $i, $i);
2019-02-14 21:24:34 +00:00
});
2019-12-05 02:47:00 +00:00
return Redis::zrevrange(self::$following_prefix, $offset, $limit);
2019-02-14 21:24:34 +00:00
} else {
2019-12-05 02:47:00 +00:00
return Redis::zrevrange(self::$following_prefix, $offset, $limit);
}
}
public static function follows(string $actor, string $target)
{
$key = self::$follower_prefix . $target;
if(Redis::zcard($key) == 0) {
$p = Profile::findOrFail($target);
self::build()->profile($p)->followers(1);
self::build()->profile($p)->following(1);
return (bool) Redis::zrank($key, $actor);
} else {
return (bool) Redis::zrank($key, $actor);
2019-02-14 21:24:34 +00:00
}
}
}