Skip to content

🚧 Backend implementation for timeline page #3251

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
167 changes: 167 additions & 0 deletions app/Actions/Photo/Timeline.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
<?php

/**
* SPDX-License-Identifier: MIT
* Copyright (c) 2017-2018 Tobias Reich
* Copyright (c) 2018-2025 LycheeOrg.
*/

namespace App\Actions\Photo;

use App\Eloquent\FixedQueryBuilder;
use App\Enum\ColumnSortingPhotoType;
use App\Enum\OrderSortingType;
use App\Enum\TimelinePhotoGranularity;
use App\Exceptions\Internal\LycheeInvalidArgumentException;
use App\Exceptions\Internal\TimelineGranularityException;
use App\Models\Configs;
use App\Models\Photo;
use App\Policies\PhotoQueryPolicy;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class Timeline
{
protected PhotoQueryPolicy $photo_query_policy;
private TimelinePhotoGranularity $photo_granularity;

public function __construct(PhotoQueryPolicy $photo_query_policy)
{
$this->photo_query_policy = $photo_query_policy;
$this->photo_granularity = Configs::getValueAsEnum('timeline_photos_granularity', TimelinePhotoGranularity::class);
}

/**
* Create the query manually.
*
* @return FixedQueryBuilder<Photo>
*/
public function do(): Builder
{
$order = Configs::getValueAsEnum('timeline_photos_order', ColumnSortingPhotoType::class);

// Safe default (should not be needed).
// @codeCoverageIgnoreStart
if (!in_array($order, [ColumnSortingPhotoType::CREATED_AT, ColumnSortingPhotoType::TAKEN_AT], true)) {
$order = ColumnSortingPhotoType::TAKEN_AT;
}
// @codeCoverageIgnoreEnd

return $this->photo_query_policy->applySearchabilityFilter(
query: Photo::query()->with(['album', 'statistics', 'size_variants', 'size_variants.sym_links']),
origin: null,
include_nsfw: !Configs::getValueAsBool('hide_nsfw_in_timeline')
)->orderBy($order->value, OrderSortingType::DESC->value);
}

/**
* Return the number of pictures that are younger than this.
* We use this to dertermine the current page given a date.
*
* @param Carbon $date
*
* @return int
*/
public function countYoungerFromDate(Carbon $date): int
{
$order = Configs::getValueAsEnum('timeline_photos_order', ColumnSortingPhotoType::class);

// Safe default (should not be needed).
// @codeCoverageIgnoreStart
if (!in_array($order, [ColumnSortingPhotoType::CREATED_AT, ColumnSortingPhotoType::TAKEN_AT], true)) {
$order = ColumnSortingPhotoType::TAKEN_AT;
}
// @codeCoverageIgnoreEnd

return $this->photo_query_policy->applySearchabilityFilter(
query: Photo::query()
->where($order->value, '>', $date)
->whereNotNull($order->value),
origin: null,
include_nsfw: !Configs::getValueAsBool('hide_nsfw_in_timeline')
)->count();
}

/**
* Return the number of pictures that are younger than this.
* We use this to dertermine the current page given a photo.
*
* @param Photo $photo
*
* @return int
*/
public function countYoungerFromPhoto(Photo $photo): int
{
$order = Configs::getValueAsEnum('timeline_photos_order', ColumnSortingPhotoType::class);

// Safe default (should not be needed).
// @codeCoverageIgnoreStart
if (!in_array($order, [ColumnSortingPhotoType::CREATED_AT, ColumnSortingPhotoType::TAKEN_AT], true)) {
$order = ColumnSortingPhotoType::TAKEN_AT;
}
// @codeCoverageIgnoreEnd

return $this->photo_query_policy->applySearchabilityFilter(
query: Photo::query()
->joinSub(
query: Photo::query()->select($order->value)->where('id', $photo->id),
as: 'sub',
first: 'sub.' . $order->value,
operator: '<',
second: 'photos.' . $order->value
)
->whereNotNull('photos.' . $order->value),
origin: null,
include_nsfw: !Configs::getValueAsBool('hide_nsfw_in_timeline')
)->count();
}

/**
* Get all the dates of the timeline.
*
* @return Collection<int,string>
*/
public function dates(): Collection
{
$order = Configs::getValueAsEnum('timeline_photos_order', ColumnSortingPhotoType::class);

// Safe default (should not be needed).
// @codeCoverageIgnoreStart
if (!in_array($order, [ColumnSortingPhotoType::CREATED_AT, ColumnSortingPhotoType::TAKEN_AT], true)) {
$order = ColumnSortingPhotoType::TAKEN_AT;
}
// @codeCoverageIgnoreEnd

// This is among the ugliest piece of code I had ever to write...
$is_driver_pgsql = DB::getDriverName() === 'pgsql';

$formatter = match (DB::getDriverName()) {
'sqlite' => 'strftime("%2$s", %1$s)',
'mysql' => 'DATE_FORMAT(%s, "%s")',
'mariadb' => 'DATE_FORMAT(%s, "%s")',
'pgsql' => "to_char(%s, '%s')",
default => throw new LycheeInvalidArgumentException('Unsupported database driver'),
};

$date_format = match ($this->photo_granularity) {
TimelinePhotoGranularity::YEAR => $is_driver_pgsql ? 'YYYY' : '%Y',
TimelinePhotoGranularity::MONTH => $is_driver_pgsql ? 'YYYY-mm' : '%Y-%m',
TimelinePhotoGranularity::DAY => $is_driver_pgsql ? 'YYYY-MM-DD' : '%Y-%m-%d',
TimelinePhotoGranularity::HOUR => $is_driver_pgsql ? 'YYYY-MM-DD"T"HH24' : '%Y-%m-%dT%H', // hoepfully this is correct
TimelinePhotoGranularity::DEFAULT, TimelinePhotoGranularity::DISABLED => throw new TimelineGranularityException(),
};

return $this->photo_query_policy->applySearchabilityFilter(
query: Photo::query()

->selectRaw(sprintf($formatter, $order->value, $date_format) . ' as date')
->whereNotNull($order->value),
origin: null,
include_nsfw: !Configs::getValueAsBool('hide_nsfw_in_timeline')
)->groupBy('date')
->orderBy('date', OrderSortingType::DESC->value)
->pluck('date');
}
}
1 change: 1 addition & 0 deletions app/Contracts/Http/Requests/RequestAttribute.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ class RequestAttribute
public const HEADER_ID_ATTRIBUTE = 'header_id';

