Merge branch 'staging' of github.com:pixelfed/pixelfed into jippi-fork

This commit is contained in:
Christian Winther 2024-03-07 19:43:30 +00:00
commit 091de696c2
11 changed files with 518 additions and 491 deletions

View file

@ -5,6 +5,11 @@
### Updates ### Updates
- Update SoftwareUpdateService, add command to refresh latest versions ([632f2cb6](https://github.com/pixelfed/pixelfed/commit/632f2cb6)) - Update SoftwareUpdateService, add command to refresh latest versions ([632f2cb6](https://github.com/pixelfed/pixelfed/commit/632f2cb6))
- Update Post.vue, fix cache bug ([3a27e637](https://github.com/pixelfed/pixelfed/commit/3a27e637))
- Update StatusHashtagService, use more efficient cached count ([592c8412](https://github.com/pixelfed/pixelfed/commit/592c8412))
- Update DiscoverController, handle discover hashtag redirects ([18382e8a](https://github.com/pixelfed/pixelfed/commit/18382e8a))
- Update ApiV1Controller, use admin filter service ([94503a1c](https://github.com/pixelfed/pixelfed/commit/94503a1c))
- Update SearchApiV2Service, use more efficient query ([cee618e8](https://github.com/pixelfed/pixelfed/commit/cee618e8))
- ([](https://github.com/pixelfed/pixelfed/commit/)) - ([](https://github.com/pixelfed/pixelfed/commit/))
## [v0.11.13 (2024-03-05)](https://github.com/pixelfed/pixelfed/compare/v0.11.12...v0.11.13) ## [v0.11.13 (2024-03-05)](https://github.com/pixelfed/pixelfed/compare/v0.11.12...v0.11.13)

View file

@ -37,6 +37,7 @@ use App\Models\Conversation;
use App\Notification; use App\Notification;
use App\Profile; use App\Profile;
use App\Services\AccountService; use App\Services\AccountService;
use App\Services\AdminShadowFilterService;
use App\Services\BookmarkService; use App\Services\BookmarkService;
use App\Services\BouncerService; use App\Services\BouncerService;
use App\Services\CollectionService; use App\Services\CollectionService;
@ -2648,7 +2649,7 @@ class ApiV1Controller extends Controller
$domainBlocks = UserFilterService::domainBlocks($user->profile_id); $domainBlocks = UserFilterService::domainBlocks($user->profile_id);
$hideNsfw = config('instance.hide_nsfw_on_public_feeds'); $hideNsfw = config('instance.hide_nsfw_on_public_feeds');
$amin = SnowflakeService::byDate(now()->subDays(config('federation.network_timeline_days_falloff'))); $amin = SnowflakeService::byDate(now()->subDays(config('federation.network_timeline_days_falloff')));
$asf = AdminShadowFilterService::getHideFromPublicFeedsList();
if ($local && $remote) { if ($local && $remote) {
$feed = Status::select( $feed = Status::select(
'id', 'id',
@ -2824,6 +2825,21 @@ class ApiV1Controller extends Controller
return ! in_array($domain, $domainBlocks); return ! in_array($domain, $domainBlocks);
}) })
->filter(function ($s) use ($asf, $user) {
if (! $asf || count($asf) === 0) {
return true;
}
if (in_array($s['account']['id'], $asf)) {
if ($user->profile_id == $s['account']['id']) {
return true;
}
return false;
}
return true;
})
->take($limit) ->take($limit)
->values(); ->values();

View file

@ -2,366 +2,379 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\{ use App\Hashtag;
DiscoverCategory, use App\Instance;
Follower, use App\Like;
Hashtag,
HashtagFollow,
Instance,
Like,
Profile,
Status,
StatusHashtag,
UserFilter
};
use Auth, DB, Cache;
use Illuminate\Http\Request;
use App\Services\BookmarkService; use App\Services\BookmarkService;
use App\Services\ConfigCacheService; use App\Services\ConfigCacheService;
use App\Services\HashtagService; use App\Services\HashtagService;
use App\Services\LikeService; use App\Services\LikeService;
use App\Services\ReblogService; use App\Services\ReblogService;
use App\Services\StatusHashtagService;
use App\Services\SnowflakeService; use App\Services\SnowflakeService;
use App\Services\StatusHashtagService;
use App\Services\StatusService; use App\Services\StatusService;
use App\Services\TrendingHashtagService; use App\Services\TrendingHashtagService;
use App\Services\UserFilterService; use App\Services\UserFilterService;
use App\Status;
use Auth;
use Cache;
use DB;
use Illuminate\Http\Request;
class DiscoverController extends Controller class DiscoverController extends Controller
{ {
public function home(Request $request) public function home(Request $request)
{ {
abort_if(!Auth::check() && config('instance.discover.public') == false, 403); abort_if(! Auth::check() && config('instance.discover.public') == false, 403);
return view('discover.home');
}
public function showTags(Request $request, $hashtag) return view('discover.home');
{ }
abort_if(!config('instance.discover.tags.is_public') && !Auth::check(), 403);
$tag = Hashtag::whereName($hashtag) public function showTags(Request $request, $hashtag)
->orWhere('slug', $hashtag) {
->where('is_banned', '!=', true) if ($request->user()) {
->firstOrFail(); return redirect('/i/web/hashtag/'.$hashtag.'?src=pd');
$tagCount = StatusHashtagService::count($tag->id); }
return view('discover.tags.show', compact('tag', 'tagCount')); abort_if(! config('instance.discover.tags.is_public') && ! Auth::check(), 403);
}
public function getHashtags(Request $request) $tag = Hashtag::whereName($hashtag)
{ ->orWhere('slug', $hashtag)
$user = $request->user(); ->where('is_banned', '!=', true)
abort_if(!config('instance.discover.tags.is_public') && !$user, 403); ->firstOrFail();
$tagCount = $tag->cached_count ?? 0;
$this->validate($request, [ return view('discover.tags.show', compact('tag', 'tagCount'));
'hashtag' => 'required|string|min:1|max:124', }
'page' => 'nullable|integer|min:1|max:' . ($user ? 29 : 3)
]);
$page = $request->input('page') ?? '1'; public function getHashtags(Request $request)
$end = $page > 1 ? $page * 9 : 0; {
$tag = $request->input('hashtag'); $user = $request->user();
abort_if(! config('instance.discover.tags.is_public') && ! $user, 403);
if(config('database.default') === 'pgsql') { $this->validate($request, [
$hashtag = Hashtag::where('name', 'ilike', $tag)->firstOrFail(); 'hashtag' => 'required|string|min:1|max:124',
} else { 'page' => 'nullable|integer|min:1|max:'.($user ? 29 : 3),
$hashtag = Hashtag::whereName($tag)->firstOrFail(); ]);
}
if($hashtag->is_banned == true) { $page = $request->input('page') ?? '1';
return []; $end = $page > 1 ? $page * 9 : 0;
} $tag = $request->input('hashtag');
if($user) {
$res['follows'] = HashtagService::isFollowing($user->profile_id, $hashtag->id);
}
$res['hashtag'] = [
'name' => $hashtag->name,
'url' => $hashtag->url()
];
if($user) {
$tags = StatusHashtagService::get($hashtag->id, $page, $end);
$res['tags'] = collect($tags)
->map(function($tag) use($user) {
$tag['status']['favourited'] = (bool) LikeService::liked($user->profile_id, $tag['status']['id']);
$tag['status']['reblogged'] = (bool) ReblogService::get($user->profile_id, $tag['status']['id']);
$tag['status']['bookmarked'] = (bool) BookmarkService::get($user->profile_id, $tag['status']['id']);
return $tag;
})
->filter(function($tag) {
if(!StatusService::get($tag['status']['id'])) {
return false;
}
return true;
})
->values();
} else {
if($page != 1) {
$res['tags'] = [];
return $res;
}
$key = 'discover:tags:public_feed:' . $hashtag->id . ':page:' . $page;
$tags = Cache::remember($key, 43200, function() use($hashtag, $page, $end) {
return collect(StatusHashtagService::get($hashtag->id, $page, $end))
->filter(function($tag) {
if(!$tag['status']['local']) {
return false;
}
return true;
})
->values();
});
$res['tags'] = collect($tags)
->filter(function($tag) {
if(!StatusService::get($tag['status']['id'])) {
return false;
}
return true;
})
->values();
}
return $res;
}
public function profilesDirectory(Request $request) if (config('database.default') === 'pgsql') {
{ $hashtag = Hashtag::where('name', 'ilike', $tag)->firstOrFail();
return redirect('/')->with('statusRedirect', 'The Profile Directory is unavailable at this time.'); } else {
} $hashtag = Hashtag::whereName($tag)->firstOrFail();
}
public function profilesDirectoryApi(Request $request) if ($hashtag->is_banned == true) {
{ return [];
return ['error' => 'Temporarily unavailable.']; }
} if ($user) {
$res['follows'] = HashtagService::isFollowing($user->profile_id, $hashtag->id);
}
$res['hashtag'] = [
'name' => $hashtag->name,
'url' => $hashtag->url(),
];
if ($user) {
$tags = StatusHashtagService::get($hashtag->id, $page, $end);
$res['tags'] = collect($tags)
->map(function ($tag) use ($user) {
$tag['status']['favourited'] = (bool) LikeService::liked($user->profile_id, $tag['status']['id']);
$tag['status']['reblogged'] = (bool) ReblogService::get($user->profile_id, $tag['status']['id']);
$tag['status']['bookmarked'] = (bool) BookmarkService::get($user->profile_id, $tag['status']['id']);
public function trendingApi(Request $request) return $tag;
{ })
abort_if(config('instance.discover.public') == false && !$request->user(), 403); ->filter(function ($tag) {
if (! StatusService::get($tag['status']['id'])) {
return false;
}
$this->validate($request, [ return true;
'range' => 'nullable|string|in:daily,monthly,yearly', })
]); ->values();
} else {
if ($page != 1) {
$res['tags'] = [];
$range = $request->input('range'); return $res;
$days = $range == 'monthly' ? 31 : ($range == 'daily' ? 1 : 365); }
$ttls = [ $key = 'discover:tags:public_feed:'.$hashtag->id.':page:'.$page;
1 => 1500, $tags = Cache::remember($key, 43200, function () use ($hashtag, $page, $end) {
31 => 14400, return collect(StatusHashtagService::get($hashtag->id, $page, $end))
365 => 86400 ->filter(function ($tag) {
]; if (! $tag['status']['local']) {
$key = ':api:discover:trending:v2.12:range:' . $days; return false;
}
$ids = Cache::remember($key, $ttls[$days], function() use($days) { return true;
$min_id = SnowflakeService::byDate(now()->subDays($days)); })
return DB::table('statuses') ->values();
->select( });
'id', $res['tags'] = collect($tags)
'scope', ->filter(function ($tag) {
'type', if (! StatusService::get($tag['status']['id'])) {
'is_nsfw', return false;
'likes_count', }
'created_at'
)
->where('id', '>', $min_id)
->whereNull('uri')
->whereScope('public')
->whereIn('type', [
'photo',
'photo:album',
'video'
])
->whereIsNsfw(false)
->orderBy('likes_count','desc')
->take(30)
->pluck('id');
});
$filtered = Auth::check() ? UserFilterService::filters(Auth::user()->profile_id) : []; return true;
})
->values();
}
$res = $ids->map(function($s) { return $res;
return StatusService::get($s); }
})->filter(function($s) use($filtered) {
return
$s &&
!in_array($s['account']['id'], $filtered) &&
isset($s['account']);
})->values();
return response()->json($res); public function profilesDirectory(Request $request)
} {
return redirect('/')->with('statusRedirect', 'The Profile Directory is unavailable at this time.');
}
public function trendingHashtags(Request $request) public function profilesDirectoryApi(Request $request)
{ {
abort_if(!$request->user(), 403); return ['error' => 'Temporarily unavailable.'];
}
$res = TrendingHashtagService::getTrending(); public function trendingApi(Request $request)
return $res; {
} abort_if(config('instance.discover.public') == false && ! $request->user(), 403);
public function trendingPlaces(Request $request) $this->validate($request, [
{ 'range' => 'nullable|string|in:daily,monthly,yearly',
return []; ]);
}
public function myMemories(Request $request) $range = $request->input('range');
{ $days = $range == 'monthly' ? 31 : ($range == 'daily' ? 1 : 365);
abort_if(!$request->user(), 404); $ttls = [
$pid = $request->user()->profile_id; 1 => 1500,
abort_if(!$this->config()['memories']['enabled'], 404); 31 => 14400,
$type = $request->input('type') ?? 'posts'; 365 => 86400,
];
$key = ':api:discover:trending:v2.12:range:'.$days;
switch($type) { $ids = Cache::remember($key, $ttls[$days], function () use ($days) {
case 'posts': $min_id = SnowflakeService::byDate(now()->subDays($days));
$res = Status::whereProfileId($pid)
->whereDay('created_at', date('d'))
->whereMonth('created_at', date('m'))
->whereYear('created_at', '!=', date('Y'))
->whereNull(['reblog_of_id', 'in_reply_to_id'])
->limit(20)
->pluck('id')
->map(function($id) {
return StatusService::get($id, false);
})
->filter(function($post) {
return $post && isset($post['account']);
})
->values();
break;
case 'liked': return DB::table('statuses')
$res = Like::whereProfileId($pid) ->select(
->whereDay('created_at', date('d')) 'id',
->whereMonth('created_at', date('m')) 'scope',
->whereYear('created_at', '!=', date('Y')) 'type',
->orderByDesc('status_id') 'is_nsfw',
->limit(20) 'likes_count',
->pluck('status_id') 'created_at'
->map(function($id) { )
$status = StatusService::get($id, false); ->where('id', '>', $min_id)
$status['favourited'] = true; ->whereNull('uri')
return $status; ->whereScope('public')
}) ->whereIn('type', [
->filter(function($post) { 'photo',
return $post && isset($post['account']); 'photo:album',
}) 'video',
->values(); ])
break; ->whereIsNsfw(false)
} ->orderBy('likes_count', 'desc')
->take(30)
->pluck('id');
});
return $res; $filtered = Auth::check() ? UserFilterService::filters(Auth::user()->profile_id) : [];
}
public function accountInsightsPopularPosts(Request $request) $res = $ids->map(function ($s) {
{ return StatusService::get($s);
abort_if(!$request->user(), 404); })->filter(function ($s) use ($filtered) {
$pid = $request->user()->profile_id; return
abort_if(!$this->config()['insights']['enabled'], 404); $s &&
$posts = Cache::remember('pf:discover:metro2:accinsights:popular:' . $pid, 43200, function() use ($pid) { ! in_array($s['account']['id'], $filtered) &&
return Status::whereProfileId($pid) isset($s['account']);
->whereNotNull('likes_count') })->values();
->orderByDesc('likes_count')
->limit(12)
->pluck('id')
->map(function($id) {
return StatusService::get($id, false);
})
->filter(function($post) {
return $post && isset($post['account']);
})
->values();
});
return $posts; return response()->json($res);
} }
public function config() public function trendingHashtags(Request $request)
{ {
$cc = ConfigCacheService::get('config.discover.features'); abort_if(! $request->user(), 403);
if($cc) {
return is_string($cc) ? json_decode($cc, true) : $cc;
}
return [
'hashtags' => [
'enabled' => false,
],
'memories' => [
'enabled' => false,
],
'insights' => [
'enabled' => false,
],
'friends' => [
'enabled' => false,
],
'server' => [
'enabled' => false,
'mode' => 'allowlist',
'domains' => []
]
];
}
public function serverTimeline(Request $request) $res = TrendingHashtagService::getTrending();
{
abort_if(!$request->user(), 404);
abort_if(!$this->config()['server']['enabled'], 404);
$pid = $request->user()->profile_id;
$domain = $request->input('domain');
$config = $this->config();
$domains = explode(',', $config['server']['domains']);
abort_unless(in_array($domain, $domains), 400);
$res = Status::whereNotNull('uri') return $res;
->where('uri', 'like', 'https://' . $domain . '%') }
->whereNull(['in_reply_to_id', 'reblog_of_id'])
->orderByDesc('id')
->limit(12)
->pluck('id')
->map(function($id) {
return StatusService::get($id);
})
->filter(function($post) {
return $post && isset($post['account']);
})
->values();
return $res;
}
public function enabledFeatures(Request $request) public function trendingPlaces(Request $request)
{ {
abort_if(!$request->user(), 404); return [];
return $this->config(); }
}
public function updateFeatures(Request $request) public function myMemories(Request $request)
{ {
abort_if(!$request->user(), 404); abort_if(! $request->user(), 404);
abort_if(!$request->user()->is_admin, 404); $pid = $request->user()->profile_id;
$pid = $request->user()->profile_id; abort_if(! $this->config()['memories']['enabled'], 404);
$this->validate($request, [ $type = $request->input('type') ?? 'posts';
'features.friends.enabled' => 'boolean',
'features.hashtags.enabled' => 'boolean', switch ($type) {
'features.insights.enabled' => 'boolean', case 'posts':
'features.memories.enabled' => 'boolean', $res = Status::whereProfileId($pid)
'features.server.enabled' => 'boolean', ->whereDay('created_at', date('d'))
]); ->whereMonth('created_at', date('m'))
$res = $request->input('features'); ->whereYear('created_at', '!=', date('Y'))
if($res['server'] && isset($res['server']['domains']) && !empty($res['server']['domains'])) { ->whereNull(['reblog_of_id', 'in_reply_to_id'])
$parts = explode(',', $res['server']['domains']); ->limit(20)
$parts = array_filter($parts, function($v) { ->pluck('id')
$len = strlen($v); ->map(function ($id) {
$pos = strpos($v, '.'); return StatusService::get($id, false);
$domain = trim($v); })
if($pos == false || $pos == ($len + 1)) { ->filter(function ($post) {
return false; return $post && isset($post['account']);
} })
if(!Instance::whereDomain($domain)->exists()) { ->values();
return false; break;
}
return true; case 'liked':
}); $res = Like::whereProfileId($pid)
$parts = array_slice($parts, 0, 10); ->whereDay('created_at', date('d'))
$d = implode(',', array_map('trim', $parts)); ->whereMonth('created_at', date('m'))
$res['server']['domains'] = $d; ->whereYear('created_at', '!=', date('Y'))
} ->orderByDesc('status_id')
ConfigCacheService::put('config.discover.features', json_encode($res)); ->limit(20)
return $res; ->pluck('status_id')
} ->map(function ($id) {
$status = StatusService::get($id, false);
$status['favourited'] = true;
return $status;
})
->filter(function ($post) {
return $post && isset($post['account']);
})
->values();
break;
}
return $res;
}
public function accountInsightsPopularPosts(Request $request)
{
abort_if(! $request->user(), 404);
$pid = $request->user()->profile_id;
abort_if(! $this->config()['insights']['enabled'], 404);
$posts = Cache::remember('pf:discover:metro2:accinsights:popular:'.$pid, 43200, function () use ($pid) {
return Status::whereProfileId($pid)
->whereNotNull('likes_count')
->orderByDesc('likes_count')
->limit(12)
->pluck('id')
->map(function ($id) {
return StatusService::get($id, false);
})
->filter(function ($post) {
return $post && isset($post['account']);
})
->values();
});
return $posts;
}
public function config()
{
$cc = ConfigCacheService::get('config.discover.features');
if ($cc) {
return is_string($cc) ? json_decode($cc, true) : $cc;
}
return [
'hashtags' => [
'enabled' => false,
],
'memories' => [
'enabled' => false,
],
'insights' => [
'enabled' => false,
],
'friends' => [
'enabled' => false,
],
'server' => [
'enabled' => false,
'mode' => 'allowlist',
'domains' => [],
],
];
}
public function serverTimeline(Request $request)
{
abort_if(! $request->user(), 404);
abort_if(! $this->config()['server']['enabled'], 404);
$pid = $request->user()->profile_id;
$domain = $request->input('domain');
$config = $this->config();
$domains = explode(',', $config['server']['domains']);
abort_unless(in_array($domain, $domains), 400);
$res = Status::whereNotNull('uri')
->where('uri', 'like', 'https://'.$domain.'%')
->whereNull(['in_reply_to_id', 'reblog_of_id'])
->orderByDesc('id')
->limit(12)
->pluck('id')
->map(function ($id) {
return StatusService::get($id);
})
->filter(function ($post) {
return $post && isset($post['account']);
})
->values();
return $res;
}
public function enabledFeatures(Request $request)
{
abort_if(! $request->user(), 404);
return $this->config();
}
public function updateFeatures(Request $request)
{
abort_if(! $request->user(), 404);
abort_if(! $request->user()->is_admin, 404);
$pid = $request->user()->profile_id;
$this->validate($request, [
'features.friends.enabled' => 'boolean',
'features.hashtags.enabled' => 'boolean',
'features.insights.enabled' => 'boolean',
'features.memories.enabled' => 'boolean',
'features.server.enabled' => 'boolean',
]);
$res = $request->input('features');
if ($res['server'] && isset($res['server']['domains']) && ! empty($res['server']['domains'])) {
$parts = explode(',', $res['server']['domains']);
$parts = array_filter($parts, function ($v) {
$len = strlen($v);
$pos = strpos($v, '.');
$domain = trim($v);
if ($pos == false || $pos == ($len + 1)) {
return false;
}
if (! Instance::whereDomain($domain)->exists()) {
return false;
}
return true;
});
$parts = array_slice($parts, 0, 10);
$d = implode(',', array_map('trim', $parts));
$res['server']['domains'] = $d;
}
ConfigCacheService::put('config.discover.features', json_encode($res));
return $res;
}
} }

View file

@ -2,28 +2,26 @@
namespace App\Services; namespace App\Services;
use Cache; use App\Hashtag;
use Illuminate\Support\Facades\Redis; use App\Profile;
use App\{Hashtag, Profile, Status}; use App\Status;
use App\Transformer\Api\AccountTransformer; use App\Transformer\Api\AccountTransformer;
use App\Transformer\Api\StatusTransformer;
use League\Fractal;
use League\Fractal\Serializer\ArraySerializer;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
use App\Util\ActivityPub\Helpers; use App\Util\ActivityPub\Helpers;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use App\Services\AccountService; use League\Fractal;
use App\Services\HashtagService; use League\Fractal\Serializer\ArraySerializer;
use App\Services\StatusService;
class SearchApiV2Service class SearchApiV2Service
{ {
private $query; private $query;
static $mastodonMode = false;
public static $mastodonMode = false;
public static function query($query, $mastodonMode = false) public static function query($query, $mastodonMode = false)
{ {
self::$mastodonMode = $mastodonMode; self::$mastodonMode = $mastodonMode;
return (new self)->run($query); return (new self)->run($query);
} }
@ -32,51 +30,51 @@ class SearchApiV2Service
$this->query = $query; $this->query = $query;
$q = urldecode($query->input('q')); $q = urldecode($query->input('q'));
if($query->has('resolve') && if ($query->has('resolve') &&
( Str::startsWith($q, 'https://') || (Str::startsWith($q, 'https://') ||
Str::substrCount($q, '@') >= 1) Str::substrCount($q, '@') >= 1)
) { ) {
return $this->resolveQuery(); return $this->resolveQuery();
} }
if($query->has('type')) { if ($query->has('type')) {
switch ($query->input('type')) { switch ($query->input('type')) {
case 'accounts': case 'accounts':
return [ return [
'accounts' => $this->accounts(), 'accounts' => $this->accounts(),
'hashtags' => [], 'hashtags' => [],
'statuses' => [] 'statuses' => [],
]; ];
break; break;
case 'hashtags': case 'hashtags':
return [ return [
'accounts' => [], 'accounts' => [],
'hashtags' => $this->hashtags(), 'hashtags' => $this->hashtags(),
'statuses' => [] 'statuses' => [],
]; ];
break; break;
case 'statuses': case 'statuses':
return [ return [
'accounts' => [], 'accounts' => [],
'hashtags' => [], 'hashtags' => [],
'statuses' => $this->statuses() 'statuses' => $this->statuses(),
]; ];
break; break;
} }
} }
if($query->has('account_id')) { if ($query->has('account_id')) {
return [ return [
'accounts' => [], 'accounts' => [],
'hashtags' => [], 'hashtags' => [],
'statuses' => $this->statusesById() 'statuses' => $this->statusesById(),
]; ];
} }
return [ return [
'accounts' => $this->accounts(), 'accounts' => $this->accounts(),
'hashtags' => $this->hashtags(), 'hashtags' => $this->hashtags(),
'statuses' => $this->statuses() 'statuses' => $this->statuses(),
]; ];
} }
@ -87,17 +85,17 @@ class SearchApiV2Service
$limit = $this->query->input('limit') ?? 20; $limit = $this->query->input('limit') ?? 20;
$offset = $this->query->input('offset') ?? 0; $offset = $this->query->input('offset') ?? 0;
$rawQuery = $initalQuery ? $initalQuery : $this->query->input('q'); $rawQuery = $initalQuery ? $initalQuery : $this->query->input('q');
$query = $rawQuery . '%'; $query = $rawQuery.'%';
$webfingerQuery = $query; $webfingerQuery = $query;
if(Str::substrCount($rawQuery, '@') == 1 && substr($rawQuery, 0, 1) !== '@') { if (Str::substrCount($rawQuery, '@') == 1 && substr($rawQuery, 0, 1) !== '@') {
$query = '@' . $query; $query = '@'.$query;
} }
if(substr($webfingerQuery, 0, 1) !== '@') { if (substr($webfingerQuery, 0, 1) !== '@') {
$webfingerQuery = '@' . $webfingerQuery; $webfingerQuery = '@'.$webfingerQuery;
} }
$banned = InstanceService::getBannedDomains() ?? []; $banned = InstanceService::getBannedDomains() ?? [];
$domainBlocks = UserFilterService::domainBlocks($user->profile_id); $domainBlocks = UserFilterService::domainBlocks($user->profile_id);
if($domainBlocks && count($domainBlocks)) { if ($domainBlocks && count($domainBlocks)) {
$banned = array_unique( $banned = array_unique(
array_values( array_values(
array_merge($banned, $domainBlocks) array_merge($banned, $domainBlocks)
@ -112,15 +110,15 @@ class SearchApiV2Service
->offset($offset) ->offset($offset)
->limit($limit) ->limit($limit)
->get() ->get()
->filter(function($profile) use ($banned) { ->filter(function ($profile) use ($banned) {
return in_array($profile->domain, $banned) == false; return in_array($profile->domain, $banned) == false;
}) })
->map(function($res) use($mastodonMode) { ->map(function ($res) use ($mastodonMode) {
return $mastodonMode ? return $mastodonMode ?
AccountService::getMastodon($res['id']) : AccountService::getMastodon($res['id']) :
AccountService::get($res['id']); AccountService::get($res['id']);
}) })
->filter(function($account) { ->filter(function ($account) {
return $account && isset($account['id']); return $account && isset($account['id']);
}) })
->values(); ->values();
@ -134,31 +132,31 @@ class SearchApiV2Service
$q = $this->query->input('q'); $q = $this->query->input('q');
$limit = $this->query->input('limit') ?? 20; $limit = $this->query->input('limit') ?? 20;
$offset = $this->query->input('offset') ?? 0; $offset = $this->query->input('offset') ?? 0;
$query = Str::startsWith($q, '#') ? '%' . substr($q, 1) . '%' : '%' . $q . '%'; $query = Str::startsWith($q, '#') ? substr($q, 1).'%' : $q;
$operator = config('database.default') === 'pgsql' ? 'ilike' : 'like'; $operator = config('database.default') === 'pgsql' ? 'ilike' : 'like';
return Hashtag::where('name', $operator, $query) return Hashtag::where('name', $operator, $query)
->orWhere('slug', $operator, $query)
->where(function($q) {
return $q->where('can_search', true)
->orWhereNull('can_search');
})
->orderByDesc('cached_count') ->orderByDesc('cached_count')
->offset($offset) ->offset($offset)
->limit($limit) ->limit($limit)
->get() ->get()
->map(function($tag) use($mastodonMode) { ->filter(function ($tag) {
return $tag->can_search != false;
})
->map(function ($tag) use ($mastodonMode) {
$res = [ $res = [
'name' => $tag->name, 'name' => $tag->name,
'url' => $tag->url() 'url' => $tag->url(),
]; ];
if(!$mastodonMode) { if (! $mastodonMode) {
$res['history'] = []; $res['history'] = [];
$res['count'] = HashtagService::count($tag->id); $res['count'] = $tag->cached_count ?? 0;
} }
return $res; return $res;
}); })
->values();
} }
protected function statuses() protected function statuses()
@ -175,7 +173,7 @@ class SearchApiV2Service
protected function resolveQuery() protected function resolveQuery()
{ {
$default = [ $default = [
'accounts' => [], 'accounts' => [],
'hashtags' => [], 'hashtags' => [],
'statuses' => [], 'statuses' => [],
@ -185,73 +183,77 @@ class SearchApiV2Service
$query = urldecode($this->query->input('q')); $query = urldecode($this->query->input('q'));
$banned = InstanceService::getBannedDomains(); $banned = InstanceService::getBannedDomains();
$domainBlocks = UserFilterService::domainBlocks($user->profile_id); $domainBlocks = UserFilterService::domainBlocks($user->profile_id);
if($domainBlocks && count($domainBlocks)) { if ($domainBlocks && count($domainBlocks)) {
$banned = array_unique( $banned = array_unique(
array_values( array_values(
array_merge($banned, $domainBlocks) array_merge($banned, $domainBlocks)
) )
); );
} }
if(substr($query, 0, 1) === '@' && !Str::contains($query, '.')) { if (substr($query, 0, 1) === '@' && ! Str::contains($query, '.')) {
$default['accounts'] = $this->accounts(substr($query, 1)); $default['accounts'] = $this->accounts(substr($query, 1));
return $default; return $default;
} }
if(Helpers::validateLocalUrl($query)) { if (Helpers::validateLocalUrl($query)) {
if(Str::contains($query, '/p/') || Str::contains($query, 'i/web/post/')) { if (Str::contains($query, '/p/') || Str::contains($query, 'i/web/post/')) {
return $this->resolveLocalStatus(); return $this->resolveLocalStatus();
} else if(Str::contains($query, 'i/web/profile/')) { } elseif (Str::contains($query, 'i/web/profile/')) {
return $this->resolveLocalProfileId(); return $this->resolveLocalProfileId();
} else { } else {
return $this->resolveLocalProfile(); return $this->resolveLocalProfile();
} }
} else { } else {
if(!Helpers::validateUrl($query) && strpos($query, '@') == -1) { if (! Helpers::validateUrl($query) && strpos($query, '@') == -1) {
return $default; return $default;
} }
if(!Str::startsWith($query, 'http') && Str::substrCount($query, '@') == 1 && strpos($query, '@') !== 0) { if (! Str::startsWith($query, 'http') && Str::substrCount($query, '@') == 1 && strpos($query, '@') !== 0) {
try { try {
$res = WebfingerService::lookup('@' . $query, $mastodonMode); $res = WebfingerService::lookup('@'.$query, $mastodonMode);
} catch (\Exception $e) { } catch (\Exception $e) {
return $default; return $default;
} }
if($res && isset($res['id'], $res['url'])) { if ($res && isset($res['id'], $res['url'])) {
$domain = strtolower(parse_url($res['url'], PHP_URL_HOST)); $domain = strtolower(parse_url($res['url'], PHP_URL_HOST));
if(in_array($domain, $banned)) { if (in_array($domain, $banned)) {
return $default; return $default;
} }
$default['accounts'][] = $res; $default['accounts'][] = $res;
return $default; return $default;
} else { } else {
return $default; return $default;
} }
} }
if(Str::substrCount($query, '@') == 2) { if (Str::substrCount($query, '@') == 2) {
try { try {
$res = WebfingerService::lookup($query, $mastodonMode); $res = WebfingerService::lookup($query, $mastodonMode);
} catch (\Exception $e) { } catch (\Exception $e) {
return $default; return $default;
} }
if($res && isset($res['id'])) { if ($res && isset($res['id'])) {
$domain = strtolower(parse_url($res['url'], PHP_URL_HOST)); $domain = strtolower(parse_url($res['url'], PHP_URL_HOST));
if(in_array($domain, $banned)) { if (in_array($domain, $banned)) {
return $default; return $default;
} }
$default['accounts'][] = $res; $default['accounts'][] = $res;
return $default; return $default;
} else { } else {
return $default; return $default;
} }
} }
if($sid = Status::whereUri($query)->first()) { if ($sid = Status::whereUri($query)->first()) {
$s = StatusService::get($sid->id, false); $s = StatusService::get($sid->id, false);
if(!$s) { if (! $s) {
return $default; return $default;
} }
if(in_array($s['visibility'], ['public', 'unlisted'])) { if (in_array($s['visibility'], ['public', 'unlisted'])) {
$default['statuses'][] = $s; $default['statuses'][] = $s;
return $default; return $default;
} }
} }
@ -259,10 +261,10 @@ class SearchApiV2Service
try { try {
$res = ActivityPubFetchService::get($query); $res = ActivityPubFetchService::get($query);
if($res) { if ($res) {
$json = json_decode($res, true); $json = json_decode($res, true);
if(!$json || !isset($json['@context']) || !isset($json['type']) || !in_array($json['type'], ['Note', 'Person'])) { if (! $json || ! isset($json['@context']) || ! isset($json['type']) || ! in_array($json['type'], ['Note', 'Person'])) {
return [ return [
'accounts' => [], 'accounts' => [],
'hashtags' => [], 'hashtags' => [],
@ -270,38 +272,40 @@ class SearchApiV2Service
]; ];
} }
switch($json['type']) { switch ($json['type']) {
case 'Note': case 'Note':
$obj = Helpers::statusFetch($query); $obj = Helpers::statusFetch($query);
if(!$obj || !isset($obj['id'])) { if (! $obj || ! isset($obj['id'])) {
return $default; return $default;
} }
$note = $mastodonMode ? $note = $mastodonMode ?
StatusService::getMastodon($obj['id'], false) : StatusService::getMastodon($obj['id'], false) :
StatusService::get($obj['id'], false); StatusService::get($obj['id'], false);
if(!$note) { if (! $note) {
return $default; return $default;
} }
if(!isset($note['visibility']) || !in_array($note['visibility'], ['public', 'unlisted'])) { if (! isset($note['visibility']) || ! in_array($note['visibility'], ['public', 'unlisted'])) {
return $default; return $default;
} }
$default['statuses'][] = $note; $default['statuses'][] = $note;
return $default; return $default;
break; break;
case 'Person': case 'Person':
$obj = Helpers::profileFetch($query); $obj = Helpers::profileFetch($query);
if(!$obj) { if (! $obj) {
return $default; return $default;
} }
if(in_array($obj['domain'], $banned)) { if (in_array($obj['domain'], $banned)) {
return $default; return $default;
} }
$default['accounts'][] = $mastodonMode ? $default['accounts'][] = $mastodonMode ?
AccountService::getMastodon($obj['id'], true) : AccountService::getMastodon($obj['id'], true) :
AccountService::get($obj['id'], true); AccountService::get($obj['id'], true);
return $default; return $default;
break; break;
default: default:
return [ return [
@ -309,7 +313,7 @@ class SearchApiV2Service
'hashtags' => [], 'hashtags' => [],
'statuses' => [], 'statuses' => [],
]; ];
break; break;
} }
} }
} catch (\Exception $e) { } catch (\Exception $e) {
@ -329,18 +333,18 @@ class SearchApiV2Service
$query = urldecode($this->query->input('q')); $query = urldecode($this->query->input('q'));
$query = last(explode('/', parse_url($query, PHP_URL_PATH))); $query = last(explode('/', parse_url($query, PHP_URL_PATH)));
$status = StatusService::getMastodon($query, false); $status = StatusService::getMastodon($query, false);
if(!$status || !in_array($status['visibility'], ['public', 'unlisted'])) { if (! $status || ! in_array($status['visibility'], ['public', 'unlisted'])) {
return [ return [
'accounts' => [], 'accounts' => [],
'hashtags' => [], 'hashtags' => [],
'statuses' => [] 'statuses' => [],
]; ];
} }
$res = [ $res = [
'accounts' => [], 'accounts' => [],
'hashtags' => [], 'hashtags' => [],
'statuses' => [$status] 'statuses' => [$status],
]; ];
return $res; return $res;
@ -355,21 +359,22 @@ class SearchApiV2Service
->whereUsername($query) ->whereUsername($query)
->first(); ->first();
if(!$profile) { if (! $profile) {
return [ return [
'accounts' => [], 'accounts' => [],
'hashtags' => [], 'hashtags' => [],
'statuses' => [] 'statuses' => [],
]; ];
} }
$fractal = new Fractal\Manager(); $fractal = new Fractal\Manager();
$fractal->setSerializer(new ArraySerializer()); $fractal->setSerializer(new ArraySerializer());
$resource = new Fractal\Resource\Item($profile, new AccountTransformer()); $resource = new Fractal\Resource\Item($profile, new AccountTransformer());
return [ return [
'accounts' => [$fractal->createData($resource)->toArray()], 'accounts' => [$fractal->createData($resource)->toArray()],
'hashtags' => [], 'hashtags' => [],
'statuses' => [] 'statuses' => [],
]; ];
} }
@ -380,22 +385,22 @@ class SearchApiV2Service
$profile = Profile::whereNull('status') $profile = Profile::whereNull('status')
->find($query); ->find($query);
if(!$profile) { if (! $profile) {
return [ return [
'accounts' => [], 'accounts' => [],
'hashtags' => [], 'hashtags' => [],
'statuses' => [] 'statuses' => [],
]; ];
} }
$fractal = new Fractal\Manager(); $fractal = new Fractal\Manager();
$fractal->setSerializer(new ArraySerializer()); $fractal->setSerializer(new ArraySerializer());
$resource = new Fractal\Resource\Item($profile, new AccountTransformer()); $resource = new Fractal\Resource\Item($profile, new AccountTransformer());
return [ return [
'accounts' => [$fractal->createData($resource)->toArray()], 'accounts' => [$fractal->createData($resource)->toArray()],
'hashtags' => [], 'hashtags' => [],
'statuses' => [] 'statuses' => [],
]; ];
} }
} }

View file

@ -2,96 +2,97 @@
namespace App\Services; namespace App\Services;
use Cache; use App\Hashtag;
use Illuminate\Support\Facades\Redis; use App\Status;
use App\{Status, StatusHashtag}; use App\StatusHashtag;
use App\Transformer\Api\StatusHashtagTransformer;
use App\Transformer\Api\HashtagTransformer; use App\Transformer\Api\HashtagTransformer;
use League\Fractal; use League\Fractal;
use League\Fractal\Serializer\ArraySerializer; use League\Fractal\Serializer\ArraySerializer;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
class StatusHashtagService { class StatusHashtagService
{
const CACHE_KEY = 'pf:services:status-hashtag:collection:';
const CACHE_KEY = 'pf:services:status-hashtag:collection:'; public static function get($id, $page = 1, $stop = 9)
{
if ($page > 20) {
return [];
}
public static function get($id, $page = 1, $stop = 9) $pid = request()->user() ? request()->user()->profile_id : false;
{ $filtered = $pid ? UserFilterService::filters($pid) : [];
if($page > 20) {
return [];
}
$pid = request()->user() ? request()->user()->profile_id : false; return StatusHashtag::whereHashtagId($id)
$filtered = $pid ? UserFilterService::filters($pid) : []; ->whereStatusVisibility('public')
->skip($stop)
->latest()
->take(9)
->pluck('status_id')
->map(function ($i, $k) use ($id) {
return self::getStatus($i, $id);
})
->filter(function ($i) use ($filtered) {
return isset($i['status']) &&
! empty($i['status']) && ! in_array($i['status']['account']['id'], $filtered) &&
isset($i['status']['media_attachments']) &&
! empty($i['status']['media_attachments']);
})
->values();
}
return StatusHashtag::whereHashtagId($id) public static function coldGet($id, $start = 0, $stop = 2000)
->whereStatusVisibility('public') {
->skip($stop) $stop = $stop > 2000 ? 2000 : $stop;
->latest() $ids = StatusHashtag::whereHashtagId($id)
->take(9) ->whereStatusVisibility('public')
->pluck('status_id') ->whereHas('media')
->map(function ($i, $k) use ($id) { ->latest()
return self::getStatus($i, $id); ->skip($start)
}) ->take($stop)
->filter(function ($i) use($filtered) { ->pluck('status_id');
return isset($i['status']) && foreach ($ids as $key) {
!empty($i['status']) && !in_array($i['status']['account']['id'], $filtered) && self::set($id, $key);
isset($i['status']['media_attachments']) && }
!empty($i['status']['media_attachments']);
})
->values();
}
public static function coldGet($id, $start = 0, $stop = 2000) return $ids;
{ }
$stop = $stop > 2000 ? 2000 : $stop;
$ids = StatusHashtag::whereHashtagId($id)
->whereStatusVisibility('public')
->whereHas('media')
->latest()
->skip($start)
->take($stop)
->pluck('status_id');
foreach($ids as $key) {
self::set($id, $key);
}
return $ids;
}
public static function set($key, $val) public static function set($key, $val)
{ {
return 1; return 1;
} }
public static function del($key) public static function del($key)
{ {
return 1; return 1;
} }
public static function count($id) public static function count($id)
{ {
$key = 'pf:services:status-hashtag:count:' . $id; $cc = Hashtag::find($id);
$ttl = now()->addMinutes(5); if (! $cc) {
return Cache::remember($key, $ttl, function() use($id) { return 0;
return StatusHashtag::whereHashtagId($id)->has('media')->count(); }
});
}
public static function getStatus($statusId, $hashtagId) return $cc->cached_count ?? 0;
{ }
return ['status' => StatusService::get($statusId)];
}
public static function statusTags($statusId) public static function getStatus($statusId, $hashtagId)
{ {
$status = Status::with('hashtags')->find($statusId); return ['status' => StatusService::get($statusId)];
if(!$status) { }
return [];
}
$fractal = new Fractal\Manager(); public static function statusTags($statusId)
$fractal->setSerializer(new ArraySerializer()); {
$resource = new Fractal\Resource\Collection($status->hashtags, new HashtagTransformer()); $status = Status::with('hashtags')->find($statusId);
return $fractal->createData($resource)->toArray(); if (! $status) {
} return [];
}
$fractal = new Fractal\Manager();
$fractal->setSerializer(new ArraySerializer());
$resource = new Fractal\Resource\Collection($status->hashtags, new HashtagTransformer());
return $fractal->createData($resource)->toArray();
}
} }

BIN
public/js/manifest.js vendored

Binary file not shown.

Binary file not shown.

BIN
public/js/post.chunk.9184101a2b809af1.js vendored Normal file

Binary file not shown.

Binary file not shown.

View file

@ -171,7 +171,7 @@
} }
}, },
beforeMount() { created() {
this.init(); this.init();
}, },
@ -181,20 +181,7 @@
methods: { methods: {
init() { init() {
if(this.cachedStatus && this.cachedProfile) { this.fetchSelf();
this.post = this.cachedStatus;
this.media = this.post.media_attachments;
this.profile = this.post.account;
this.user = this.cachedProfile;
if(this.post.in_reply_to_id) {
this.fetchReply();
} else {
this.isReply = false;
this.fetchRelationship();
}
} else {
this.fetchSelf();
}
}, },
fetchSelf() { fetchSelf() {