From 310b29a9d7d8753bdba9fee16cce5654f6bf199b Mon Sep 17 00:00:00 2001 From: Elyess Zouaghi Date: Fri, 27 Nov 2026 19:25:00 +0100 Subject: [PATCH] feat: moments carry the display width and height of photos and videos; kinlore:media-dimensions fills older media - Migration: nullable width and height on moments; photos get them after orientation from the preview decode, videos from the upright processed frame - Moment API and sync pull send width and height (null for text moments and unknown sizes) - kinlore:media-dimensions (--dry-run): fills older photos from their preview and videos from their processing data; bumps updated_at so phones get the size on their next sync - Tests: MomentDimensionsTest; docs: API, commands, updating (run the command once after updating) --- CHANGELOG.md | 6 + docs/reference/api.md | 6 +- docs/reference/commands.md | 1 + docs/self-hosting/updating.md | 12 + .../app/Console/Commands/MediaDimensions.php | 75 ++++++ kinlore-api/app/Models/Moment.php | 6 + kinlore-api/app/Services/MomentService.php | 32 ++- kinlore-api/app/Services/SyncService.php | 2 + ...026_11_27_000001_add_moment_dimensions.php | 25 ++ kinlore-api/openapi.yaml | 18 +- .../tests/Feature/MomentDimensionsTest.php | 233 ++++++++++++++++++ 11 files changed, 400 insertions(+), 16 deletions(-) create mode 100644 kinlore-api/app/Console/Commands/MediaDimensions.php create mode 100644 kinlore-api/database/migrations/2026_11_27_000001_add_moment_dimensions.php create mode 100644 kinlore-api/tests/Feature/MomentDimensionsTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 72b058e..923e7f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ The version numbers are explained in "Project status" in the [README](README.md) ### Added +- Every moment in the REST payload and in the sync pull has `width` and `height`: the pixel size of the photo or video as it is shown, after the EXIF orientation of a photo and the rotation of a video. They are `null` for story, milestone and growth moments and for a video that is still processing. The app can lay out the timeline before an image loads. +- `php artisan kinlore:media-dimensions` fills `width` and `height` of older photos and videos. Run it once after this update. An older photo gets the size of its 1200-pixel preview, so the ratio is exact but the size can be smaller than the original. It skips and counts files it cannot read, and `--dry-run` changes nothing. Phones get the sizes at their next sync. See [Updating](docs/self-hosting/updating.md#from-1-5-to-1-6). - `POST /auth/login` and `POST /auth/register` accept an optional `device_name` (up to 60 characters). It is the session `name` in `GET /auth/sessions`, so the app can show each signed-in device. Without it the name stays `mobile-app`. `POST /auth/refresh` keeps the name. ### Fixed @@ -22,6 +24,10 @@ The version numbers are explained in "Project status" in the [README](README.md) - `POST /v1/invitations` returns `public_url_configured` (bool), so the app can tell the admin to set `APP_URL`. `GET /health/detailed` has a `public_url` check, and `php artisan kinlore:setup-token` prints a warning. - `openapi.yaml` describes `device_name`, the session `name`, `public_url_configured` in `POST /v1/invitations` and the `public_url` check of `GET /health/detailed`. +### Upgrade notes + +- **Docker and host install:** after the update, run `php artisan kinlore:media-dimensions` once. It fills the size of the photos and videos that you already have. See [Updating](docs/self-hosting/updating.md#from-1-5-to-1-6). + ## [1.5.1] - 2026-11-26 Use this release with version 1.2.0 or newer of the mobile app. The update needs no manual step. diff --git a/docs/reference/api.md b/docs/reference/api.md index 71ab7be..97b7e2a 100644 --- a/docs/reference/api.md +++ b/docs/reference/api.md @@ -111,7 +111,9 @@ Kid payload: `{ id, user_id, name, date_of_birth: "YYYY-MM-DD"|null, due_date: " Types: `photo`, `video`, `story`, `milestone`, `growth`. Moment payload (REST and the inside of `data.moment`): -`{ id, kid_id, user_id: int|null, uploader_name: string|null, moment_type, title, description, milestone_id, exif_date (ISO|null), display_date (ISO, exif_date or created_at), latitude: number|null, longitude: number|null, orientation, camera_make, camera_model, file_size, mime_type, original_filename, device_asset_id, duration: number|null (seconds), video_status: "processing"|"ready"|"failed"|null, height_cm: number|null, weight_kg: number|null, head_circumference_cm: number|null, likes_count, comments_count, is_liked, created_at, updated_at, media?: {...}, milestone?: {...} }`. It has no file links: the app uses `/file/{type}` and `/playback`. +`{ id, kid_id, user_id: int|null, uploader_name: string|null, moment_type, title, description, milestone_id, exif_date (ISO|null), display_date (ISO, exif_date or created_at), latitude: number|null, longitude: number|null, orientation, width: int|null, height: int|null, camera_make, camera_model, file_size, mime_type, original_filename, device_asset_id, duration: number|null (seconds), video_status: "processing"|"ready"|"failed"|null, height_cm: number|null, weight_kg: number|null, head_circumference_cm: number|null, likes_count, comments_count, is_liked, created_at, updated_at, media?: {...}, milestone?: {...} }`. It has no file links: the app uses `/file/{type}` and `/playback`. + +`width` and `height` are the pixel size of the photo or video as it is shown: after the EXIF orientation of a photo and after the rotation of a video. They are `null` for story, milestone and growth moments, for a video that is still processing, and for an older photo or video that `php artisan kinlore:media-dimensions` has not filled. For an older photo, that command stores the size of the 1200-pixel preview: the ratio is right, the size can be smaller than the original. - `POST /v1/moments`: - photo/video: multipart `kid_id, file (required, also with moment_type=photo|video), title?, description?, device_asset_id?, exif_date?, latitude?, longitude?, camera_make?, camera_model?, orientation?`. @@ -161,7 +163,7 @@ Response: `{ changes: { kids: {created, updated, deleted}, moments: {created, up - The server returns rows with `updated_at >= lastPulledAt - 1000` (database times have second precision). The client must therefore **upsert** every row in `created` and `updated` (insert when missing, otherwise update all fields). Rows may come again. - `deleted`: ids of kids and moments soft-deleted since `lastPulledAt - 1000`, including the moments of deleted kids. - Kid row: `{ id, user_id, name, date_of_birth, due_date, avatar_color, created_at, updated_at }` (times in ms, dates as ms at UTC midnight, or null). -- Moment row: `{ id, kid_id, user_id, uploader_name, moment_type, title, description, milestone_id, exif_date, latitude, longitude, orientation, duration, video_status, height_cm, weight_kg, head_circumference_cm, likes_count, comments_count, is_liked, file_size, mime_type, device_asset_id, created_at, updated_at }`. No file fields. `is_liked` is for the caller. +- Moment row: `{ id, kid_id, user_id, uploader_name, moment_type, title, description, milestone_id, exif_date, latitude, longitude, orientation, width, height, duration, video_status, height_cm, weight_kg, head_circumference_cm, likes_count, comments_count, is_liked, file_size, mime_type, device_asset_id, created_at, updated_at }`. No file fields. `width` and `height` are as in the moment payload (section 6). `is_liked` is for the caller. `POST /v1/sync/push` request: `{ changes: { kids: {created, updated, deleted}, moments: {created, updated, deleted} }, lastPulledAt }`. - Kid fields: `id, name, date_of_birth (ms|null), due_date (ms|null), avatar_color`. The server keeps the client `id`. diff --git a/docs/reference/commands.md b/docs/reference/commands.md index fd1cad7..5acec6d 100644 --- a/docs/reference/commands.md +++ b/docs/reference/commands.md @@ -19,6 +19,7 @@ This page lists the commands that a server owner uses. Artisan is the command to |---|---| | `php artisan kinlore:setup-token` | Prints the token that the setup page asks for, while the server has no user. With `SETUP_TOKEN` set, it tells you to use that value. See [Create the first admin](/self-hosting/first-admin). | | `php artisan kinlore:reset-password ` | Sets a new password for a user and signs them out on all devices. It asks for the password. `--password=` gives it on the command line instead; the password then shows in the shell history. The password needs at least 8 characters. | +| `php artisan kinlore:media-dimensions` | Fills the width and height of older photos and videos, so the app can lay out the timeline before the images load. Run it once after the update to 1.6. A video gets the size that its conversion saved. A photo gets the size of its preview: the real size up to 1200 pixels wide, else the same ratio at 1200 pixels wide. It works in groups of 200 and changes only moments without a size, so you can run it again at any time. A file that it cannot read is skipped, counted in the result and written to the log. `--dry-run` shows the counts and changes nothing. Phones get the new sizes at their next sync. | | `php artisan seaweedfs:test` | Writes, reads, lists and deletes a test file in the media storage, then prints the storage settings. It works for S3 storage and the local disk. | ## Laravel commands diff --git a/docs/self-hosting/updating.md b/docs/self-hosting/updating.md index 3a3b6ed..9ccd093 100644 --- a/docs/self-hosting/updating.md +++ b/docs/self-hosting/updating.md @@ -59,6 +59,18 @@ On a host install, also check the workers: `systemctl is-active kinlore-queue ki Do the steps of every version between your version and the new one, oldest first. +### From 1.5 to 1.6 + +**Docker and host install** + +After the update, fill the size of the photos and videos that you already have. The app needs it for the timeline. Run this command once (see [How to run an Artisan command](/reference/commands#how-to-run-an-artisan-command)): + +```sh [Fill the media sizes] +php artisan kinlore:media-dimensions +``` + +It reads one small preview per photo, so it can take some minutes on a large library. The last line shows how many moments it filled and how many files it could not read. Phones get the sizes at their next sync. New uploads get their size by themselves. + ### From 1.3 to 1.4 **Docker** diff --git a/kinlore-api/app/Console/Commands/MediaDimensions.php b/kinlore-api/app/Console/Commands/MediaDimensions.php new file mode 100644 index 0000000..023f939 --- /dev/null +++ b/kinlore-api/app/Console/Commands/MediaDimensions.php @@ -0,0 +1,75 @@ +option('dry-run'); + $filled = 0; + $unreadable = 0; + + Moment::query() + ->with('media:id,video_metadata') + ->whereIn('moment_type', [MomentType::Photo, MomentType::Video]) + ->where(fn ($q) => $q->whereNull('width')->orWhereNull('height')) + // A video still processing gets its size from the job; a failed one has no preview. + ->where(fn ($q) => $q->whereNull('video_status')->orWhere('video_status', VideoStatus::Ready)) + ->chunkById(200, function ($moments) use ($storage, $dryRun, &$filled, &$unreadable): void { + foreach ($moments as $moment) { + $size = $this->size($moment, $storage); + if (! $size) { + $unreadable++; + Log::warning('kinlore:media-dimensions cannot read the size', ['moment_id' => $moment->id]); + + continue; + } + + // A query update: updated_at changes, so phones get the row on their next sync; edited_at + // stays, so this is no edit and causes no sync conflict. + if (! $dryRun) { + Moment::whereKey($moment->id)->update($size); + } + $filled++; + } + }); + + $this->info(($dryRun ? 'Would fill' : 'Filled')." {$filled} moments. Cannot read {$unreadable}."); + + return self::SUCCESS; + } + + /** @return array{width: int, height: int}|null */ + private function size(Moment $moment, FileStorageService $storage): ?array + { + $metadata = $moment->media?->video_metadata; + if (($metadata['width'] ?? 0) > 0 && ($metadata['height'] ?? 0) > 0) { + return ['width' => (int) $metadata['width'], 'height' => (int) $metadata['height']]; + } + + $path = $moment->getRawOriginal('medium_url'); + $bytes = $path ? $storage->get($path) : null; + $info = $bytes ? @getimagesizefromstring($bytes) : false; + + return $info && $info[0] > 0 && $info[1] > 0 ? ['width' => $info[0], 'height' => $info[1]] : null; + } +} diff --git a/kinlore-api/app/Models/Moment.php b/kinlore-api/app/Models/Moment.php index ccca3bc..dd931c4 100644 --- a/kinlore-api/app/Models/Moment.php +++ b/kinlore-api/app/Models/Moment.php @@ -42,6 +42,8 @@ 'latitude', 'longitude', 'orientation', + 'width', + 'height', 'camera_make', 'camera_model', 'duration', @@ -83,6 +85,8 @@ protected function casts(): array 'weight_kg' => 'float', 'head_circumference_cm' => 'float', 'orientation' => 'integer', + 'width' => 'integer', + 'height' => 'integer', 'moment_type' => MomentType::class, 'video_status' => VideoStatus::class, ]; @@ -200,6 +204,8 @@ public function toArray(): array 'longitude' => $this->longitude, 'has_location' => $this->has_location, 'orientation' => $this->orientation, + 'width' => $this->width, + 'height' => $this->height, 'camera_make' => $this->camera_make, 'camera_model' => $this->camera_model, 'duration' => $this->duration, diff --git a/kinlore-api/app/Services/MomentService.php b/kinlore-api/app/Services/MomentService.php index 19a9462..36a01c4 100644 --- a/kinlore-api/app/Services/MomentService.php +++ b/kinlore-api/app/Services/MomentService.php @@ -133,10 +133,8 @@ private function createMediaMoment(User $user, Kid $kid, UploadedFile $file, arr 'processing_started_at' => now(), ]); - // Videos are processed by a queued job so the upload returns at once - if ($type === MomentType::Photo) { - $this->processPhoto($media, $file, $basePath); - } + // Videos are processed by a queued job so the upload returns at once; it sets their size + $size = $type === MomentType::Photo ? $this->processPhoto($media, $file, $basePath) : []; $media->refresh(); $moment = Moment::create([ @@ -162,7 +160,7 @@ private function createMediaMoment(User $user, Kid $kid, UploadedFile $file, arr 'camera_make' => $media->camera_make, 'camera_model' => $media->camera_model, 'video_status' => $type === MomentType::Video ? VideoStatus::Processing : null, - ]); + ] + $size); } catch (\Throwable $e) { Log::error('Media upload failed: '.$e->getMessage()); $media?->forceDelete(); @@ -213,7 +211,8 @@ private function createTextMoment(User $user, Kid $kid, array $data, MomentType return ['moment' => $moment]; } - private function processPhoto(Media $media, UploadedFile $file, string $basePath): void + /** @return array{width: int, height: int} display size of the photo */ + private function processPhoto(Media $media, UploadedFile $file, string $basePath): array { $thumbnailPath = "{$basePath}/thumbnail.jpg"; $mediumPath = "{$basePath}/medium.jpg"; @@ -230,7 +229,7 @@ private function processPhoto(Media $media, UploadedFile $file, string $basePath $source = $decoded; } - $this->storePreviews($source, $thumbnailPath, $mediumPath); + $size = $this->storePreviews($source, $thumbnailPath, $mediumPath); } finally { if ($decoded) { @unlink($decoded); @@ -243,15 +242,17 @@ private function processPhoto(Media $media, UploadedFile $file, string $basePath 'thumbnail_url' => $thumbnailPath, 'medium_url' => $mediumPath, ]); + + return $size; } - private function storePreviews(string $source, string $thumbnailPath, string $mediumPath): void + /** @return array{width: int, height: int} size after the EXIF orientation */ + private function storePreviews(string $source, string $thumbnailPath, string $mediumPath): array { // Generate medium (1200px width) - $mediumImage = Image::decodePath($source) - ->orient() - ->scaleDown(width: 1200) - ->encode(new JpegEncoder(quality: 85)); + $image = Image::decodePath($source)->orient(); + $size = ['width' => $image->width(), 'height' => $image->height()]; + $mediumImage = $image->scaleDown(width: 1200)->encode(new JpegEncoder(quality: 85)); $this->storage->store($mediumPath, (string) $mediumImage); @@ -262,6 +263,8 @@ private function storePreviews(string $source, string $thumbnailPath, string $me ->encode(new JpegEncoder(quality: 80)); $this->storage->store($thumbnailPath, (string) $thumbnailImage); + + return $size; } // Run by ProcessVideoJob: make the HLS stream and set the moment's video_status to ready or failed. @@ -286,6 +289,8 @@ public function processVideoMoment(Media $media): void 'medium_url' => $media->getRawMediumUrl(), 'hls_url' => $media->getRawHlsUrl(), 'duration' => $media->duration, + 'width' => $media->width, + 'height' => $media->height, 'video_status' => VideoStatus::Ready, ]); } @@ -334,7 +339,8 @@ private function processVideo(Media $media): void ->export() ->getFrameContents(); - // Use GD to create resized versions + // Use GD to create resized versions. ffmpeg applies the rotation tag when it decodes (autorotate is on + // by default), so this frame and the width and height saved below are already the display size. $sourceImage = imagecreatefromstring($frameContent) ?: throw new \RuntimeException('Cannot decode the video frame'); $origWidth = imagesx($sourceImage); $origHeight = imagesy($sourceImage); diff --git a/kinlore-api/app/Services/SyncService.php b/kinlore-api/app/Services/SyncService.php index 319c4a6..fcf0c50 100644 --- a/kinlore-api/app/Services/SyncService.php +++ b/kinlore-api/app/Services/SyncService.php @@ -387,6 +387,8 @@ public function formatMomentForSync(Moment $moment): array 'latitude' => $moment->latitude, 'longitude' => $moment->longitude, 'orientation' => $moment->orientation, + 'width' => $moment->width, + 'height' => $moment->height, 'duration' => $moment->duration, 'video_status' => $moment->video_status?->value, 'height_cm' => $moment->height_cm, diff --git a/kinlore-api/database/migrations/2026_11_27_000001_add_moment_dimensions.php b/kinlore-api/database/migrations/2026_11_27_000001_add_moment_dimensions.php new file mode 100644 index 0000000..400923b --- /dev/null +++ b/kinlore-api/database/migrations/2026_11_27_000001_add_moment_dimensions.php @@ -0,0 +1,25 @@ +unsignedInteger('width')->nullable(); + $table->unsignedInteger('height')->nullable(); + }); + } + + public function down(): void + { + Schema::table('moments', fn (Blueprint $table) => $table->dropColumn(['width', 'height'])); + } +}; diff --git a/kinlore-api/openapi.yaml b/kinlore-api/openapi.yaml index 182d2b4..ea33d91 100644 --- a/kinlore-api/openapi.yaml +++ b/kinlore-api/openapi.yaml @@ -2237,6 +2237,14 @@ components: type: [integer, 'null'] minimum: 1 maximum: 8 + width: + type: [integer, 'null'] + minimum: 1 + description: Pixels as the photo or video is shown: after the EXIF orientation of a photo and the rotation of a video. `null` for story, growth and milestone moments, a video still processing, and an older photo or video that `kinlore:media-dimensions` has not filled. + height: + type: [integer, 'null'] + minimum: 1 + description: Pixels as shown. See `width`. camera_make: type: [string, 'null'] camera_model: @@ -2793,7 +2801,7 @@ components: SyncMomentRow: type: object description: All times in milliseconds. No file fields; the app uses `/file/{type}`. - required: [id, kid_id, user_id, uploader_name, moment_type, title, description, milestone_id, exif_date, latitude, longitude, orientation, duration, video_status, height_cm, weight_kg, head_circumference_cm, likes_count, comments_count, is_liked, file_size, mime_type, device_asset_id, created_at, updated_at] + required: [id, kid_id, user_id, uploader_name, moment_type, title, description, milestone_id, exif_date, latitude, longitude, orientation, width, height, duration, video_status, height_cm, weight_kg, head_circumference_cm, likes_count, comments_count, is_liked, file_size, mime_type, device_asset_id, created_at, updated_at] properties: id: type: string @@ -2822,6 +2830,14 @@ components: type: [number, 'null'] orientation: type: [integer, 'null'] + width: + type: [integer, 'null'] + minimum: 1 + description: Pixels as the photo or video is shown: after the EXIF orientation of a photo and the rotation of a video. `null` for story, growth and milestone moments, a video still processing, and an older photo or video that `kinlore:media-dimensions` has not filled. + height: + type: [integer, 'null'] + minimum: 1 + description: Pixels as shown. See `width`. duration: type: [number, 'null'] description: Seconds. diff --git a/kinlore-api/tests/Feature/MomentDimensionsTest.php b/kinlore-api/tests/Feature/MomentDimensionsTest.php new file mode 100644 index 0000000..7b7500d --- /dev/null +++ b/kinlore-api/tests/Feature/MomentDimensionsTest.php @@ -0,0 +1,233 @@ + [300, 400, null, 300, 400], + 'landscape' => [400, 300, null, 400, 300], + 'EXIF orientation 6 (stored landscape, shown portrait)' => [400, 300, 6, 300, 400], + ]; + } + + #[DataProvider('photos')] + public function test_photo_upload_stores_the_display_size(int $w, int $h, ?int $orientation, int $width, int $height): void + { + $kid = Kid::factory()->create(); + Sanctum::actingAs(User::factory()->create()); + $file = UploadedFile::fake()->createWithContent('photo.jpg', $this->jpeg($w, $h, $orientation)); + + $response = $this->post('/api/v1/moments', ['kid_id' => $kid->id, 'file' => $file], ['Accept' => 'application/json']) + ->assertStatus(201); + + $response->assertJsonPath('data.moment.width', $width)->assertJsonPath('data.moment.height', $height); + $this->assertSame([$width, $height], [Moment::sole()->width, Moment::sole()->height]); + } + + public function test_photo_wider_than_the_medium_keeps_its_full_size(): void + { + $user = User::factory()->create(); + $kid = Kid::factory()->create(); + $file = UploadedFile::fake()->createWithContent('big.jpg', $this->jpeg(1600, 900)); + + $moment = app(MomentService::class)->create($user, $kid, ['moment_type' => 'photo'], $file)['moment']; + + $this->assertSame([1600, 900], [$moment->width, $moment->height]); + } + + public function test_video_gets_the_size_of_its_decoded_frame(): void + { + // ffmpeg applies the rotation tag when it decodes, so a portrait phone video gives a portrait frame. + $media = $this->videoMedia(); + $this->fakeFfmpeg($media, 48, 64); + + app(MomentService::class)->processVideoMoment($media); + + $moment = $media->moments()->sole(); + $this->assertSame([48, 64], [$moment->width, $moment->height]); + } + + public function test_text_moments_have_no_size(): void + { + $kid = Kid::factory()->create(); + Sanctum::actingAs(User::factory()->create()); + + $this->postJson('/api/v1/moments', ['kid_id' => $kid->id, 'moment_type' => 'story', 'description' => 'First steps']) + ->assertStatus(201) + ->assertJsonPath('data.moment.width', null) + ->assertJsonPath('data.moment.height', null); + } + + public function test_moment_api_and_sync_pull_send_the_size(): void + { + $user = User::factory()->create(); + $kid = Kid::factory()->create(); + $photo = Moment::factory()->create(['kid_id' => $kid->id, 'moment_type' => 'photo', 'width' => 3024, 'height' => 4032]); + $story = Moment::factory()->create(['kid_id' => $kid->id, 'moment_type' => 'story', 'description' => 'Hi']); + Sanctum::actingAs($user); + + $this->getJson("/api/v1/moments/{$photo->id}")->assertOk() + ->assertJsonPath('data.width', 3024)->assertJsonPath('data.height', 4032); + + $rows = collect($this->postJson('/api/v1/sync/pull', ['lastPulledAt' => null])->assertOk() + ->json('changes.moments.created'))->keyBy('id'); + $this->assertSame([3024, 4032], [$rows[$photo->id]['width'], $rows[$photo->id]['height']]); + $this->assertArrayHasKey('width', $rows[$story->id]); + $this->assertNull($rows[$story->id]['width']); + $this->assertNull($rows[$story->id]['height']); + } + + public function test_backfill_fills_from_the_medium_or_video_metadata_and_skips_unreadable(): void + { + $kid = Kid::factory()->create(); + $photo = $this->oldMoment($kid, 'photo', 'media/a/medium.jpg'); + Storage::disk('seaweedfs')->put('media/a/medium.jpg', $this->jpeg(900, 1200)); + $broken = $this->oldMoment($kid, 'photo', 'media/b/medium.jpg'); + Storage::disk('seaweedfs')->put('media/b/medium.jpg', 'not an image'); + $missing = $this->oldMoment($kid, 'photo', 'media/c/medium.jpg'); + $video = $this->oldMoment($kid, 'video', 'media/d/medium.jpg', ['video_status' => 'ready']); + $video->media->update(['video_metadata' => ['duration' => 3, 'width' => 1080, 'height' => 1920]]); + $story = Moment::factory()->create(['kid_id' => $kid->id, 'moment_type' => 'story', 'description' => 'Hi']); + + $this->artisan('kinlore:media-dimensions', ['--dry-run' => true]) + ->expectsOutputToContain('Would fill 2 moments. Cannot read 2.')->assertSuccessful(); + $this->assertNull($photo->fresh()->width); + + $this->artisan('kinlore:media-dimensions')->expectsOutputToContain('Filled 2 moments. Cannot read 2.')->assertSuccessful(); + + $this->assertSame([900, 1200], [$photo->fresh()->width, $photo->fresh()->height]); + $this->assertSame([1080, 1920], [$video->fresh()->width, $video->fresh()->height]); + $this->assertNull($broken->fresh()->width); + $this->assertNull($missing->fresh()->width); + $this->assertNull($story->fresh()->width); + + // A second run changes nothing it filled before. + $this->artisan('kinlore:media-dimensions')->expectsOutputToContain('Filled 0 moments. Cannot read 2.')->assertSuccessful(); + } + + public function test_a_backfilled_moment_reaches_the_next_sync_pull_without_a_conflict(): void + { + $user = User::factory()->create(); + $kid = Kid::factory()->create(); + $photo = $this->oldMoment($kid, 'photo', 'media/a/medium.jpg'); + Storage::disk('seaweedfs')->put('media/a/medium.jpg', $this->jpeg(1200, 800)); + $editedAt = $photo->fresh()->edited_at; + $lastPulledAt = now()->getTimestampMs(); + $this->travel(5)->seconds(); + + $this->artisan('kinlore:media-dimensions')->assertSuccessful(); + + $this->assertEquals($editedAt, $photo->fresh()->edited_at); + Sanctum::actingAs($user); + $this->postJson('/api/v1/sync/pull', ['lastPulledAt' => $lastPulledAt])->assertOk() + ->assertJsonPath('changes.moments.updated.0.id', $photo->id) + ->assertJsonPath('changes.moments.updated.0.width', 1200) + ->assertJsonPath('changes.moments.updated.0.height', 800); + } + + /** A photo or video moment from before this update: no size, made an hour ago. */ + private function oldMoment(Kid $kid, string $type, string $mediumPath, array $extra = []): Moment + { + $this->travel(-1)->hours(); + $media = Media::create([ + 'kid_id' => $kid->id, + 'user_id' => $kid->user_id, + 'type' => $type, + 'original_filename' => 'x', + 'file_path' => dirname($mediumPath).'/original.jpg', + 'mime_type' => 'image/jpeg', + 'file_size' => 1, + 'status' => Media::STATUS_COMPLETED, + ]); + $moment = Moment::factory()->create(['kid_id' => $kid->id, 'media_id' => $media->id, 'moment_type' => $type, + 'medium_url' => $mediumPath, 'width' => null, 'height' => null] + $extra); + $this->travelBack(); + + return $moment; + } + + /** A JPEG of $width x $height pixels, with an EXIF Orientation tag when $orientation is given. */ + private function jpeg(int $width, int $height, ?int $orientation = null): string + { + ob_start(); + imagejpeg(imagecreatetruecolor($width, $height)); + $jpeg = ob_get_clean(); + if ($orientation === null) { + return $jpeg; + } + + // Big-endian TIFF with one IFD entry: tag 0x0112 (Orientation), type SHORT, count 1 + $tiff = "MM\x00\x2A\x00\x00\x00\x08\x00\x01\x01\x12\x00\x03\x00\x00\x00\x01".pack('n', $orientation)."\x00\x00\x00\x00\x00\x00"; + $app1 = "Exif\x00\x00".$tiff; + + return "\xFF\xD8\xFF\xE1".pack('n', strlen($app1) + 2).$app1.substr($jpeg, 2); + } + + // ffmpeg is not installed on every machine: the fake gives one frame and writes a one-file HLS stream. + private function fakeFfmpeg(Media $media, int $width, int $height): void + { + ob_start(); + imagejpeg(imagecreatetruecolor($width, $height)); + $frame = ob_get_clean(); + + $hls = Mockery::mock(); + $hls->shouldReceive('addFormat', 'setSegmentLength', 'toDisk')->andReturnSelf(); + $hls->shouldReceive('save')->andReturnUsing(fn () => Storage::disk('local')->put("tmp/video_{$media->id}/hls/playlist.m3u8", '#EXTM3U')); + $video = Mockery::mock(); + $video->shouldReceive('getDurationInSeconds')->andReturn(1); + $video->shouldReceive('getFrameFromSeconds->export->getFrameContents')->andReturn($frame); + $video->shouldReceive('exportForHLS')->andReturn($hls); + FFMpeg::shouldReceive('fromDisk->open')->andReturn($video); + } + + private function videoMedia(): Media + { + $kid = Kid::factory()->create(); + $id = (string) Str::uuid(); + $media = Media::create([ + 'id' => $id, + 'kid_id' => $kid->id, + 'user_id' => $kid->user_id, + 'type' => Media::TYPE_VIDEO, + 'original_filename' => 'clip.mov', + 'file_path' => "media/{$kid->id}/{$id}/original.mov", + 'mime_type' => 'video/quicktime', + 'file_size' => 5, + 'status' => Media::STATUS_PROCESSING, + ]); + Storage::disk('seaweedfs')->put($media->file_path, 'VIDEO'); + Moment::factory()->create(['kid_id' => $kid->id, 'media_id' => $media->id, 'moment_type' => 'video', 'video_status' => 'processing']); + + return $media; + } +}