public const TITLE_ATTRIBUTE = 'title';
public const DATE_ATTRIBUTE = 'date';
public const UPLOAD_DATE_ATTRIBUTE = 'upload_date';
public const TAKEN_DATE_ATTRIBUTE = 'taken_at';
public const DESCRIPTION_ATTRIBUTE = 'description';
Expand Down
17 changes: 17 additions & 0 deletions app/Enum/TimelineAlbumGranularity.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

namespace App\Enum;

use App\Exceptions\Internal\TimelineGranularityException;

/**
* Defines the possible granularities for album timelines.
*/
Expand All @@ -18,4 +20,19 @@ enum TimelineAlbumGranularity: string
case YEAR = 'year';
case MONTH = 'month';
case DAY = 'day';

/**
* Return the ISO date format for the associated granularity.
*
* @return string
*/
public function format(): string
{
return match ($this) {
self::YEAR => 'Y',
self::MONTH => 'Y-m',
self::DAY => 'Y-m-d',
self::DEFAULT, self::DISABLED => throw new TimelineGranularityException(),
};
}
}
18 changes: 18 additions & 0 deletions app/Enum/TimelinePhotoGranularity.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

namespace App\Enum;

use App\Exceptions\Internal\TimelineGranularityException;

/**
* Defines the possible granularities for photo timelines.
*/
Expand All @@ -19,4 +21,20 @@ enum TimelinePhotoGranularity: string
case MONTH = 'month';
case DAY = 'day';
case HOUR = 'hour';

/**
* Return whether the smart album is enabled.
*
* @return string
*/
public function format(): string
{
return match ($this) {
self::YEAR => 'Y',
self::MONTH => 'Y-m',
self::DAY => 'Y-m-d',
self::HOUR => 'Y-m-d H',
self::DEFAULT, self::DISABLED => throw new TimelineGranularityException(),
};
}
}
17 changes: 17 additions & 0 deletions app/Exceptions/Internal/TimelineGranularityException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

