FollowerController.php 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\{
  4. Follower,
  5. FollowRequest,
  6. Profile,
  7. UserFilter
  8. };
  9. use Auth, Cache;
  10. use Illuminate\Http\Request;
  11. use App\Jobs\FollowPipeline\FollowPipeline;
  12. class FollowerController extends Controller
  13. {
  14. public function __construct()
  15. {
  16. $this->middleware('auth');
  17. }
  18. public function store(Request $request)
  19. {
  20. $this->validate($request, [
  21. 'item' => 'required|integer',
  22. ]);
  23. $item = $request->input('item');
  24. $this->handleFollowRequest($item);
  25. if($request->wantsJson()) {
  26. return response()->json([
  27. 200
  28. ], 200);
  29. }
  30. return redirect()->back();
  31. }
  32. protected function handleFollowRequest($item)
  33. {
  34. $user = Auth::user()->profile;
  35. $target = Profile::where('id', '!=', $user->id)->whereNull('status')->findOrFail($item);
  36. $private = (bool) $target->is_private;
  37. $remote = (bool) $target->domain;
  38. $blocked = UserFilter::whereUserId($target->id)
  39. ->whereFilterType('block')
  40. ->whereFilterableId($user->id)
  41. ->whereFilterableType('App\Profile')
  42. ->exists();
  43. if($blocked == true) {
  44. abort(400, 'You cannot follow this user.');
  45. }
  46. $isFollowing = Follower::whereProfileId($user->id)->whereFollowingId($target->id)->count();
  47. if($private == true && $isFollowing == 0 || $remote == true) {
  48. $follow = FollowRequest::firstOrCreate([
  49. 'follower_id' => $user->id,
  50. 'following_id' => $target->id
  51. ]);
  52. if($remote == true) {
  53. }
  54. } elseif ($isFollowing == 0) {
  55. if($user->following()->count() >= Follower::MAX_FOLLOWING) {
  56. abort(400, 'You cannot follow more than ' . Follower::MAX_FOLLOWING . ' accounts');
  57. }
  58. if($user->following()->where('followers.created_at', '>', now()->subHour())->count() >= Follower::FOLLOW_PER_HOUR) {
  59. abort(400, 'You can only follow ' . Follower::FOLLOW_PER_HOUR . ' users per hour');
  60. }
  61. $follower = new Follower();
  62. $follower->profile_id = $user->id;
  63. $follower->following_id = $target->id;
  64. $follower->save();
  65. FollowPipeline::dispatch($follower);
  66. } else {
  67. $follower = Follower::whereProfileId($user->id)->whereFollowingId($target->id)->firstOrFail();
  68. $follower->delete();
  69. }
  70. Cache::forget('profile:following:'.$target->id);
  71. Cache::forget('profile:followers:'.$target->id);
  72. Cache::forget('profile:following:'.$user->id);
  73. Cache::forget('profile:followers:'.$user->id);
  74. Cache::forget('api:local:exp:rec:'.$user->id);
  75. Cache::forget('user:account:id:'.$target->user_id);
  76. Cache::forget('user:account:id:'.$user->user_id);
  77. }
  78. }