ApiV2Controller.php 9.2 KB

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