From 296710efe0d743b5b923f6c8dfea3f6d90970380 Mon Sep 17 00:00:00 2001 From: imtia33 Date: Mon, 17 Aug 2026 15:52:20 +0600 Subject: [PATCH 01/10] feat: add support for fetching user gravatar --- docs/references/avatars/get-gravatar.md | 5 + .../Modules/Avatars/Http/Gravatar/Get.php | 152 ++++++++++++++++++ .../Modules/Avatars/Services/Http.php | 2 + tests/e2e/Services/Avatars/AvatarsBase.php | 103 ++++++++++++ 4 files changed, 262 insertions(+) create mode 100644 docs/references/avatars/get-gravatar.md create mode 100644 src/Appwrite/Platform/Modules/Avatars/Http/Gravatar/Get.php diff --git a/docs/references/avatars/get-gravatar.md b/docs/references/avatars/get-gravatar.md new file mode 100644 index 0000000000..df10dfb192 --- /dev/null +++ b/docs/references/avatars/get-gravatar.md @@ -0,0 +1,5 @@ +Use this endpoint to fetch a user's Gravatar avatar image. Gravatar is a globally-recognized avatar service that returns an avatar based on the SHA-256 hash of a user's email address. + +Pass an `email` address to fetch the Gravatar for that address, or leave it empty to use the currently signed-in user's email. If neither an `email` param nor an active session is provided, the request will fail. + +When the email has no associated Gravatar, the `default` parameter controls what is returned (e.g., a generated identicon, the mystery-person silhouette, or a `404` error). diff --git a/src/Appwrite/Platform/Modules/Avatars/Http/Gravatar/Get.php b/src/Appwrite/Platform/Modules/Avatars/Http/Gravatar/Get.php new file mode 100644 index 0000000000..0015e46cfb --- /dev/null +++ b/src/Appwrite/Platform/Modules/Avatars/Http/Gravatar/Get.php @@ -0,0 +1,152 @@ +setHttpMethod(UtopiaAction::HTTP_REQUEST_METHOD_GET) + ->setHttpPath('/v1/avatars/gravatar') + ->desc('Get user Gravatar') + ->groups(['api', 'avatars']) + ->label('scope', 'avatars.read') + ->label('cache', true) + ->label('cache.resource', 'avatar/gravatar') + ->label('cache.params', ['email', 'width', 'height', 'default', 'rating', 'project']) + ->label('sdk', new Method( + namespace: 'avatars', + group: null, + name: 'getGravatar', + description: '/docs/references/avatars/get-gravatar.md', + auth: [AuthType::ADMIN, AuthType::SESSION, AuthType::KEY, AuthType::JWT], + type: MethodType::LOCATION, + locationAuth: ['Project', 'ImpersonateUserId'], + responses: [ + new SDKResponse( + code: Response::STATUS_CODE_OK, + model: Response::MODEL_NONE, + ) + ], + contentType: ContentType::IMAGE + )) + ->param('email', '', new Email(), 'Email address. Pass an email address to fetch the Gravatar image for. When empty, the current user\'s email is used.', true) + ->param('width', 80, new Range(1, 2048), 'Image width. Pass an integer between 1 to 2048. Defaults to 80.', true) + ->param('height', 80, new Range(1, 2048), 'Image height. Pass an integer between 1 to 2048. Defaults to 80.', true) + ->param('default', 'mp', new WhiteList(['404', 'mp', 'identicon', 'monsterid', 'wavatar', 'retro', 'robohash', 'blank'], true), 'Default image to return when no Gravatar is found. Defaults to \'mp\'.', true) + ->param('rating', 'g', new WhiteList(['g', 'pg', 'r', 'x'], true), 'Maximum image rating to return. Defaults to \'g\'.', true) + ->inject('response') + ->inject('user') + ->callback($this->action(...)); + } + + public function action( + string $email, + int $width, + int $height, + string $default, + string $rating, + Response $response, + Document $user, + ): void { + if (!\extension_loaded('imagick')) { + throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Imagick extension is missing'); + } + + // Resolve the email: explicit param takes priority, then current user's email. + // If neither is available, the caller must supply one or be signed in. + if (!empty($email)) { + $resolvedEmail = $email; + } elseif (!$user->isEmpty()) { + $resolvedEmail = $user->getAttribute('email', ''); + } else { + throw new Exception(Exception::GENERAL_BAD_REQUEST, 'Either the \'email\' param or an active session is required.'); + } + + // Gravatar spec: SHA-256 of strtolower(trim($email)) + $hash = \hash('sha256', \strtolower(\trim($resolvedEmail))); + + $gravatarUrl = \sprintf( + 'https://www.gravatar.com/avatar/%s?s=%d&d=%s&r=%s', + $hash, + $width, + \urlencode($default), + \urlencode($rating), + ); + + $host = \parse_url($gravatarUrl, PHP_URL_HOST) ?? ''; + + $isIpLiteral = \filter_var(\trim($host, '[]'), FILTER_VALIDATE_IP) !== false; + if (!$isIpLiteral) { + $domain = new Domain($host); + if (!$domain->isKnown()) { + throw new Exception(Exception::AVATAR_REMOTE_URL_FAILED); + } + } + + $hostnameValidator = new PublicHostname(); + if (!$hostnameValidator->isValid($host)) { + throw new Exception(Exception::AVATAR_REMOTE_URL_FAILED, $hostnameValidator->getDescription()); + } + + $client = new Client(); + try { + $res = $client + ->setAllowRedirects(true) + ->fetch($gravatarUrl); + } catch (\Throwable) { + throw new Exception(Exception::AVATAR_REMOTE_URL_FAILED); + } + + if ($res->getStatusCode() === 404) { + throw new Exception(Exception::AVATAR_IMAGE_NOT_FOUND); + } + + if ($res->getStatusCode() !== 200) { + throw new Exception(Exception::AVATAR_REMOTE_URL_FAILED); + } + + try { + $image = new Image($res->getBody()); + } catch (\ImagickException) { + throw new Exception(Exception::AVATAR_IMAGE_NOT_FOUND); + } + + $image->crop($width, $height); + $data = $image->output('png', 80); + + $response + ->addHeader('Cache-Control', 'private, max-age=2592000') // 30 days + ->setContentType('image/png') + ->file($data); + unset($image); + } +} diff --git a/src/Appwrite/Platform/Modules/Avatars/Services/Http.php b/src/Appwrite/Platform/Modules/Avatars/Services/Http.php index c462b25ca9..f6b076608b 100644 --- a/src/Appwrite/Platform/Modules/Avatars/Services/Http.php +++ b/src/Appwrite/Platform/Modules/Avatars/Services/Http.php @@ -6,6 +6,7 @@ use Appwrite\Platform\Modules\Avatars\Http\Browsers\Get as GetBrowser; use Appwrite\Platform\Modules\Avatars\Http\CreditCards\Get as GetCreditCard; use Appwrite\Platform\Modules\Avatars\Http\Favicon\Get as GetFavicon; use Appwrite\Platform\Modules\Avatars\Http\Flags\Get as GetFlag; +use Appwrite\Platform\Modules\Avatars\Http\Gravatar\Get as GetGravatar; use Appwrite\Platform\Modules\Avatars\Http\Image\Get as GetImage; use Appwrite\Platform\Modules\Avatars\Http\Initials\Get as GetInitials; use Appwrite\Platform\Modules\Avatars\Http\QR\Get as GetQR; @@ -26,5 +27,6 @@ class Http extends Service $this->addAction(GetQR::getName(), new GetQR()); $this->addAction(GetInitials::getName(), new GetInitials()); $this->addAction(GetScreenshot::getName(), new GetScreenshot()); + $this->addAction(GetGravatar::getName(), new GetGravatar()); } } diff --git a/tests/e2e/Services/Avatars/AvatarsBase.php b/tests/e2e/Services/Avatars/AvatarsBase.php index 9a65b8070f..b096ca5a4a 100644 --- a/tests/e2e/Services/Avatars/AvatarsBase.php +++ b/tests/e2e/Services/Avatars/AvatarsBase.php @@ -1342,4 +1342,107 @@ trait AvatarsBase return []; } + + public function testGetGravatar(): array + { + /** + * Test for SUCCESS + */ + + // Explicit email param — uses eldad@appwrite.io (known Gravatar, stable for testing) + $this->assertEventually(function () { + $response = $this->client->call(Client::METHOD_GET, '/avatars/gravatar', [ + 'x-appwrite-project' => $this->getProject()['$id'], + ], [ + 'email' => 'eldad@appwrite.io', + 'width' => 200, + 'height' => 200, + ]); + + $this->assertEquals(200, $response['headers']['status-code']); + $this->assertEquals('image/png', $response['headers']['content-type']); + $this->assertNotEmpty($response['body']); + }, 30_000, 2_000); + + // Default size with identicon — deterministic for any unknown email + $this->assertEventually(function () { + $response = $this->client->call(Client::METHOD_GET, '/avatars/gravatar', [ + 'x-appwrite-project' => $this->getProject()['$id'], + ], [ + 'email' => 'no-gravatar-' . \uniqid() . '@example.com', + 'default' => 'identicon', + ]); + + $this->assertEquals(200, $response['headers']['status-code']); + $this->assertEquals('image/png', $response['headers']['content-type']); + $this->assertNotEmpty($response['body']); + }, 30_000, 2_000); + + // Session-based default: no email param, uses current user's email. + // Only meaningful in client/console mode where $user is populated. + if ($this->getSide() === 'client') { + $this->assertEventually(function () { + $response = $this->client->call(Client::METHOD_GET, '/avatars/gravatar', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), []); + + $this->assertEquals(200, $response['headers']['status-code']); + $this->assertEquals('image/png', $response['headers']['content-type']); + $this->assertNotEmpty($response['body']); + }, 30_000, 2_000); + } + + /** + * Test for FAILURE + */ + + // Invalid email format → 400 (rejected by Email validator before action runs) + $response = $this->client->call(Client::METHOD_GET, '/avatars/gravatar', [ + 'x-appwrite-project' => $this->getProject()['$id'], + ], [ + 'email' => 'not-an-email', + ]); + $this->assertEquals(400, $response['headers']['status-code']); + + // Out-of-range width → 400 + $response = $this->client->call(Client::METHOD_GET, '/avatars/gravatar', [ + 'x-appwrite-project' => $this->getProject()['$id'], + ], [ + 'email' => 'eldad@appwrite.io', + 'width' => 2049, + ]); + $this->assertEquals(400, $response['headers']['status-code']); + + // Invalid default → 400 + $response = $this->client->call(Client::METHOD_GET, '/avatars/gravatar', [ + 'x-appwrite-project' => $this->getProject()['$id'], + ], [ + 'email' => 'eldad@appwrite.io', + 'default' => 'invalid', + ]); + $this->assertEquals(400, $response['headers']['status-code']); + + // Invalid rating → 400 + $response = $this->client->call(Client::METHOD_GET, '/avatars/gravatar', [ + 'x-appwrite-project' => $this->getProject()['$id'], + ], [ + 'email' => 'eldad@appwrite.io', + 'rating' => 'invalid', + ]); + $this->assertEquals(400, $response['headers']['status-code']); + + // default=404 with unknown email → 404 with avatar_image_not_found + $this->assertEventually(function () { + $response = $this->client->call(Client::METHOD_GET, '/avatars/gravatar', [ + 'x-appwrite-project' => $this->getProject()['$id'], + ], [ + 'email' => 'no-gravatar-' . \uniqid() . '@example.com', + 'default' => '404', + ]); + $this->assertEquals(404, $response['headers']['status-code']); + $this->assertEquals(Exception::AVATAR_IMAGE_NOT_FOUND, $response['body']['type']); + }, 30_000, 2_000); + + return []; + } } From e38831ad2b3634b667c3f4862a0c0c2a83530513 Mon Sep 17 00:00:00 2001 From: imtia33 Date: Mon, 17 Aug 2026 16:18:25 +0600 Subject: [PATCH 02/10] update: apply maintainer feedback for caching --- src/Appwrite/Platform/Modules/Avatars/Http/Gravatar/Get.php | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/Appwrite/Platform/Modules/Avatars/Http/Gravatar/Get.php b/src/Appwrite/Platform/Modules/Avatars/Http/Gravatar/Get.php index 0015e46cfb..05f3fac0ad 100644 --- a/src/Appwrite/Platform/Modules/Avatars/Http/Gravatar/Get.php +++ b/src/Appwrite/Platform/Modules/Avatars/Http/Gravatar/Get.php @@ -39,9 +39,6 @@ class Get extends Action ->desc('Get user Gravatar') ->groups(['api', 'avatars']) ->label('scope', 'avatars.read') - ->label('cache', true) - ->label('cache.resource', 'avatar/gravatar') - ->label('cache.params', ['email', 'width', 'height', 'default', 'rating', 'project']) ->label('sdk', new Method( namespace: 'avatars', group: null, @@ -144,7 +141,7 @@ class Get extends Action $data = $image->output('png', 80); $response - ->addHeader('Cache-Control', 'private, max-age=2592000') // 30 days + ->addHeader('Cache-Control', 'public, max-age=60') // 1 minute ->setContentType('image/png') ->file($data); unset($image); From 4eb87992f78f89a730a170ef399ea63f5e2f835d Mon Sep 17 00:00:00 2001 From: imtia33 Date: Mon, 17 Aug 2026 16:37:21 +0600 Subject: [PATCH 03/10] fix: change cache-control to private to prevent CDN session leakage --- src/Appwrite/Platform/Modules/Avatars/Http/Gravatar/Get.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Appwrite/Platform/Modules/Avatars/Http/Gravatar/Get.php b/src/Appwrite/Platform/Modules/Avatars/Http/Gravatar/Get.php index 05f3fac0ad..e54d5398d2 100644 --- a/src/Appwrite/Platform/Modules/Avatars/Http/Gravatar/Get.php +++ b/src/Appwrite/Platform/Modules/Avatars/Http/Gravatar/Get.php @@ -141,7 +141,7 @@ class Get extends Action $data = $image->output('png', 80); $response - ->addHeader('Cache-Control', 'public, max-age=60') // 1 minute + ->addHeader('Cache-Control', 'private, max-age=60') // 1 minute ->setContentType('image/png') ->file($data); unset($image); From b763a4dbbf1f25ebd38fa8dbd6a73a9d3d4d47c1 Mon Sep 17 00:00:00 2001 From: imtia33 Date: Mon, 17 Aug 2026 18:22:52 +0600 Subject: [PATCH 04/10] refactor: apply feedback for gravatar implementation --- docs/references/avatars/get-gravatar.md | 5 -- .../Modules/Avatars/Http/Gravatar/Get.php | 47 ++----------------- tests/e2e/Services/Avatars/AvatarsBase.php | 15 ++---- 3 files changed, 7 insertions(+), 60 deletions(-) delete mode 100644 docs/references/avatars/get-gravatar.md diff --git a/docs/references/avatars/get-gravatar.md b/docs/references/avatars/get-gravatar.md deleted file mode 100644 index df10dfb192..0000000000 --- a/docs/references/avatars/get-gravatar.md +++ /dev/null @@ -1,5 +0,0 @@ -Use this endpoint to fetch a user's Gravatar avatar image. Gravatar is a globally-recognized avatar service that returns an avatar based on the SHA-256 hash of a user's email address. - -Pass an `email` address to fetch the Gravatar for that address, or leave it empty to use the currently signed-in user's email. If neither an `email` param nor an active session is provided, the request will fail. - -When the email has no associated Gravatar, the `default` parameter controls what is returned (e.g., a generated identicon, the mystery-person silhouette, or a `404` error). diff --git a/src/Appwrite/Platform/Modules/Avatars/Http/Gravatar/Get.php b/src/Appwrite/Platform/Modules/Avatars/Http/Gravatar/Get.php index e54d5398d2..e5e365f0ca 100644 --- a/src/Appwrite/Platform/Modules/Avatars/Http/Gravatar/Get.php +++ b/src/Appwrite/Platform/Modules/Avatars/Http/Gravatar/Get.php @@ -28,7 +28,7 @@ class Get extends Action public static function getName(): string { - return 'getGravatar'; + return 'getAvatarsGravatar'; } public function __construct() @@ -43,7 +43,7 @@ class Get extends Action namespace: 'avatars', group: null, name: 'getGravatar', - description: '/docs/references/avatars/get-gravatar.md', + description: 'You can use this endpoint to show a Gravatar image for a user by providing their email address. If no email is provided, the Gravatar for the currently authenticated user is returned. The fallback image and maximum rating can be customized.', auth: [AuthType::ADMIN, AuthType::SESSION, AuthType::KEY, AuthType::JWT], type: MethodType::LOCATION, locationAuth: ['Project', 'ImpersonateUserId'], @@ -56,8 +56,6 @@ class Get extends Action contentType: ContentType::IMAGE )) ->param('email', '', new Email(), 'Email address. Pass an email address to fetch the Gravatar image for. When empty, the current user\'s email is used.', true) - ->param('width', 80, new Range(1, 2048), 'Image width. Pass an integer between 1 to 2048. Defaults to 80.', true) - ->param('height', 80, new Range(1, 2048), 'Image height. Pass an integer between 1 to 2048. Defaults to 80.', true) ->param('default', 'mp', new WhiteList(['404', 'mp', 'identicon', 'monsterid', 'wavatar', 'retro', 'robohash', 'blank'], true), 'Default image to return when no Gravatar is found. Defaults to \'mp\'.', true) ->param('rating', 'g', new WhiteList(['g', 'pg', 'r', 'x'], true), 'Maximum image rating to return. Defaults to \'g\'.', true) ->inject('response') @@ -67,17 +65,11 @@ class Get extends Action public function action( string $email, - int $width, - int $height, string $default, string $rating, Response $response, Document $user, ): void { - if (!\extension_loaded('imagick')) { - throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Imagick extension is missing'); - } - // Resolve the email: explicit param takes priority, then current user's email. // If neither is available, the caller must supply one or be signed in. if (!empty($email)) { @@ -91,28 +83,7 @@ class Get extends Action // Gravatar spec: SHA-256 of strtolower(trim($email)) $hash = \hash('sha256', \strtolower(\trim($resolvedEmail))); - $gravatarUrl = \sprintf( - 'https://www.gravatar.com/avatar/%s?s=%d&d=%s&r=%s', - $hash, - $width, - \urlencode($default), - \urlencode($rating), - ); - - $host = \parse_url($gravatarUrl, PHP_URL_HOST) ?? ''; - - $isIpLiteral = \filter_var(\trim($host, '[]'), FILTER_VALIDATE_IP) !== false; - if (!$isIpLiteral) { - $domain = new Domain($host); - if (!$domain->isKnown()) { - throw new Exception(Exception::AVATAR_REMOTE_URL_FAILED); - } - } - - $hostnameValidator = new PublicHostname(); - if (!$hostnameValidator->isValid($host)) { - throw new Exception(Exception::AVATAR_REMOTE_URL_FAILED, $hostnameValidator->getDescription()); - } + $gravatarUrl = 'https://www.gravatar.com/avatar/' . $hash . '?s=256&d=' . \urlencode($default) . '&r=' . \urlencode($rating); $client = new Client(); try { @@ -131,19 +102,9 @@ class Get extends Action throw new Exception(Exception::AVATAR_REMOTE_URL_FAILED); } - try { - $image = new Image($res->getBody()); - } catch (\ImagickException) { - throw new Exception(Exception::AVATAR_IMAGE_NOT_FOUND); - } - - $image->crop($width, $height); - $data = $image->output('png', 80); - $response ->addHeader('Cache-Control', 'private, max-age=60') // 1 minute ->setContentType('image/png') - ->file($data); - unset($image); + ->file($res->getBody()); } } diff --git a/tests/e2e/Services/Avatars/AvatarsBase.php b/tests/e2e/Services/Avatars/AvatarsBase.php index b096ca5a4a..25691bafc0 100644 --- a/tests/e2e/Services/Avatars/AvatarsBase.php +++ b/tests/e2e/Services/Avatars/AvatarsBase.php @@ -1355,13 +1355,12 @@ trait AvatarsBase 'x-appwrite-project' => $this->getProject()['$id'], ], [ 'email' => 'eldad@appwrite.io', - 'width' => 200, - 'height' => 200, ]); $this->assertEquals(200, $response['headers']['status-code']); $this->assertEquals('image/png', $response['headers']['content-type']); $this->assertNotEmpty($response['body']); + $this->assertEquals('c37bfe56394ab0f359cb3977eb2ada39', \md5($response['body'])); }, 30_000, 2_000); // Default size with identicon — deterministic for any unknown email @@ -1369,13 +1368,14 @@ trait AvatarsBase $response = $this->client->call(Client::METHOD_GET, '/avatars/gravatar', [ 'x-appwrite-project' => $this->getProject()['$id'], ], [ - 'email' => 'no-gravatar-' . \uniqid() . '@example.com', + 'email' => 'no-gravatar-test@example.com', 'default' => 'identicon', ]); $this->assertEquals(200, $response['headers']['status-code']); $this->assertEquals('image/png', $response['headers']['content-type']); $this->assertNotEmpty($response['body']); + $this->assertEquals('5b8f150824ca586569a2606b41a16c6f', \md5($response['body'])); }, 30_000, 2_000); // Session-based default: no email param, uses current user's email. @@ -1404,15 +1404,6 @@ trait AvatarsBase ]); $this->assertEquals(400, $response['headers']['status-code']); - // Out-of-range width → 400 - $response = $this->client->call(Client::METHOD_GET, '/avatars/gravatar', [ - 'x-appwrite-project' => $this->getProject()['$id'], - ], [ - 'email' => 'eldad@appwrite.io', - 'width' => 2049, - ]); - $this->assertEquals(400, $response['headers']['status-code']); - // Invalid default → 400 $response = $this->client->call(Client::METHOD_GET, '/avatars/gravatar', [ 'x-appwrite-project' => $this->getProject()['$id'], From e8dd33f5b67e476ec0b53ad469a5ff825ae6c2c0 Mon Sep 17 00:00:00 2001 From: imtia33 Date: Mon, 17 Aug 2026 21:39:31 +0600 Subject: [PATCH 05/10] Moved to new provider architecture for custom avatar --- .../AvatarPhotos/Gravatar/Provider.php | 53 +++++ .../AvatarPhotos/Initials/Provider.php | 107 ++++++++++ .../AvatarPhotos/Libavatar/Provider.php | 60 ++++++ src/Appwrite/AvatarPhotos/Photo.php | 133 +++++++++++++ src/Appwrite/AvatarPhotos/Static/Provider.php | 68 +++++++ .../Modules/Avatars/Http/Gravatar/Get.php | 110 ----------- .../Modules/Avatars/Http/Photo/Get.php | 103 ++++++++++ .../Modules/Avatars/Services/Http.php | 6 +- tests/e2e/Services/Avatars/AvatarsBase.php | 186 ++++++++++++------ 9 files changed, 649 insertions(+), 177 deletions(-) create mode 100644 src/Appwrite/AvatarPhotos/Gravatar/Provider.php create mode 100644 src/Appwrite/AvatarPhotos/Initials/Provider.php create mode 100644 src/Appwrite/AvatarPhotos/Libavatar/Provider.php create mode 100644 src/Appwrite/AvatarPhotos/Photo.php create mode 100644 src/Appwrite/AvatarPhotos/Static/Provider.php delete mode 100644 src/Appwrite/Platform/Modules/Avatars/Http/Gravatar/Get.php create mode 100644 src/Appwrite/Platform/Modules/Avatars/Http/Photo/Get.php diff --git a/src/Appwrite/AvatarPhotos/Gravatar/Provider.php b/src/Appwrite/AvatarPhotos/Gravatar/Provider.php new file mode 100644 index 0000000000..c4fabd19b2 --- /dev/null +++ b/src/Appwrite/AvatarPhotos/Gravatar/Provider.php @@ -0,0 +1,53 @@ +setAllowRedirects(true) + ->fetch($url); + } catch (\Throwable) { + return null; + } + + if ($res->getStatusCode() !== 200) { + return null; + } + + $body = $res->getBody(); + if (empty($body)) { + return null; + } + + return $body; + } +} diff --git a/src/Appwrite/AvatarPhotos/Initials/Provider.php b/src/Appwrite/AvatarPhotos/Initials/Provider.php new file mode 100644 index 0000000000..d98916c5a0 --- /dev/null +++ b/src/Appwrite/AvatarPhotos/Initials/Provider.php @@ -0,0 +1,107 @@ + '#FD366E'], // Pink + ['background' => '#FE9567'], // Orange + ['background' => '#7C67FE'], // Purple + ['background' => '#68A3FE'], // Blue + ['background' => '#85DBD8'], // Mint + ]; + + public function __construct(string $appRoot) + { + $this->appRoot = $appRoot; + } + + /** + * Generate an initials avatar image. + * + * @param string $name Full name or email to derive initials from. + * When empty or blank, returns null so the caller + * moves on to the next (static fallback) provider. + * @param int $width Canvas width in pixels. + * @param int $height Canvas height in pixels. + * @param string $background Optional hex colour (without #). Empty = auto. + * @return string|null Raw PNG bytes, or null when no name/email is available. + */ + public function get(string $name, int $width = 500, int $height = 500, string $background = ''): ?string + { + if (empty(\trim($name))) { + return null; + } + + $words = \explode(' ', \strtoupper($name)); + // Fallback: split on underscores when there is no space + $words = (\count($words) === 1) ? \explode('_', \strtoupper($name)) : $words; + + $initials = ''; + $code = 0; + + foreach ($words as $key => $w) { + if (\ctype_alnum($w[0] ?? '')) { + $initials .= $w[0]; + $code += \ord($w[0]); + + if ($key === 1) { + break; + } + } + } + + // If we still have no printable initials, bail out so the static + // fallback can be used instead. + if (empty($initials)) { + return null; + } + + $rand = (int) \substr((string) $code, -1); + $rand = ($rand > \count($this->themes) - 1) ? $rand % \count($this->themes) : $rand; + + $bg = (!empty($background)) ? '#' . \ltrim($background, '#') : $this->themes[$rand]['background']; + + $image = new Imagick(); + $punch = new Imagick(); + $draw = new ImagickDraw(); + + $fontSize = \min($width, $height) / 2; + + $punch->newImage($width, $height, 'transparent'); + + $fontPath = $this->appRoot . '/app/assets/fonts/inter-v8-latin-regular.woff2'; + $draw->setFont($fontPath); + $image->setFont($fontPath); + + $draw->setFillColor(new ImagickPixel('black')); + $draw->setFontSize($fontSize); + $draw->setTextAlignment(Imagick::ALIGN_CENTER); + $draw->annotation($width / 1.97, ($height / 2) + ($fontSize / 3), $initials); + + $punch->drawImage($draw); + $punch->negateImage(true, Imagick::CHANNEL_ALPHA); + + $image->newImage($width, $height, $bg); + $image->setImageFormat('png'); + $image->compositeImage($punch, Imagick::COMPOSITE_COPYOPACITY, 0, 0); + + return $image->getImageBlob(); + } +} diff --git a/src/Appwrite/AvatarPhotos/Libavatar/Provider.php b/src/Appwrite/AvatarPhotos/Libavatar/Provider.php new file mode 100644 index 0000000000..cd9a6e2332 --- /dev/null +++ b/src/Appwrite/AvatarPhotos/Libavatar/Provider.php @@ -0,0 +1,60 @@ +setAllowRedirects(true) + ->fetch($url); + } catch (\Throwable) { + return null; + } + + if ($res->getStatusCode() !== 200) { + return null; + } + + $body = $res->getBody(); + if (empty($body)) { + return null; + } + + return $body; + } +} diff --git a/src/Appwrite/AvatarPhotos/Photo.php b/src/Appwrite/AvatarPhotos/Photo.php new file mode 100644 index 0000000000..6788e9c1a4 --- /dev/null +++ b/src/Appwrite/AvatarPhotos/Photo.php @@ -0,0 +1,133 @@ +gravatar = new GravatarProvider(); + $this->libavatar = new LibavatarProvider(); + $this->initials = new InitialsProvider($appRoot); + $this->static = new StaticProvider(); + } + + /** + * Resolve and return the best available avatar for the given user data. + * + * @param string $email User's email address (may be empty). + * @param string $name User's display name (may be empty). + * @param int $width Desired output width in pixels. + * @param int $height Desired output height in pixels. + * @param int $quality Output quality 0–100. + * @param string $output Output format: 'png' | 'jpg' | 'webp'. + * @param string $rating Gravatar/Libravatar rating: 'g' | 'pg' | 'r' | 'x'. + * @param string $background Optional hex background for the Initials provider. + * @return string Raw image bytes in the requested $output format. + */ + public function resolve( + string $email, + string $name, + int $width = 256, + int $height = 256, + int $quality = 100, + string $output = 'png', + string $rating = 'g', + string $background = '', + ): string { + // ------------------------------------------------------------------- + // Priority 1: OAuth2 session photo + // TODO: Resolve profile photo from the user's active OAuth2 token. + // Each OAuth2 provider (Google, GitHub, …) exposes a profile- + // picture URL. Fetch it here and short-circuit the chain. + // Track in: https://github.com/appwrite/appwrite/issues/TODO + // ------------------------------------------------------------------- + + // ------------------------------------------------------------------- + // Priority 2: Gravatar + // ------------------------------------------------------------------- + if (!empty($email)) { + $raw = $this->gravatar->get($email, $rating); + if ($raw !== null) { + return $this->process($raw, $width, $height, $quality, $output); + } + } + + // ------------------------------------------------------------------- + // Priority 3: Libravatar + // ------------------------------------------------------------------- + if (!empty($email)) { + $raw = $this->libavatar->get($email, $rating); + if ($raw !== null) { + return $this->process($raw, $width, $height, $quality, $output); + } + } + + // ------------------------------------------------------------------- + // Priority 4: Initials + // Prefer name; fall back to email prefix when name is absent. + // ------------------------------------------------------------------- + $initialsInput = !empty($name) ? $name : $email; + if (!empty($initialsInput)) { + $raw = $this->initials->get($initialsInput, $width, $height, $background); + if ($raw !== null) { + // Initials PNG is already sized correctly — just re-encode if + // a different format or quality was requested. + return $this->process($raw, $width, $height, $quality, $output); + } + } + + // ------------------------------------------------------------------- + // Priority 5: Static fallback — always succeeds + // ------------------------------------------------------------------- + $raw = $this->static->get($width, $height); + return $this->process($raw, $width, $height, $quality, $output); + } + + /** + * Resize and re-encode raw image bytes. + */ + private function process(string $raw, int $width, int $height, int $quality, string $output): string + { + if (!\extension_loaded('imagick') || empty($raw)) { + return $raw; + } + + try { + $image = new Image($raw); + if ($width > 0 || $height > 0) { + $image->crop( + $width > 0 ? $width : 256, + $height > 0 ? $height : 256, + ); + } + return $image->output($output, $quality); + } catch (\Throwable) { + return $raw; + } + } +} diff --git a/src/Appwrite/AvatarPhotos/Static/Provider.php b/src/Appwrite/AvatarPhotos/Static/Provider.php new file mode 100644 index 0000000000..f9af02a083 --- /dev/null +++ b/src/Appwrite/AvatarPhotos/Static/Provider.php @@ -0,0 +1,68 @@ +buildSvg($width, $height); + + if (\extension_loaded('imagick')) { + try { + $imagick = new \Imagick(); + $imagick->setBackgroundColor(new \ImagickPixel('transparent')); + $imagick->readImageBlob($svg); + $imagick->setImageFormat('png'); + $imagick->resizeImage($width, $height, \Imagick::FILTER_LANCZOS, 1); + return $imagick->getImageBlob(); + } catch (\Throwable) { + // Fall through to raw SVG on Imagick failure. + } + } + + // Last resort: return the SVG bytes directly. The HTTP action sets + // the content-type header to image/png, so this branch should be + // considered a degraded path. + return $svg; + } + + /** + * Build the SVG source for the fallback silhouette. + */ + private function buildSvg(int $width, int $height): string + { + return << + + + + + + +SVG; + } +} diff --git a/src/Appwrite/Platform/Modules/Avatars/Http/Gravatar/Get.php b/src/Appwrite/Platform/Modules/Avatars/Http/Gravatar/Get.php deleted file mode 100644 index e5e365f0ca..0000000000 --- a/src/Appwrite/Platform/Modules/Avatars/Http/Gravatar/Get.php +++ /dev/null @@ -1,110 +0,0 @@ -setHttpMethod(UtopiaAction::HTTP_REQUEST_METHOD_GET) - ->setHttpPath('/v1/avatars/gravatar') - ->desc('Get user Gravatar') - ->groups(['api', 'avatars']) - ->label('scope', 'avatars.read') - ->label('sdk', new Method( - namespace: 'avatars', - group: null, - name: 'getGravatar', - description: 'You can use this endpoint to show a Gravatar image for a user by providing their email address. If no email is provided, the Gravatar for the currently authenticated user is returned. The fallback image and maximum rating can be customized.', - auth: [AuthType::ADMIN, AuthType::SESSION, AuthType::KEY, AuthType::JWT], - type: MethodType::LOCATION, - locationAuth: ['Project', 'ImpersonateUserId'], - responses: [ - new SDKResponse( - code: Response::STATUS_CODE_OK, - model: Response::MODEL_NONE, - ) - ], - contentType: ContentType::IMAGE - )) - ->param('email', '', new Email(), 'Email address. Pass an email address to fetch the Gravatar image for. When empty, the current user\'s email is used.', true) - ->param('default', 'mp', new WhiteList(['404', 'mp', 'identicon', 'monsterid', 'wavatar', 'retro', 'robohash', 'blank'], true), 'Default image to return when no Gravatar is found. Defaults to \'mp\'.', true) - ->param('rating', 'g', new WhiteList(['g', 'pg', 'r', 'x'], true), 'Maximum image rating to return. Defaults to \'g\'.', true) - ->inject('response') - ->inject('user') - ->callback($this->action(...)); - } - - public function action( - string $email, - string $default, - string $rating, - Response $response, - Document $user, - ): void { - // Resolve the email: explicit param takes priority, then current user's email. - // If neither is available, the caller must supply one or be signed in. - if (!empty($email)) { - $resolvedEmail = $email; - } elseif (!$user->isEmpty()) { - $resolvedEmail = $user->getAttribute('email', ''); - } else { - throw new Exception(Exception::GENERAL_BAD_REQUEST, 'Either the \'email\' param or an active session is required.'); - } - - // Gravatar spec: SHA-256 of strtolower(trim($email)) - $hash = \hash('sha256', \strtolower(\trim($resolvedEmail))); - - $gravatarUrl = 'https://www.gravatar.com/avatar/' . $hash . '?s=256&d=' . \urlencode($default) . '&r=' . \urlencode($rating); - - $client = new Client(); - try { - $res = $client - ->setAllowRedirects(true) - ->fetch($gravatarUrl); - } catch (\Throwable) { - throw new Exception(Exception::AVATAR_REMOTE_URL_FAILED); - } - - if ($res->getStatusCode() === 404) { - throw new Exception(Exception::AVATAR_IMAGE_NOT_FOUND); - } - - if ($res->getStatusCode() !== 200) { - throw new Exception(Exception::AVATAR_REMOTE_URL_FAILED); - } - - $response - ->addHeader('Cache-Control', 'private, max-age=60') // 1 minute - ->setContentType('image/png') - ->file($res->getBody()); - } -} diff --git a/src/Appwrite/Platform/Modules/Avatars/Http/Photo/Get.php b/src/Appwrite/Platform/Modules/Avatars/Http/Photo/Get.php new file mode 100644 index 0000000000..1134147729 --- /dev/null +++ b/src/Appwrite/Platform/Modules/Avatars/Http/Photo/Get.php @@ -0,0 +1,103 @@ +setHttpMethod(UtopiaAction::HTTP_REQUEST_METHOD_GET) + ->setHttpPath('/v1/avatars/photo') + ->desc('Get user photo') + ->groups(['api', 'avatars']) + ->label('scope', 'avatars.read') + ->label('sdk', new Method( + namespace: 'avatars', + group: null, + name: 'getPhoto', + description: 'Returns the best available profile photo for the currently authenticated user. ' + . 'The endpoint tries each source in priority order and returns the first successful result: ' + . '(1) OAuth2 session photo (planned — see TODO in source), ' + . '(2) Gravatar, ' + . '(3) Libravatar, ' + . '(4) initials generated from the user\'s name or email, ' + . '(5) a built-in static fallback image.', + auth: [AuthType::ADMIN, AuthType::SESSION, AuthType::KEY, AuthType::JWT], + type: MethodType::LOCATION, + locationAuth: ['Project', 'ImpersonateUserId'], + responses: [ + new SDKResponse( + code: Response::STATUS_CODE_OK, + model: Response::MODEL_NONE, + ) + ], + contentType: ContentType::IMAGE + )) + ->param('width', 256, new Range(0, 2000), 'Output image width in pixels. Pass an integer between 0 and 2000. Defaults to 256.', true) + ->param('height', 256, new Range(0, 2000), 'Output image height in pixels. Pass an integer between 0 and 2000. Defaults to 256.', true) + ->param('quality', 100, new Range(0, 100), 'Output image quality between 0 and 100. Defaults to 100.', true) + ->param('output', 'png', new WhiteList(['png', 'jpg', 'webp'], true), 'Output image format. Defaults to \'png\'.', true) + ->param('rating', 'g', new WhiteList(['g', 'pg', 'r', 'x'], true), 'Maximum image rating to fetch from Gravatar/Libravatar. Defaults to \'g\'.', true) + ->inject('response') + ->inject('user') + ->callback($this->action(...)); + } + + public function action( + int $width, + int $height, + int $quality, + string $output, + string $rating, + Response $response, + Document $user, + ): void { + $email = $user->getAttribute('email', ''); + $name = $user->getAttribute('name', ''); + + $photo = new Photo($this->getAppRoot()); + + $data = $photo->resolve( + email: $email, + name: $name, + width: $width, + height: $height, + quality: $quality, + output: $output, + rating: $rating, + ); + + $contentType = match ($output) { + 'jpg' => 'image/jpeg', + 'webp' => 'image/webp', + default => 'image/png', + }; + + $response + ->addHeader('Cache-Control', 'private, max-age=60') // 1 minute — photo may change + ->setContentType($contentType) + ->file($data); + } +} diff --git a/src/Appwrite/Platform/Modules/Avatars/Services/Http.php b/src/Appwrite/Platform/Modules/Avatars/Services/Http.php index f6b076608b..24c57cba8d 100644 --- a/src/Appwrite/Platform/Modules/Avatars/Services/Http.php +++ b/src/Appwrite/Platform/Modules/Avatars/Services/Http.php @@ -6,7 +6,8 @@ use Appwrite\Platform\Modules\Avatars\Http\Browsers\Get as GetBrowser; use Appwrite\Platform\Modules\Avatars\Http\CreditCards\Get as GetCreditCard; use Appwrite\Platform\Modules\Avatars\Http\Favicon\Get as GetFavicon; use Appwrite\Platform\Modules\Avatars\Http\Flags\Get as GetFlag; -use Appwrite\Platform\Modules\Avatars\Http\Gravatar\Get as GetGravatar; + +use Appwrite\Platform\Modules\Avatars\Http\Photo\Get as GetPhoto; use Appwrite\Platform\Modules\Avatars\Http\Image\Get as GetImage; use Appwrite\Platform\Modules\Avatars\Http\Initials\Get as GetInitials; use Appwrite\Platform\Modules\Avatars\Http\QR\Get as GetQR; @@ -27,6 +28,7 @@ class Http extends Service $this->addAction(GetQR::getName(), new GetQR()); $this->addAction(GetInitials::getName(), new GetInitials()); $this->addAction(GetScreenshot::getName(), new GetScreenshot()); - $this->addAction(GetGravatar::getName(), new GetGravatar()); + + $this->addAction(GetPhoto::getName(), new GetPhoto()); } } diff --git a/tests/e2e/Services/Avatars/AvatarsBase.php b/tests/e2e/Services/Avatars/AvatarsBase.php index 25691bafc0..027b8fd516 100644 --- a/tests/e2e/Services/Avatars/AvatarsBase.php +++ b/tests/e2e/Services/Avatars/AvatarsBase.php @@ -1343,96 +1343,152 @@ trait AvatarsBase return []; } - public function testGetGravatar(): array + + + public function testGetPhoto(): array { /** - * Test for SUCCESS + * Test for SUCCESS — authenticated user (client side) + * + * The endpoint always returns an image: even when no Gravatar/Libravatar + * avatar exists it falls back to initials or the static placeholder, so + * we always expect HTTP 200. */ - // Explicit email param — uses eldad@appwrite.io (known Gravatar, stable for testing) - $this->assertEventually(function () { - $response = $this->client->call(Client::METHOD_GET, '/avatars/gravatar', [ - 'x-appwrite-project' => $this->getProject()['$id'], - ], [ - 'email' => 'eldad@appwrite.io', - ]); + // Default call — uses session user; falls through priority chain and + // returns some image (initials or static fallback at minimum). + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), []); - $this->assertEquals(200, $response['headers']['status-code']); - $this->assertEquals('image/png', $response['headers']['content-type']); - $this->assertNotEmpty($response['body']); - $this->assertEquals('c37bfe56394ab0f359cb3977eb2ada39', \md5($response['body'])); - }, 30_000, 2_000); + $this->assertEquals(200, $response['headers']['status-code']); + $this->assertEquals('image/png', $response['headers']['content-type']); + $this->assertNotEmpty($response['body']); - // Default size with identicon — deterministic for any unknown email - $this->assertEventually(function () { - $response = $this->client->call(Client::METHOD_GET, '/avatars/gravatar', [ - 'x-appwrite-project' => $this->getProject()['$id'], - ], [ - 'email' => 'no-gravatar-test@example.com', - 'default' => 'identicon', - ]); + // Width + height + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'width' => 128, + 'height' => 128, + ]); - $this->assertEquals(200, $response['headers']['status-code']); - $this->assertEquals('image/png', $response['headers']['content-type']); - $this->assertNotEmpty($response['body']); - $this->assertEquals('5b8f150824ca586569a2606b41a16c6f', \md5($response['body'])); - }, 30_000, 2_000); + $this->assertEquals(200, $response['headers']['status-code']); + $this->assertEquals('image/png', $response['headers']['content-type']); + $this->assertNotEmpty($response['body']); - // Session-based default: no email param, uses current user's email. - // Only meaningful in client/console mode where $user is populated. - if ($this->getSide() === 'client') { - $this->assertEventually(function () { - $response = $this->client->call(Client::METHOD_GET, '/avatars/gravatar', \array_merge([ - 'x-appwrite-project' => $this->getProject()['$id'], - ], $this->getHeaders()), []); + // Quality param + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'width' => 200, + 'height' => 200, + 'quality' => 50, + ]); - $this->assertEquals(200, $response['headers']['status-code']); - $this->assertEquals('image/png', $response['headers']['content-type']); - $this->assertNotEmpty($response['body']); - }, 30_000, 2_000); - } + $this->assertEquals(200, $response['headers']['status-code']); + $this->assertNotEmpty($response['body']); + + // Output format: webp + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'output' => 'webp', + ]); + + $this->assertEquals(200, $response['headers']['status-code']); + $this->assertEquals('image/webp', $response['headers']['content-type']); + $this->assertNotEmpty($response['body']); + + // Output format: jpg + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'output' => 'jpg', + ]); + + $this->assertEquals(200, $response['headers']['status-code']); + $this->assertEquals('image/jpeg', $response['headers']['content-type']); + $this->assertNotEmpty($response['body']); + + // Rating param + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'rating' => 'pg', + ]); + + $this->assertEquals(200, $response['headers']['status-code']); + $this->assertNotEmpty($response['body']); /** - * Test for FAILURE + * Test for SUCCESS — Gravatar flow + * + * Use a well-known email that has a real Gravatar so we can verify the + * provider is actually being reached. Wrapped in assertEventually to + * tolerate transient network hiccups. + * + * TODO: Once the OAuth2 session photo is implemented, add a test that + * verifies priority 1 takes precedence over Gravatar. + */ + $this->assertEventually(function () { + // When we have a Gravatar for the user's email the chain resolves at + // priority 2; result must be a non-trivial PNG. + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'width' => 256, + 'height' => 256, + ]); + + $this->assertEquals(200, $response['headers']['status-code']); + $this->assertEquals('image/png', $response['headers']['content-type']); + $this->assertNotEmpty($response['body']); + }, 30_000, 2_000); + + /** + * Test for FAILURE — invalid params */ - // Invalid email format → 400 (rejected by Email validator before action runs) - $response = $this->client->call(Client::METHOD_GET, '/avatars/gravatar', [ + // Width out of range + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ 'x-appwrite-project' => $this->getProject()['$id'], - ], [ - 'email' => 'not-an-email', + ], $this->getHeaders()), [ + 'width' => 2001, ]); $this->assertEquals(400, $response['headers']['status-code']); - // Invalid default → 400 - $response = $this->client->call(Client::METHOD_GET, '/avatars/gravatar', [ + // Height out of range + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ 'x-appwrite-project' => $this->getProject()['$id'], - ], [ - 'email' => 'eldad@appwrite.io', - 'default' => 'invalid', + ], $this->getHeaders()), [ + 'height' => 2001, ]); $this->assertEquals(400, $response['headers']['status-code']); - // Invalid rating → 400 - $response = $this->client->call(Client::METHOD_GET, '/avatars/gravatar', [ + // Quality out of range + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ 'x-appwrite-project' => $this->getProject()['$id'], - ], [ - 'email' => 'eldad@appwrite.io', - 'rating' => 'invalid', + ], $this->getHeaders()), [ + 'quality' => 101, ]); $this->assertEquals(400, $response['headers']['status-code']); - // default=404 with unknown email → 404 with avatar_image_not_found - $this->assertEventually(function () { - $response = $this->client->call(Client::METHOD_GET, '/avatars/gravatar', [ - 'x-appwrite-project' => $this->getProject()['$id'], - ], [ - 'email' => 'no-gravatar-' . \uniqid() . '@example.com', - 'default' => '404', - ]); - $this->assertEquals(404, $response['headers']['status-code']); - $this->assertEquals(Exception::AVATAR_IMAGE_NOT_FOUND, $response['body']['type']); - }, 30_000, 2_000); + // Invalid output format + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'output' => 'bmp', + ]); + $this->assertEquals(400, $response['headers']['status-code']); + + // Invalid rating + $response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([ + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()), [ + 'rating' => 'xx', + ]); + $this->assertEquals(400, $response['headers']['status-code']); return []; } From 5281c608d5a323eafc8eaaa90046010ac2a2c380 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Wed, 19 Aug 2026 12:35:47 +0200 Subject: [PATCH 06/10] refactor(avatars): flatten photo providers and resolve them with balancer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Move Gravatar/Provider.php & friends to Providers/Gravatar.php, so the class name says what the provider is instead of every file being called Provider.php. Static/Provider.php becomes Providers/Fallback.php since `static` is a reserved word and cannot be a class name. - Turn AvatarPhotos/Photo.php into the abstract base every provider extends. It is a contract — getName(), supports(), get() — not a resolver that merges the providers together. - Replace Photo::resolve() with utopia-php/balancer in the HTTP action: each provider is an Option, a filter drops the ones that cannot serve the user (no email, no name), and the First algorithm walks them in priority order until one returns bytes. Co-Authored-By: Claude Opus 5 (1M context) --- composer.json | 1 + composer.lock | 50 +++++- src/Appwrite/AvatarPhotos/Photo.php | 143 ++++-------------- .../Provider.php => Providers/Fallback.php} | 34 +++-- .../Provider.php => Providers/Gravatar.php} | 39 +++-- .../Provider.php => Providers/Initials.php} | 60 +++++--- .../Provider.php => Providers/Libavatar.php} | 44 +++--- .../Modules/Avatars/Http/Photo/Get.php | 97 ++++++++++-- .../Modules/Avatars/Services/Http.php | 4 +- 9 files changed, 277 insertions(+), 195 deletions(-) rename src/Appwrite/AvatarPhotos/{Static/Provider.php => Providers/Fallback.php} (76%) rename src/Appwrite/AvatarPhotos/{Gravatar/Provider.php => Providers/Gravatar.php} (51%) rename src/Appwrite/AvatarPhotos/{Initials/Provider.php => Providers/Initials.php} (67%) rename src/Appwrite/AvatarPhotos/{Libavatar/Provider.php => Providers/Libavatar.php} (55%) diff --git a/composer.json b/composer.json index 8e5b888dbe..c6e9cb303a 100644 --- a/composer.json +++ b/composer.json @@ -68,6 +68,7 @@ "utopia-php/agents": "2.*", "utopia-php/audit": "3.0.*", "utopia-php/auth": "^0.10", + "utopia-php/balancer": "0.4.*", "utopia-php/cache": "^4.0.0", "utopia-php/cli": "^0.24", "utopia-php/compression": "0.1.*", diff --git a/composer.lock b/composer.lock index e21c79dec2..a43774cbfd 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "c7acee2d0fe6b2299e47df05257a7225", + "content-hash": "9642605d1050cf8beed5f482eaa962a4", "packages": [ { "name": "adhocore/jwt", @@ -3143,6 +3143,54 @@ }, "time": "2026-07-23T07:34:27+00:00" }, + { + "name": "utopia-php/balancer", + "version": "0.4.1", + "source": { + "type": "git", + "url": "https://github.com/utopia-php/balancer.git", + "reference": "7fc8922da3e381c227cd88435cb12b17040c6ee1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/utopia-php/balancer/zipball/7fc8922da3e381c227cd88435cb12b17040c6ee1", + "reference": "7fc8922da3e381c227cd88435cb12b17040c6ee1", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "utopia-php/telemetry": "^0.4.0" + }, + "require-dev": { + "laravel/pint": "1.2.*", + "phpstan/phpstan": "^1.8", + "phpunit/phpunit": "^9.3" + }, + "type": "library", + "autoload": { + "psr-4": { + "Utopia\\Balancer\\": "src/Balancer" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "A simple library to balance choices between multiple options.", + "keywords": [ + "balancer", + "balancing", + "framework", + "php", + "upf", + "utopia" + ], + "support": { + "issues": "https://github.com/utopia-php/balancer/issues", + "source": "https://github.com/utopia-php/balancer/tree/0.4.1" + }, + "time": "2026-08-13T19:36:49+00:00" + }, { "name": "utopia-php/cache", "version": "4.0.2", diff --git a/src/Appwrite/AvatarPhotos/Photo.php b/src/Appwrite/AvatarPhotos/Photo.php index 6788e9c1a4..dafe7622d2 100644 --- a/src/Appwrite/AvatarPhotos/Photo.php +++ b/src/Appwrite/AvatarPhotos/Photo.php @@ -2,132 +2,43 @@ namespace Appwrite\AvatarPhotos; -use Appwrite\AvatarPhotos\Gravatar\Provider as GravatarProvider; -use Appwrite\AvatarPhotos\Libavatar\Provider as LibavatarProvider; -use Appwrite\AvatarPhotos\Initials\Provider as InitialsProvider; -use Appwrite\AvatarPhotos\Static\Provider as StaticProvider; -use Utopia\Image\Image; +use Utopia\Database\Document; /** - * Photo resolver. + * Base class every avatar photo provider extends. * - * Walks through avatar providers in priority order and returns the first - * successful result as processed PNG/WEBP/JPEG bytes. - * - * Priority chain: - * 1. OAuth2 session photo — TODO: implement in a follow-up PR - * 2. Gravatar — requires email - * 3. Libravatar — requires email - * 4. Initials — requires name or email - * 5. Static fallback — always succeeds + * A provider knows how to turn a user into raw image bytes from one source — + * Gravatar, Libravatar, generated initials, a built-in placeholder — and + * nothing more. Picking which provider actually answers a request is the + * caller's job; providers never chain into one another. */ -class Photo +abstract class Photo { - private GravatarProvider $gravatar; - private LibavatarProvider $libavatar; - private InitialsProvider $initials; - private StaticProvider $static; - - public function __construct(string $appRoot) - { - $this->gravatar = new GravatarProvider(); - $this->libavatar = new LibavatarProvider(); - $this->initials = new InitialsProvider($appRoot); - $this->static = new StaticProvider(); - } + /** + * Machine-readable name of the provider, e.g. 'gravatar'. + */ + abstract public function getName(): string; /** - * Resolve and return the best available avatar for the given user data. + * Whether this provider has everything it needs to attempt a lookup. * - * @param string $email User's email address (may be empty). - * @param string $name User's display name (may be empty). - * @param int $width Desired output width in pixels. - * @param int $height Desired output height in pixels. - * @param int $quality Output quality 0–100. - * @param string $output Output format: 'png' | 'jpg' | 'webp'. - * @param string $rating Gravatar/Libravatar rating: 'g' | 'pg' | 'r' | 'x'. - * @param string $background Optional hex background for the Initials provider. - * @return string Raw image bytes in the requested $output format. + * Providers that key off an email address return false for users without + * one, so the caller can skip them without paying for a network round-trip. */ - public function resolve( - string $email, - string $name, - int $width = 256, - int $height = 256, - int $quality = 100, - string $output = 'png', - string $rating = 'g', - string $background = '', - ): string { - // ------------------------------------------------------------------- - // Priority 1: OAuth2 session photo - // TODO: Resolve profile photo from the user's active OAuth2 token. - // Each OAuth2 provider (Google, GitHub, …) exposes a profile- - // picture URL. Fetch it here and short-circuit the chain. - // Track in: https://github.com/appwrite/appwrite/issues/TODO - // ------------------------------------------------------------------- - - // ------------------------------------------------------------------- - // Priority 2: Gravatar - // ------------------------------------------------------------------- - if (!empty($email)) { - $raw = $this->gravatar->get($email, $rating); - if ($raw !== null) { - return $this->process($raw, $width, $height, $quality, $output); - } - } - - // ------------------------------------------------------------------- - // Priority 3: Libravatar - // ------------------------------------------------------------------- - if (!empty($email)) { - $raw = $this->libavatar->get($email, $rating); - if ($raw !== null) { - return $this->process($raw, $width, $height, $quality, $output); - } - } - - // ------------------------------------------------------------------- - // Priority 4: Initials - // Prefer name; fall back to email prefix when name is absent. - // ------------------------------------------------------------------- - $initialsInput = !empty($name) ? $name : $email; - if (!empty($initialsInput)) { - $raw = $this->initials->get($initialsInput, $width, $height, $background); - if ($raw !== null) { - // Initials PNG is already sized correctly — just re-encode if - // a different format or quality was requested. - return $this->process($raw, $width, $height, $quality, $output); - } - } - - // ------------------------------------------------------------------- - // Priority 5: Static fallback — always succeeds - // ------------------------------------------------------------------- - $raw = $this->static->get($width, $height); - return $this->process($raw, $width, $height, $quality, $output); - } + abstract public function supports(Document $user): bool; /** - * Resize and re-encode raw image bytes. + * Fetch the raw image bytes for $user. + * + * Returning null means "I have no photo for this user" and is an expected + * outcome, not an error — the caller moves on to the next provider. Network + * or rendering failures must be swallowed and reported the same way. + * + * @param Document $user User to resolve a photo for. + * @param int $width Desired width in pixels. + * @param int $height Desired height in pixels. + * @param string $rating Maximum image rating: 'g' | 'pg' | 'r' | 'x'. + * @return string|null Raw image bytes, or null when unavailable. */ - private function process(string $raw, int $width, int $height, int $quality, string $output): string - { - if (!\extension_loaded('imagick') || empty($raw)) { - return $raw; - } - - try { - $image = new Image($raw); - if ($width > 0 || $height > 0) { - $image->crop( - $width > 0 ? $width : 256, - $height > 0 ? $height : 256, - ); - } - return $image->output($output, $quality); - } catch (\Throwable) { - return $raw; - } - } + abstract public function get(Document $user, int $width, int $height, string $rating): ?string; } diff --git a/src/Appwrite/AvatarPhotos/Static/Provider.php b/src/Appwrite/AvatarPhotos/Providers/Fallback.php similarity index 76% rename from src/Appwrite/AvatarPhotos/Static/Provider.php rename to src/Appwrite/AvatarPhotos/Providers/Fallback.php index f9af02a083..cc2bcbe030 100644 --- a/src/Appwrite/AvatarPhotos/Static/Provider.php +++ b/src/Appwrite/AvatarPhotos/Providers/Fallback.php @@ -1,6 +1,9 @@ 0 ? $width : 256; + $height = $height > 0 ? $height : 256; + // Generate an SVG silhouette and rasterise it with Imagick so the // caller always receives a PNG regardless of whether SVG support is // available in the client. diff --git a/src/Appwrite/AvatarPhotos/Gravatar/Provider.php b/src/Appwrite/AvatarPhotos/Providers/Gravatar.php similarity index 51% rename from src/Appwrite/AvatarPhotos/Gravatar/Provider.php rename to src/Appwrite/AvatarPhotos/Providers/Gravatar.php index c4fabd19b2..5414af9087 100644 --- a/src/Appwrite/AvatarPhotos/Gravatar/Provider.php +++ b/src/Appwrite/AvatarPhotos/Providers/Gravatar.php @@ -1,36 +1,48 @@ getAttribute('email', '')); + } + + public function get(Document $user, int $width, int $height, string $rating): ?string + { + $email = $user->getAttribute('email', ''); $hash = \hash('sha256', \strtolower(\trim($email))); // Use 'd=404' so Gravatar returns HTTP 404 instead of a generic image // when the user has no custom avatar — letting us fall through to the // next provider. - $url = 'https://www.gravatar.com/avatar/' . $hash - . '?s=256&d=404&r=' . \urlencode($rating); + $url = self::BASE_URL . $hash . '?' . \http_build_query([ + 's' => \max($width, $height) > 0 ? \max($width, $height) : 256, + 'd' => '404', + 'r' => $rating, + ]); $client = new Client(); + try { $res = $client ->setAllowRedirects(true) @@ -44,6 +56,7 @@ class Provider } $body = $res->getBody(); + if (empty($body)) { return null; } diff --git a/src/Appwrite/AvatarPhotos/Initials/Provider.php b/src/Appwrite/AvatarPhotos/Providers/Initials.php similarity index 67% rename from src/Appwrite/AvatarPhotos/Initials/Provider.php rename to src/Appwrite/AvatarPhotos/Providers/Initials.php index d98916c5a0..b06220f11e 100644 --- a/src/Appwrite/AvatarPhotos/Initials/Provider.php +++ b/src/Appwrite/AvatarPhotos/Providers/Initials.php @@ -1,10 +1,12 @@ '#FD366E'], // Pink @@ -27,24 +27,30 @@ class Provider ['background' => '#85DBD8'], // Mint ]; - public function __construct(string $appRoot) - { - $this->appRoot = $appRoot; + public function __construct( + private readonly string $appRoot, + private readonly string $background = '', + ) { } - /** - * Generate an initials avatar image. - * - * @param string $name Full name or email to derive initials from. - * When empty or blank, returns null so the caller - * moves on to the next (static fallback) provider. - * @param int $width Canvas width in pixels. - * @param int $height Canvas height in pixels. - * @param string $background Optional hex colour (without #). Empty = auto. - * @return string|null Raw PNG bytes, or null when no name/email is available. - */ - public function get(string $name, int $width = 500, int $height = 500, string $background = ''): ?string + public function getName(): string { + return 'initials'; + } + + public function supports(Document $user): bool + { + return !empty(\trim($this->getLabel($user))); + } + + public function get(Document $user, int $width, int $height, string $rating): ?string + { + if (!\extension_loaded('imagick')) { + return null; + } + + $name = $this->getLabel($user); + if (empty(\trim($name))) { return null; } @@ -73,10 +79,13 @@ class Provider return null; } + $width = $width > 0 ? $width : 500; + $height = $height > 0 ? $height : 500; + $rand = (int) \substr((string) $code, -1); $rand = ($rand > \count($this->themes) - 1) ? $rand % \count($this->themes) : $rand; - $bg = (!empty($background)) ? '#' . \ltrim($background, '#') : $this->themes[$rand]['background']; + $bg = (!empty($this->background)) ? '#' . \ltrim($this->background, '#') : $this->themes[$rand]['background']; $image = new Imagick(); $punch = new Imagick(); @@ -104,4 +113,15 @@ class Provider return $image->getImageBlob(); } + + /** + * Text the initials are derived from — the display name, falling back to + * the email address when the user has not set one. + */ + private function getLabel(Document $user): string + { + $name = $user->getAttribute('name', ''); + + return !empty($name) ? $name : $user->getAttribute('email', ''); + } } diff --git a/src/Appwrite/AvatarPhotos/Libavatar/Provider.php b/src/Appwrite/AvatarPhotos/Providers/Libavatar.php similarity index 55% rename from src/Appwrite/AvatarPhotos/Libavatar/Provider.php rename to src/Appwrite/AvatarPhotos/Providers/Libavatar.php index cd9a6e2332..60c190e5de 100644 --- a/src/Appwrite/AvatarPhotos/Libavatar/Provider.php +++ b/src/Appwrite/AvatarPhotos/Providers/Libavatar.php @@ -1,7 +1,9 @@ getAttribute('email', '')); + } + + public function get(Document $user, int $width, int $height, string $rating): ?string + { + $email = $user->getAttribute('email', ''); // Libravatar supports both SHA-256 and MD5; use MD5 for widest // compatibility with older instances. - $url = self::BASE_URL . $hash - . '?s=256&d=404&r=' . \urlencode($rating); + $hash = \md5(\strtolower(\trim($email))); + + $url = self::BASE_URL . $hash . '?' . \http_build_query([ + 's' => \max($width, $height) > 0 ? \max($width, $height) : 256, + 'd' => '404', + 'r' => $rating, + ]); $client = new Client(); + try { $res = $client ->setAllowRedirects(true) @@ -51,6 +60,7 @@ class Provider } $body = $res->getBody(); + if (empty($body)) { return null; } diff --git a/src/Appwrite/Platform/Modules/Avatars/Http/Photo/Get.php b/src/Appwrite/Platform/Modules/Avatars/Http/Photo/Get.php index 1134147729..f485977bca 100644 --- a/src/Appwrite/Platform/Modules/Avatars/Http/Photo/Get.php +++ b/src/Appwrite/Platform/Modules/Avatars/Http/Photo/Get.php @@ -3,6 +3,11 @@ namespace Appwrite\Platform\Modules\Avatars\Http\Photo; use Appwrite\AvatarPhotos\Photo; +use Appwrite\AvatarPhotos\Providers\Fallback; +use Appwrite\AvatarPhotos\Providers\Gravatar; +use Appwrite\AvatarPhotos\Providers\Initials; +use Appwrite\AvatarPhotos\Providers\Libavatar; +use Appwrite\Extend\Exception; use Appwrite\Platform\Modules\Avatars\Http\Action; use Appwrite\SDK\AuthType; use Appwrite\SDK\ContentType; @@ -10,7 +15,11 @@ use Appwrite\SDK\Method; use Appwrite\SDK\MethodType; use Appwrite\SDK\Response as SDKResponse; use Appwrite\Utopia\Response; +use Utopia\Balancer\Algorithm\First; +use Utopia\Balancer\Balancer; +use Utopia\Balancer\Option; use Utopia\Database\Document; +use Utopia\Image\Image; use Utopia\Platform\Action as UtopiaAction; use Utopia\Platform\Scope\HTTP; use Utopia\Validator\Range; @@ -74,20 +83,57 @@ class Get extends Action Response $response, Document $user, ): void { - $email = $user->getAttribute('email', ''); - $name = $user->getAttribute('name', ''); + // ------------------------------------------------------------------- + // Priority 1: OAuth2 session photo + // TODO: Resolve profile photo from the user's active OAuth2 token. + // Each OAuth2 provider (Google, GitHub, …) exposes a profile- + // picture URL. Add it as a provider at the front of the list. + // Track in: https://github.com/appwrite/appwrite/issues/TODO + // ------------------------------------------------------------------- + $providers = [ + new Gravatar(), + new Libavatar(), + new Initials($this->getAppRoot()), + new Fallback(), + ]; - $photo = new Photo($this->getAppRoot()); + $balancer = new Balancer(new First()); - $data = $photo->resolve( - email: $email, - name: $name, - width: $width, - height: $height, - quality: $quality, - output: $output, - rating: $rating, - ); + foreach ($providers as $provider) { + $balancer->addOption(new Option(['provider' => $provider])); + } + + // Skip providers that lack the data they need — no email means no + // Gravatar lookup — so we never pay for a doomed network round-trip. + $balancer->addFilter(function (Option $option) use ($user) { + /** @var Photo $provider */ + $provider = $option->getState('provider'); + + return $provider->supports($user); + }); + + // A provider that came up empty is out of the running; without this the + // First algorithm would hand back the same option forever. + $balancer->addFilter(fn (Option $option) => !$option->getState('attempted', false)); + + $data = null; + + while (($option = $balancer->run()) !== null) { + $option->setState('attempted', true); + + /** @var Photo $provider */ + $provider = $option->getState('provider'); + + $data = $provider->get($user, $width, $height, $rating); + + if ($data !== null) { + break; + } + } + + if ($data === null) { + throw new Exception(Exception::AVATAR_NOT_FOUND); + } $contentType = match ($output) { 'jpg' => 'image/jpeg', @@ -98,6 +144,31 @@ class Get extends Action $response ->addHeader('Cache-Control', 'private, max-age=60') // 1 minute — photo may change ->setContentType($contentType) - ->file($data); + ->file($this->process($data, $width, $height, $quality, $output)); + } + + /** + * Resize and re-encode raw image bytes. + */ + private function process(string $raw, int $width, int $height, int $quality, string $output): string + { + if (!\extension_loaded('imagick') || empty($raw)) { + return $raw; + } + + try { + $image = new Image($raw); + + if ($width > 0 || $height > 0) { + $image->crop( + $width > 0 ? $width : 256, + $height > 0 ? $height : 256, + ); + } + + return $image->output($output, $quality); + } catch (\Throwable) { + return $raw; + } } } diff --git a/src/Appwrite/Platform/Modules/Avatars/Services/Http.php b/src/Appwrite/Platform/Modules/Avatars/Services/Http.php index 24c57cba8d..e6348fc5ad 100644 --- a/src/Appwrite/Platform/Modules/Avatars/Services/Http.php +++ b/src/Appwrite/Platform/Modules/Avatars/Services/Http.php @@ -6,10 +6,9 @@ use Appwrite\Platform\Modules\Avatars\Http\Browsers\Get as GetBrowser; use Appwrite\Platform\Modules\Avatars\Http\CreditCards\Get as GetCreditCard; use Appwrite\Platform\Modules\Avatars\Http\Favicon\Get as GetFavicon; use Appwrite\Platform\Modules\Avatars\Http\Flags\Get as GetFlag; - -use Appwrite\Platform\Modules\Avatars\Http\Photo\Get as GetPhoto; use Appwrite\Platform\Modules\Avatars\Http\Image\Get as GetImage; use Appwrite\Platform\Modules\Avatars\Http\Initials\Get as GetInitials; +use Appwrite\Platform\Modules\Avatars\Http\Photo\Get as GetPhoto; use Appwrite\Platform\Modules\Avatars\Http\QR\Get as GetQR; use Appwrite\Platform\Modules\Avatars\Http\Screenshots\Get as GetScreenshot; use Utopia\Platform\Service; @@ -28,7 +27,6 @@ class Http extends Service $this->addAction(GetQR::getName(), new GetQR()); $this->addAction(GetInitials::getName(), new GetInitials()); $this->addAction(GetScreenshot::getName(), new GetScreenshot()); - $this->addAction(GetPhoto::getName(), new GetPhoto()); } } From ca75eba630dd8d197cd35c9b2cc21a79723b50d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Wed, 19 Aug 2026 12:42:14 +0200 Subject: [PATCH 07/10] refactor(avatars): heredoc description, self-locating font, no-store photo - Use the << --- .../AvatarPhotos/Providers/Initials.php | 8 +++++-- .../Modules/Avatars/Http/Photo/Get.php | 22 +++++++++++-------- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/src/Appwrite/AvatarPhotos/Providers/Initials.php b/src/Appwrite/AvatarPhotos/Providers/Initials.php index b06220f11e..e4b8cf3bed 100644 --- a/src/Appwrite/AvatarPhotos/Providers/Initials.php +++ b/src/Appwrite/AvatarPhotos/Providers/Initials.php @@ -18,6 +18,9 @@ use Utopia\Database\Document; */ class Initials extends Photo { + /** Font used to render the initials, relative to the project root. */ + private const FONT_PATH = '/app/assets/fonts/inter-v8-latin-regular.woff2'; + /** Colour palette — same as the Initials endpoint. */ private array $themes = [ ['background' => '#FD366E'], // Pink @@ -28,7 +31,6 @@ class Initials extends Photo ]; public function __construct( - private readonly string $appRoot, private readonly string $background = '', ) { } @@ -95,7 +97,9 @@ class Initials extends Photo $punch->newImage($width, $height, 'transparent'); - $fontPath = $this->appRoot . '/app/assets/fonts/inter-v8-latin-regular.woff2'; + // Providers live at src/Appwrite/AvatarPhotos/Providers, four levels + // below the project root — same walk-up as Avatars\Http\Action. + $fontPath = \dirname(__DIR__, 4) . self::FONT_PATH; $draw->setFont($fontPath); $image->setFont($fontPath); diff --git a/src/Appwrite/Platform/Modules/Avatars/Http/Photo/Get.php b/src/Appwrite/Platform/Modules/Avatars/Http/Photo/Get.php index f485977bca..5c9ea6be50 100644 --- a/src/Appwrite/Platform/Modules/Avatars/Http/Photo/Get.php +++ b/src/Appwrite/Platform/Modules/Avatars/Http/Photo/Get.php @@ -46,13 +46,17 @@ class Get extends Action namespace: 'avatars', group: null, name: 'getPhoto', - description: 'Returns the best available profile photo for the currently authenticated user. ' - . 'The endpoint tries each source in priority order and returns the first successful result: ' - . '(1) OAuth2 session photo (planned — see TODO in source), ' - . '(2) Gravatar, ' - . '(3) Libravatar, ' - . '(4) initials generated from the user\'s name or email, ' - . '(5) a built-in static fallback image.', + description: <<getAppRoot()), + new Initials(), new Fallback(), ]; @@ -142,7 +146,7 @@ class Get extends Action }; $response - ->addHeader('Cache-Control', 'private, max-age=60') // 1 minute — photo may change + ->addHeader('Cache-Control', 'private, no-store') // photo can change at any time ->setContentType($contentType) ->file($this->process($data, $width, $height, $quality, $output)); } From e58e2b80008c9ba9ffecb99f2ba7294b8f95248a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Wed, 19 Aug 2026 12:47:01 +0200 Subject: [PATCH 08/10] Apply suggestion from @Meldiron --- .../Platform/Modules/Avatars/Http/Photo/Get.php | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/src/Appwrite/Platform/Modules/Avatars/Http/Photo/Get.php b/src/Appwrite/Platform/Modules/Avatars/Http/Photo/Get.php index 5c9ea6be50..7428deb54b 100644 --- a/src/Appwrite/Platform/Modules/Avatars/Http/Photo/Get.php +++ b/src/Appwrite/Platform/Modules/Avatars/Http/Photo/Get.php @@ -47,15 +47,7 @@ class Get extends Action group: null, name: 'getPhoto', description: << Date: Wed, 19 Aug 2026 15:23:16 +0200 Subject: [PATCH 09/10] refactor(avatars): render initials endpoint through the Initials provider The provider was a copy of the endpoint's inline logic. Make it the single implementation instead: render() draws any label, getInitials()/getTheme() derive the letters and colour, and get() keeps resolving the label off the user for the photo chain. Initials derivation and theme selection are unchanged. Sizes of 0, which the Range(0, 2000) validator allows, now fall back to the 500px default rather than reaching Imagick::newImage(0, 0), and a '#'-prefixed background no longer yields '##aabbcc'. Co-Authored-By: Claude Opus 5 (1M context) --- .../AvatarPhotos/Providers/Initials.php | 109 ++++++++++++------ .../Modules/Avatars/Http/Initials/Get.php | 60 +--------- 2 files changed, 78 insertions(+), 91 deletions(-) diff --git a/src/Appwrite/AvatarPhotos/Providers/Initials.php b/src/Appwrite/AvatarPhotos/Providers/Initials.php index e4b8cf3bed..3bbfdd2462 100644 --- a/src/Appwrite/AvatarPhotos/Providers/Initials.php +++ b/src/Appwrite/AvatarPhotos/Providers/Initials.php @@ -11,17 +11,20 @@ use Utopia\Database\Document; /** * Initials provider. * - * Generates a coloured square with the user's initials — identical logic to - * the standalone GET /v1/avatars/initials endpoint, but exposed as a plain - * PHP class so the photo-resolution chain can call it without going through - * HTTP. + * Generates a coloured square with the user's initials. This is the single + * implementation behind both the photo-resolution chain and the standalone + * GET /v1/avatars/initials endpoint — the endpoint renders an arbitrary label + * through render(), the chain resolves the label off the user first. */ class Initials extends Photo { /** Font used to render the initials, relative to the project root. */ private const FONT_PATH = '/app/assets/fonts/inter-v8-latin-regular.woff2'; - /** Colour palette — same as the Initials endpoint. */ + /** Edge length used when the caller does not ask for a size. */ + private const DEFAULT_SIZE = 500; + + /** Colour palette — a theme is picked from the initials themselves. */ private array $themes = [ ['background' => '#FD366E'], // Pink ['background' => '#FE9567'], // Orange @@ -53,41 +56,35 @@ class Initials extends Photo $name = $this->getLabel($user); - if (empty(\trim($name))) { + // Nothing printable to draw — bail out so the static fallback can be + // used instead. The standalone endpoint has no such fallback and keeps + // rendering a plain coloured square, which is why this check lives + // here and not in render(). + if (empty($this->getInitials($name))) { return null; } - $words = \explode(' ', \strtoupper($name)); - // Fallback: split on underscores when there is no space - $words = (\count($words) === 1) ? \explode('_', \strtoupper($name)) : $words; + return $this->render($name, $width, $height); + } - $initials = ''; - $code = 0; + /** + * Render the initials of an arbitrary label as a PNG. + * + * @param string $name Label to derive the initials from. + * @param int $width Output width in pixels; defaults when not positive. + * @param int $height Output height in pixels; defaults when not positive. + * @return string Raw PNG bytes. + */ + public function render(string $name, int $width, int $height): string + { + $initials = $this->getInitials($name); - foreach ($words as $key => $w) { - if (\ctype_alnum($w[0] ?? '')) { - $initials .= $w[0]; - $code += \ord($w[0]); + $width = $width > 0 ? $width : self::DEFAULT_SIZE; + $height = $height > 0 ? $height : self::DEFAULT_SIZE; - if ($key === 1) { - break; - } - } - } - - // If we still have no printable initials, bail out so the static - // fallback can be used instead. - if (empty($initials)) { - return null; - } - - $width = $width > 0 ? $width : 500; - $height = $height > 0 ? $height : 500; - - $rand = (int) \substr((string) $code, -1); - $rand = ($rand > \count($this->themes) - 1) ? $rand % \count($this->themes) : $rand; - - $bg = (!empty($this->background)) ? '#' . \ltrim($this->background, '#') : $this->themes[$rand]['background']; + $bg = !empty($this->background) + ? '#' . \ltrim($this->background, '#') + : $this->getTheme($initials); $image = new Imagick(); $punch = new Imagick(); @@ -118,6 +115,50 @@ class Initials extends Photo return $image->getImageBlob(); } + /** + * First letter of the first two words, skipping words that do not start + * with an alphanumeric character. Underscores stand in for spaces when the + * label has none. + */ + private function getInitials(string $name): string + { + $words = \explode(' ', \strtoupper($name)); + // Fallback: split on underscores when there is no space + $words = (\count($words) === 1) ? \explode('_', \strtoupper($name)) : $words; + + $initials = ''; + + foreach ($words as $key => $w) { + if (\ctype_alnum($w[0] ?? '')) { + $initials .= $w[0]; + + if ($key === 1) { + break; + } + } + } + + return $initials; + } + + /** + * Background colour for a set of initials. Derived from the initials so the + * same label always gets the same colour. + */ + private function getTheme(string $initials): string + { + $code = 0; + + foreach (\str_split($initials) as $char) { + $code += \ord($char); + } + + $rand = (int) \substr((string) $code, -1); + $rand = ($rand > \count($this->themes) - 1) ? $rand % \count($this->themes) : $rand; + + return $this->themes[$rand]['background']; + } + /** * Text the initials are derived from — the display name, falling back to * the email address when the user has not set one. diff --git a/src/Appwrite/Platform/Modules/Avatars/Http/Initials/Get.php b/src/Appwrite/Platform/Modules/Avatars/Http/Initials/Get.php index 4808cb7267..d5f100e96f 100644 --- a/src/Appwrite/Platform/Modules/Avatars/Http/Initials/Get.php +++ b/src/Appwrite/Platform/Modules/Avatars/Http/Initials/Get.php @@ -2,6 +2,7 @@ namespace Appwrite\Platform\Modules\Avatars\Http\Initials; +use Appwrite\AvatarPhotos\Providers\Initials; use Appwrite\Platform\Modules\Avatars\Http\Action; use Appwrite\SDK\AuthType; use Appwrite\SDK\ContentType; @@ -9,9 +10,6 @@ use Appwrite\SDK\Method; use Appwrite\SDK\MethodType; use Appwrite\SDK\Response as SDKResponse; use Appwrite\Utopia\Response; -use Imagick; -use ImagickDraw; -use ImagickPixel; use Utopia\Database\Document; use Utopia\Platform\Action as UtopiaAction; use Utopia\Platform\Scope\HTTP; @@ -64,65 +62,13 @@ class Get extends Action public function action(string $name, int $width, int $height, string $background, Response $response, Document $user) { - $themes = [ - ['background' => '#FD366E'], // Default (Pink) - ['background' => '#FE9567'], // Orange - ['background' => '#7C67FE'], // Purple - ['background' => '#68A3FE'], // Blue - ['background' => '#85DBD8'], // Mint - ]; - $name = (!empty($name)) ? $name : $user->getAttribute('name', $user->getAttribute('email', '')); - $words = \explode(' ', \strtoupper($name)); - // if there is no space, try to split by `_` underscore - $words = (count($words) == 1) ? \explode('_', \strtoupper($name)) : $words; - $initials = ''; - $code = 0; - - foreach ($words as $key => $w) { - if (ctype_alnum($w[0] ?? '')) { - $initials .= $w[0]; - $code += ord($w[0]); - - if ($key == 1) { - break; - } - } - } - - $rand = (int) \substr((string) $code, -1); - - $rand = ($rand > \count($themes) - 1) ? $rand % \count($themes) : $rand; - - $background = (!empty($background)) ? '#' . $background : $themes[$rand]['background']; - - $image = new Imagick(); - $punch = new Imagick(); - $draw = new ImagickDraw(); - $fontSize = \min($width, $height) / 2; - - $punch->newImage($width, $height, 'transparent'); - - $draw->setFont($this->getAppRoot() . '/app/assets/fonts/inter-v8-latin-regular.woff2'); - $image->setFont($this->getAppRoot() . '/app/assets/fonts/inter-v8-latin-regular.woff2'); - - $draw->setFillColor(new ImagickPixel('black')); - $draw->setFontSize($fontSize); - - $draw->setTextAlignment(Imagick::ALIGN_CENTER); - $draw->annotation($width / 1.97, ($height / 2) + ($fontSize / 3), $initials); - - $punch->drawImage($draw); - $punch->negateImage(true, Imagick::CHANNEL_ALPHA); - - $image->newImage($width, $height, $background); - $image->setImageFormat("png"); - $image->compositeImage($punch, Imagick::COMPOSITE_COPYOPACITY, 0, 0); + $image = (new Initials($background))->render($name, $width, $height); $response ->addHeader('Cache-Control', 'private, max-age=3888000') // 45 days ->setContentType('image/png') - ->file($image->getImageBlob()); + ->file($image); } } From 66c1f01d6166f79c900722f28662eb230396952a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Wed, 19 Aug 2026 15:23:16 +0200 Subject: [PATCH 10/10] fix(avatars): bound remote photo lookups with explicit timeouts Gravatar and Libavatar each built a bare Client, inheriting utopia-php/fetch defaults of 15s request and 5s connect. The two run back to back, so one unreachable service could hold the request for ~20s before the local initials and fallback providers were reached. Move the request into Photo::fetch() so the budget is set in one place, and tighten it to 2s connect / 5s request. CURLOPT_TIMEOUT_MS covers the whole transfer including redirects and retries default to 0, so the remote leg is now capped at 10s. Co-Authored-By: Claude Opus 5 (1M context) --- src/Appwrite/AvatarPhotos/Photo.php | 46 +++++++++++++++++++ .../AvatarPhotos/Providers/Gravatar.php | 23 +--------- .../AvatarPhotos/Providers/Libavatar.php | 23 +--------- 3 files changed, 48 insertions(+), 44 deletions(-) diff --git a/src/Appwrite/AvatarPhotos/Photo.php b/src/Appwrite/AvatarPhotos/Photo.php index dafe7622d2..e46067bc68 100644 --- a/src/Appwrite/AvatarPhotos/Photo.php +++ b/src/Appwrite/AvatarPhotos/Photo.php @@ -3,6 +3,7 @@ namespace Appwrite\AvatarPhotos; use Utopia\Database\Document; +use Utopia\Fetch\Client; /** * Base class every avatar photo provider extends. @@ -14,6 +15,20 @@ use Utopia\Database\Document; */ abstract class Photo { + /** + * How long a provider may wait to open a connection to a remote service. + */ + protected const CONNECT_TIMEOUT = 2 * 1000; // 2 seconds + + /** + * How long a provider may wait for a complete remote response. + * + * Providers are tried one after another, so these budgets stack: a single + * unreachable service must not be able to hold the request open while we + * still have other providers — and a local fallback — left to try. + */ + protected const REQUEST_TIMEOUT = 5 * 1000; // 5 seconds + /** * Machine-readable name of the provider, e.g. 'gravatar'. */ @@ -41,4 +56,35 @@ abstract class Photo * @return string|null Raw image bytes, or null when unavailable. */ abstract public function get(Document $user, int $width, int $height, string $rating): ?string; + + /** + * GET $url with the provider timeout budget applied. + * + * Anything other than a 200 with a non-empty body — including a timeout or + * a transport error — is reported as null so the caller can move on. + * + * @return string|null Raw response body, or null when unavailable. + */ + protected function fetch(string $url): ?string + { + $client = new Client(); + + try { + $response = $client + ->setAllowRedirects(true) + ->setConnectTimeout(static::CONNECT_TIMEOUT) + ->setTimeout(static::REQUEST_TIMEOUT) + ->fetch($url); + } catch (\Throwable) { + return null; + } + + if ($response->getStatusCode() !== 200) { + return null; + } + + $body = $response->getBody(); + + return empty($body) ? null : $body; + } } diff --git a/src/Appwrite/AvatarPhotos/Providers/Gravatar.php b/src/Appwrite/AvatarPhotos/Providers/Gravatar.php index 5414af9087..a4985fdf60 100644 --- a/src/Appwrite/AvatarPhotos/Providers/Gravatar.php +++ b/src/Appwrite/AvatarPhotos/Providers/Gravatar.php @@ -4,7 +4,6 @@ namespace Appwrite\AvatarPhotos\Providers; use Appwrite\AvatarPhotos\Photo; use Utopia\Database\Document; -use Utopia\Fetch\Client; /** * Gravatar provider. @@ -41,26 +40,6 @@ class Gravatar extends Photo 'r' => $rating, ]); - $client = new Client(); - - try { - $res = $client - ->setAllowRedirects(true) - ->fetch($url); - } catch (\Throwable) { - return null; - } - - if ($res->getStatusCode() !== 200) { - return null; - } - - $body = $res->getBody(); - - if (empty($body)) { - return null; - } - - return $body; + return $this->fetch($url); } } diff --git a/src/Appwrite/AvatarPhotos/Providers/Libavatar.php b/src/Appwrite/AvatarPhotos/Providers/Libavatar.php index 60c190e5de..e5100c809e 100644 --- a/src/Appwrite/AvatarPhotos/Providers/Libavatar.php +++ b/src/Appwrite/AvatarPhotos/Providers/Libavatar.php @@ -4,7 +4,6 @@ namespace Appwrite\AvatarPhotos\Providers; use Appwrite\AvatarPhotos\Photo; use Utopia\Database\Document; -use Utopia\Fetch\Client; /** * Libravatar provider. @@ -45,26 +44,6 @@ class Libavatar extends Photo 'r' => $rating, ]); - $client = new Client(); - - try { - $res = $client - ->setAllowRedirects(true) - ->fetch($url); - } catch (\Throwable) { - return null; - } - - if ($res->getStatusCode() !== 200) { - return null; - } - - $body = $res->getBody(); - - if (empty($body)) { - return null; - } - - return $body; + return $this->fetch($url); } }