DiscoverController.php 12 KB

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