InternalApiController.php 16 KB

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