1
0

DiscoverController.php 9.2 KB

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