1
0

DiscoverController.php 9.4 KB

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