Merge pull request #13252 from imtia33/feature/avatars-gravatar

feat: Add Gravatar avatar support with session fallback
This commit is contained in:
Matej Bačo authored and GitHub committed 2026-08-19 15:42:08 +02:00
commit 84c641e641
11 files changed
+809 -58

No files matched your search

+1
View File
@@ -94,6 +94,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.*",
Generated
+49 -1
View File
@@ -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": "bc7793f803702df7c7726d103a13f599",
"content-hash": "4fd078c5f4c652e6b07c639e275b520c",
"packages": [
{
"name": "adhocore/jwt",
@@ -3144,6 +3144,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",
+90
View File
@@ -0,0 +1,90 @@
<?php
namespace Appwrite\AvatarPhotos;
use Utopia\Database\Document;
use Utopia\Fetch\Client;
/**
* Base class every avatar photo provider extends.
*
* 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.
*/
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'.
*/
abstract public function getName(): string;
/**
* Whether this provider has everything it needs to attempt a lookup.
*
* 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.
*/
abstract public function supports(Document $user): bool;
/**
* 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.
*/
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;
}
}
@@ -0,0 +1,78 @@
<?php
namespace Appwrite\AvatarPhotos\Providers;
use Appwrite\AvatarPhotos\Photo;
use Utopia\Database\Document;
/**
* Static fallback provider.
*
* Returns a minimal built-in avatar image when all other providers have
* failed. The image is a simple SVG rendered to a PNG-compatible byte
* string; designers can swap it out later for a brand-aligned asset
* without changing any surrounding logic.
*
* The SVG depicts a neutral silhouette on an Appwrite-pink background —
* similar to what "mystery man" (mp) looks like on Gravatar, but ours.
*
* This provider needs nothing from the user and never returns null, so it is
* always safe to place last in the chain.
*/
class Fallback extends Photo
{
public function getName(): string
{
return 'fallback';
}
public function supports(Document $user): bool
{
return true;
}
public function get(Document $user, int $width, int $height, string $rating): ?string
{
$width = $width > 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.
$svg = $this->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
<svg xmlns="http://www.w3.org/2000/svg" width="{$width}" height="{$height}" viewBox="0 0 {$width} {$height}">
<rect width="{$width}" height="{$height}" fill="#FD366E"/>
<!-- Head -->
<circle cx="50%" cy="38%" r="22%" fill="rgba(255,255,255,0.85)"/>
<!-- Body / shoulder shape -->
<ellipse cx="50%" cy="90%" rx="35%" ry="30%" fill="rgba(255,255,255,0.85)"/>
</svg>
SVG;
}
}
@@ -0,0 +1,45 @@
<?php
namespace Appwrite\AvatarPhotos\Providers;
use Appwrite\AvatarPhotos\Photo;
use Utopia\Database\Document;
/**
* Gravatar provider.
*
* Resolves a photo for a user's email address via the Gravatar service.
* Uses the '404' fallback so we get a clear signal when the user has no
* custom Gravatar; the caller can then move on to the next provider.
*/
class Gravatar extends Photo
{
private const BASE_URL = 'https://www.gravatar.com/avatar/';
public function getName(): string
{
return 'gravatar';
}
public function supports(Document $user): bool
{
return !empty($user->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 = self::BASE_URL . $hash . '?' . \http_build_query([
's' => \max($width, $height) > 0 ? \max($width, $height) : 256,
'd' => '404',
'r' => $rating,
]);
return $this->fetch($url);
}
}
@@ -0,0 +1,172 @@
<?php
namespace Appwrite\AvatarPhotos\Providers;
use Appwrite\AvatarPhotos\Photo;
use Imagick;
use ImagickDraw;
use ImagickPixel;
use Utopia\Database\Document;
/**
* Initials provider.
*
* 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';
/** 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
['background' => '#7C67FE'], // Purple
['background' => '#68A3FE'], // Blue
['background' => '#85DBD8'], // Mint
];
public function __construct(
private readonly string $background = '',
) {
}
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);
// 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;
}
return $this->render($name, $width, $height);
}
/**
* 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);
$width = $width > 0 ? $width : self::DEFAULT_SIZE;
$height = $height > 0 ? $height : self::DEFAULT_SIZE;
$bg = !empty($this->background)
? '#' . \ltrim($this->background, '#')
: $this->getTheme($initials);
$image = new Imagick();
$punch = new Imagick();
$draw = new ImagickDraw();
$fontSize = \min($width, $height) / 2;
$punch->newImage($width, $height, 'transparent');
// 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);
$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();
}
/**
* 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.
*/
private function getLabel(Document $user): string
{
$name = $user->getAttribute('name', '');
return !empty($name) ? $name : $user->getAttribute('email', '');
}
}
@@ -0,0 +1,49 @@
<?php
namespace Appwrite\AvatarPhotos\Providers;
use Appwrite\AvatarPhotos\Photo;
use Utopia\Database\Document;
/**
* Libravatar provider.
*
* Libravatar is a federated, self-hosted alternative to Gravatar.
* Resolution order: the domain's SRV record is consulted first
* (federation); when that is absent we fall back to the central
* seccdn.libravatar.org service.
*
* Libravatar supports d=404 just like Gravatar — we use that for a clean
* "no photo here" signal.
*/
class Libavatar extends Photo
{
private const BASE_URL = 'https://seccdn.libravatar.org/avatar/';
public function getName(): string
{
return 'libavatar';
}
public function supports(Document $user): bool
{
return !empty($user->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.
$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,
]);
return $this->fetch($url);
}
}
@@ -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);
}
}
@@ -0,0 +1,170 @@
<?php
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;
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;
use Utopia\Validator\WhiteList;
class Get extends Action
{
use HTTP;
public static function getName(): string
{
return 'getPhoto';
}
public function __construct()
{
$this
->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: <<<EOT
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: Gravatar, Libavatar, Appwrite Initials, built-in static fallback file.
EOT,
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 {
// -------------------------------------------------------------------
// 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(),
new Fallback(),
];
$balancer = new Balancer(new First());
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',
'webp' => 'image/webp',
default => 'image/png',
};
$response
->addHeader('Cache-Control', 'private, no-store') // photo can change at any time
->setContentType($contentType)
->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;
}
}
}
@@ -8,6 +8,7 @@ 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\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;
@@ -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(GetPhoto::getName(), new GetPhoto());
}
}
+150
View File
@@ -1342,4 +1342,154 @@ trait AvatarsBase
return [];
}
public function testGetPhoto(): array
{
/**
* 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.
*/
// 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']);
// 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']);
// 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->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 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
*/
// Width out of range
$response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getHeaders()), [
'width' => 2001,
]);
$this->assertEquals(400, $response['headers']['status-code']);
// Height out of range
$response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getHeaders()), [
'height' => 2001,
]);
$this->assertEquals(400, $response['headers']['status-code']);
// Quality out of range
$response = $this->client->call(Client::METHOD_GET, '/avatars/photo', \array_merge([
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getHeaders()), [
'quality' => 101,
]);
$this->assertEquals(400, $response['headers']['status-code']);
// 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 [];
}
}