DiscoverController.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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', 3600, function() {
  165. return StatusHashtag::select('hashtag_id', \DB::raw('count(*) as total'))
  166. ->groupBy('hashtag_id')
  167. ->orderBy('total','desc')
  168. ->where('created_at', '>', now()->subDays(90))
  169. ->take(9)
  170. ->get()
  171. ->map(function($h) {
  172. $hashtag = $h->hashtag;
  173. return [
  174. 'id' => $hashtag->id,
  175. 'total' => $h->total,
  176. 'name' => '#'.$hashtag->name,
  177. 'url' => $hashtag->url()
  178. ];
  179. });
  180. });
  181. return $res;
  182. }
  183. public function trendingPlaces(Request $request)
  184. {
  185. return [];
  186. }
  187. public function myMemories(Request $request)
  188. {
  189. abort_if(!$request->user(), 404);
  190. $pid = $request->user()->profile_id;
  191. abort_if(!$this->config()['memories']['enabled'], 404);
  192. $type = $request->input('type') ?? 'posts';
  193. switch($type) {
  194. case 'posts':
  195. $res = Status::whereProfileId($pid)
  196. ->whereDay('created_at', date('d'))
  197. ->whereMonth('created_at', date('m'))
  198. ->whereYear('created_at', '!=', date('Y'))
  199. ->whereNull(['reblog_of_id', 'in_reply_to_id'])
  200. ->limit(20)
  201. ->pluck('id')
  202. ->map(function($id) {
  203. return StatusService::get($id, false);
  204. })
  205. ->filter(function($post) {
  206. return $post && isset($post['account']);
  207. })
  208. ->values();
  209. break;
  210. case 'liked':
  211. $res = Like::whereProfileId($pid)
  212. ->whereDay('created_at', date('d'))
  213. ->whereMonth('created_at', date('m'))
  214. ->whereYear('created_at', '!=', date('Y'))
  215. ->orderByDesc('status_id')
  216. ->limit(20)
  217. ->pluck('status_id')
  218. ->map(function($id) {
  219. $status = StatusService::get($id, false);
  220. $status['favourited'] = true;
  221. return $status;
  222. })
  223. ->filter(function($post) {
  224. return $post && isset($post['account']);
  225. })
  226. ->values();
  227. break;
  228. }
  229. return $res;
  230. }
  231. public function accountInsightsPopularPosts(Request $request)
  232. {
  233. abort_if(!$request->user(), 404);
  234. $pid = $request->user()->profile_id;
  235. abort_if(!$this->config()['insights']['enabled'], 404);
  236. $posts = Cache::remember('pf:discover:metro2:accinsights:popular:' . $pid, 43200, function() use ($pid) {
  237. return Status::whereProfileId($pid)
  238. ->whereNotNull('likes_count')
  239. ->orderByDesc('likes_count')
  240. ->limit(12)
  241. ->pluck('id')
  242. ->map(function($id) {
  243. return StatusService::get($id, false);
  244. })
  245. ->filter(function($post) {
  246. return $post && isset($post['account']);
  247. })
  248. ->values();
  249. });
  250. return $posts;
  251. }
  252. public function config()
  253. {
  254. $cc = ConfigCacheService::get('config.discover.features');
  255. if($cc) {
  256. return is_string($cc) ? json_decode($cc, true) : $cc;
  257. }
  258. return [
  259. 'hashtags' => [
  260. 'enabled' => false,
  261. ],
  262. 'memories' => [
  263. 'enabled' => false,
  264. ],
  265. 'insights' => [
  266. 'enabled' => false,
  267. ],
  268. 'friends' => [
  269. 'enabled' => false,
  270. ],
  271. 'server' => [
  272. 'enabled' => false,
  273. 'mode' => 'allowlist',
  274. 'domains' => []
  275. ]
  276. ];
  277. }
  278. public function serverTimeline(Request $request)
  279. {
  280. abort_if(!$request->user(), 404);
  281. abort_if(!$this->config()['server']['enabled'], 404);
  282. $pid = $request->user()->profile_id;
  283. $domain = $request->input('domain');
  284. $config = $this->config();
  285. $domains = explode(',', $config['server']['domains']);
  286. abort_unless(in_array($domain, $domains), 400);
  287. $res = Status::whereNotNull('uri')
  288. ->where('uri', 'like', 'https://' . $domain . '%')
  289. ->whereNull(['in_reply_to_id', 'reblog_of_id'])
  290. ->orderByDesc('id')
  291. ->limit(12)
  292. ->pluck('id')
  293. ->map(function($id) {
  294. return StatusService::get($id);
  295. })
  296. ->filter(function($post) {
  297. return $post && isset($post['account']);
  298. })
  299. ->values();
  300. return $res;
  301. }
  302. public function enabledFeatures(Request $request)
  303. {
  304. abort_if(!$request->user(), 404);
  305. return $this->config();
  306. }
  307. public function updateFeatures(Request $request)
  308. {
  309. abort_if(!$request->user(), 404);
  310. abort_if(!$request->user()->is_admin, 404);
  311. $pid = $request->user()->profile_id;
  312. $this->validate($request, [
  313. 'features.friends.enabled' => 'boolean',
  314. 'features.hashtags.enabled' => 'boolean',
  315. 'features.insights.enabled' => 'boolean',
  316. 'features.memories.enabled' => 'boolean',
  317. 'features.server.enabled' => 'boolean',
  318. ]);
  319. $res = $request->input('features');
  320. if($res['server'] && isset($res['server']['domains']) && !empty($res['server']['domains'])) {
  321. $parts = explode(',', $res['server']['domains']);
  322. $parts = array_filter($parts, function($v) {
  323. $len = strlen($v);
  324. $pos = strpos($v, '.');
  325. $domain = trim($v);
  326. if($pos == false || $pos == ($len + 1)) {
  327. return false;
  328. }
  329. if(!Instance::whereDomain($domain)->exists()) {
  330. return false;
  331. }
  332. return true;
  333. });
  334. $parts = array_slice($parts, 0, 10);
  335. $d = implode(',', array_map('trim', $parts));
  336. $res['server']['domains'] = $d;
  337. }
  338. ConfigCacheService::put('config.discover.features', json_encode($res));
  339. return $res;
  340. }
  341. }