Files
SkinbaseNova/app/Http/Controllers/Web/DiscoverController.php
2026-03-28 19:15:39 +01:00

517 lines
22 KiB
PHP

<?php
namespace App\Http\Controllers\Web;
use App\Http\Controllers\Controller;
use App\Models\Artwork;
use App\Services\CommunityActivityService;
use App\Services\ArtworkSearchService;
use App\Services\ArtworkService;
use App\Services\EarlyGrowth\FeedBlender;
use App\Services\EarlyGrowth\GridFiller;
use App\Services\Recommendations\RecommendationFeedResolver;
use App\Services\UserSuggestionService;
use App\Services\ThumbnailPresenter;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
/**
* DiscoverController
*
* Powers the /discover/* discovery pages:
* - /discover/trending → most viewed in last 7 days
* - /discover/fresh → latest uploads (replaces /uploads/latest)
* - /discover/top-rated → highest favourite count
* - /discover/most-downloaded → most downloaded all-time
* - /discover/on-this-day → published on this calendar day in previous years
* - /discover/for-you → personalised feed (auth required)
*/
final class DiscoverController extends Controller
{
public function __construct(
private readonly ArtworkService $artworkService,
private readonly ArtworkSearchService $searchService,
private readonly RecommendationFeedResolver $feedResolver,
private readonly FeedBlender $feedBlender,
private readonly GridFiller $gridFiller,
private readonly CommunityActivityService $communityActivity,
private readonly UserSuggestionService $userSuggestions,
) {}
// ─── /discover/trending ──────────────────────────────────────────────────
public function trending(Request $request)
{
$perPage = 24;
$page = max(1, (int) $request->query('page', 1));
$results = $this->searchService->discoverTrending($perPage);
$results = $this->gridFiller->fill($results, 0, $page);
$this->hydrateDiscoverSearchResults($results);
return view('web.discover.index', [
'artworks' => $results,
'page_title' => 'Trending Artworks',
'section' => 'trending',
'description' => 'The most-viewed artworks on Skinbase over the past 7 days.',
'icon' => 'fa-fire',
]);
}
// ─── /discover/rising ────────────────────────────────────────────────────
public function rising(Request $request)
{
$perPage = 24;
$page = max(1, (int) $request->query('page', 1));
$results = $this->searchService->discoverRising($perPage);
$results = $this->gridFiller->fill($results, 0, $page);
$this->hydrateDiscoverSearchResults($results);
return view('web.discover.index', [
'artworks' => $results,
'page_title' => 'Rising Now',
'section' => 'rising',
'description' => 'Fastest growing artworks right now.',
'icon' => 'fa-rocket',
]);
}
// ─── /discover/fresh ─────────────────────────────────────────────────────
public function fresh(Request $request)
{
$perPage = 24;
$page = max(1, (int) $request->query('page', 1));
$results = $this->searchService->discoverFresh($perPage);
// EGS: blend fresh feed with curated + spotlight on page 1
$results = $this->feedBlender->blend($results, $perPage, $page);
$results = $this->gridFiller->fill($results, 0, $page);
$this->hydrateDiscoverSearchResults($results);
return view('web.discover.index', [
'artworks' => $results,
'page_title' => 'Fresh Uploads',
'section' => 'fresh',
'description' => 'The latest artworks just uploaded to Skinbase.',
'icon' => 'fa-bolt',
]);
}
// ─── /discover/top-rated ─────────────────────────────────────────────────
public function topRated(Request $request)
{
$perPage = 24;
$page = max(1, (int) $request->query('page', 1));
$results = $this->searchService->discoverTopRated($perPage);
$results = $this->gridFiller->fill($results, 0, $page);
$this->hydrateDiscoverSearchResults($results);
return view('web.discover.index', [
'artworks' => $results,
'page_title' => 'Top Rated Artworks',
'section' => 'top-rated',
'description' => 'The most-loved artworks on Skinbase, ranked by community favourites.',
'icon' => 'fa-medal',
]);
}
// ─── /discover/most-downloaded ───────────────────────────────────────────
public function mostDownloaded(Request $request)
{
$perPage = 24;
$page = max(1, (int) $request->query('page', 1));
$results = $this->searchService->discoverMostDownloaded($perPage);
$results = $this->gridFiller->fill($results, 0, $page);
$this->hydrateDiscoverSearchResults($results);
return view('web.discover.index', [
'artworks' => $results,
'page_title' => 'Most Downloaded',
'section' => 'most-downloaded',
'description' => 'All-time most downloaded artworks on Skinbase.',
'icon' => 'fa-download',
]);
}
// ─── /discover/on-this-day ───────────────────────────────────────────────
public function onThisDay(Request $request)
{
$perPage = 24;
$today = now();
$artworks = Artwork::query()
->public()
->published()
->with([
'user:id,name',
'user.profile:user_id,avatar_hash',
'categories:id,name,slug,content_type_id,parent_id,sort_order',
])
->whereRaw('MONTH(published_at) = ?', [$today->month])
->whereRaw('DAY(published_at) = ?', [$today->day])
->whereRaw('YEAR(published_at) < ?', [$today->year])
->orderByDesc('published_at')
->paginate($perPage)
->withQueryString();
$artworks->getCollection()->transform(fn ($a) => $this->presentArtwork($a));
return view('web.discover.index', [
'artworks' => $artworks,
'page_title' => 'On This Day',
'section' => 'on-this-day',
'description' => 'Artworks published on ' . $today->format('F j') . ' in previous years.',
'icon' => 'fa-calendar-day',
]);
}
// ─── /creators/rising ────────────────────────────────────────────────────
public function risingCreators(Request $request)
{
$perPage = 20;
// Creators with artworks published in the last 90 days, ordered by total recent views.
$hasStats = false;
try { $hasStats = Schema::hasTable('artwork_stats'); } catch (\Throwable) {}
if ($hasStats) {
$sub = Artwork::query()
->public()
->published()
->join('artwork_stats', 'artwork_stats.artwork_id', '=', 'artworks.id')
->where('artworks.published_at', '>=', now()->subDays(90))
->selectRaw('artworks.user_id, SUM(artwork_stats.views) as recent_views, MAX(artworks.published_at) as latest_published')
->groupBy('artworks.user_id');
} else {
$sub = Artwork::query()
->public()
->published()
->where('published_at', '>=', now()->subDays(90))
->selectRaw('user_id, COUNT(*) as recent_views, MAX(published_at) as latest_published')
->groupBy('user_id');
}
$creators = DB::table(DB::raw('(' . $sub->toSql() . ') as t'))
->mergeBindings($sub->getQuery())
->join('users as u', 'u.id', '=', 't.user_id')
->leftJoin('user_profiles as up', 'up.user_id', '=', 't.user_id')
->select('u.id as user_id', 'u.name as uname', 'u.username', 't.recent_views', 't.latest_published', 'up.avatar_hash')
->orderByDesc('t.recent_views')
->orderByDesc('t.latest_published')
->paginate($perPage)
->withQueryString();
$creators->getCollection()->transform(function ($row) {
return (object) [
'user_id' => $row->user_id,
'uname' => $row->uname,
'username' => $row->username,
'total' => (int) $row->recent_views,
'metric' => 'views',
'avatar_hash' => $row->avatar_hash ?? null,
];
});
return view('web.creators.rising', [
'creators' => $creators,
'page_title' => 'Rising Creators — Skinbase',
]);
}
// ─── /discover/for-you ───────────────────────────────────────────────────
/**
* Personalised "For You" feed page.
*
* Uses the newer personalized feed service so the web surface stays aligned
* with the API recommendation stack and discovery-event training loop.
*/
public function forYou(Request $request)
{
$user = $request->user();
$limit = max(1, min(50, (int) $request->query('limit', 40)));
$cursor = $request->query('cursor') ?: null;
$feedResult = $this->feedResolver->getFeed(
userId: (int) $user->id,
limit: $limit,
cursor: is_string($cursor) ? $cursor : null,
algoVersion: $request->filled('algo_version') ? (string) $request->query('algo_version') : null,
);
$artworks = collect($feedResult['data'] ?? [])->map(
fn (array $item) => $this->presentRecommendedArtwork($item)
)->values();
$meta = $feedResult['meta'] ?? [];
$nextCursor = $meta['next_cursor'] ?? null;
if ($request->ajax()) {
return response()->json([
'artworks' => $artworks->map(fn (object $artwork) => (array) $artwork)->all(),
'next_cursor' => $nextCursor,
'has_more' => ! empty($nextCursor),
'meta' => $meta,
]);
}
return view('web.discover.for-you', [
'artworks' => $artworks,
'page_title' => 'For You',
'section' => 'for-you',
'description' => 'Artworks picked for you based on your taste.',
'icon' => 'fa-wand-magic-sparkles',
'next_cursor' => $nextCursor,
'feed_meta' => $meta,
'cache_status' => $meta['cache_status'] ?? null,
]);
}
// ─── /discover/following ─────────────────────────────────────────────────
public function following(Request $request)
{
$user = $request->user();
$perPage = 24;
// Subquery: IDs of users this viewer follows
$followingIds = DB::table('user_followers')
->where('follower_id', $user->id)
->pluck('user_id');
if ($followingIds->isEmpty()) {
// Trending fallback: show popular artworks so the page isn't blank
try {
$fallbackResults = $this->searchService->discoverTrending(12);
$fallbackArtworks = $fallbackResults->getCollection()
->transform(fn ($a) => $this->presentArtwork($a));
} catch (\Throwable) {
$fallbackArtworks = collect();
}
// Suggested creators: most-followed users the viewer doesn't follow yet
$suggestedCreators = $this->userSuggestions->suggestFor($user, 6);
return view('web.discover.index', [
'artworks' => collect(),
'page_title' => 'Following Feed',
'section' => 'following',
'description' => 'Follow some creators to see their work here.',
'icon' => 'fa-user-group',
'empty' => true,
'fallback_trending' => $fallbackArtworks,
'fallback_creators' => $suggestedCreators,
'following_activity' => [],
'network_trending' => [],
'suggested_users' => $suggestedCreators,
]);
}
$page = (int) request()->get('page', 1);
$cacheKey = "discover.following.{$user->id}.p{$page}";
$artworks = Cache::remember($cacheKey, 60, function () use ($user, $followingIds, $perPage): \Illuminate\Pagination\LengthAwarePaginator {
return Artwork::query()
->public()
->published()
->with(['user:id,name,username', 'categories:id,name,slug,content_type_id,parent_id,sort_order'])
->whereIn('user_id', $followingIds)
->orderByDesc('published_at')
->paginate($perPage)
->withQueryString();
});
$artworks->getCollection()->transform(fn ($a) => $this->presentArtwork($a));
$networkActivity = $this->communityActivity->getFeed(
viewer: $user,
filter: 'following',
page: 1,
perPage: 8,
actorUserId: null,
);
return view('web.discover.index', [
'artworks' => $artworks,
'page_title' => 'Following Feed',
'section' => 'following',
'description' => 'The latest artworks from creators you follow.',
'icon' => 'fa-user-group',
'following_activity' => $networkActivity['data'] ?? [],
'network_trending' => $this->buildNetworkTrendingArtworks($followingIds->all(), 8),
'suggested_users' => $this->userSuggestions->suggestFor($user, 6),
]);
}
// ─── Helpers ─────────────────────────────────────────────────────────────
private function hydrateDiscoverSearchResults($paginator): void
{
if (!is_object($paginator) || !method_exists($paginator, 'getCollection') || !method_exists($paginator, 'setCollection')) {
return;
}
$items = $paginator->getCollection();
if (!$items || $items->isEmpty()) {
return;
}
$ids = $items
->pluck('id')
->filter(fn ($id) => is_numeric($id) && (int) $id > 0)
->map(fn ($id) => (int) $id)
->values();
if ($ids->isEmpty()) {
return;
}
$byId = Artwork::query()
->whereIn('id', $ids)
->with([
'user:id,name,username',
'user.profile:user_id,avatar_hash',
'categories:id,name,slug,content_type_id,parent_id,sort_order',
])
->get()
->keyBy('id');
$paginator->setCollection(
$items->map(function ($item) use ($byId) {
$id = (int) ($item->id ?? 0);
$full = $id > 0 ? $byId->get($id) : null;
if ($full instanceof Artwork) {
return $this->presentArtwork($full);
}
return (object) [
'id' => $item->id ?? 0,
'name' => $item->title ?? $item->name ?? 'Untitled',
'category_name' => $item->category_name ?? $item->category ?? '',
'category_slug' => $item->category_slug ?? '',
'thumb_url' => $item->thumbnail_url ?? $item->thumb_url ?? $item->thumb ?? null,
'thumb_srcset' => $item->thumb_srcset ?? null,
'uname' => $item->author ?? $item->uname ?? 'Skinbase',
'username' => $item->username ?? '',
'avatar_url' => \App\Support\AvatarUrl::forUser((int) ($item->user_id ?? $item->author_id ?? 0), null, 64),
'published_at' => $item->published_at ?? null,
'width' => isset($item->width) && $item->width ? (int) $item->width : null,
'height' => isset($item->height) && $item->height ? (int) $item->height : null,
];
})
);
}
private function presentArtwork(Artwork $artwork): object
{
$primaryCategory = $artwork->categories->sortBy('sort_order')->first();
$present = ThumbnailPresenter::present($artwork, 'md');
$avatarUrl = \App\Support\AvatarUrl::forUser(
(int) ($artwork->user_id ?? 0),
$artwork->user?->profile?->avatar_hash ?? null,
64
);
return (object) [
'id' => $artwork->id,
'name' => $artwork->title,
'content_type_name' => $primaryCategory?->contentType?->name ?? '',
'content_type_slug' => $primaryCategory?->contentType?->slug ?? '',
'category_name' => $primaryCategory->name ?? '',
'category_slug' => $primaryCategory->slug ?? '',
'gid_num' => $primaryCategory ? ((int) $primaryCategory->id % 5) * 5 : 0,
'thumb_url' => $present['url'],
'thumb_srcset' => $present['srcset'] ?? $present['url'],
'uname' => $artwork->user->name ?? 'Skinbase',
'avatar_url' => $avatarUrl,
'published_at' => $artwork->published_at,
'width' => $artwork->width ?? null,
'height' => $artwork->height ?? null,
];
}
/**
* @param array<string, mixed> $item
*/
private function presentRecommendedArtwork(array $item): object
{
$width = isset($item['width']) && (int) $item['width'] > 0 ? (int) $item['width'] : null;
$height = isset($item['height']) && (int) $item['height'] > 0 ? (int) $item['height'] : null;
return (object) [
'id' => (int) ($item['id'] ?? 0),
'name' => (string) ($item['title'] ?? 'Untitled'),
'thumb_url' => $item['thumbnail_url'] ?? null,
'thumb_srcset' => $item['thumbnail_srcset'] ?? null,
'uname' => (string) ($item['author'] ?? 'Artist'),
'username' => (string) ($item['username'] ?? ''),
'avatar_url' => $item['avatar_url'] ?? null,
'published_at' => $item['published_at'] ?? null,
'slug' => (string) ($item['slug'] ?? ''),
'url' => $item['url'] ?? null,
'width' => $width,
'height' => $height,
'content_type_name' => (string) ($item['content_type_name'] ?? ''),
'content_type_slug' => (string) ($item['content_type_slug'] ?? ''),
'category_name' => (string) ($item['category_name'] ?? ''),
'category_slug' => (string) ($item['category_slug'] ?? ''),
'primary_tag' => $item['primary_tag'] ?? null,
'tags' => is_array($item['tags'] ?? null) ? $item['tags'] : [],
'recommendation_source' => (string) ($item['source'] ?? 'mixed'),
'recommendation_reason' => (string) ($item['reason'] ?? 'Picked for you'),
'recommendation_score' => isset($item['score']) ? round((float) $item['score'], 4) : null,
'recommendation_algo_version' => (string) ($item['algo_version'] ?? ''),
'hide_artwork_endpoint' => route('api.discovery.feedback.hide-artwork'),
'dislike_tag_endpoint' => route('api.discovery.feedback.dislike-tag'),
];
}
private function buildNetworkTrendingArtworks(array $followingIds, int $limit = 8): array
{
if ($followingIds === []) {
return [];
}
return Artwork::query()
->public()
->published()
->with(['user:id,name,username', 'user.profile:user_id,avatar_hash', 'stats:artwork_id,views,favorites,comments_count,heat_score'])
->whereIn('user_id', $followingIds)
->where('published_at', '>=', now()->subDays(30))
->leftJoin('artwork_stats as ast', 'ast.artwork_id', '=', 'artworks.id')
->orderByDesc(DB::raw('COALESCE(ast.heat_score, 0)'))
->orderByDesc(DB::raw('COALESCE(ast.favorites, 0)'))
->orderByDesc('artworks.published_at')
->limit(max(1, $limit))
->select('artworks.*')
->get()
->map(fn (Artwork $artwork) => [
'id' => (int) $artwork->id,
'title' => (string) $artwork->title,
'url' => route('art.show', ['id' => (int) $artwork->id, 'slug' => $artwork->slug]),
'thumb_url' => $artwork->thumb_url,
'published_at' => $artwork->published_at?->diffForHumans(),
'author' => [
'username' => $artwork->user?->username,
'name' => $artwork->user?->name,
'avatar_url' => $artwork->user?->profile?->avatar_url,
'profile_url' => $artwork->user?->username ? '/@' . strtolower((string) $artwork->user->username) : null,
],
'stats' => [
'favorites' => (int) ($artwork->stats?->favorites ?? 0),
'views' => (int) ($artwork->stats?->views ?? 0),
'comments' => (int) ($artwork->stats?->comments_count ?? 0),
],
])
->values()
->all();
}
}