Skip to content
Merged
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
1 change: 1 addition & 0 deletions app/Devnull/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,7 @@ private function get(string $path, array $query = []): array
{
$json = $this->json($this->send('GET', $path, $query));
$this->cache->put($path, $query, $json);
ImageCache::prefetch($json);

return $json;
}
Expand Down
70 changes: 70 additions & 0 deletions app/Devnull/DownloadImages.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php

namespace App\Devnull;

use Illuminate\Http\Client\Pool;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;
use Native\Mobile\AsyncTask;
use Throwable;

/**
* Downloads images for ImageCache on one of NativePHP's background PHP threads,
* a few at a time, so the screen never waits on them. Only images are kept,
* and each is written whole before it can be drawn. Images past the cache's
* age are cleared out first, so the folder holds about a day's worth.
*/
final class DownloadImages extends AsyncTask
{
private const int AtOnce = 6;

/**
* @param list<string> $urls
*/
public function handle(array $urls): int
{
File::ensureDirectoryExists(ImageCache::directory());
self::prune();

$saved = 0;

foreach (array_chunk($urls, self::AtOnce) as $batch) {
$responses = Http::pool(fn (Pool $pool): array => array_map(
fn (string $url) => $pool->timeout(15)->get($url),
$batch,
));

foreach ($batch as $index => $url) {
$response = $responses[$index] ?? null;

if ($response instanceof Response && $response->successful() && str_starts_with((string) $response->header('Content-Type'), 'image/')) {
$path = ImageCache::path($url);
File::put($path.'.part', $response->body());
File::move($path.'.part', $path);
$saved++;
}
}
}

return $saved;
}

/**
* Deletes images older than the cache keeps them, and any half-written ones.
*/
private static function prune(): void
{
$oldest = time() - ImageCache::hours() * 3600;

foreach (File::files(ImageCache::directory()) as $file) {
try {
if (str_ends_with($file->getFilename(), '.part') || $file->getMTime() <= $oldest) {
File::delete($file->getPathname());
}
} catch (Throwable) {
// Another download may have just replaced it.
}
}
}
}
119 changes: 119 additions & 0 deletions app/Devnull/ImageCache.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
<?php

namespace App\Devnull;

