ApiController.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Http\Controllers\Api\BaseApiController;
  4. use App\{
  5. Follower,
  6. Like,
  7. Profile,
  8. UserFilter
  9. };
  10. use Auth, Cache, Redis;
  11. use App\Util\Site\Config;
  12. use Illuminate\Http\Request;
  13. use App\Services\SuggestionService;
  14. class ApiController extends BaseApiController
  15. {
  16. // todo: deprecate and remove
  17. public function hydrateLikes(Request $request)
  18. {
  19. return response()->json([]);
  20. }
  21. public function siteConfiguration(Request $request)
  22. {
  23. return response()->json(Config::get());
  24. }
  25. public function userRecommendations(Request $request)
  26. {
  27. abort_if(!Auth::check(), 403);
  28. abort_if(!config('exp.rec'), 400);
  29. $id = Auth::user()->profile->id;
  30. $following = Cache::remember('profile:following:'.$id, now()->addHours(12), function() use ($id) {
  31. return Follower::whereProfileId($id)->pluck('following_id')->toArray();
  32. });
  33. array_push($following, $id);
  34. $ids = SuggestionService::get();
  35. $filters = UserFilter::whereUserId($id)
  36. ->whereFilterableType('App\Profile')
  37. ->whereIn('filter_type', ['mute', 'block'])
  38. ->pluck('filterable_id')->toArray();
  39. $following = array_merge($following, $filters);
  40. $key = config('cache.prefix').':api:local:exp:rec:'.$id;
  41. $ttl = (int) Redis::ttl($key);
  42. if($request->filled('refresh') == true && (290 > $ttl) == true) {
  43. Cache::forget('api:local:exp:rec:'.$id);
  44. }
  45. $res = Cache::remember('api:local:exp:rec:'.$id, now()->addMinutes(5), function() use($id, $following, $ids) {
  46. return Profile::select(
  47. 'id',
  48. 'username'
  49. )
  50. ->whereNotIn('id', $following)
  51. ->whereIn('id', $ids)
  52. ->whereIsPrivate(0)
  53. ->whereNull('status')
  54. ->whereNull('domain')
  55. ->inRandomOrder()
  56. ->take(3)
  57. ->get()
  58. ->map(function($item, $key) {
  59. return [
  60. 'id' => $item->id,
  61. 'avatar' => $item->avatarUrl(),
  62. 'username' => $item->username,
  63. 'message' => 'Recommended for You'
  64. ];
  65. });
  66. });
  67. return response()->json($res->all());
  68. }
  69. }