DiscoverController.php 8.3 KB

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