/**
* Remote images kept on the device: avatars, commit images and link preview
* images. NativePHP's image element streams a remote URL every time it comes
* into view, but draws a file on the device from memory, so an image is
* downloaded once in the background (see DownloadImages) and drawn from its
* file until it's older than config('devnull.image_cache_hours').
*
* Downloads start when an answer from devnull arrives, never while a screen is
* drawn, so an image not downloaded yet just loads from its URL as before.
*/
final class ImageCache
{
public const string Directory = 'image-cache';

/**
* What to give an image element: the file this URL was downloaded to while
* it's fresh, otherwise the URL itself.
*/
public static function src(?string $url): ?string
{
return self::freshPath($url) ?? $url;
}

/**
* Downloads, in the background, the images in an answer from devnull that
* aren't on the device yet.
*
* @param array<array-key, mixed> $json
*/
public static function prefetch(array $json): void
{
if (self::hours() <= 0) {
return;
}

$missing = array_values(array_filter(
array_unique(self::urlsIn($json)),
fn (string $url): bool => self::freshPath($url) === null,
));

if ($missing !== []) {
DownloadImages::dispatch($missing)->timeout(120);
}
}

/**
* Every image URL in an answer, wherever it's nested: people's avatars,
* commits' images and link previews' images.
*
* @param array<array-key, mixed> $json
* @return list<string>
*/
public static function urlsIn(array $json): array
{
$urls = [];

foreach ($json as $key => $value) {
if (in_array($key, ['avatar_url', 'image_url'], true) && self::isRemote($value)) {
$urls[] = $value;
} elseif ($key === 'images' && is_array($value)) {
foreach ($value as $image) {
if (is_array($image) && self::isRemote($image['url'] ?? null)) {
$urls[] = $image['url'];
}
}
} elseif (is_array($value)) {
$urls = [...$urls, ...self::urlsIn($value)];
}
}

return $urls;
}

/**
* Where a URL's image is kept, named for the URL.
*/
public static function path(string $url): string
{
return self::directory().'/'.hash('sha256', $url);
}

public static function directory(): string
{
return storage_path('app/'.self::Directory);
}

public static function hours(): int
{
return (int) config('devnull.image_cache_hours');
}

/**
* The file a URL was downloaded to, while it's younger than the cache
* keeps images, or null.
*/
private static function freshPath(?string $url): ?string
{
if (self::hours() <= 0 || ! self::isRemote($url)) {
return null;
}

$path = self::path($url);
$modified = is_file($path) ? filemtime($path) : false;

return $modified !== false && $modified > time() - self::hours() * 3600 ? $path : null;
}

/**
* @phpstan-assert-if-true string $value
*/
private static function isRemote(mixed $value): bool
{
return is_string($value) && preg_match('#^https?://#i', $value) === 1;
}
}
2 changes: 2 additions & 0 deletions app/NativeComponents/Concerns/RefreshesInBackground.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use App\Devnull\Exceptions\KeychainUnavailable;
use App\Devnull\Exceptions\Unauthenticated;
use App\Devnull\FetchInBackground;
use App\Devnull\ImageCache;
use App\Devnull\ResponseCache;
use Closure;
use Throwable;
Expand Down Expand Up @@ -177,6 +178,7 @@ private function settleRefresh(array $result, string $path, array $query, Closur
$json = is_array($result['json'] ?? null) ? $result['json'] : [];

app(ResponseCache::class)->put($path, $query, $json);
ImageCache::prefetch($json);
$this->refreshFailed = false;
$this->error = null;
$apply($json);
Expand Down
14 changes: 14 additions & 0 deletions config/devnull.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,20 @@

'key_store' => env('DEVNULL_KEY_STORE'),

/*
|--------------------------------------------------------------------------
| Image cache
|--------------------------------------------------------------------------
|
| Avatars, commit images and link preview images are downloaded in the
| background the first time an answer from devnull carries them, then drawn
| from the device for this many hours instead of being fetched again each
| time they scroll into view. 0 turns the cache off.
|
*/

'image_cache_hours' => (int) env('DEVNULL_IMAGE_CACHE_HOURS', 24),

/*
|--------------------------------------------------------------------------
| Sign in with Apple
Expand Down
1 change: 1 addition & 0 deletions phpunit.xml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
<env name="DEVNULL_KEY_STORE" value="keychain"/>
<env name="DEVNULL_APPLE_SIGN_IN" value="true"/>
<env name="DEVNULL_IMAGE_CACHE_HOURS" value="0"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="BROADCAST_CONNECTION" value="null"/>
<env name="CACHE_STORE" value="array"/>
Expand Down
4 changes: 2 additions & 2 deletions resources/views/native/partials/avatar.blade.php
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
{{-- A person as a circle: their GitHub avatar on the wash, or their initial while it loads. --}}
{{-- A person as a circle: their GitHub avatar on the wash, kept on the device for a day (see ImageCache), or their initial while it loads. --}}
@php($size ??= 40)
<native:stack :width="$size" :height="$size" class="rounded-full bg-theme-wash" center>
<native:text font="semibold" class="text-theme-ink-muted" :font-size="$size * 0.4">{{ mb_strtoupper(mb_substr($user->name, 0, 1)) }}</native:text>
@if ($user->avatarUrl)
<native:image :src="$user->avatarUrl" :width="$size" :height="$size" :fit="2" class="rounded-full" />
<native:image :src="\App\Devnull\ImageCache::src($user->avatarUrl)" :width="$size" :height="$size" :fit="2" class="rounded-full" />
@endif
</native:stack>
9 changes: 5 additions & 4 deletions resources/views/native/partials/commit-media.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@
What hangs under a commit's body on the web: its images, its poll, the commit it quotes, then the link preview.
A reply in a thread shows only its images and link preview ($withEmbeds false), as the web's thread does.
Images hold their space at their aspect ratio on a wash, so one that fails to load leaves the row as it was. Each is
read out by the description its author gave it, as the web's alt text.
read out by the description its author gave it, as the web's alt text. Images come from the device once ImageCache has
them, so they don't load again each time they scroll into view.
--}}
@php($images = $commit->images)
@if (count($images) === 1)
<native:pressable ref="image-{{ $images[0]->id }}" @press="openImage('{{ $commit->id }}', 0)" class="w-full mt-2" a11y-label="{{ $images[0]->label() }}">
<native:column class="w-full aspect-[{{ $images[0]->ratio() }}] rounded-lg border border-theme-hairline bg-theme-wash">
<native:image :src="$images[0]->url" :fit="2" alt="{{ $images[0]->label() }}" class="w-full h-full rounded-lg" />
<native:image :src="\App\Devnull\ImageCache::src($images[0]->url)" :fit="2" alt="{{ $images[0]->label() }}" class="w-full h-full rounded-lg" />
</native:column>
</native:pressable>
@elseif (count($images) > 1)
Expand All @@ -19,7 +20,7 @@
@foreach ($column as $image)
@php($index = array_search($image, $images, true))
<native:pressable ref="image-{{ $image->id }}" @press="openImage('{{ $commit->id }}', {{ $index }})" class="w-full flex-1 bg-theme-wash" a11y-label="{{ $image->label($index, count($images)) }}">
<native:image :src="$image->url" :fit="2" alt="{{ $image->label($index, count($images)) }}" class="w-full h-full" />
<native:image :src="\App\Devnull\ImageCache::src($image->url)" :fit="2" alt="{{ $image->label($index, count($images)) }}" class="w-full h-full" />
</native:pressable>
@endforeach
</native:column>
Expand All @@ -42,7 +43,7 @@
<native:row class="w-full gap-3 p-2 items-center rounded-lg border border-theme-hairline">
@if ($preview->imageUrl)
<native:column :width="56" :height="56" class="rounded-md bg-theme-wash">
<native:image :src="$preview->imageUrl" :width="56" :height="56" :fit="2" class="rounded-md" />
<native:image :src="\App\Devnull\ImageCache::src($preview->imageUrl)" :width="56" :height="56" :fit="2" class="rounded-md" />
</native:column>
@endif
<native:column class="flex-1 gap-[2] pr-1">
Expand Down
Loading
Loading