Update api controllers, add parental control support

This commit is contained in:
Daniel Supernault 2024-01-11 04:50:11 -07:00
parent 9d365d07f9
commit fd9b5ad443
No known key found for this signature in database
GPG key ID: 23740873EE6F76A1
2 changed files with 267 additions and 253 deletions

View file

@ -758,6 +758,8 @@ class ApiV1Controller extends Controller
abort_if(!$request->user(), 403); abort_if(!$request->user(), 403);
$user = $request->user(); $user = $request->user();
abort_if($user->has_roles && !UserRoleService::can('can-follow', $user->id), 403, 'Invalid permissions for this action');
AccountService::setLastActive($user->id); AccountService::setLastActive($user->id);
$target = Profile::where('id', '!=', $user->profile_id) $target = Profile::where('id', '!=', $user->profile_id)
@ -843,6 +845,7 @@ class ApiV1Controller extends Controller
abort_if(!$request->user(), 403); abort_if(!$request->user(), 403);
$user = $request->user(); $user = $request->user();
AccountService::setLastActive($user->id); AccountService::setLastActive($user->id);
$target = Profile::where('id', '!=', $user->profile_id) $target = Profile::where('id', '!=', $user->profile_id)
@ -947,6 +950,8 @@ class ApiV1Controller extends Controller
]); ]);
$user = $request->user(); $user = $request->user();
abort_if($user->has_roles && !UserRoleService::can('can-view-discover', $user->id), 403, 'Invalid permissions for this action');
AccountService::setLastActive($user->id); AccountService::setLastActive($user->id);
$query = $request->input('q'); $query = $request->input('q');
$limit = $request->input('limit') ?? 20; $limit = $request->input('limit') ?? 20;

View file

