DiscoverController.php 9.7 KB

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