ApiV2Controller.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use Illuminate\Http\Request;
  4. use App\Http\Controllers\Controller;
  5. use App\Media;
  6. use App\UserSetting;
  7. use App\User;
  8. use Illuminate\Support\Facades\Cache;
  9. use App\Services\AccountService;
  10. use App\Services\BouncerService;
  11. use App\Services\InstanceService;
  12. use App\Services\MediaBlocklistService;
  13. use App\Services\MediaPathService;
  14. use App\Services\SearchApiV2Service;
  15. use App\Util\Media\Filter;
  16. use App\Jobs\MediaPipeline\MediaDeletePipeline;
  17. use App\Jobs\VideoPipeline\{
  18. VideoOptimize,
  19. VideoPostProcess,
  20. VideoThumbnail
  21. };
  22. use App\Jobs\ImageOptimizePipeline\ImageOptimize;
  23. use League\Fractal;
  24. use League\Fractal\Serializer\ArraySerializer;
  25. use League\Fractal\Pagination\IlluminatePaginatorAdapter;
  26. use App\Transformer\Api\Mastodon\v1\{
  27. AccountTransformer,
  28. MediaTransformer,
  29. NotificationTransformer,
  30. StatusTransformer,
  31. };
  32. use App\Transformer\Api\{
  33. RelationshipTransformer,
  34. };
  35. use App\Util\Site\Nodeinfo;
  36. use App\Services\UserRoleService;
  37. class ApiV2Controller extends Controller
  38. {
  39. const PF_API_ENTITY_KEY = "_pe";
  40. public function json($res, $code = 200, $headers = [])
  41. {
  42. return response()->json($res, $code, $headers, JSON_UNESCAPED_SLASHES);
  43. }
  44. public function instance(Request $request)
  45. {
  46. $contact = Cache::remember('api:v1:instance-data:contact', 604800, function () {
  47. if(config_cache('instance.admin.pid')) {
  48. return AccountService::getMastodon(config_cache('instance.admin.pid'), true);
  49. }
  50. $admin = User::whereIsAdmin(true)->first();
  51. return $admin && isset($admin->profile_id) ?
  52. AccountService::getMastodon($admin->profile_id, true) :
  53. null;
  54. });
  55. $rules = Cache::remember('api:v1:instance-data:rules', 604800, function () {
  56. return config_cache('app.rules') ?
  57. collect(json_decode(config_cache('app.rules'), true))
  58. ->map(function($rule, $key) {
  59. $id = $key + 1;
  60. return [
  61. 'id' => "{$id}",
  62. 'text' => $rule
  63. ];
  64. })
  65. ->toArray() : [];
  66. });
  67. $res = [
  68. 'domain' => config('pixelfed.domain.app'),
  69. 'title' => config_cache('app.name'),
  70. 'version' => config('pixelfed.version'),
  71. 'source_url' => 'https://github.com/pixelfed/pixelfed',
  72. 'description' => config_cache('app.short_description'),
  73. 'usage' => [
  74. 'users' => [
  75. 'active_month' => (int) Nodeinfo::activeUsersMonthly()
  76. ]
  77. ],
  78. 'thumbnail' => [
  79. 'url' => config_cache('app.banner_image') ?? url(Storage::url('public/headers/default.jpg')),
  80. 'blurhash' => InstanceService::headerBlurhash(),
  81. 'versions' => [
  82. '@1x' => config_cache('app.banner_image') ?? url(Storage::url('public/headers/default.jpg')),
  83. '@2x' => config_cache('app.banner_image') ?? url(Storage::url('public/headers/default.jpg'))
  84. ]
  85. ],
  86. 'languages' => [config('app.locale')],
  87. 'configuration' => [
  88. 'urls' => [
  89. 'streaming' => 'wss://' . config('pixelfed.domain.app'),
  90. 'status' => null
  91. ],
  92. 'vapid' => [
  93. 'public_key' => config('webpush.vapid.public_key'),
  94. ],
  95. 'accounts' => [
  96. 'max_featured_tags' => 0,
  97. ],
  98. 'statuses' => [
  99. 'max_characters' => (int) config('pixelfed.max_caption_length'),
  100. 'max_media_attachments' => (int) config_cache('pixelfed.max_album_length'),
  101. 'characters_reserved_per_url' => 23
  102. ],
  103. 'media_attachments' => [
  104. 'supported_mime_types' => explode(',', config_cache('pixelfed.media_types')),
  105. 'image_size_limit' => config_cache('pixelfed.max_photo_size') * 1024,
  106. 'image_matrix_limit' => 3686400,
  107. 'video_size_limit' => config_cache('pixelfed.max_photo_size') * 1024,
  108. 'video_frame_rate_limit' => 240,
  109. 'video_matrix_limit' => 3686400
  110. ],
  111. 'polls' => [
  112. 'max_options' => 4,
  113. 'max_characters_per_option' => 50,
  114. 'min_expiration' => 300,
  115. 'max_expiration' => 2629746,
  116. ],
  117. 'translation' => [
  118. 'enabled' => false,
  119. ],
  120. ],
  121. 'registrations' => [
  122. 'enabled' => (bool) config_cache('pixelfed.open_registration'),
  123. 'approval_required' => false,
  124. 'message' => null
  125. ],
  126. 'contact' => [
  127. 'email' => config('instance.email'),
  128. 'account' => $contact
  129. ],
  130. 'rules' => $rules
  131. ];
  132. return response()->json($res, 200, [], JSON_UNESCAPED_SLASHES);
  133. }
  134. /**
  135. * GET /api/v2/search
  136. *
  137. *
  138. * @return array
  139. */
  140. public function search(Request $request)
  141. {
  142. abort_if(!$request->user(), 403);
  143. $this->validate($request, [
  144. 'q' => 'required|string|min:1|max:100',
  145. 'account_id' => 'nullable|string',
  146. 'max_id' => 'nullable|string',
  147. 'min_id' => 'nullable|string',
  148. 'type' => 'nullable|in:accounts,hashtags,statuses',
  149. 'exclude_unreviewed' => 'nullable',
  150. 'resolve' => 'nullable',
  151. 'limit' => 'nullable|integer|max:40',
  152. 'offset' => 'nullable|integer',
  153. 'following' => 'nullable'
  154. ]);
  155. if($request->user()->has_roles && !UserRoleService::can('can-view-discover', $request->user()->id)) {
  156. return [
  157. 'accounts' => [],
  158. 'hashtags' => [],
  159. 'statuses' => []
  160. ];
  161. }
  162. $mastodonMode = !$request->has('_pe');
  163. return $this->json(SearchApiV2Service::query($request, $mastodonMode));
  164. }
  165. /**
  166. * GET /api/v2/streaming/config
  167. *
  168. *
  169. * @return object
  170. */
  171. public function getWebsocketConfig()
  172. {
  173. return config('broadcasting.default') === 'pusher' ? [
  174. 'host' => config('broadcasting.connections.pusher.options.host'),
  175. 'port' => config('broadcasting.connections.pusher.options.port'),
  176. 'key' => config('broadcasting.connections.pusher.key'),
  177. 'cluster' => config('broadcasting.connections.pusher.options.cluster')
  178. ] : [];
  179. }
  180. /**
  181. * POST /api/v2/media
  182. *
  183. *
  184. * @return MediaTransformer
  185. */
  186. public function mediaUploadV2(Request $request)
  187. {
  188. abort_if(!$request->user(), 403);
  189. $this->validate($request, [
  190. 'file.*' => [
  191. 'required_without:file',
  192. 'mimetypes:' . config_cache('pixelfed.media_types'),
  193. 'max:' . config_cache('pixelfed.max_photo_size'),
  194. ],
  195. 'file' => [
  196. 'required_without:file.*',
  197. 'mimetypes:' . config_cache('pixelfed.media_types'),
  198. 'max:' . config_cache('pixelfed.max_photo_size'),
  199. ],
  200. 'filter_name' => 'nullable|string|max:24',
  201. 'filter_class' => 'nullable|alpha_dash|max:24',
  202. 'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length'),
  203. 'replace_id' => 'sometimes'
  204. ]);
  205. $user = $request->user();
  206. if($user->last_active_at == null) {
  207. return [];
  208. }
  209. if(empty($request->file('file'))) {
  210. return response('', 422);
  211. }
  212. $limitKey = 'compose:rate-limit:media-upload:' . $user->id;
  213. $limitTtl = now()->addMinutes(15);
  214. $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
  215. $dailyLimit = Media::whereUserId($user->id)->where('created_at', '>', now()->subDays(1))->count();
  216. return $dailyLimit >= 1250;
  217. });
  218. abort_if($limitReached == true, 429);
  219. $profile = $user->profile;
  220. if(config_cache('pixelfed.enforce_account_limit') == true) {
  221. $size = Cache::remember($user->storageUsedKey(), now()->addDays(3), function() use($user) {
  222. return Media::whereUserId($user->id)->sum('size') / 1000;
  223. });
  224. $limit = (int) config_cache('pixelfed.max_account_size');
  225. if ($size >= $limit) {
  226. abort(403, 'Account size limit reached.');
  227. }
  228. }
  229. $filterClass = in_array($request->input('filter_class'), Filter::classes()) ? $request->input('filter_class') : null;
  230. $filterName = in_array($request->input('filter_name'), Filter::names()) ? $request->input('filter_name') : null;
  231. $photo = $request->file('file');
  232. $mimes = explode(',', config_cache('pixelfed.media_types'));
  233. if(in_array($photo->getMimeType(), $mimes) == false) {
  234. abort(403, 'Invalid or unsupported mime type.');
  235. }
  236. $storagePath = MediaPathService::get($user, 2);
  237. $path = $photo->storePublicly($storagePath);
  238. $hash = \hash_file('sha256', $photo);
  239. $license = null;
  240. $mime = $photo->getMimeType();
  241. $settings = UserSetting::whereUserId($user->id)->first();
  242. if($settings && !empty($settings->compose_settings)) {
  243. $compose = $settings->compose_settings;
  244. if(isset($compose['default_license']) && $compose['default_license'] != 1) {
  245. $license = $compose['default_license'];
  246. }
  247. }
  248. abort_if(MediaBlocklistService::exists($hash) == true, 451);
  249. if($request->has('replace_id')) {
  250. $rpid = $request->input('replace_id');
  251. $removeMedia = Media::whereNull('status_id')
  252. ->whereUserId($user->id)
  253. ->whereProfileId($profile->id)
  254. ->where('created_at', '>', now()->subHours(2))
  255. ->find($rpid);
  256. if($removeMedia) {
  257. MediaDeletePipeline::dispatch($removeMedia)
  258. ->onQueue('mmo')
  259. ->delay(now()->addMinutes(15));
  260. }
  261. }
  262. $media = new Media();
  263. $media->status_id = null;
  264. $media->profile_id = $profile->id;
  265. $media->user_id = $user->id;
  266. $media->media_path = $path;
  267. $media->original_sha256 = $hash;
  268. $media->size = $photo->getSize();
  269. $media->mime = $mime;
  270. $media->caption = $request->input('description');
  271. $media->filter_class = $filterClass;
  272. $media->filter_name = $filterName;
  273. if($license) {
  274. $media->license = $license;
  275. }
  276. $media->save();
  277. switch ($media->mime) {
  278. case 'image/jpeg':
  279. case 'image/png':
  280. ImageOptimize::dispatch($media)->onQueue('mmo');
  281. break;
  282. case 'video/mp4':
  283. VideoThumbnail::dispatch($media)->onQueue('mmo');
  284. $preview_url = '/storage/no-preview.png';
  285. $url = '/storage/no-preview.png';
  286. break;
  287. }
  288. Cache::forget($limitKey);
  289. $fractal = new Fractal\Manager();
  290. $fractal->setSerializer(new ArraySerializer());
  291. $resource = new Fractal\Resource\Item($media, new MediaTransformer());
  292. $res = $fractal->createData($resource)->toArray();
  293. $res['preview_url'] = $media->url(). '?v=' . time();
  294. $res['url'] = null;
  295. return $this->json($res, 202);
  296. }
  297. }