DiscoverController.php 9.1 KB

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