DiscoverController.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Hashtag;
  4. use App\Instance;
  5. use App\Like;
  6. use App\Services\AccountService;
  7. use App\Services\AdminShadowFilterService;
  8. use App\Services\BookmarkService;
  9. use App\Services\ConfigCacheService;
  10. use App\Services\FollowerService;
  11. use App\Services\HashtagService;
  12. use App\Services\Internal\BeagleService;
  13. use App\Services\LikeService;
  14. use App\Services\ReblogService;
  15. use App\Services\SnowflakeService;
  16. use App\Services\StatusHashtagService;
  17. use App\Services\StatusService;
  18. use App\Services\TrendingHashtagService;
  19. use App\Services\UserFilterService;
  20. use App\Status;
  21. use Auth;
  22. use Cache;
  23. use DB;
  24. use Illuminate\Http\Request;
  25. class DiscoverController extends Controller
  26. {
  27. public function home(Request $request)
  28. {
  29. abort_if(! Auth::check() && config('instance.discover.public') == false, 403);
  30. return view('discover.home');
  31. }
  32. public function showTags(Request $request, $hashtag)
  33. {
  34. if ($request->user()) {
  35. return redirect('/i/web/hashtag/'.$hashtag.'?src=pd');
  36. }
  37. abort_if(! config('instance.discover.tags.is_public') && ! Auth::check(), 403);
  38. $tag = Hashtag::whereName($hashtag)
  39. ->orWhere('slug', $hashtag)
  40. ->where('is_banned', '!=', true)
  41. ->firstOrFail();
  42. $tagCount = $tag->cached_count ?? 0;
  43. return view('discover.tags.show', compact('tag', 'tagCount'));
  44. }
  45. public function getHashtags(Request $request)
  46. {
  47. $user = $request->user();
  48. abort_if(! config('instance.discover.tags.is_public') && ! $user, 403);
  49. $this->validate($request, [
  50. 'hashtag' => 'required|string|min:1|max:124',
  51. 'page' => 'nullable|integer|min:1',
  52. ]);
  53. $page = $request->input('page') ?? '1';
  54. $end = $page > 1 ? $page * 9 : (($page * 9) + 9);
  55. $tag = $request->input('hashtag');
  56. if (config('database.default') === 'pgsql') {
  57. $hashtag = Hashtag::where('name', 'ilike', $tag)->firstOrFail();
  58. } else {
  59. $hashtag = Hashtag::whereName($tag)->firstOrFail();
  60. }
  61. if ($hashtag->is_banned == true) {
  62. return [];
  63. }
  64. if ($user) {
  65. $res['follows'] = HashtagService::isFollowing($user->profile_id, $hashtag->id);
  66. }
  67. $res['hashtag'] = [
  68. 'name' => $hashtag->name,
  69. 'url' => $hashtag->url(),
  70. ];
  71. $res['tags'] = [];
  72. if ($page >= 8) {
  73. if ($user) {
  74. if ($page >= 29) {
  75. return $res;
  76. }
  77. } else {
  78. return $res;
  79. }
  80. }
  81. if ($user) {
  82. $tags = StatusHashtagService::get($hashtag->id, $page, $end);
  83. $res['tags'] = collect($tags)
  84. ->map(function ($tag) use ($user) {
  85. $tag['status']['favourited'] = (bool) LikeService::liked($user->profile_id, $tag['status']['id']);
  86. $tag['status']['reblogged'] = (bool) ReblogService::get($user->profile_id, $tag['status']['id']);
  87. $tag['status']['bookmarked'] = (bool) BookmarkService::get($user->profile_id, $tag['status']['id']);
  88. return $tag;
  89. })
  90. ->filter(function ($tag) {
  91. if (! StatusService::get($tag['status']['id'])) {
  92. return false;
  93. }
  94. return true;
  95. })
  96. ->values();
  97. } else {
  98. $key = 'discover:tags:public_feed:'.$hashtag->id.':page:'.$page.':end'.$end;
  99. $tags = StatusHashtagService::get($hashtag->id, $page, $end);
  100. $res['tags'] = collect($tags)
  101. ->filter(function ($tag) {
  102. if (! StatusService::get($tag['status']['id'])) {
  103. return false;
  104. }
  105. return true;
  106. })
  107. ->values();
  108. }
  109. return $res;
  110. }
  111. public function profilesDirectory(Request $request)
  112. {
  113. return redirect('/')->with('statusRedirect', 'The Profile Directory is unavailable at this time.');
  114. }
  115. public function profilesDirectoryApi(Request $request)
  116. {
  117. return ['error' => 'Temporarily unavailable.'];
  118. }
  119. public function trendingApi(Request $request)
  120. {
  121. abort_if(config('instance.discover.public') == false && ! $request->user(), 403);
  122. $this->validate($request, [
  123. 'range' => 'nullable|string|in:daily,monthly,yearly',
  124. ]);
  125. $range = $request->input('range');
  126. $days = $range == 'monthly' ? 31 : ($range == 'daily' ? 1 : 365);
  127. $ttls = [
  128. 1 => 1500,
  129. 31 => 14400,
  130. 365 => 86400,
  131. ];
  132. $key = ':api:discover:trending:v2.12:range:'.$days;
  133. $ids = Cache::remember($key, $ttls[$days], function () use ($days) {
  134. $min_id = SnowflakeService::byDate(now()->subDays($days));
  135. return DB::table('statuses')
  136. ->select(
  137. 'id',
  138. 'scope',
  139. 'type',
  140. 'is_nsfw',
  141. 'likes_count',
  142. 'created_at'
  143. )
  144. ->where('id', '>', $min_id)
  145. ->whereNull('uri')
  146. ->whereScope('public')
  147. ->whereIn('type', [
  148. 'photo',
  149. 'photo:album',
  150. 'video',
  151. ])
  152. ->whereIsNsfw(false)
  153. ->orderBy('likes_count', 'desc')
  154. ->take(30)
  155. ->pluck('id');
  156. });
  157. $filtered = Auth::check() ? UserFilterService::filters(Auth::user()->profile_id) : [];
  158. $res = $ids->map(function ($s) {
  159. return StatusService::get($s);
  160. })->filter(function ($s) use ($filtered) {
  161. return
  162. $s &&
  163. isset($s['account'], $s['account']['id']) &&
  164. ! in_array($s['account']['id'], $filtered) &&
  165. isset($s['account']);
  166. })->values();
  167. return response()->json($res);
  168. }
  169. public function trendingHashtags(Request $request)
  170. {
  171. abort_if(! $request->user(), 403);
  172. $res = TrendingHashtagService::getTrending();
  173. return $res;
  174. }
  175. public function trendingPlaces(Request $request)
  176. {
  177. return [];
  178. }
  179. public function myMemories(Request $request)
  180. {
  181. abort_if(! $request->user(), 404);
  182. $pid = $request->user()->profile_id;
  183. abort_if(! $this->config()['memories']['enabled'], 404);
  184. $type = $request->input('type') ?? 'posts';
  185. switch ($type) {
  186. case 'posts':
  187. $res = Status::whereProfileId($pid)
  188. ->whereDay('created_at', date('d'))
  189. ->whereMonth('created_at', date('m'))
  190. ->whereYear('created_at', '!=', date('Y'))
  191. ->whereNull(['reblog_of_id', 'in_reply_to_id'])
  192. ->limit(20)
  193. ->pluck('id')
  194. ->map(function ($id) {
  195. return StatusService::get($id, false);
  196. })
  197. ->filter(function ($post) {
  198. return $post && isset($post['account']);
  199. })
  200. ->values();
  201. break;
  202. case 'liked':
  203. $res = Like::whereProfileId($pid)
  204. ->whereDay('created_at', date('d'))
  205. ->whereMonth('created_at', date('m'))
  206. ->whereYear('created_at', '!=', date('Y'))
  207. ->orderByDesc('status_id')
  208. ->limit(20)
  209. ->pluck('status_id')
  210. ->map(function ($id) {
  211. $status = StatusService::get($id, false);
  212. $status['favourited'] = true;
  213. return $status;
  214. })
  215. ->filter(function ($post) {
  216. return $post && isset($post['account']);
  217. })
  218. ->values();
  219. break;
  220. }
  221. return $res;
  222. }
  223. public function accountInsightsPopularPosts(Request $request)
  224. {
  225. abort_if(! $request->user(), 404);
  226. $pid = $request->user()->profile_id;
  227. abort_if(! $this->config()['insights']['enabled'], 404);
  228. $posts = Cache::remember('pf:discover:metro2:accinsights:popular:'.$pid, 43200, function () use ($pid) {
  229. return Status::whereProfileId($pid)
  230. ->whereNotNull('likes_count')
  231. ->orderByDesc('likes_count')
  232. ->limit(12)
  233. ->pluck('id')
  234. ->map(function ($id) {
  235. return StatusService::get($id, false);
  236. })
  237. ->filter(function ($post) {
  238. return $post && isset($post['account']);
  239. })
  240. ->values();
  241. });
  242. return $posts;
  243. }
  244. public function config()
  245. {
  246. $cc = ConfigCacheService::get('config.discover.features');
  247. if ($cc) {
  248. return is_string($cc) ? json_decode($cc, true) : $cc;
  249. }
  250. return [
  251. 'hashtags' => [
  252. 'enabled' => false,
  253. ],
  254. 'memories' => [
  255. 'enabled' => false,
  256. ],
  257. 'insights' => [
  258. 'enabled' => false,
  259. ],
  260. 'friends' => [
  261. 'enabled' => false,
  262. ],
  263. 'server' => [
  264. 'enabled' => false,
  265. 'mode' => 'allowlist',
  266. 'domains' => [],
  267. ],
  268. ];
  269. }
  270. public function serverTimeline(Request $request)
  271. {
  272. abort_if(! $request->user(), 404);
  273. abort_if(! $this->config()['server']['enabled'], 404);
  274. $pid = $request->user()->profile_id;
  275. $domain = $request->input('domain');
  276. $config = $this->config();
  277. $domains = explode(',', $config['server']['domains']);
  278. abort_unless(in_array($domain, $domains), 400);
  279. $res = Status::whereNotNull('uri')
  280. ->where('uri', 'like', 'https://'.$domain.'%')
  281. ->whereNull(['in_reply_to_id', 'reblog_of_id'])
  282. ->orderByDesc('id')
  283. ->limit(12)
  284. ->pluck('id')
  285. ->map(function ($id) {
  286. return StatusService::get($id);
  287. })
  288. ->filter(function ($post) {
  289. return $post && isset($post['account']);
  290. })
  291. ->values();
  292. return $res;
  293. }
  294. public function enabledFeatures(Request $request)
  295. {
  296. abort_if(! $request->user(), 404);
  297. return $this->config();
  298. }
  299. public function updateFeatures(Request $request)
  300. {
  301. abort_if(! $request->user(), 404);
  302. abort_if(! $request->user()->is_admin, 404);
  303. $pid = $request->user()->profile_id;
  304. $this->validate($request, [
  305. 'features.friends.enabled' => 'boolean',
  306. 'features.hashtags.enabled' => 'boolean',
  307. 'features.insights.enabled' => 'boolean',
  308. 'features.memories.enabled' => 'boolean',
  309. 'features.server.enabled' => 'boolean',
  310. ]);
  311. $res = $request->input('features');
  312. if ($res['server'] && isset($res['server']['domains']) && ! empty($res['server']['domains'])) {
  313. $parts = explode(',', $res['server']['domains']);
  314. $parts = array_filter($parts, function ($v) {
  315. $len = strlen($v);
  316. $pos = strpos($v, '.');
  317. $domain = trim($v);
  318. if ($pos == false || $pos == ($len + 1)) {
  319. return false;
  320. }
  321. if (! Instance::whereDomain($domain)->exists()) {
  322. return false;
  323. }
  324. return true;
  325. });
  326. $parts = array_slice($parts, 0, 10);
  327. $d = implode(',', array_map('trim', $parts));
  328. $res['server']['domains'] = $d;
  329. }
  330. ConfigCacheService::put('config.discover.features', json_encode($res));
  331. return $res;
  332. }
  333. public function discoverAccountsPopular(Request $request)
  334. {
  335. abort_if(! $request->user(), 403);
  336. $pid = $request->user()->profile_id;
  337. $ids = Cache::remember('api:v1.1:discover:accounts:popular', 14400, function () {
  338. return DB::table('profiles')
  339. ->where('is_private', false)
  340. ->whereNull('status')
  341. ->orderByDesc('profiles.followers_count')
  342. ->limit(30)
  343. ->get();
  344. });
  345. $filters = UserFilterService::filters($pid);
  346. $asf = AdminShadowFilterService::getHideFromPublicFeedsList();
  347. $ids = $ids->map(function ($profile) {
  348. return AccountService::get($profile->id, true);
  349. })
  350. ->filter(function ($profile) {
  351. return $profile && isset($profile['id'], $profile['locked']) && ! $profile['locked'];
  352. })
  353. ->filter(function ($profile) use ($pid) {
  354. return $profile['id'] != $pid;
  355. })
  356. ->filter(function ($profile) use ($pid) {
  357. return ! FollowerService::follows($pid, $profile['id'], true);
  358. })
  359. ->filter(function ($profile) use ($asf) {
  360. return ! in_array($profile['id'], $asf);
  361. })
  362. ->filter(function ($profile) use ($filters) {
  363. return ! in_array($profile['id'], $filters);
  364. })
  365. ->take(16)
  366. ->values();
  367. return response()->json($ids, 200, [], JSON_UNESCAPED_SLASHES);
  368. }
  369. public function discoverNetworkTrending(Request $request)
  370. {
  371. abort_if(! $request->user(), 404);
  372. return BeagleService::getDiscoverPosts();
  373. }
  374. }