1
0

DiscoverController.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. $status = StatusService::get($id, false);
  191. $status['favourited'] = true;
  192. return $status;
  193. })
  194. ->filter(function($post) {
  195. return $post && isset($post['account']);
  196. })
  197. ->values();
  198. break;
  199. }
  200. return $res;
  201. }
  202. public function accountInsightsPopularPosts(Request $request)
  203. {
  204. abort_if(!$request->user(), 404);
  205. $pid = $request->user()->profile_id;
  206. abort_if(!$this->config()['insights']['enabled'], 404);
  207. $posts = Cache::remember('pf:discover:metro2:accinsights:popular:' . $pid, 43200, function() use ($pid) {
  208. return Status::whereProfileId($pid)
  209. ->whereNotNull('likes_count')
  210. ->orderByDesc('likes_count')
  211. ->limit(12)
  212. ->pluck('id')
  213. ->map(function($id) {
  214. return StatusService::get($id, false);
  215. })
  216. ->filter(function($post) {
  217. return $post && isset($post['account']);
  218. })
  219. ->values();
  220. });
  221. return $posts;
  222. }
  223. public function config()
  224. {
  225. $cc = ConfigCacheService::get('config.discover.features');
  226. if($cc) {
  227. return is_string($cc) ? json_decode($cc, true) : $cc;
  228. }
  229. return [
  230. 'hashtags' => [
  231. 'enabled' => false,
  232. ],
  233. 'memories' => [
  234. 'enabled' => false,
  235. ],
  236. 'insights' => [
  237. 'enabled' => false,
  238. ],
  239. 'friends' => [
  240. 'enabled' => false,
  241. ],
  242. 'server' => [
  243. 'enabled' => false,
  244. 'mode' => 'allowlist',
  245. 'domains' => []
  246. ]
  247. ];
  248. }
  249. public function serverTimeline(Request $request)
  250. {
  251. abort_if(!$request->user(), 404);
  252. abort_if(!$this->config()['server']['enabled'], 404);
  253. $pid = $request->user()->profile_id;
  254. $domain = $request->input('domain');
  255. $config = $this->config();
  256. $domains = explode(',', $config['server']['domains']);
  257. abort_unless(in_array($domain, $domains), 400);
  258. $res = Status::whereNotNull('uri')
  259. ->where('uri', 'like', 'https://' . $domain . '%')
  260. ->whereNull(['in_reply_to_id', 'reblog_of_id'])
  261. ->orderByDesc('id')
  262. ->limit(12)
  263. ->pluck('id')
  264. ->map(function($id) {
  265. return StatusService::get($id);
  266. })
  267. ->filter(function($post) {
  268. return $post && isset($post['account']);
  269. })
  270. ->values();
  271. return $res;
  272. }
  273. public function enabledFeatures(Request $request)
  274. {
  275. abort_if(!$request->user(), 404);
  276. return $this->config();
  277. }
  278. public function updateFeatures(Request $request)
  279. {
  280. abort_if(!$request->user(), 404);
  281. abort_if(!$request->user()->is_admin, 404);
  282. $pid = $request->user()->profile_id;
  283. $this->validate($request, [
  284. 'features.friends.enabled' => 'boolean',
  285. 'features.hashtags.enabled' => 'boolean',
  286. 'features.insights.enabled' => 'boolean',
  287. 'features.memories.enabled' => 'boolean',
  288. 'features.server.enabled' => 'boolean',
  289. ]);
  290. $res = $request->input('features');
  291. if($res['server'] && isset($res['server']['domains']) && !empty($res['server']['domains'])) {
  292. $parts = explode(',', $res['server']['domains']);
  293. $parts = array_filter($parts, function($v) {
  294. $len = strlen($v);
  295. $pos = strpos($v, '.');
  296. $domain = trim($v);
  297. if($pos == false || $pos == ($len + 1)) {
  298. return false;
  299. }
  300. if(!Instance::whereDomain($domain)->exists()) {
  301. return false;
  302. }
  303. return true;
  304. });
  305. $parts = array_slice($parts, 0, 10);
  306. $d = implode(',', array_map('trim', $parts));
  307. $res['server']['domains'] = $d;
  308. }
  309. ConfigCacheService::put('config.discover.features', json_encode($res));
  310. return $res;
  311. }
  312. }