/**
* SPDX-License-Identifier: MIT
* Copyright (c) 2017-2018 Tobias Reich
* Copyright (c) 2018-2025 LycheeOrg.
*/

namespace App\Exceptions\Internal;

class TimelineGranularityException extends LycheeLogicException
{
public function __construct(?string $msg = null)
{
parent::__construct($msg ?? 'Invalid granularity for timeline');
}
}
78 changes: 78 additions & 0 deletions app/Http/Controllers/Gallery/TimelineController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php

/**
* SPDX-License-Identifier: MIT
* Copyright (c) 2017-2018 Tobias Reich
* Copyright (c) 2018-2025 LycheeOrg.
*/

namespace App\Http\Controllers\Gallery;

use App\Actions\Photo\Timeline;
use App\Http\Requests\Timeline\GetTimelineRequest;
use App\Http\Requests\Timeline\IdOrDatedTimelineRequest;
use App\Http\Resources\Models\Utils\TimelineData;
use App\Http\Resources\Timeline\InitResource;
use App\Http\Resources\Timeline\TimelineResource;
use App\Models\Configs;
use App\Models\Photo;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Routing\Controller;
use Spatie\LaravelData\Data;

/**
* Controller responsible for the Timeline data.
*/
class TimelineController extends Controller
{
/**
* Return the photos given some contraints.
*
* @param IdOrDatedTimelineRequest $request
* @param Timeline $timeline
*
* @return Data
*/
public function __invoke(IdOrDatedTimelineRequest $request, Timeline $timeline): Data
{
$pagination_limit = Configs::getValueAsInt('timeline_photos_pagination_limit');

if ($request->photo() !== null) {
$youngers = $timeline->countYoungerFromPhoto($request->photo());
Paginator::currentPageResolver(fn () => ceil($youngers / $pagination_limit));
} elseif ($request->date !== null) {
$youngers = $timeline->countYoungerFromDate($request->date);
Paginator::currentPageResolver(fn () => ceil($youngers / $pagination_limit));
}

/** @var LengthAwarePaginator<Photo> $photo_results */
/** @disregard P1013 Undefined method withQueryString() (stupid intelephense) */
$photo_results = $timeline->do()->paginate($pagination_limit);

return TimelineResource::fromData($photo_results);
}

/**
* Return init Search.
*
* @return InitResource
*/
public function init(): Data
{
return new InitResource();
}

/**
* Return all the dates of the timeline.
*
* @param GetTimelineRequest $request
* @param Timeline $timeline
*
* @return TimelineData[]
*/
public function dates(GetTimelineRequest $request, Timeline $timeline): array
{
return $timeline->dates()->map(fn (string $date) => TimelineData::fromDate($date))->toArray();
}
}
4 changes: 4 additions & 0 deletions app/Http/Middleware/ConfigIntegrity.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ class ConfigIntegrity
'timeline_album_date_format_year',
'timeline_album_date_format_month',
'timeline_album_date_format_day',
'timeline_quick_access_date_format_year',
'timeline_quick_access_date_format_month',
'timeline_quick_access_date_format_day',
'timeline_quick_access_date_format_hour',
'number_albums_per_row_mobile',
'client_side_favourite_enabled',
'cache_ttl',
Expand Down
28 changes: 28 additions & 0 deletions app/Http/Requests/Timeline/GetTimelineRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

/**
* SPDX-License-Identifier: MIT
* Copyright (c) 2017-2018 Tobias Reich
* Copyright (c) 2018-2025 LycheeOrg.
*/

namespace App\Http\Requests\Timeline;

use App\Http\Requests\AbstractEmptyRequest;
use App\Models\Configs;
use Illuminate\Support\Facades\Auth;

class GetTimelineRequest extends AbstractEmptyRequest
{
/**
* {@inheritDoc}
*/
public function authorize(): bool
{
if (!Auth::check() && !Configs::getValueAsBool('timeline_photos_public')) {
return false;
}

return Configs::getValueAsBool('timeline_page_enabled');
}
}
Loading