@ -17,304 +17,313 @@ use App\Services\SearchApiV2Service;
use App\Util\Media\Filter; use App\Util\Media\Filter;
use App\Jobs\MediaPipeline\MediaDeletePipeline; use App\Jobs\MediaPipeline\MediaDeletePipeline;
use App\Jobs\VideoPipeline\{ use App\Jobs\VideoPipeline\{
VideoOptimize, VideoOptimize,
VideoPostProcess, VideoPostProcess,
VideoThumbnail VideoThumbnail
}; };
use App\Jobs\ImageOptimizePipeline\ImageOptimize; use App\Jobs\ImageOptimizePipeline\ImageOptimize;
use League\Fractal; use League\Fractal;
use League\Fractal\Serializer\ArraySerializer; use League\Fractal\Serializer\ArraySerializer;
use League\Fractal\Pagination\IlluminatePaginatorAdapter; use League\Fractal\Pagination\IlluminatePaginatorAdapter;
use App\Transformer\Api\Mastodon\v1\{ use App\Transformer\Api\Mastodon\v1\{
AccountTransformer, AccountTransformer,
MediaTransformer, MediaTransformer,
NotificationTransformer, NotificationTransformer,
StatusTransformer, StatusTransformer,
}; };
use App\Transformer\Api\{ use App\Transformer\Api\{
RelationshipTransformer, RelationshipTransformer,
}; };
use App\Util\Site\Nodeinfo; use App\Util\Site\Nodeinfo;
use App\Services\UserRoleService;
class ApiV2Controller extends Controller class ApiV2Controller extends Controller
{ {
const PF_API_ENTITY_KEY = "_pe"; const PF_API_ENTITY_KEY = "_pe";
public function json($res, $code = 200, $headers = []) public function json($res, $code = 200, $headers = [])
{ {
return response()->json($res, $code, $headers, JSON_UNESCAPED_SLASHES); return response()->json($res, $code, $headers, JSON_UNESCAPED_SLASHES);
} }
public function instance(Request $request) public function instance(Request $request)
{ {
$contact = Cache::remember('api:v1:instance-data:contact', 604800, function () { $contact = Cache::remember('api:v1:instance-data:contact', 604800, function () {
if(config_cache('instance.admin.pid')) { if(config_cache('instance.admin.pid')) {
return AccountService::getMastodon(config_cache('instance.admin.pid'), true); return AccountService::getMastodon(config_cache('instance.admin.pid'), true);
} }
$admin = User::whereIsAdmin(true)->first(); $admin = User::whereIsAdmin(true)->first();
return $admin && isset($admin->profile_id) ? return $admin && isset($admin->profile_id) ?
AccountService::getMastodon($admin->profile_id, true) : AccountService::getMastodon($admin->profile_id, true) :
null; null;
}); });
$rules = Cache::remember('api:v1:instance-data:rules', 604800, function () { $rules = Cache::remember('api:v1:instance-data:rules', 604800, function () {
return config_cache('app.rules') ? return config_cache('app.rules') ?
collect(json_decode(config_cache('app.rules'), true)) collect(json_decode(config_cache('app.rules'), true))
->map(function($rule, $key) { ->map(function($rule, $key) {
$id = $key + 1; $id = $key + 1;
return [ return [
'id' => "{$id}", 'id' => "{$id}",
'text' => $rule 'text' => $rule
]; ];
}) })
->toArray() : []; ->toArray() : [];
}); });
$res = [ $res = [
'domain' => config('pixelfed.domain.app'), 'domain' => config('pixelfed.domain.app'),
'title' => config_cache('app.name'), 'title' => config_cache('app.name'),
'version' => config('pixelfed.version'), 'version' => config('pixelfed.version'),
'source_url' => 'https://github.com/pixelfed/pixelfed', 'source_url' => 'https://github.com/pixelfed/pixelfed',
'description' => config_cache('app.short_description'), 'description' => config_cache('app.short_description'),
'usage' => [ 'usage' => [
'users' => [ 'users' => [
'active_month' => (int) Nodeinfo::activeUsersMonthly() 'active_month' => (int) Nodeinfo::activeUsersMonthly()
] ]
], ],
'thumbnail' => [ 'thumbnail' => [
'url' => config_cache('app.banner_image') ?? url(Storage::url('public/headers/default.jpg')), 'url' => config_cache('app.banner_image') ?? url(Storage::url('public/headers/default.jpg')),
'blurhash' => InstanceService::headerBlurhash(), 'blurhash' => InstanceService::headerBlurhash(),
'versions' => [ 'versions' => [
'@1x' => config_cache('app.banner_image') ?? url(Storage::url('public/headers/default.jpg')), '@1x' => config_cache('app.banner_image') ?? url(Storage::url('public/headers/default.jpg')),
'@2x' => config_cache('app.banner_image') ?? url(Storage::url('public/headers/default.jpg')) '@2x' => config_cache('app.banner_image') ?? url(Storage::url('public/headers/default.jpg'))
] ]
], ],
'languages' => [config('app.locale')], 'languages' => [config('app.locale')],
'configuration' => [ 'configuration' => [
'urls' => [ 'urls' => [
'streaming' => 'wss://' . config('pixelfed.domain.app'), 'streaming' => 'wss://' . config('pixelfed.domain.app'),
'status' => null 'status' => null
], ],
'accounts' => [ 'accounts' => [
'max_featured_tags' => 0, 'max_featured_tags' => 0,
], ],
'statuses' => [ 'statuses' => [
'max_characters' => (int) config('pixelfed.max_caption_length'), 'max_characters' => (int) config('pixelfed.max_caption_length'),
'max_media_attachments' => (int) config_cache('pixelfed.max_album_length'), 'max_media_attachments' => (int) config_cache('pixelfed.max_album_length'),
'characters_reserved_per_url' => 23 'characters_reserved_per_url' => 23
], ],
'media_attachments' => [ 'media_attachments' => [
'supported_mime_types' => explode(',', config_cache('pixelfed.media_types')), 'supported_mime_types' => explode(',', config_cache('pixelfed.media_types')),
'image_size_limit' => config_cache('pixelfed.max_photo_size') * 1024, 'image_size_limit' => config_cache('pixelfed.max_photo_size') * 1024,
'image_matrix_limit' => 3686400, 'image_matrix_limit' => 3686400,
'video_size_limit' => config_cache('pixelfed.max_photo_size') * 1024, 'video_size_limit' => config_cache('pixelfed.max_photo_size') * 1024,
'video_frame_rate_limit' => 240, 'video_frame_rate_limit' => 240,
'video_matrix_limit' => 3686400 'video_matrix_limit' => 3686400
], ],
'polls' => [ 'polls' => [
'max_options' => 4, 'max_options' => 4,
'max_characters_per_option' => 50, 'max_characters_per_option' => 50,
'min_expiration' => 300, 'min_expiration' => 300,
'max_expiration' => 2629746, 'max_expiration' => 2629746,
], ],
'translation' => [ 'translation' => [
'enabled' => false, 'enabled' => false,
], ],
], ],
'registrations' => [ 'registrations' => [
'enabled' => (bool) config_cache('pixelfed.open_registration'), 'enabled' => (bool) config_cache('pixelfed.open_registration'),
'approval_required' => false, 'approval_required' => false,
'message' => null 'message' => null
], ],
'contact' => [ 'contact' => [
'email' => config('instance.email'), 'email' => config('instance.email'),
'account' => $contact 'account' => $contact
], ],
'rules' => $rules 'rules' => $rules
]; ];
return response()->json($res, 200, [], JSON_UNESCAPED_SLASHES); return response()->json($res, 200, [], JSON_UNESCAPED_SLASHES);
} }
/** /**
* GET /api/v2/search * GET /api/v2/search
* *
* *
* @return array * @return array
*/ */
public function search(Request $request) public function search(Request $request)
{ {
abort_if(!$request->user(), 403); abort_if(!$request->user(), 403);
$this->validate($request, [ $this->validate($request, [
'q' => 'required|string|min:1|max:100', 'q' => 'required|string|min:1|max:100',
'account_id' => 'nullable|string', 'account_id' => 'nullable|string',
'max_id' => 'nullable|string', 'max_id' => 'nullable|string',
'min_id' => 'nullable|string', 'min_id' => 'nullable|string',
'type' => 'nullable|in:accounts,hashtags,statuses', 'type' => 'nullable|in:accounts,hashtags,statuses',
'exclude_unreviewed' => 'nullable', 'exclude_unreviewed' => 'nullable',
'resolve' => 'nullable', 'resolve' => 'nullable',
'limit' => 'nullable|integer|max:40', 'limit' => 'nullable|integer|max:40',
'offset' => 'nullable|integer', 'offset' => 'nullable|integer',
'following' => 'nullable' 'following' => 'nullable'
]); ]);
$mastodonMode = !$request->has('_pe'); if($request->user()->has_roles && !UserRoleService::can('can-view-discover', $request->user()->id)) {
return $this->json(SearchApiV2Service::query($request, $mastodonMode)); return [
} 'accounts' => [],
'hashtags' => [],
'statuses' => []
];
}
/** $mastodonMode = !$request->has('_pe');
* GET /api/v2/streaming/config return $this->json(SearchApiV2Service::query($request, $mastodonMode));
* }
*
* @return object
*/
public function getWebsocketConfig()
{
return config('broadcasting.default') === 'pusher' ? [
'host' => config('broadcasting.connections.pusher.options.host'),
'port' => config('broadcasting.connections.pusher.options.port'),
'key' => config('broadcasting.connections.pusher.key'),
'cluster' => config('broadcasting.connections.pusher.options.cluster')
] : [];
}
/** /**
* POST /api/v2/media * GET /api/v2/streaming/config
* *
* *
* @return MediaTransformer * @return object
*/ */
public function mediaUploadV2(Request $request) public function getWebsocketConfig()
{ {
abort_if(!$request->user(), 403); return config('broadcasting.default') === 'pusher' ? [
'host' => config('broadcasting.connections.pusher.options.host'),
'port' => config('broadcasting.connections.pusher.options.port'),
'key' => config('broadcasting.connections.pusher.key'),
'cluster' => config('broadcasting.connections.pusher.options.cluster')
] : [];
}
$this->validate($request, [ /**
'file.*' => [ * POST /api/v2/media
'required_without:file', *
'mimetypes:' . config_cache('pixelfed.media_types'), *
'max:' . config_cache('pixelfed.max_photo_size'), * @return MediaTransformer
], */
'file' => [ public function mediaUploadV2(Request $request)
'required_without:file.*', {
'mimetypes:' . config_cache('pixelfed.media_types'), abort_if(!$request->user(), 403);
'max:' . config_cache('pixelfed.max_photo_size'),
],
'filter_name' => 'nullable|string|max:24',
'filter_class' => 'nullable|alpha_dash|max:24',
'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length'),
'replace_id' => 'sometimes'
]);
$user = $request->user(); $this->validate($request, [
'file.*' => [
'required_without:file',
'mimetypes:' . config_cache('pixelfed.media_types'),
'max:' . config_cache('pixelfed.max_photo_size'),
],
'file' => [
'required_without:file.*',
'mimetypes:' . config_cache('pixelfed.media_types'),
'max:' . config_cache('pixelfed.max_photo_size'),
],
'filter_name' => 'nullable|string|max:24',
'filter_class' => 'nullable|alpha_dash|max:24',
'description' => 'nullable|string|max:' . config_cache('pixelfed.max_altext_length'),
'replace_id' => 'sometimes'
]);
if($user->last_active_at == null) { $user = $request->user();
return [];
}
if(empty($request->file('file'))) { if($user->last_active_at == null) {
return response('', 422); return [];
} }
$limitKey = 'compose:rate-limit:media-upload:' . $user->id; if(empty($request->file('file'))) {
$limitTtl = now()->addMinutes(15); return response('', 422);
$limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) { }
$dailyLimit = Media::whereUserId($user->id)->where('created_at', '>', now()->subDays(1))->count();
return $dailyLimit >= 1250; $limitKey = 'compose:rate-limit:media-upload:' . $user->id;
}); $limitTtl = now()->addMinutes(15);
abort_if($limitReached == true, 429); $limitReached = Cache::remember($limitKey, $limitTtl, function() use($user) {
$dailyLimit = Media::whereUserId($user->id)->where('created_at', '>', now()->subDays(1))->count();
$profile = $user->profile; return $dailyLimit >= 1250;
});
abort_if($limitReached == true, 429);
if(config_cache('pixelfed.enforce_account_limit') == true) { $profile = $user->profile;
$size = Cache::remember($user->storageUsedKey(), now()->addDays(3), function() use($user) {
return Media::whereUserId($user->id)->sum('size') / 1000;
});
$limit = (int) config_cache('pixelfed.max_account_size');
if ($size >= $limit) {
abort(403, 'Account size limit reached.');
}
}
$filterClass = in_array($request->input('filter_class'), Filter::classes()) ? $request->input('filter_class') : null; if(config_cache('pixelfed.enforce_account_limit') == true) {
$filterName = in_array($request->input('filter_name'), Filter::names()) ? $request->input('filter_name') : null; $size = Cache::remember($user->storageUsedKey(), now()->addDays(3), function() use($user) {
return Media::whereUserId($user->id)->sum('size') / 1000;
});
$limit = (int) config_cache('pixelfed.max_account_size');
if ($size >= $limit) {
abort(403, 'Account size limit reached.');
}
}
$photo = $request->file('file'); $filterClass = in_array($request->input('filter_class'), Filter::classes()) ? $request->input('filter_class') : null;
$filterName = in_array($request->input('filter_name'), Filter::names()) ? $request->input('filter_name') : null;
$mimes = explode(',', config_cache('pixelfed.media_types')); $photo = $request->file('file');
if(in_array($photo->getMimeType(), $mimes) == false) {
abort(403, 'Invalid or unsupported mime type.');
}
$storagePath = MediaPathService::get($user, 2); $mimes = explode(',', config_cache('pixelfed.media_types'));
$path = $photo->storePublicly($storagePath); if(in_array($photo->getMimeType(), $mimes) == false) {
$hash = \hash_file('sha256', $photo); abort(403, 'Invalid or unsupported mime type.');
$license = null; }
$mime = $photo->getMimeType();
$settings = UserSetting::whereUserId($user->id)->first(); $storagePath = MediaPathService::get($user, 2);
$path = $photo->storePublicly($storagePath);
$hash = \hash_file('sha256', $photo);
$license = null;
$mime = $photo->getMimeType();
if($settings && !empty($settings->compose_settings)) { $settings = UserSetting::whereUserId($user->id)->first();
$compose = $settings->compose_settings;
if(isset($compose['default_license']) && $compose['default_license'] != 1) { if($settings && !empty($settings->compose_settings)) {
$license = $compose['default_license']; $compose = $settings->compose_settings;
}
}
abort_if(MediaBlocklistService::exists($hash) == true, 451); if(isset($compose['default_license']) && $compose['default_license'] != 1) {
$license = $compose['default_license'];
}
}
if($request->has('replace_id')) { abort_if(MediaBlocklistService::exists($hash) == true, 451);
$rpid = $request->input('replace_id');
$removeMedia = Media::whereNull('status_id')
->whereUserId($user->id)
->whereProfileId($profile->id)
->where('created_at', '>', now()->subHours(2))
->find($rpid);
if($removeMedia) {
MediaDeletePipeline::dispatch($removeMedia)
->onQueue('mmo')
->delay(now()->addMinutes(15));
}
}
$media = new Media(); if($request->has('replace_id')) {
$media->status_id = null; $rpid = $request->input('replace_id');
$media->profile_id = $profile->id; $removeMedia = Media::whereNull('status_id')
$media->user_id = $user->id; ->whereUserId($user->id)
$media->media_path = $path; ->whereProfileId($profile->id)
$media->original_sha256 = $hash; ->where('created_at', '>', now()->subHours(2))
$media->size = $photo->getSize(); ->find($rpid);
$media->mime = $mime; if($removeMedia) {
$media->caption = $request->input('description'); MediaDeletePipeline::dispatch($removeMedia)
$media->filter_class = $filterClass; ->onQueue('mmo')
$media->filter_name = $filterName; ->delay(now()->addMinutes(15));
if($license) { }
$media->license = $license; }
}
$media->save();
switch ($media->mime) { $media = new Media();
case 'image/jpeg': $media->status_id = null;
case 'image/png': $media->profile_id = $profile->id;
ImageOptimize::dispatch($media)->onQueue('mmo'); $media->user_id = $user->id;
break; $media->media_path = $path;
$media->original_sha256 = $hash;
$media->size = $photo->getSize();
$media->mime = $mime;
$media->caption = $request->input('description');
$media->filter_class = $filterClass;
$media->filter_name = $filterName;
if($license) {
$media->license = $license;
}
$media->save();
case 'video/mp4': switch ($media->mime) {
VideoThumbnail::dispatch($media)->onQueue('mmo'); case 'image/jpeg':
$preview_url = '/storage/no-preview.png'; case 'image/png':
$url = '/storage/no-preview.png'; ImageOptimize::dispatch($media)->onQueue('mmo');
break; break;
}
Cache::forget($limitKey); case 'video/mp4':
$fractal = new Fractal\Manager(); VideoThumbnail::dispatch($media)->onQueue('mmo');
$fractal->setSerializer(new ArraySerializer()); $preview_url = '/storage/no-preview.png';
$resource = new Fractal\Resource\Item($media, new MediaTransformer()); $url = '/storage/no-preview.png';
$res = $fractal->createData($resource)->toArray(); break;
$res['preview_url'] = $media->url(). '?v=' . time(); }
$res['url'] = null;
return $this->json($res, 202); Cache::forget($limitKey);
} $fractal = new Fractal\Manager();
$fractal->setSerializer(new ArraySerializer());
$resource = new Fractal\Resource\Item($media, new MediaTransformer());
$res = $fractal->createData($resource)->toArray();
$res['preview_url'] = $media->url(). '?v=' . time();
$res['url'] = null;
return $this->json($res, 202);
}
} }