InternalApiController.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use App\{
  5. AccountInterstitial,
  6. Bookmark,
  7. DirectMessage,
  8. DiscoverCategory,
  9. Hashtag,
  10. Follower,
  11. Like,
  12. Media,
  13. MediaTag,
  14. Notification,
  15. Profile,
  16. StatusHashtag,
  17. Status,
  18. User,
  19. UserFilter,
  20. };
  21. use Auth,Cache;
  22. use Illuminate\Support\Facades\Redis;
  23. use Carbon\Carbon;
  24. use League\Fractal;
  25. use App\Transformer\Api\{
  26. AccountTransformer,
  27. StatusTransformer,
  28. // StatusMediaContainerTransformer,
  29. };
  30. use App\Util\Media\Filter;
  31. use App\Jobs\StatusPipeline\NewStatusPipeline;
  32. use App\Jobs\ModPipeline\HandleSpammerPipeline;
  33. use League\Fractal\Serializer\ArraySerializer;
  34. use League\Fractal\Pagination\IlluminatePaginatorAdapter;
  35. use Illuminate\Validation\Rule;
  36. use Illuminate\Support\Str;
  37. use App\Services\MediaTagService;
  38. use App\Services\ModLogService;
  39. use App\Services\PublicTimelineService;
  40. use App\Services\SnowflakeService;
  41. use App\Services\StatusService;
  42. class InternalApiController extends Controller
  43. {
  44. protected $fractal;
  45. public function __construct()
  46. {
  47. $this->middleware('auth');
  48. $this->fractal = new Fractal\Manager();
  49. $this->fractal->setSerializer(new ArraySerializer());
  50. }
  51. // deprecated v2 compose api
  52. public function compose(Request $request)
  53. {
  54. return redirect('/');
  55. }
  56. // deprecated
  57. public function discover(Request $request)
  58. {
  59. return;
  60. }
  61. public function discoverPosts(Request $request)
  62. {
  63. $profile = Auth::user()->profile;
  64. $pid = $profile->id;
  65. $following = Cache::remember('feature:discover:following:'.$pid, now()->addMinutes(15), function() use ($pid) {
  66. return Follower::whereProfileId($pid)->pluck('following_id')->toArray();
  67. });
  68. $filters = Cache::remember("user:filter:list:$pid", now()->addMinutes(15), function() use($pid) {
  69. $private = Profile::whereIsPrivate(true)
  70. ->orWhere('unlisted', true)
  71. ->orWhere('status', '!=', null)
  72. ->pluck('id')
  73. ->toArray();
  74. $filters = UserFilter::whereUserId($pid)
  75. ->whereFilterableType('App\Profile')
  76. ->whereIn('filter_type', ['mute', 'block'])
  77. ->pluck('filterable_id')
  78. ->toArray();
  79. return array_merge($private, $filters);
  80. });
  81. $following = array_merge($following, $filters);
  82. $sql = config('database.default') !== 'pgsql';
  83. $min_id = SnowflakeService::byDate(now()->subMonths(3));
  84. $posts = Status::select(
  85. 'id',
  86. 'is_nsfw',
  87. 'profile_id',
  88. 'type',
  89. 'uri',
  90. )
  91. ->whereNull('uri')
  92. ->whereIn('type', ['photo','photo:album', 'video'])
  93. ->whereIsNsfw(false)
  94. ->whereVisibility('public')
  95. ->whereNotIn('profile_id', $following)
  96. ->where('id', '>', $min_id)
  97. ->inRandomOrder()
  98. ->take(39)
  99. ->pluck('id');
  100. $res = [
  101. 'posts' => $posts->map(function($post) {
  102. return StatusService::get($post);
  103. })
  104. ];
  105. return response()->json($res);
  106. }
  107. public function directMessage(Request $request, $profileId, $threadId)
  108. {
  109. $profile = Auth::user()->profile;
  110. if($profileId != $profile->id) {
  111. abort(403);
  112. }
  113. $msg = DirectMessage::whereToId($profile->id)
  114. ->orWhere('from_id',$profile->id)
  115. ->findOrFail($threadId);
  116. $thread = DirectMessage::with('status')->whereIn('to_id', [$profile->id, $msg->from_id])
  117. ->whereIn('from_id', [$profile->id,$msg->from_id])
  118. ->orderBy('created_at', 'asc')
  119. ->paginate(30);
  120. return response()->json(compact('msg', 'profile', 'thread'), 200, [], JSON_PRETTY_PRINT);
  121. }
  122. public function statusReplies(Request $request, int $id)
  123. {
  124. $this->validate($request, [
  125. 'limit' => 'nullable|int|min:1|max:6'
  126. ]);
  127. $parent = Status::whereScope('public')->findOrFail($id);
  128. $limit = $request->input('limit') ?? 3;
  129. $children = Status::whereInReplyToId($parent->id)
  130. ->orderBy('created_at', 'desc')
  131. ->take($limit)
  132. ->get();
  133. $resource = new Fractal\Resource\Collection($children, new StatusTransformer());
  134. $res = $this->fractal->createData($resource)->toArray();
  135. return response()->json($res);
  136. }
  137. public function stories(Request $request)
  138. {
  139. }
  140. public function discoverCategories(Request $request)
  141. {
  142. $categories = DiscoverCategory::whereActive(true)->orderBy('order')->take(10)->get();
  143. $res = $categories->map(function($item) {
  144. return [
  145. 'name' => $item->name,
  146. 'url' => $item->url(),
  147. 'thumb' => $item->thumb()
  148. ];
  149. });
  150. return response()->json($res);
  151. }
  152. public function modAction(Request $request)
  153. {
  154. abort_unless(Auth::user()->is_admin, 400);
  155. $this->validate($request, [
  156. 'action' => [
  157. 'required',
  158. 'string',
  159. Rule::in([
  160. 'addcw',
  161. 'remcw',
  162. 'unlist',
  163. 'spammer'
  164. ])
  165. ],
  166. 'item_id' => 'required|integer|min:1',
  167. 'item_type' => [
  168. 'required',
  169. 'string',
  170. Rule::in(['profile', 'status'])
  171. ]
  172. ]);
  173. $action = $request->input('action');
  174. $item_id = $request->input('item_id');
  175. $item_type = $request->input('item_type');
  176. $status = Status::findOrFail($item_id);
  177. $author = User::whereProfileId($status->profile_id)->first();
  178. abort_if($author && $author->is_admin, 422, 'Cannot moderate administrator accounts');
  179. switch($action) {
  180. case 'addcw':
  181. $status->is_nsfw = true;
  182. $status->save();
  183. ModLogService::boot()
  184. ->user(Auth::user())
  185. ->objectUid($status->profile->user_id)
  186. ->objectId($status->id)
  187. ->objectType('App\Status::class')
  188. ->action('admin.status.moderate')
  189. ->metadata([
  190. 'action' => 'cw',
  191. 'message' => 'Success!'
  192. ])
  193. ->accessLevel('admin')
  194. ->save();
  195. if($status->uri == null) {
  196. $media = $status->media;
  197. $ai = new AccountInterstitial;
  198. $ai->user_id = $status->profile->user_id;
  199. $ai->type = 'post.cw';
  200. $ai->view = 'account.moderation.post.cw';
  201. $ai->item_type = 'App\Status';
  202. $ai->item_id = $status->id;
  203. $ai->has_media = (bool) $media->count();
  204. $ai->blurhash = $media->count() ? $media->first()->blurhash : null;
  205. $ai->meta = json_encode([
  206. 'caption' => $status->caption,
  207. 'created_at' => $status->created_at,
  208. 'type' => $status->type,
  209. 'url' => $status->url(),
  210. 'is_nsfw' => $status->is_nsfw,
  211. 'scope' => $status->scope,
  212. 'reblog' => $status->reblog_of_id,
  213. 'likes_count' => $status->likes_count,
  214. 'reblogs_count' => $status->reblogs_count,
  215. ]);
  216. $ai->save();
  217. $u = $status->profile->user;
  218. $u->has_interstitial = true;
  219. $u->save();
  220. }
  221. break;
  222. case 'remcw':
  223. $status->is_nsfw = false;
  224. $status->save();
  225. ModLogService::boot()
  226. ->user(Auth::user())
  227. ->objectUid($status->profile->user_id)
  228. ->objectId($status->id)
  229. ->objectType('App\Status::class')
  230. ->action('admin.status.moderate')
  231. ->metadata([
  232. 'action' => 'remove_cw',
  233. 'message' => 'Success!'
  234. ])
  235. ->accessLevel('admin')
  236. ->save();
  237. if($status->uri == null) {
  238. $ai = AccountInterstitial::whereUserId($status->profile->user_id)
  239. ->whereType('post.cw')
  240. ->whereItemId($status->id)
  241. ->whereItemType('App\Status')
  242. ->first();
  243. $ai->delete();
  244. }
  245. break;
  246. case 'unlist':
  247. $status->scope = $status->visibility = 'unlisted';
  248. $status->save();
  249. PublicTimelineService::del($status->id);
  250. ModLogService::boot()
  251. ->user(Auth::user())
  252. ->objectUid($status->profile->user_id)
  253. ->objectId($status->id)
  254. ->objectType('App\Status::class')
  255. ->action('admin.status.moderate')
  256. ->metadata([
  257. 'action' => 'unlist',
  258. 'message' => 'Success!'
  259. ])
  260. ->accessLevel('admin')
  261. ->save();
  262. if($status->uri == null) {
  263. $media = $status->media;
  264. $ai = new AccountInterstitial;
  265. $ai->user_id = $status->profile->user_id;
  266. $ai->type = 'post.unlist';
  267. $ai->view = 'account.moderation.post.unlist';
  268. $ai->item_type = 'App\Status';
  269. $ai->item_id = $status->id;
  270. $ai->has_media = (bool) $media->count();
  271. $ai->blurhash = $media->count() ? $media->first()->blurhash : null;
  272. $ai->meta = json_encode([
  273. 'caption' => $status->caption,
  274. 'created_at' => $status->created_at,
  275. 'type' => $status->type,
  276. 'url' => $status->url(),
  277. 'is_nsfw' => $status->is_nsfw,
  278. 'scope' => $status->scope,
  279. 'reblog' => $status->reblog_of_id,
  280. 'likes_count' => $status->likes_count,
  281. 'reblogs_count' => $status->reblogs_count,
  282. ]);
  283. $ai->save();
  284. $u = $status->profile->user;
  285. $u->has_interstitial = true;
  286. $u->save();
  287. }
  288. break;
  289. case 'spammer':
  290. HandleSpammerPipeline::dispatch($status->profile);
  291. ModLogService::boot()
  292. ->user(Auth::user())
  293. ->objectUid($status->profile->user_id)
  294. ->objectId($status->id)
  295. ->objectType('App\User::class')
  296. ->action('admin.status.moderate')
  297. ->metadata([
  298. 'action' => 'spammer',
  299. 'message' => 'Success!'
  300. ])
  301. ->accessLevel('admin')
  302. ->save();
  303. break;
  304. }
  305. StatusService::del($status->id);
  306. return ['msg' => 200];
  307. }
  308. public function composePost(Request $request)
  309. {
  310. abort(400, 'Endpoint deprecated');
  311. }
  312. public function bookmarks(Request $request)
  313. {
  314. $res = Bookmark::whereProfileId($request->user()->profile_id)
  315. ->orderByDesc('created_at')
  316. ->simplePaginate(10)
  317. ->map(function($bookmark) {
  318. $status = StatusService::get($bookmark->status_id);
  319. $status['bookmarked_at'] = $bookmark->created_at->format('c');
  320. return $status;
  321. })
  322. ->filter(function($bookmark) {
  323. return isset($bookmark['id']);
  324. })
  325. ->values();
  326. return response()->json($res);
  327. }
  328. public function accountStatuses(Request $request, $id)
  329. {
  330. $this->validate($request, [
  331. 'only_media' => 'nullable',
  332. 'pinned' => 'nullable',
  333. 'exclude_replies' => 'nullable',
  334. 'max_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  335. 'since_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  336. 'min_id' => 'nullable|integer|min:0|max:' . PHP_INT_MAX,
  337. 'limit' => 'nullable|integer|min:1|max:24'
  338. ]);
  339. $profile = Profile::whereNull('status')->findOrFail($id);
  340. $limit = $request->limit ?? 9;
  341. $max_id = $request->max_id;
  342. $min_id = $request->min_id;
  343. $scope = $request->only_media == true ?
  344. ['photo', 'photo:album', 'video', 'video:album'] :
  345. ['photo', 'photo:album', 'video', 'video:album', 'share', 'reply'];
  346. if($profile->is_private) {
  347. if(!Auth::check()) {
  348. return response()->json([]);
  349. }
  350. $pid = Auth::user()->profile->id;
  351. $following = Cache::remember('profile:following:'.$pid, now()->addMinutes(1440), function() use($pid) {
  352. $following = Follower::whereProfileId($pid)->pluck('following_id');
  353. return $following->push($pid)->toArray();
  354. });
  355. $visibility = true == in_array($profile->id, $following) ? ['public', 'unlisted', 'private'] : [];
  356. } else {
  357. if(Auth::check()) {
  358. $pid = Auth::user()->profile->id;
  359. $following = Cache::remember('profile:following:'.$pid, now()->addMinutes(1440), function() use($pid) {
  360. $following = Follower::whereProfileId($pid)->pluck('following_id');
  361. return $following->push($pid)->toArray();
  362. });
  363. $visibility = true == in_array($profile->id, $following) ? ['public', 'unlisted', 'private'] : ['public', 'unlisted'];
  364. } else {
  365. $visibility = ['public', 'unlisted'];
  366. }
  367. }
  368. $dir = $min_id ? '>' : '<';
  369. $id = $min_id ?? $max_id;
  370. $timeline = Status::select(
  371. 'id',
  372. 'uri',
  373. 'caption',
  374. 'rendered',
  375. 'profile_id',
  376. 'type',
  377. 'in_reply_to_id',
  378. 'reblog_of_id',
  379. 'is_nsfw',
  380. 'likes_count',
  381. 'reblogs_count',
  382. 'scope',
  383. 'local',
  384. 'created_at',
  385. 'updated_at'
  386. )->whereProfileId($profile->id)
  387. ->whereIn('type', $scope)
  388. ->where('id', $dir, $id)
  389. ->whereIn('visibility', $visibility)
  390. ->latest()
  391. ->limit($limit)
  392. ->get();
  393. $resource = new Fractal\Resource\Collection($timeline, new StatusTransformer());
  394. $res = $this->fractal->createData($resource)->toArray();
  395. return response()->json($res);
  396. }
  397. public function remoteProfile(Request $request, $id)
  398. {
  399. $profile = Profile::whereNull('status')
  400. ->whereNotNull('domain')
  401. ->findOrFail($id);
  402. $user = Auth::user();
  403. return view('profile.remote', compact('profile', 'user'));
  404. }
  405. public function remoteStatus(Request $request, $profileId, $statusId)
  406. {
  407. $user = Profile::whereNull('status')
  408. ->whereNotNull('domain')
  409. ->findOrFail($profileId);
  410. $status = Status::whereProfileId($user->id)
  411. ->whereNull('reblog_of_id')
  412. ->whereIn('visibility', ['public', 'unlisted'])
  413. ->findOrFail($statusId);
  414. $template = $status->in_reply_to_id ? 'status.reply' : 'status.remote';
  415. return view($template, compact('user', 'status'));
  416. }
  417. public function requestEmailVerification(Request $request)
  418. {
  419. $pid = $request->user()->profile_id;
  420. $exists = Redis::sismember('email:manual', $pid);
  421. return view('account.email.request_verification', compact('exists'));
  422. }
  423. public function requestEmailVerificationStore(Request $request)
  424. {
  425. $pid = $request->user()->profile_id;
  426. Redis::sadd('email:manual', $pid);
  427. return redirect('/i/verify-email')->with(['status' => 'Successfully sent manual verification request!']);
  428. }
  429. }