BookmarkController.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Bookmark;
  4. use App\Services\AccountService;
  5. use App\Services\BookmarkService;
  6. use App\Services\FollowerService;
  7. use App\Services\UserRoleService;
  8. use App\Status;
  9. use Illuminate\Http\Request;
  10. class BookmarkController extends Controller
  11. {
  12. public function __construct()
  13. {
  14. $this->middleware('auth');
  15. }
  16. public function store(Request $request)
  17. {
  18. $this->validate($request, [
  19. 'item' => 'required|integer|min:1',
  20. ]);
  21. $user = $request->user();
  22. $status = Status::findOrFail($request->input('item'));
  23. $account = AccountService::get($status->profile_id);
  24. abort_if(isset($account['moved'], $account['moved']['id']), 422, 'Cannot bookmark or unbookmark a post from an account that has migrated');
  25. abort_if($user->has_roles && ! UserRoleService::can('can-bookmark', $user->id), 403, 'Invalid permissions for this action');
  26. abort_if($status->in_reply_to_id || $status->reblog_of_id, 404);
  27. abort_if(! in_array($status->scope, ['public', 'unlisted', 'private']), 404);
  28. abort_if(! in_array($status->type, ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album']), 404);
  29. if ($status->scope == 'private') {
  30. if ($user->profile_id !== $status->profile_id && ! FollowerService::follows($user->profile_id, $status->profile_id)) {
  31. if ($exists = Bookmark::whereStatusId($status->id)->whereProfileId($user->profile_id)->first()) {
  32. BookmarkService::del($user->profile_id, $status->id);
  33. $exists->delete();
  34. if ($request->ajax()) {
  35. return ['code' => 200, 'msg' => 'Bookmark removed!'];
  36. } else {
  37. return redirect()->back();
  38. }
  39. }
  40. abort(404, 'Error: You cannot bookmark private posts from accounts you do not follow.');
  41. }
  42. }
  43. $bookmark = Bookmark::firstOrCreate(
  44. ['status_id' => $status->id], ['profile_id' => $user->profile_id]
  45. );
  46. if (! $bookmark->wasRecentlyCreated) {
  47. BookmarkService::del($user->profile_id, $status->id);
  48. $bookmark->delete();
  49. } else {
  50. BookmarkService::add($user->profile_id, $status->id);
  51. }
  52. return $request->expectsJson() ? ['code' => 200, 'msg' => 'Bookmark saved!'] : redirect()->back();
  53. }
  54. }