Skip to content

Migration to Unsplash API #1144

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

Merged
merged 25 commits into from
Nov 1, 2024
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
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ TELEGRAM_CHANNEL=

FATHOM_SITE_ID=
FATHOM_TOKEN=

UNSPLASH_ACCESS_KEY=

LOG_STACK=single
SESSION_ENCRYPT=false
SESSION_PATH=/
Expand Down
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,20 @@ FATHOM_SITE_ID=
FATHOM_TOKEN=
```

### Unsplash (optional)

To make sure article and user header images get synced into the database we'll need to setup an access key from [Unsplash](https://unsplash.com/developers). Please note that your Unsplash app requires production access.

```
UNSPLASH_ACCESS_KEY=
```

After that you can add an Unsplash photo ID to any article row in the `hero_image_id` column and run the sync command to fetch the image url and author data:

```bash
php artisan lio:sync-article-images
```

## Commands

Command | Description
Expand Down
65 changes: 65 additions & 0 deletions app/Console/Commands/SyncArticleImages.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php

namespace App\Console\Commands;

use App\Models\Article;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;

final class SyncArticleImages extends Command
{
protected $signature = 'lio:sync-article-images';

protected $description = 'Updates the Unsplash image for all unsynced articles';

public function handle(): void
{
if (! config('services.unsplash.access_key')) {
$this->error('Unsplash access key must be configured');

return;
}

Article::unsyncedImages()->chunk(100, function ($articles) {
$articles->each(function ($article) {
$imageData = $this->fetchUnsplashImageDataFromId($article->hero_image_id);

if (! is_null($imageData)) {
$article->hero_image_url = $imageData['image_url'];
$article->hero_image_author_name = $imageData['author_name'];
$article->hero_image_author_url = $imageData['author_url'];
$article->save();
}
});
});
}

protected function fetchUnsplashImageDataFromId(string $imageId): ?array
{
$response = Http::retry(3, 100, throw: false)
->withToken(config('services.unsplash.access_key'), 'Client-ID')
->get("https://api.unsplash.com/photos/{$imageId}");

if ($response->failed()) {
logger()->error('Failed to get raw image url from unsplash for', [
'imageId' => $imageId,
'response' => $response->json(),
]);

return null;
}

$response = $response->json();

// Trigger as download...
Http::retry(3, 100, throw: false)
->withToken(config('services.unsplash.access_key'), 'Client-ID')
->get($response['links']['download_location']);

return [
'image_url' => $response['urls']['raw'],
'author_name' => $response['user']['name'],
'author_url' => $response['user']['links']['html']
];
}
}
23 changes: 19 additions & 4 deletions app/Models/Article.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,10 @@ final class Article extends Model implements Feedable
'body',
'original_url',
'slug',
'hero_image',
'hero_image_id',
'hero_image_url',
'hero_image_author_name',
'hero_image_author_url',
'is_pinned',
'view_count',
'tweet_id',
Expand Down Expand Up @@ -100,13 +103,19 @@ public function excerpt(int $limit = 100): string

public function hasHeroImage(): bool
{
return $this->hero_image !== null;
return $this->hero_image_url !== null;
}

public function hasHeroImageAuthor(): bool
{
return $this->hero_image_author_name !== null &&
$this->hero_image_author_url !== null;
}

public function heroImage($width = 400, $height = 300): string
{
if ($this->hero_image) {
return "https://source.unsplash.com/{$this->hero_image}/{$width}x{$height}";
if ($this->hasHeroImage()) {
return "{$this->hero_image_url}&fit=clip&w={$width}&h={$height}&utm_source=Laravel.io&utm_medium=referral";
}

return asset('images/default-background.svg');
Expand Down Expand Up @@ -309,6 +318,12 @@ public function scopeTrending(Builder $query): Builder
->orderBy('submitted_at', 'desc');
}

public function scopeUnsyncedImages(Builder $query): Builder
{
return $query->whereNotNull('hero_image_id')
->whereNull('hero_image_url');
}

public function shouldBeSearchable()
{
return $this->isPublished();
Expand Down
4 changes: 4 additions & 0 deletions config/services.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,8 @@
'token' => env('FATHOM_TOKEN'),
],

'unsplash' => [
'access_key' => env('UNSPLASH_ACCESS_KEY'),
],

];
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('articles', function (Blueprint $table) {
$table->after('hero_image', function () use ($table) {
$table->string('hero_image_url')->nullable();
$table->string('hero_image_author_name')->nullable();
$table->string('hero_image_author_url')->nullable();
});
});

Schema::table('articles', function (Blueprint $table) {
$table->renameColumn('hero_image', 'hero_image_id');
});
}
};
2 changes: 1 addition & 1 deletion database/seeders/UserSeeder.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public function run(): void
[
'submitted_at' => now(),
'approved_at' => now(),
'hero_image' => 'sxiSod0tyYQ',
'hero_image_id' => 'sxiSod0tyYQ',
],
['submitted_at' => now(), 'approved_at' => now()],
['submitted_at' => now()],
Expand Down
3 changes: 2 additions & 1 deletion phpunit.xml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
<env name="APP_HOST" value="localhost"/>
<env name="APP_URL" value="http://localhost"/>
<env name="AUTH_PASSWORD_RESET_TOKEN_TABLE" value="password_resets"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="CACHE_STORE" value="array"/>
<env name="DB_CONNECTION" value="mysql"/>
<env name="DB_DATABASE" value="testing"/>
Expand All @@ -32,6 +33,6 @@
<env name="TELEGRAM_CHANNEL" value="null"/>
<env name="FATHOM_SITE_ID" value="1234"/>
<env name="FATHOM_TOKEN" value="5678"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="UNSPLASH_ACCESS_KEY" value="null"/>
</php>
</phpunit>
6 changes: 6 additions & 0 deletions resources/views/articles/show.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,12 @@ class="w-full bg-center {{ $article->hasHeroImage() ? 'bg-cover' : '' }} bg-gray
</div>
</div>
</div>

@if ($article->hasHeroImageAuthor())
<p class="text-xs text-black/50 text-center mt-2">
Photo by <a class="underline font-medium" href="{{ $article->hero_image_author_url }}?ref=laravel.io&utm_source=Laravel.io&utm_medium=referral" target="_blank">{{ $article->hero_image_author_name }} </a> on <a class="underline font-medium" href="https://unsplash.com/?ref=laravel.io&utm_source=Laravel.io&utm_medium=referral" target="_blank">Unsplash</a>
</p>
@endif
</div>
</div>

Expand Down
60 changes: 60 additions & 0 deletions tests/Integration/Commands/SyncArticleImagesTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

use App\Console\Commands\SyncArticleImages;
use App\Models\Article;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

uses(TestCase::class);
uses(DatabaseMigrations::class);

test('hero image url and author information is updated for published articles with hero image', function () {
Config::set('services.unsplash.access_key', 'test');

Http::fake(function () {
return [
'urls' => [
'raw' => 'https://images.unsplash.com/photo-1584824486509-112e4181ff6b?ixid=M3w2NTgwOTl8MHwxfGFsbHx8fHx8fHx8fDE3Mjc2ODMzMzZ8&ixlib=rb-4.0.3'
],
'user' => [
'name' => 'Erik Mclean',
'links' => [
'html' => 'https://unsplash.com/@introspectivedsgn',
]
],
];
});

$article = Article::factory()->create([
'hero_image_id' => 'sxiSod0tyYQ',
'submitted_at' => now(),
'approved_at' => now(),
]);

(new SyncArticleImages)->handle();

$article->refresh();

expect($article->heroImage())->toContain('https://images.unsplash.com/photo-1584824486509-112e4181ff6b');
expect($article->hero_image_author_name)->toBe('Erik Mclean');
expect($article->hero_image_author_url)->toBe('https://unsplash.com/@introspectivedsgn');
});

test('hero image url and author information is not updated for published articles with no hero image', function () {
Config::set('services.unsplash.access_key', 'test');

$article = Article::factory()->create([
'submitted_at' => now(),
'approved_at' => now(),
]);

(new SyncArticleImages)->handle();

$article->refresh();

expect($article->hero_image_url)->toBe(null);
expect($article->hero_image_author_name)->toBe(null);
expect($article->hero_image_author_url)->toBe(null);
});