DiscoverController.php 9.1 KB

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