Update activitpub setting, use config_cache()

This commit is contained in:
Daniel Supernault 2024-03-12 02:20:37 -06:00
parent 40478f258a
commit 5071aaf408
No known key found for this signature in database
GPG key ID: 23740873EE6F76A1
10 changed files with 833 additions and 839 deletions

View file

@ -2,57 +2,42 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Jobs\InboxPipeline\{ use App\Jobs\InboxPipeline\DeleteWorker;
DeleteWorker, use App\Jobs\InboxPipeline\InboxValidator;
InboxWorker, use App\Jobs\InboxPipeline\InboxWorker;
InboxValidator use App\Profile;
};
use App\Jobs\RemoteFollowPipeline\RemoteFollowPipeline;
use App\{
AccountLog,
Like,
Profile,
Status,
User
};
use App\Util\Lexer\Nickname;
use App\Util\Webfinger\Webfinger;
use Auth;
use Cache;
use Carbon\Carbon;
use Illuminate\Http\Request;
use League\Fractal;
use App\Util\Site\Nodeinfo;
use App\Util\ActivityPub\{
Helpers,
HttpSignature,
Outbox
};
use Zttp\Zttp;
use App\Services\InstanceService;
use App\Services\AccountService; use App\Services\AccountService;
use App\Services\InstanceService;
use App\Status;
use App\Util\Lexer\Nickname;
use App\Util\Site\Nodeinfo;
use App\Util\Webfinger\Webfinger;
use Cache;
use Illuminate\Http\Request;
class FederationController extends Controller class FederationController extends Controller
{ {
public function nodeinfoWellKnown() public function nodeinfoWellKnown()
{ {
abort_if(!config('federation.nodeinfo.enabled'), 404); abort_if(! config('federation.nodeinfo.enabled'), 404);
return response()->json(Nodeinfo::wellKnown(), 200, [], JSON_UNESCAPED_SLASHES) return response()->json(Nodeinfo::wellKnown(), 200, [], JSON_UNESCAPED_SLASHES)
->header('Access-Control-Allow-Origin','*'); ->header('Access-Control-Allow-Origin', '*');
} }
public function nodeinfo() public function nodeinfo()
{ {
abort_if(!config('federation.nodeinfo.enabled'), 404); abort_if(! config('federation.nodeinfo.enabled'), 404);
return response()->json(Nodeinfo::get(), 200, [], JSON_UNESCAPED_SLASHES) return response()->json(Nodeinfo::get(), 200, [], JSON_UNESCAPED_SLASHES)
->header('Access-Control-Allow-Origin','*'); ->header('Access-Control-Allow-Origin', '*');
} }
public function webfinger(Request $request) public function webfinger(Request $request)
{ {
if (!config('federation.webfinger.enabled') || if (! config('federation.webfinger.enabled') ||
!$request->has('resource') || ! $request->has('resource') ||
!$request->filled('resource') ! $request->filled('resource')
) { ) {
return response('', 400); return response('', 400);
} }
@ -60,55 +45,56 @@ class FederationController extends Controller
$resource = $request->input('resource'); $resource = $request->input('resource');
$domain = config('pixelfed.domain.app'); $domain = config('pixelfed.domain.app');
if(config('federation.activitypub.sharedInbox') && if (config('federation.activitypub.sharedInbox') &&
$resource == 'acct:' . $domain . '@' . $domain) { $resource == 'acct:'.$domain.'@'.$domain) {
$res = [ $res = [
'subject' => 'acct:' . $domain . '@' . $domain, 'subject' => 'acct:'.$domain.'@'.$domain,
'aliases' => [ 'aliases' => [
'https://' . $domain . '/i/actor' 'https://'.$domain.'/i/actor',
], ],
'links' => [ 'links' => [
[ [
'rel' => 'http://webfinger.net/rel/profile-page', 'rel' => 'http://webfinger.net/rel/profile-page',
'type' => 'text/html', 'type' => 'text/html',
'href' => 'https://' . $domain . '/site/kb/instance-actor' 'href' => 'https://'.$domain.'/site/kb/instance-actor',
], ],
[ [
'rel' => 'self', 'rel' => 'self',
'type' => 'application/activity+json', 'type' => 'application/activity+json',
'href' => 'https://' . $domain . '/i/actor' 'href' => 'https://'.$domain.'/i/actor',
] ],
] ],
]; ];
return response()->json($res, 200, [], JSON_UNESCAPED_SLASHES); return response()->json($res, 200, [], JSON_UNESCAPED_SLASHES);
} }
$hash = hash('sha256', $resource); $hash = hash('sha256', $resource);
$key = 'federation:webfinger:sha256:' . $hash; $key = 'federation:webfinger:sha256:'.$hash;
if($cached = Cache::get($key)) { if ($cached = Cache::get($key)) {
return response()->json($cached, 200, [], JSON_UNESCAPED_SLASHES); return response()->json($cached, 200, [], JSON_UNESCAPED_SLASHES);
} }
if(strpos($resource, $domain) == false) { if (strpos($resource, $domain) == false) {
return response('', 400); return response('', 400);
} }
$parsed = Nickname::normalizeProfileUrl($resource); $parsed = Nickname::normalizeProfileUrl($resource);
if(empty($parsed) || $parsed['domain'] !== $domain) { if (empty($parsed) || $parsed['domain'] !== $domain) {
return response('', 400); return response('', 400);
} }
$username = $parsed['username']; $username = $parsed['username'];
$profile = Profile::whereNull('domain')->whereUsername($username)->first(); $profile = Profile::whereNull('domain')->whereUsername($username)->first();
if(!$profile || $profile->status !== null) { if (! $profile || $profile->status !== null) {
return response('', 400); return response('', 400);
} }
$webfinger = (new Webfinger($profile))->generate(); $webfinger = (new Webfinger($profile))->generate();
Cache::put($key, $webfinger, 1209600); Cache::put($key, $webfinger, 1209600);
return response()->json($webfinger, 200, [], JSON_UNESCAPED_SLASHES) return response()->json($webfinger, 200, [], JSON_UNESCAPED_SLASHES)
->header('Access-Control-Allow-Origin','*'); ->header('Access-Control-Allow-Origin', '*');
} }
public function hostMeta(Request $request) public function hostMeta(Request $request)
{ {
abort_if(!config('federation.webfinger.enabled'), 404); abort_if(! config('federation.webfinger.enabled'), 404);
$path = route('well-known.webfinger'); $path = route('well-known.webfinger');
$xml = '<?xml version="1.0" encoding="UTF-8"?><XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0"><Link rel="lrdd" type="application/xrd+xml" template="'.$path.'?resource={uri}"/></XRD>'; $xml = '<?xml version="1.0" encoding="UTF-8"?><XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0"><Link rel="lrdd" type="application/xrd+xml" template="'.$path.'?resource={uri}"/></XRD>';
@ -118,19 +104,19 @@ class FederationController extends Controller
public function userOutbox(Request $request, $username) public function userOutbox(Request $request, $username)
{ {
abort_if(!config_cache('federation.activitypub.enabled'), 404); abort_if(! (bool) config_cache('federation.activitypub.enabled'), 404);
if(!$request->wantsJson()) { if (! $request->wantsJson()) {
return redirect('/' . $username); return redirect('/'.$username);
} }
$id = AccountService::usernameToId($username); $id = AccountService::usernameToId($username);
abort_if(!$id, 404); abort_if(! $id, 404);
$account = AccountService::get($id); $account = AccountService::get($id);
abort_if(!$account || !isset($account['statuses_count']), 404); abort_if(! $account || ! isset($account['statuses_count']), 404);
$res = [ $res = [
'@context' => 'https://www.w3.org/ns/activitystreams', '@context' => 'https://www.w3.org/ns/activitystreams',
'id' => 'https://' . config('pixelfed.domain.app') . '/users/' . $username . '/outbox', 'id' => 'https://'.config('pixelfed.domain.app').'/users/'.$username.'/outbox',
'type' => 'OrderedCollection', 'type' => 'OrderedCollection',
'totalItems' => $account['statuses_count'] ?? 0, 'totalItems' => $account['statuses_count'] ?? 0,
]; ];
@ -140,135 +126,145 @@ class FederationController extends Controller
public function userInbox(Request $request, $username) public function userInbox(Request $request, $username)
{ {
abort_if(!config_cache('federation.activitypub.enabled'), 404); abort_if(! (bool) config_cache('federation.activitypub.enabled'), 404);
abort_if(!config('federation.activitypub.inbox'), 404); abort_if(! config('federation.activitypub.inbox'), 404);
$headers = $request->headers->all(); $headers = $request->headers->all();
$payload = $request->getContent(); $payload = $request->getContent();
if(!$payload || empty($payload)) { if (! $payload || empty($payload)) {
return; return;
} }
$obj = json_decode($payload, true, 8); $obj = json_decode($payload, true, 8);
if(!isset($obj['id'])) { if (! isset($obj['id'])) {
return; return;
} }
$domain = parse_url($obj['id'], PHP_URL_HOST); $domain = parse_url($obj['id'], PHP_URL_HOST);
if(in_array($domain, InstanceService::getBannedDomains())) { if (in_array($domain, InstanceService::getBannedDomains())) {
return; return;
} }
if(isset($obj['type']) && $obj['type'] === 'Delete') { if (isset($obj['type']) && $obj['type'] === 'Delete') {
if(isset($obj['object']) && isset($obj['object']['type']) && isset($obj['object']['id'])) { if (isset($obj['object']) && isset($obj['object']['type']) && isset($obj['object']['id'])) {
if($obj['object']['type'] === 'Person') { if ($obj['object']['type'] === 'Person') {
if(Profile::whereRemoteUrl($obj['object']['id'])->exists()) { if (Profile::whereRemoteUrl($obj['object']['id'])->exists()) {
dispatch(new DeleteWorker($headers, $payload))->onQueue('inbox'); dispatch(new DeleteWorker($headers, $payload))->onQueue('inbox');
return; return;
} }
} }
if($obj['object']['type'] === 'Tombstone') { if ($obj['object']['type'] === 'Tombstone') {
if(Status::whereObjectUrl($obj['object']['id'])->exists()) { if (Status::whereObjectUrl($obj['object']['id'])->exists()) {
dispatch(new DeleteWorker($headers, $payload))->onQueue('delete'); dispatch(new DeleteWorker($headers, $payload))->onQueue('delete');
return; return;
} }
} }
if($obj['object']['type'] === 'Story') { if ($obj['object']['type'] === 'Story') {
dispatch(new DeleteWorker($headers, $payload))->onQueue('story'); dispatch(new DeleteWorker($headers, $payload))->onQueue('story');
return; return;
} }
} }
return; return;
} else if( isset($obj['type']) && in_array($obj['type'], ['Follow', 'Accept'])) { } elseif (isset($obj['type']) && in_array($obj['type'], ['Follow', 'Accept'])) {
dispatch(new InboxValidator($username, $headers, $payload))->onQueue('follow'); dispatch(new InboxValidator($username, $headers, $payload))->onQueue('follow');
} else { } else {
dispatch(new InboxValidator($username, $headers, $payload))->onQueue('high'); dispatch(new InboxValidator($username, $headers, $payload))->onQueue('high');
} }
return;
} }
public function sharedInbox(Request $request) public function sharedInbox(Request $request)
{ {
abort_if(!config_cache('federation.activitypub.enabled'), 404); abort_if(! (bool) config_cache('federation.activitypub.enabled'), 404);
abort_if(!config('federation.activitypub.sharedInbox'), 404); abort_if(! config('federation.activitypub.sharedInbox'), 404);
$headers = $request->headers->all(); $headers = $request->headers->all();
$payload = $request->getContent(); $payload = $request->getContent();
if(!$payload || empty($payload)) { if (! $payload || empty($payload)) {
return; return;
} }
$obj = json_decode($payload, true, 8); $obj = json_decode($payload, true, 8);
if(!isset($obj['id'])) { if (! isset($obj['id'])) {
return; return;
} }
$domain = parse_url($obj['id'], PHP_URL_HOST); $domain = parse_url($obj['id'], PHP_URL_HOST);
if(in_array($domain, InstanceService::getBannedDomains())) { if (in_array($domain, InstanceService::getBannedDomains())) {
return; return;
} }
if(isset($obj['type']) && $obj['type'] === 'Delete') { if (isset($obj['type']) && $obj['type'] === 'Delete') {
if(isset($obj['object']) && isset($obj['object']['type']) && isset($obj['object']['id'])) { if (isset($obj['object']) && isset($obj['object']['type']) && isset($obj['object']['id'])) {
if($obj['object']['type'] === 'Person') { if ($obj['object']['type'] === 'Person') {
if(Profile::whereRemoteUrl($obj['object']['id'])->exists()) { if (Profile::whereRemoteUrl($obj['object']['id'])->exists()) {
dispatch(new DeleteWorker($headers, $payload))->onQueue('inbox'); dispatch(new DeleteWorker($headers, $payload))->onQueue('inbox');
return; return;
} }
} }
if($obj['object']['type'] === 'Tombstone') { if ($obj['object']['type'] === 'Tombstone') {
if(Status::whereObjectUrl($obj['object']['id'])->exists()) { if (Status::whereObjectUrl($obj['object']['id'])->exists()) {
dispatch(new DeleteWorker($headers, $payload))->onQueue('delete'); dispatch(new DeleteWorker($headers, $payload))->onQueue('delete');
return; return;
} }
} }
if($obj['object']['type'] === 'Story') { if ($obj['object']['type'] === 'Story') {
dispatch(new DeleteWorker($headers, $payload))->onQueue('story'); dispatch(new DeleteWorker($headers, $payload))->onQueue('story');
return; return;
} }
} }
return; return;
} else if( isset($obj['type']) && in_array($obj['type'], ['Follow', 'Accept'])) { } elseif (isset($obj['type']) && in_array($obj['type'], ['Follow', 'Accept'])) {
dispatch(new InboxWorker($headers, $payload))->onQueue('follow'); dispatch(new InboxWorker($headers, $payload))->onQueue('follow');
} else { } else {
dispatch(new InboxWorker($headers, $payload))->onQueue('shared'); dispatch(new InboxWorker($headers, $payload))->onQueue('shared');
} }
return;
} }
public function userFollowing(Request $request, $username) public function userFollowing(Request $request, $username)
{ {
abort_if(!config_cache('federation.activitypub.enabled'), 404); abort_if(! (bool) config_cache('federation.activitypub.enabled'), 404);
$id = AccountService::usernameToId($username); $id = AccountService::usernameToId($username);
abort_if(!$id, 404); abort_if(! $id, 404);
$account = AccountService::get($id); $account = AccountService::get($id);
abort_if(!$account || !isset($account['following_count']), 404); abort_if(! $account || ! isset($account['following_count']), 404);
$obj = [ $obj = [
'@context' => 'https://www.w3.org/ns/activitystreams', '@context' => 'https://www.w3.org/ns/activitystreams',
'id' => $request->getUri(), 'id' => $request->getUri(),
'type' => 'OrderedCollection', 'type' => 'OrderedCollection',
'totalItems' => $account['following_count'] ?? 0, 'totalItems' => $account['following_count'] ?? 0,
]; ];
return response()->json($obj)->header('Content-Type', 'application/activity+json'); return response()->json($obj)->header('Content-Type', 'application/activity+json');
} }
public function userFollowers(Request $request, $username) public function userFollowers(Request $request, $username)
{ {
abort_if(!config_cache('federation.activitypub.enabled'), 404); abort_if(! (bool) config_cache('federation.activitypub.enabled'), 404);
$id = AccountService::usernameToId($username); $id = AccountService::usernameToId($username);
abort_if(!$id, 404); abort_if(! $id, 404);
$account = AccountService::get($id); $account = AccountService::get($id);
abort_if(!$account || !isset($account['followers_count']), 404); abort_if(! $account || ! isset($account['followers_count']), 404);
$obj = [ $obj = [
'@context' => 'https://www.w3.org/ns/activitystreams', '@context' => 'https://www.w3.org/ns/activitystreams',
'id' => $request->getUri(), 'id' => $request->getUri(),
'type' => 'OrderedCollection', 'type' => 'OrderedCollection',
'totalItems' => $account['followers_count'] ?? 0, 'totalItems' => $account['followers_count'] ?? 0,
]; ];
return response()->json($obj)->header('Content-Type', 'application/activity+json'); return response()->json($obj)->header('Content-Type', 'application/activity+json');
} }
} }

View file

@ -2,27 +2,25 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use Auth;
use App\Hashtag; use App\Hashtag;
use App\Place; use App\Place;
use App\Profile; use App\Profile;
use App\Services\WebfingerService;
use App\Status; use App\Status;
use Illuminate\Http\Request;
use App\Util\ActivityPub\Helpers; use App\Util\ActivityPub\Helpers;
use Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use App\Transformer\Api\{
AccountTransformer,
HashtagTransformer,
StatusTransformer,
};
use App\Services\WebfingerService;
class SearchController extends Controller class SearchController extends Controller
{ {
public $tokens = []; public $tokens = [];
public $term = ''; public $term = '';
public $hash = ''; public $hash = '';
public $cacheKey = 'api:search:tag:'; public $cacheKey = 'api:search:tag:';
public function __construct() public function __construct()
@ -36,7 +34,7 @@ class SearchController extends Controller
'q' => 'required|string|min:3|max:120', 'q' => 'required|string|min:3|max:120',
'src' => 'required|string|in:metro', 'src' => 'required|string|in:metro',
'v' => 'required|integer|in:2', 'v' => 'required|integer|in:2',
'scope' => 'required|in:all,hashtag,profile,remote,webfinger' 'scope' => 'required|in:all,hashtag,profile,remote,webfinger',
]); ]);
$scope = $request->input('scope') ?? 'all'; $scope = $request->input('scope') ?? 'all';
@ -82,14 +80,15 @@ class SearchController extends Controller
{ {
$tag = $this->term; $tag = $this->term;
$hash = hash('sha256', $tag); $hash = hash('sha256', $tag);
if( Helpers::validateUrl($tag) != false && if (Helpers::validateUrl($tag) != false &&
Helpers::validateLocalUrl($tag) != true && Helpers::validateLocalUrl($tag) != true &&
config_cache('federation.activitypub.enabled') == true && (bool) config_cache('federation.activitypub.enabled') == true &&
config('federation.activitypub.remoteFollow') == true config('federation.activitypub.remoteFollow') == true
) { ) {
$remote = Helpers::fetchFromUrl($tag); $remote = Helpers::fetchFromUrl($tag);
if( isset($remote['type']) && if (isset($remote['type']) &&
$remote['type'] == 'Note') { in_array($remote['type'], ['Note', 'Question'])
) {
$item = Helpers::statusFetch($tag); $item = Helpers::statusFetch($tag);
$this->tokens['posts'] = [[ $this->tokens['posts'] = [[
'count' => 0, 'count' => 0,
@ -112,8 +111,8 @@ class SearchController extends Controller
->limit(10) ->limit(10)
->get(); ->get();
if($posts->count() > 0) { if ($posts->count() > 0) {
$posts = $posts->map(function($item, $key) { $posts = $posts->map(function ($item, $key) {
return [ return [
'count' => 0, 'count' => 0,
'url' => $item->url(), 'url' => $item->url(),
@ -122,7 +121,7 @@ class SearchController extends Controller
'tokens' => [$item->caption], 'tokens' => [$item->caption],
'name' => $item->caption, 'name' => $item->caption,
'thumb' => $item->thumb(), 'thumb' => $item->thumb(),
'filter' => $item->firstMedia()->filter_class 'filter' => $item->firstMedia()->filter_class,
]; ];
}); });
$this->tokens['posts'] = $posts; $this->tokens['posts'] = $posts;
@ -133,16 +132,16 @@ class SearchController extends Controller
protected function getHashtags() protected function getHashtags()
{ {
$tag = $this->term; $tag = $this->term;
$key = $this->cacheKey . 'hashtags:' . $this->hash; $key = $this->cacheKey.'hashtags:'.$this->hash;
$ttl = now()->addMinutes(1); $ttl = now()->addMinutes(1);
$tokens = Cache::remember($key, $ttl, function() use($tag) { $tokens = Cache::remember($key, $ttl, function () use ($tag) {
$htag = Str::startsWith($tag, '#') == true ? mb_substr($tag, 1) : $tag; $htag = Str::startsWith($tag, '#') == true ? mb_substr($tag, 1) : $tag;
$hashtags = Hashtag::select('id', 'name', 'slug') $hashtags = Hashtag::select('id', 'name', 'slug')
->where('slug', 'like', '%'.$htag.'%') ->where('slug', 'like', '%'.$htag.'%')
->whereHas('posts') ->whereHas('posts')
->limit(20) ->limit(20)
->get(); ->get();
if($hashtags->count() > 0) { if ($hashtags->count() > 0) {
$tags = $hashtags->map(function ($item, $key) { $tags = $hashtags->map(function ($item, $key) {
return [ return [
'count' => $item->posts()->count(), 'count' => $item->posts()->count(),
@ -153,6 +152,7 @@ class SearchController extends Controller
'name' => null, 'name' => null,
]; ];
}); });
return $tags; return $tags;
} }
}); });
@ -170,17 +170,17 @@ class SearchController extends Controller
->where('name', 'like', '%'.$htag[0].'%') ->where('name', 'like', '%'.$htag[0].'%')
->paginate(20); ->paginate(20);
$tags = []; $tags = [];
if($hashtags->count() > 0) { if ($hashtags->count() > 0) {
$tags = $hashtags->map(function ($item, $key) { $tags = $hashtags->map(function ($item, $key) {
return [ return [
'count' => null, 'count' => null,
'url' => $item->url(), 'url' => $item->url(),
'type' => 'place', 'type' => 'place',
'value' => $item->name . ', ' . $item->country, 'value' => $item->name.', '.$item->country,
'tokens' => '', 'tokens' => '',
'name' => null, 'name' => null,
'city' => $item->name, 'city' => $item->name,
'country' => $item->country 'country' => $item->country,
]; ];
}); });
// return $tags; // return $tags;
@ -190,27 +190,27 @@ class SearchController extends Controller
$this->tokens['placesPagination'] = [ $this->tokens['placesPagination'] = [
'total' => $hashtags->total(), 'total' => $hashtags->total(),
'current_page' => $hashtags->currentPage(), 'current_page' => $hashtags->currentPage(),
'last_page' => $hashtags->lastPage() 'last_page' => $hashtags->lastPage(),
]; ];
} }
protected function getProfiles() protected function getProfiles()
{ {
$tag = $this->term; $tag = $this->term;
$remoteKey = $this->cacheKey . 'profiles:remote:' . $this->hash; $remoteKey = $this->cacheKey.'profiles:remote:'.$this->hash;
$key = $this->cacheKey . 'profiles:' . $this->hash; $key = $this->cacheKey.'profiles:'.$this->hash;
$remoteTtl = now()->addMinutes(15); $remoteTtl = now()->addMinutes(15);
$ttl = now()->addHours(2); $ttl = now()->addHours(2);
if( Helpers::validateUrl($tag) != false && if (Helpers::validateUrl($tag) != false &&
Helpers::validateLocalUrl($tag) != true && Helpers::validateLocalUrl($tag) != true &&
config_cache('federation.activitypub.enabled') == true && (bool) config_cache('federation.activitypub.enabled') == true &&
config('federation.activitypub.remoteFollow') == true config('federation.activitypub.remoteFollow') == true
) { ) {
$remote = Helpers::fetchFromUrl($tag); $remote = Helpers::fetchFromUrl($tag);
if( isset($remote['type']) && if (isset($remote['type']) &&
$remote['type'] == 'Person' $remote['type'] == 'Person'
) { ) {
$this->tokens['profiles'] = Cache::remember($remoteKey, $remoteTtl, function() use($tag) { $this->tokens['profiles'] = Cache::remember($remoteKey, $remoteTtl, function () use ($tag) {
$item = Helpers::profileFirstOrNew($tag); $item = Helpers::profileFirstOrNew($tag);
$tokens = [[ $tokens = [[
'count' => 1, 'count' => 1,
@ -224,18 +224,17 @@ class SearchController extends Controller
'following' => $item->followedBy(Auth::user()->profile), 'following' => $item->followedBy(Auth::user()->profile),
'follow_request' => $item->hasFollowRequestById(Auth::user()->profile_id), 'follow_request' => $item->hasFollowRequestById(Auth::user()->profile_id),
'thumb' => $item->avatarUrl(), 'thumb' => $item->avatarUrl(),
'local' => (bool) !$item->domain, 'local' => (bool) ! $item->domain,
'post_count' => $item->statuses()->count() 'post_count' => $item->statuses()->count(),
] ],
]]; ]];
return $tokens; return $tokens;
}); });
} }
} } else {
$this->tokens['profiles'] = Cache::remember($key, $ttl, function () use ($tag) {
else { if (Str::startsWith($tag, '@')) {
$this->tokens['profiles'] = Cache::remember($key, $ttl, function() use($tag) {
if(Str::startsWith($tag, '@')) {
$tag = substr($tag, 1); $tag = substr($tag, 1);
} }
$users = Profile::select('status', 'domain', 'username', 'name', 'id') $users = Profile::select('status', 'domain', 'username', 'name', 'id')
@ -245,7 +244,7 @@ class SearchController extends Controller
->orderBy('domain') ->orderBy('domain')
->get(); ->get();
if($users->count() > 0) { if ($users->count() > 0) {
return $users->map(function ($item, $key) { return $users->map(function ($item, $key) {
return [ return [
'count' => 0, 'count' => 0,
@ -261,9 +260,9 @@ class SearchController extends Controller
'following' => $item->followedBy(Auth::user()->profile), 'following' => $item->followedBy(Auth::user()->profile),
'follow_request' => $item->hasFollowRequestById(Auth::user()->profile_id), 'follow_request' => $item->hasFollowRequestById(Auth::user()->profile_id),
'thumb' => $item->avatarUrl(), 'thumb' => $item->avatarUrl(),
'local' => (bool) !$item->domain, 'local' => (bool) ! $item->domain,
'post_count' => $item->statuses()->count() 'post_count' => $item->statuses()->count(),
] ],
]; ];
}); });
} }
@ -284,7 +283,7 @@ class SearchController extends Controller
{ {
$wfs = WebfingerService::lookup($this->term); $wfs = WebfingerService::lookup($this->term);
if(empty($wfs)) { if (empty($wfs)) {
return; return;
} }
@ -301,11 +300,11 @@ class SearchController extends Controller
'following' => null, 'following' => null,
'follow_request' => null, 'follow_request' => null,
'thumb' => $wfs['avatar'], 'thumb' => $wfs['avatar'],
'local' => (bool) $wfs['local'] 'local' => (bool) $wfs['local'],
] ],
] ],
]; ];
return;
} }
protected function remotePostLookup() protected function remotePostLookup()
@ -315,15 +314,15 @@ class SearchController extends Controller
$local = Helpers::validateLocalUrl($tag); $local = Helpers::validateLocalUrl($tag);
$valid = Helpers::validateUrl($tag); $valid = Helpers::validateUrl($tag);
if($valid == false || $local == true) { if ($valid == false || $local == true) {
return; return;
} }
if(Status::whereUri($tag)->whereLocal(false)->exists()) { if (Status::whereUri($tag)->whereLocal(false)->exists()) {
$item = Status::whereUri($tag)->first(); $item = Status::whereUri($tag)->first();
$media = $item->firstMedia(); $media = $item->firstMedia();
$url = null; $url = null;
if($media) { if ($media) {
$url = $media->remote_url; $url = $media->remote_url;
} }
$this->tokens['posts'] = [[ $this->tokens['posts'] = [[
@ -333,17 +332,17 @@ class SearchController extends Controller
'username' => $item->profile->username, 'username' => $item->profile->username,
'caption' => $item->rendered ?? $item->caption, 'caption' => $item->rendered ?? $item->caption,
'thumb' => $url, 'thumb' => $url,
'timestamp' => $item->created_at->diffForHumans() 'timestamp' => $item->created_at->diffForHumans(),
]]; ]];
} }
$remote = Helpers::fetchFromUrl($tag); $remote = Helpers::fetchFromUrl($tag);
if(isset($remote['type']) && $remote['type'] == 'Note') { if (isset($remote['type']) && $remote['type'] == 'Note') {
$item = Helpers::statusFetch($tag); $item = Helpers::statusFetch($tag);
$media = $item->firstMedia(); $media = $item->firstMedia();
$url = null; $url = null;
if($media) { if ($media) {
$url = $media->remote_url; $url = $media->remote_url;
} }
$this->tokens['posts'] = [[ $this->tokens['posts'] = [[
@ -353,14 +352,14 @@ class SearchController extends Controller
'username' => $item->profile->username, 'username' => $item->profile->username,
'caption' => $item->rendered ?? $item->caption, 'caption' => $item->rendered ?? $item->caption,
'thumb' => $url, 'thumb' => $url,
'timestamp' => $item->created_at->diffForHumans() 'timestamp' => $item->created_at->diffForHumans(),
]]; ]];
} }
} }
protected function remoteLookupSearch() protected function remoteLookupSearch()
{ {
if(!Helpers::validateUrl($this->term)) { if (! Helpers::validateUrl($this->term)) {
return; return;
} }
$this->getProfiles(); $this->getProfiles();

View file

@ -78,7 +78,7 @@ class StatusController extends Controller
]); ]);
} }
if ($request->wantsJson() && config_cache('federation.activitypub.enabled')) { if ($request->wantsJson() && (bool) config_cache('federation.activitypub.enabled')) {
return $this->showActivityPub($request, $status); return $this->showActivityPub($request, $status);
} }

View file

@ -2,9 +2,15 @@
namespace App\Jobs\SharePipeline; namespace App\Jobs\SharePipeline;
use Cache, Log; use App\Jobs\HomeFeedPipeline\FeedInsertPipeline;
use Illuminate\Support\Facades\Redis; use App\Notification;
use App\{Status, Notification}; use App\Services\ReblogService;
use App\Services\StatusService;
use App\Status;
use App\Transformer\ActivityPub\Verb\Announce;
use App\Util\ActivityPub\HttpSignature;
use GuzzleHttp\Client;
use GuzzleHttp\Pool;
use Illuminate\Bus\Queueable; use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Foundation\Bus\Dispatchable;
@ -12,12 +18,6 @@ use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
use League\Fractal; use League\Fractal;
use League\Fractal\Serializer\ArraySerializer; use League\Fractal\Serializer\ArraySerializer;
use App\Transformer\ActivityPub\Verb\Announce;
use GuzzleHttp\{Pool, Client, Promise};
use App\Util\ActivityPub\HttpSignature;
use App\Services\ReblogService;
use App\Services\StatusService;
use App\Jobs\HomeFeedPipeline\FeedInsertPipeline;
class SharePipeline implements ShouldQueue class SharePipeline implements ShouldQueue
{ {
@ -51,7 +51,7 @@ class SharePipeline implements ShouldQueue
{ {
$status = $this->status; $status = $this->status;
$parent = Status::find($this->status->reblog_of_id); $parent = Status::find($this->status->reblog_of_id);
if(!$parent) { if (! $parent) {
return; return;
} }
$actor = $status->profile; $actor = $status->profile;
@ -62,8 +62,9 @@ class SharePipeline implements ShouldQueue
return; return;
} }
if($target->id === $status->profile_id) { if ($target->id === $status->profile_id) {
$this->remoteAnnounceDeliver(); $this->remoteAnnounceDeliver();
return true; return true;
} }
@ -90,7 +91,7 @@ class SharePipeline implements ShouldQueue
public function remoteAnnounceDeliver() public function remoteAnnounceDeliver()
{ {
if(config('app.env') !== 'production' || config_cache('federation.activitypub.enabled') == false) { if (config('app.env') !== 'production' || (bool) config_cache('federation.activitypub.enabled') == false) {
return true; return true;
} }
$status = $this->status; $status = $this->status;
@ -103,7 +104,7 @@ class SharePipeline implements ShouldQueue
$audience = $status->profile->getAudienceInbox(); $audience = $status->profile->getAudienceInbox();
if(empty($audience) || $status->scope != 'public') { if (empty($audience) || $status->scope != 'public') {
// Return on profiles with no remote followers // Return on profiles with no remote followers
return; return;
} }
@ -111,26 +112,26 @@ class SharePipeline implements ShouldQueue
$payload = json_encode($activity); $payload = json_encode($activity);
$client = new Client([ $client = new Client([
'timeout' => config('federation.activitypub.delivery.timeout') 'timeout' => config('federation.activitypub.delivery.timeout'),
]); ]);
$version = config('pixelfed.version'); $version = config('pixelfed.version');
$appUrl = config('app.url'); $appUrl = config('app.url');
$userAgent = "(Pixelfed/{$version}; +{$appUrl})"; $userAgent = "(Pixelfed/{$version}; +{$appUrl})";
$requests = function($audience) use ($client, $activity, $profile, $payload, $userAgent) { $requests = function ($audience) use ($client, $activity, $profile, $payload, $userAgent) {
foreach($audience as $url) { foreach ($audience as $url) {
$headers = HttpSignature::sign($profile, $url, $activity, [ $headers = HttpSignature::sign($profile, $url, $activity, [
'Content-Type' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"', 'Content-Type' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
'User-Agent' => $userAgent, 'User-Agent' => $userAgent,
]); ]);
yield function() use ($client, $url, $headers, $payload) { yield function () use ($client, $url, $headers, $payload) {
return $client->postAsync($url, [ return $client->postAsync($url, [
'curl' => [ 'curl' => [
CURLOPT_HTTPHEADER => $headers, CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $payload, CURLOPT_POSTFIELDS => $payload,
CURLOPT_HEADER => true CURLOPT_HEADER => true,
] ],
]); ]);
}; };
} }
@ -141,7 +142,7 @@ class SharePipeline implements ShouldQueue
'fulfilled' => function ($response, $index) { 'fulfilled' => function ($response, $index) {
}, },
'rejected' => function ($reason, $index) { 'rejected' => function ($reason, $index) {
} },
]); ]);
$promise = $pool->promise(); $promise = $pool->promise();

View file

@ -2,9 +2,15 @@
namespace App\Jobs\SharePipeline; namespace App\Jobs\SharePipeline;
use Cache, Log; use App\Jobs\HomeFeedPipeline\FeedRemovePipeline;
use Illuminate\Support\Facades\Redis; use App\Notification;
use App\{Status, Notification}; use App\Services\ReblogService;
use App\Services\StatusService;
use App\Status;
use App\Transformer\ActivityPub\Verb\UndoAnnounce;
use App\Util\ActivityPub\HttpSignature;
use GuzzleHttp\Client;
use GuzzleHttp\Pool;
use Illuminate\Bus\Queueable; use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Foundation\Bus\Dispatchable;
@ -12,17 +18,13 @@ use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
use League\Fractal; use League\Fractal;
use League\Fractal\Serializer\ArraySerializer; use League\Fractal\Serializer\ArraySerializer;
use App\Transformer\ActivityPub\Verb\UndoAnnounce;
use GuzzleHttp\{Pool, Client, Promise};
use App\Util\ActivityPub\HttpSignature;
use App\Services\ReblogService;
use App\Services\StatusService;
use App\Jobs\HomeFeedPipeline\FeedRemovePipeline;
class UndoSharePipeline implements ShouldQueue class UndoSharePipeline implements ShouldQueue
{ {
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $status; protected $status;
public $deleteWhenMissingModels = true; public $deleteWhenMissingModels = true;
public function __construct(Status $status) public function __construct(Status $status)
@ -38,11 +40,11 @@ class UndoSharePipeline implements ShouldQueue
FeedRemovePipeline::dispatch($status->id, $status->profile_id)->onQueue('feed'); FeedRemovePipeline::dispatch($status->id, $status->profile_id)->onQueue('feed');
if($parent) { if ($parent) {
$target = $parent->profile_id; $target = $parent->profile_id;
ReblogService::removePostReblog($parent->profile_id, $status->id); ReblogService::removePostReblog($parent->profile_id, $status->id);
if($parent->reblogs_count > 0) { if ($parent->reblogs_count > 0) {
$parent->reblogs_count = $parent->reblogs_count - 1; $parent->reblogs_count = $parent->reblogs_count - 1;
$parent->save(); $parent->save();
StatusService::del($parent->id); StatusService::del($parent->id);
@ -55,7 +57,7 @@ class UndoSharePipeline implements ShouldQueue
->whereItemType('App\Status') ->whereItemType('App\Status')
->first(); ->first();
if($notification) { if ($notification) {
$notification->forceDelete(); $notification->forceDelete();
} }
} }
@ -64,7 +66,7 @@ class UndoSharePipeline implements ShouldQueue
return; return;
} }
if(config('app.env') !== 'production' || config_cache('federation.activitypub.enabled') == false) { if (config('app.env') !== 'production' || (bool) config_cache('federation.activitypub.enabled') == false) {
return $status->delete(); return $status->delete();
} else { } else {
return $this->remoteAnnounceDeliver(); return $this->remoteAnnounceDeliver();
@ -73,8 +75,9 @@ class UndoSharePipeline implements ShouldQueue
public function remoteAnnounceDeliver() public function remoteAnnounceDeliver()
{ {
if(config('app.env') !== 'production' || config_cache('federation.activitypub.enabled') == false) { if (config('app.env') !== 'production' || (bool) config_cache('federation.activitypub.enabled') == false) {
$status->delete(); $status->delete();
return 1; return 1;
} }
@ -88,33 +91,33 @@ class UndoSharePipeline implements ShouldQueue
$audience = $status->profile->getAudienceInbox(); $audience = $status->profile->getAudienceInbox();
if(empty($audience) || $status->scope != 'public') { if (empty($audience) || $status->scope != 'public') {
return 1; return 1;
} }
$payload = json_encode($activity); $payload = json_encode($activity);
$client = new Client([ $client = new Client([
'timeout' => config('federation.activitypub.delivery.timeout') 'timeout' => config('federation.activitypub.delivery.timeout'),
]); ]);
$version = config('pixelfed.version'); $version = config('pixelfed.version');
$appUrl = config('app.url'); $appUrl = config('app.url');
$userAgent = "(Pixelfed/{$version}; +{$appUrl})"; $userAgent = "(Pixelfed/{$version}; +{$appUrl})";
$requests = function($audience) use ($client, $activity, $profile, $payload, $userAgent) { $requests = function ($audience) use ($client, $activity, $profile, $payload, $userAgent) {
foreach($audience as $url) { foreach ($audience as $url) {
$headers = HttpSignature::sign($profile, $url, $activity, [ $headers = HttpSignature::sign($profile, $url, $activity, [
'Content-Type' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"', 'Content-Type' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
'User-Agent' => $userAgent, 'User-Agent' => $userAgent,
]); ]);
yield function() use ($client, $url, $headers, $payload) { yield function () use ($client, $url, $headers, $payload) {
return $client->postAsync($url, [ return $client->postAsync($url, [
'curl' => [ 'curl' => [
CURLOPT_HTTPHEADER => $headers, CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $payload, CURLOPT_POSTFIELDS => $payload,
CURLOPT_HEADER => true CURLOPT_HEADER => true,
] ],
]); ]);
}; };
} }
@ -125,7 +128,7 @@ class UndoSharePipeline implements ShouldQueue
'fulfilled' => function ($response, $index) { 'fulfilled' => function ($response, $index) {
}, },
'rejected' => function ($reason, $index) { 'rejected' => function ($reason, $index) {
} },
]); ]);
$promise = $pool->promise(); $promise = $pool->promise();

View file

@ -2,41 +2,36 @@
namespace App\Jobs\StatusPipeline; namespace App\Jobs\StatusPipeline;
use DB, Cache, Storage; use App\AccountInterstitial;
use App\{ use App\Bookmark;
AccountInterstitial, use App\CollectionItem;
Bookmark, use App\DirectMessage;
CollectionItem, use App\Jobs\MediaPipeline\MediaDeletePipeline;
DirectMessage, use App\Like;
Like, use App\Media;
Media, use App\MediaTag;
MediaTag, use App\Mention;
Mention, use App\Notification;
Notification, use App\Report;
Report, use App\Services\CollectionService;
Status, use App\Services\NotificationService;
StatusArchived, use App\Services\StatusService;
StatusHashtag, use App\Status;
StatusView use App\StatusArchived;
}; use App\StatusHashtag;
use App\StatusView;
use App\Transformer\ActivityPub\Verb\DeleteNote;
use App\Util\ActivityPub\HttpSignature;
use Cache;
use GuzzleHttp\Client;
use GuzzleHttp\Pool;
use Illuminate\Bus\Queueable; use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
use League\Fractal; use League\Fractal;
use Illuminate\Support\Str;
use League\Fractal\Serializer\ArraySerializer; use League\Fractal\Serializer\ArraySerializer;
use App\Transformer\ActivityPub\Verb\DeleteNote;
use App\Util\ActivityPub\Helpers;
use GuzzleHttp\Pool;
use GuzzleHttp\Client;
use GuzzleHttp\Promise;
use App\Util\ActivityPub\HttpSignature;
use App\Services\CollectionService;
use App\Services\StatusService;
use App\Services\NotificationService;
use App\Jobs\MediaPipeline\MediaDeletePipeline;
class StatusDelete implements ShouldQueue class StatusDelete implements ShouldQueue
{ {
@ -52,6 +47,7 @@ class StatusDelete implements ShouldQueue
public $deleteWhenMissingModels = true; public $deleteWhenMissingModels = true;
public $timeout = 900; public $timeout = 900;
public $tries = 2; public $tries = 2;
/** /**
@ -75,16 +71,16 @@ class StatusDelete implements ShouldQueue
$profile = $this->status->profile; $profile = $this->status->profile;
StatusService::del($status->id, true); StatusService::del($status->id, true);
if($profile) { if ($profile) {
if(in_array($status->type, ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])) { if (in_array($status->type, ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])) {
$profile->status_count = $profile->status_count - 1; $profile->status_count = $profile->status_count - 1;
$profile->save(); $profile->save();
} }
} }
Cache::forget('pf:atom:user-feed:by-id:' . $status->profile_id); Cache::forget('pf:atom:user-feed:by-id:'.$status->profile_id);
if(config_cache('federation.activitypub.enabled') == true) { if ((bool) config_cache('federation.activitypub.enabled') == true) {
return $this->fanoutDelete($status); return $this->fanoutDelete($status);
} else { } else {
return $this->unlinkRemoveMedia($status); return $this->unlinkRemoveMedia($status);
@ -95,13 +91,13 @@ class StatusDelete implements ShouldQueue
{ {
Media::whereStatusId($status->id) Media::whereStatusId($status->id)
->get() ->get()
->each(function($media) { ->each(function ($media) {
MediaDeletePipeline::dispatch($media); MediaDeletePipeline::dispatch($media);
}); });
if($status->in_reply_to_id) { if ($status->in_reply_to_id) {
$parent = Status::findOrFail($status->in_reply_to_id); $parent = Status::findOrFail($status->in_reply_to_id);
--$parent->reply_count; $parent->reply_count--;
$parent->save(); $parent->save();
StatusService::del($parent->id); StatusService::del($parent->id);
} }
@ -111,17 +107,17 @@ class StatusDelete implements ShouldQueue
CollectionItem::whereObjectType('App\Status') CollectionItem::whereObjectType('App\Status')
->whereObjectId($status->id) ->whereObjectId($status->id)
->get() ->get()
->each(function($col) { ->each(function ($col) {
CollectionService::removeItem($col->collection_id, $col->object_id); CollectionService::removeItem($col->collection_id, $col->object_id);
$col->delete(); $col->delete();
}); });
$dms = DirectMessage::whereStatusId($status->id)->get(); $dms = DirectMessage::whereStatusId($status->id)->get();
foreach($dms as $dm) { foreach ($dms as $dm) {
$not = Notification::whereItemType('App\DirectMessage') $not = Notification::whereItemType('App\DirectMessage')
->whereItemId($dm->id) ->whereItemId($dm->id)
->first(); ->first();
if($not) { if ($not) {
NotificationService::del($not->profile_id, $not->id); NotificationService::del($not->profile_id, $not->id);
$not->forceDeleteQuietly(); $not->forceDeleteQuietly();
} }
@ -130,11 +126,11 @@ class StatusDelete implements ShouldQueue
Like::whereStatusId($status->id)->delete(); Like::whereStatusId($status->id)->delete();
$mediaTags = MediaTag::where('status_id', $status->id)->get(); $mediaTags = MediaTag::where('status_id', $status->id)->get();
foreach($mediaTags as $mtag) { foreach ($mediaTags as $mtag) {
$not = Notification::whereItemType('App\MediaTag') $not = Notification::whereItemType('App\MediaTag')
->whereItemId($mtag->id) ->whereItemId($mtag->id)
->first(); ->first();
if($not) { if ($not) {
NotificationService::del($not->profile_id, $not->id); NotificationService::del($not->profile_id, $not->id);
$not->forceDeleteQuietly(); $not->forceDeleteQuietly();
} }
@ -168,7 +164,7 @@ class StatusDelete implements ShouldQueue
{ {
$profile = $status->profile; $profile = $status->profile;
if(!$profile) { if (! $profile) {
return; return;
} }
@ -184,26 +180,26 @@ class StatusDelete implements ShouldQueue
$payload = json_encode($activity); $payload = json_encode($activity);
$client = new Client([ $client = new Client([
'timeout' => config('federation.activitypub.delivery.timeout') 'timeout' => config('federation.activitypub.delivery.timeout'),
]); ]);
$version = config('pixelfed.version'); $version = config('pixelfed.version');
$appUrl = config('app.url'); $appUrl = config('app.url');
$userAgent = "(Pixelfed/{$version}; +{$appUrl})"; $userAgent = "(Pixelfed/{$version}; +{$appUrl})";
$requests = function($audience) use ($client, $activity, $profile, $payload, $userAgent) { $requests = function ($audience) use ($client, $activity, $profile, $payload, $userAgent) {
foreach($audience as $url) { foreach ($audience as $url) {
$headers = HttpSignature::sign($profile, $url, $activity, [ $headers = HttpSignature::sign($profile, $url, $activity, [
'Content-Type' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"', 'Content-Type' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
'User-Agent' => $userAgent, 'User-Agent' => $userAgent,
]); ]);
yield function() use ($client, $url, $headers, $payload) { yield function () use ($client, $url, $headers, $payload) {
return $client->postAsync($url, [ return $client->postAsync($url, [
'curl' => [ 'curl' => [
CURLOPT_HTTPHEADER => $headers, CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $payload, CURLOPT_POSTFIELDS => $payload,
CURLOPT_HEADER => true CURLOPT_HEADER => true,
] ],
]); ]);
}; };
} }
@ -214,7 +210,7 @@ class StatusDelete implements ShouldQueue
'fulfilled' => function ($response, $index) { 'fulfilled' => function ($response, $index) {
}, },
'rejected' => function ($reason, $index) { 'rejected' => function ($reason, $index) {
} },
]); ]);
$promise = $pool->promise(); $promise = $pool->promise();

View file

@ -3,12 +3,16 @@
namespace App\Jobs\StatusPipeline; namespace App\Jobs\StatusPipeline;
use App\Hashtag; use App\Hashtag;
use App\Jobs\HomeFeedPipeline\FeedInsertPipeline;
use App\Jobs\MentionPipeline\MentionPipeline; use App\Jobs\MentionPipeline\MentionPipeline;
use App\Mention; use App\Mention;
use App\Profile; use App\Profile;
use App\Services\AdminShadowFilterService;
use App\Services\PublicTimelineService;
use App\Services\StatusService;
use App\Services\UserFilterService;
use App\Status; use App\Status;
use App\StatusHashtag; use App\StatusHashtag;
use App\Services\PublicTimelineService;
use App\Util\Lexer\Autolink; use App\Util\Lexer\Autolink;
use App\Util\Lexer\Extractor; use App\Util\Lexer\Extractor;
use App\Util\Sentiment\Bouncer; use App\Util\Sentiment\Bouncer;
@ -19,18 +23,15 @@ use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
use App\Services\StatusService;
use App\Services\UserFilterService;
use App\Services\AdminShadowFilterService;
use App\Jobs\HomeFeedPipeline\FeedInsertPipeline;
use App\Jobs\HomeFeedPipeline\HashtagInsertFanoutPipeline;
class StatusEntityLexer implements ShouldQueue class StatusEntityLexer implements ShouldQueue
{ {
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $status; protected $status;
protected $entities; protected $entities;
protected $autolink; protected $autolink;
/** /**
@ -60,12 +61,12 @@ class StatusEntityLexer implements ShouldQueue
$profile = $this->status->profile; $profile = $this->status->profile;
$status = $this->status; $status = $this->status;
if(in_array($status->type, ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])) { if (in_array($status->type, ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])) {
$profile->status_count = $profile->status_count + 1; $profile->status_count = $profile->status_count + 1;
$profile->save(); $profile->save();
} }
if($profile->no_autolink == false) { if ($profile->no_autolink == false) {
$this->parseEntities(); $this->parseEntities();
} }
} }
@ -103,16 +104,16 @@ class StatusEntityLexer implements ShouldQueue
$status = $this->status; $status = $this->status;
foreach ($tags as $tag) { foreach ($tags as $tag) {
if(mb_strlen($tag) > 124) { if (mb_strlen($tag) > 124) {
continue; continue;
} }
DB::transaction(function () use ($status, $tag) { DB::transaction(function () use ($status, $tag) {
$slug = str_slug($tag, '-', false); $slug = str_slug($tag, '-', false);
$hashtag = Hashtag::firstOrCreate([ $hashtag = Hashtag::firstOrCreate([
'slug' => $slug 'slug' => $slug,
], [ ], [
'name' => $tag 'name' => $tag,
]); ]);
StatusHashtag::firstOrCreate( StatusHashtag::firstOrCreate(
@ -136,11 +137,11 @@ class StatusEntityLexer implements ShouldQueue
foreach ($mentions as $mention) { foreach ($mentions as $mention) {
$mentioned = Profile::whereUsername($mention)->first(); $mentioned = Profile::whereUsername($mention)->first();
if (empty($mentioned) || !isset($mentioned->id)) { if (empty($mentioned) || ! isset($mentioned->id)) {
continue; continue;
} }
$blocks = UserFilterService::blocks($mentioned->id); $blocks = UserFilterService::blocks($mentioned->id);
if($blocks && in_array($status->profile_id, $blocks)) { if ($blocks && in_array($status->profile_id, $blocks)) {
continue; continue;
} }
@ -161,8 +162,8 @@ class StatusEntityLexer implements ShouldQueue
$status = $this->status; $status = $this->status;
StatusService::refresh($status->id); StatusService::refresh($status->id);
if(config('exp.cached_home_timeline')) { if (config('exp.cached_home_timeline')) {
if( $status->in_reply_to_id === null && if ($status->in_reply_to_id === null &&
in_array($status->scope, ['public', 'unlisted', 'private']) in_array($status->scope, ['public', 'unlisted', 'private'])
) { ) {
FeedInsertPipeline::dispatch($status->id, $status->profile_id)->onQueue('feed'); FeedInsertPipeline::dispatch($status->id, $status->profile_id)->onQueue('feed');
@ -179,28 +180,28 @@ class StatusEntityLexer implements ShouldQueue
'photo:album', 'photo:album',
'video', 'video',
'video:album', 'video:album',
'photo:video:album' 'photo:video:album',
]; ];
if(config_cache('pixelfed.bouncer.enabled')) { if (config_cache('pixelfed.bouncer.enabled')) {
Bouncer::get($status); Bouncer::get($status);
} }
Cache::forget('pf:atom:user-feed:by-id:' . $status->profile_id); Cache::forget('pf:atom:user-feed:by-id:'.$status->profile_id);
$hideNsfw = config('instance.hide_nsfw_on_public_feeds'); $hideNsfw = config('instance.hide_nsfw_on_public_feeds');
if( $status->uri == null && if ($status->uri == null &&
$status->scope == 'public' && $status->scope == 'public' &&
in_array($status->type, $types) && in_array($status->type, $types) &&
$status->in_reply_to_id === null && $status->in_reply_to_id === null &&
$status->reblog_of_id === null && $status->reblog_of_id === null &&
($hideNsfw ? $status->is_nsfw == false : true) ($hideNsfw ? $status->is_nsfw == false : true)
) { ) {
if(AdminShadowFilterService::canAddToPublicFeedByProfileId($status->profile_id)) { if (AdminShadowFilterService::canAddToPublicFeedByProfileId($status->profile_id)) {
PublicTimelineService::add($status->id); PublicTimelineService::add($status->id);
} }
} }
if(config_cache('federation.activitypub.enabled') == true && config('app.env') == 'production') { if ((bool) config_cache('federation.activitypub.enabled') == true && config('app.env') == 'production') {
StatusActivityPubDeliver::dispatch($status); StatusActivityPubDeliver::dispatch($status);
} }
} }

View file

@ -85,7 +85,7 @@ class LandingService
'media_types' => config_cache('pixelfed.media_types'), 'media_types' => config_cache('pixelfed.media_types'),
], ],
'features' => [ 'features' => [
'federation' => config_cache('federation.activitypub.enabled'), 'federation' => (bool) config_cache('federation.activitypub.enabled'),
'timelines' => [ 'timelines' => [
'local' => true, 'local' => true,
'network' => (bool) config_cache('federation.network_timeline'), 'network' => (bool) config_cache('federation.network_timeline'),

View file

@ -2,26 +2,24 @@
namespace App\Util\ActivityPub; namespace App\Util\ActivityPub;
use App\Profile;
use App\Status;
use League\Fractal;
use App\Http\Controllers\ProfileController; use App\Http\Controllers\ProfileController;
use App\Transformer\ActivityPub\ProfileOutbox; use App\Status;
use App\Transformer\ActivityPub\Verb\CreateNote; use App\Transformer\ActivityPub\Verb\CreateNote;
use League\Fractal;
class Outbox { class Outbox
{
public static function get($profile) public static function get($profile)
{ {
abort_if(!config_cache('federation.activitypub.enabled'), 404); abort_if(! (bool) config_cache('federation.activitypub.enabled'), 404);
abort_if(!config('federation.activitypub.outbox'), 404); abort_if(! config('federation.activitypub.outbox'), 404);
if($profile->status != null) { if ($profile->status != null) {
return ProfileController::accountCheck($profile); return ProfileController::accountCheck($profile);
} }
if($profile->is_private) { if ($profile->is_private) {
return ['error'=>'403', 'msg' => 'private profile']; return ['error' => '403', 'msg' => 'private profile'];
} }
$timeline = $profile $timeline = $profile
@ -43,9 +41,9 @@ class Outbox {
'id' => $profile->permalink('/outbox'), 'id' => $profile->permalink('/outbox'),
'type' => 'OrderedCollection', 'type' => 'OrderedCollection',
'totalItems' => $count, 'totalItems' => $count,
'orderedItems' => $res['data'] 'orderedItems' => $res['data'],
]; ];
return $outbox; return $outbox;
} }
} }

View file

@ -298,7 +298,7 @@
<tr> <tr>
<td><span class="badge badge-primary">FEDERATION</span></td> <td><span class="badge badge-primary">FEDERATION</span></td>
<td><strong>ACTIVITY_PUB</strong></td> <td><strong>ACTIVITY_PUB</strong></td>
<td><span>{{config_cache('federation.activitypub.enabled') ? '✅ true' : '❌ false' }}</span></td> <td><span>{{(bool) config_cache('federation.activitypub.enabled') ? '✅ true' : '❌ false' }}</span></td>
</tr> </tr>
<tr> <tr>
<td><span class="badge badge-primary">FEDERATION</span></td> <td><span class="badge badge-primary">FEDERATION</span></td>