DiscoverController.php 14 KB

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