DiscoverController.php 9.6 KB

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