DiscoverController.php 9.2 KB

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