InternalApiController.php 16 KB

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