Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

avatar: Add support to generate avatar using Jdenticon.

Prakhar Pratyush5c4382023ed9
diff --git a/api_docs/changelog.md b/api_docs/changelog.md
index 4f6631f5dd5..4abaa3bfce4 100644
--- a/api_docs/changelog.md
+++ b/api_docs/changelog.md
@@ -25,6 +25,9 @@ format used by the Zulip server that they are interacting with.
* [`POST /register`](/api/register-queue): Added `realm_uuid`
field to response. Used by clients that prefer to compute
Jdenticon avatars locally.
+* [`POST /register`](/api/register-queue), [`GET
+ /events`](/api/get-events): The `avatar_source` fields may now have
+ the value `"J"`, for Jdenticons.
**Feature level 465**
diff --git a/package.json b/package.json
index 188508b64fa..fd4fd880d52 100644
--- a/package.json
+++ b/package.json
@@ -51,6 +51,7 @@
"html-webpack-plugin": "^5.3.2",
"intl-messageformat": "^11.0.7",
"is-url": "^1.2.4",
+ "jdenticon": "^3.3.0",
"jquery": "^4.0.0",
"jquery-caret-plugin": "^1.5.2",
"jquery-validation": "^1.19.0",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index bb00fc61dce..eacb8fef4e5 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -179,6 +179,9 @@ importers:
is-url:
specifier: ^1.2.4
version: 1.2.4
+ jdenticon:
+ specifier: ^3.3.0
+ version: 3.3.0
jquery:
specifier: ^4.0.0
version: 4.0.0
@@ -3825,6 +3828,9 @@ packages:
resolution: {integrity: sha512-onIcjRpz69/Hx5bB5HGbYKUF2uC6QT6Gp+pfpGm3A7mPfcluSLV5v4Zu+oflDUwLdUw0rLIBhUbi0v8hM4FJQQ==}
+ resolution: {integrity: sha512-RrBgVL5qCEDIXpJ6NrzyRNoTnXxYarqm/cS/W6ERhUJts5UQtt/XPEosGN3rqUkZ4fjBArlnCbsISJ+KCFnIAg==}
+
resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==}
@@ -6155,6 +6161,11 @@ packages:
resolution: {integrity: sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==}
+ resolution: {integrity: sha512-DhuBRNRIybGPeAjMjdHbkIfiwZCCmf8ggu7C49jhp6aJ7DYsZfudnvnTY5/1vgUhrGA7JaDAx1WevnpjCPvaGg==}
+ engines: {node: '>=6.4.0'}
+ hasBin: true
+
resolution: {integrity: sha512-jHEQgBXAgc+Gh4g0p3bCevgRCVRkB4VB70zhoAE48gxeSr1hfUOsM/C2WoJgVL7Eyg//hudYENbm3Ne+/dRVVA==}
engines: {node: ^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0}
@@ -13769,6 +13780,10 @@ snapshots:
dependencies:
element-size: 1.1.1
+ dependencies:
+ '@types/node': 24.10.10
+
@@ -16528,6 +16543,10 @@ snapshots:
optionalDependencies:
'@pkgjs/parseargs': 0.11.0
+ dependencies:
+ canvas-renderer: 2.2.1
+
diff --git a/version.py b/version.py
index 88b846213c6..32e45acbed9 100644
--- a/version.py
+++ b/version.py
@@ -48,4 +48,4 @@ API_FEATURE_LEVEL = 466
# historical commits sharing the same major version, in which case a
# minor version bump suffices.
-PROVISION_VERSION = (369, 1) # bumped 2026-02-02 to add compressorjs
+PROVISION_VERSION = (369, 2) # bumped 2026-02-09 to add jdenticon
diff --git a/web/src/avatar.ts b/web/src/avatar.ts
index f5ff66eb12a..dafd81c38e4 100644
--- a/web/src/avatar.ts
+++ b/web/src/avatar.ts
@@ -72,8 +72,11 @@ export function build_user_avatar_widget(upload_function: UploadFunction): void
return $<HTMLInputElement>("#user-avatar-upload-widget input.image_file_input").expectOne();
};
- if (current_user.avatar_source === "G") {
+ if (current_user.avatar_source !== "U") {
$("#user-avatar-upload-widget .image-delete-button").hide();
+ }
+
+ if (current_user.avatar_source === "G") {
$("#user-avatar-source").show();
} else {
$("#user-avatar-source").hide();
diff --git a/web/webpack.config.ts b/web/webpack.config.ts
index 28cd88d47d4..1858df08fb9 100644
--- a/web/webpack.config.ts
+++ b/web/webpack.config.ts
@@ -273,6 +273,7 @@ const config = (
entry: {
katex_server: "babel-loader!./server/katex_server.ts",
"katex-cli": "shebang-loader!katex/cli",
+ jdenticon: "shebang-loader!../node_modules/jdenticon/bin/jdenticon.js",
},
output: {
path: path.resolve(import.meta.dirname, "../static/webpack-bundles"),
diff --git a/zerver/actions/create_user.py b/zerver/actions/create_user.py
index ccf1cec5c59..577e0b782a9 100644
--- a/zerver/actions/create_user.py
+++ b/zerver/actions/create_user.py
@@ -26,7 +26,7 @@ from zerver.actions.users import (
get_service_dicts_for_bot,
send_update_events_for_anonymous_group_settings,
)
-from zerver.lib.avatar import avatar_url
+from zerver.lib.avatar import avatar_url, generate_and_upload_jdenticon_avatar
from zerver.lib.create_user import create_user
from zerver.lib.default_streams import get_slim_realm_default_streams
from zerver.lib.email_notifications import enqueue_welcome_emails, send_account_registered_email
@@ -520,7 +520,7 @@ def do_create_user(
bot_owner: UserProfile | None = None,
tos_version: str | None = None,
timezone: str = "",
- avatar_source: str = UserProfile.AVATAR_FROM_GRAVATAR,
+ avatar_source: str | None = None,
default_language: str | None = None,
default_sending_stream: Stream | None = None,
default_events_register_stream: Stream | None = None,
@@ -560,6 +560,9 @@ def do_create_user(
email_address_visibility=email_address_visibility,
)
+ if user_profile.avatar_source == UserProfile.AVATAR_FROM_JDENTICON:
+ generate_and_upload_jdenticon_avatar(user_profile, str(realm.uuid), future=False)
+
event_time = user_profile.date_joined
if not acting_user:
acting_user = user_profile
diff --git a/zerver/actions/user_settings.py b/zerver/actions/user_settings.py
index 5871f79a1d1..42d1eaed666 100644
--- a/zerver/actions/user_settings.py
+++ b/zerver/actions/user_settings.py
@@ -11,7 +11,7 @@ from confirmation.models import Confirmation, create_confirmation_link
from confirmation.settings import STATUS_REVOKED, STATUS_USED
from zerver.actions.message_send import send_user_profile_update_notification
from zerver.actions.presence import do_update_user_presence
-from zerver.lib.avatar import avatar_url
+from zerver.lib.avatar import avatar_url, generate_and_upload_jdenticon_avatar
from zerver.lib.cache import (
bulk_flush_users,
cache_delete,
@@ -438,13 +438,28 @@ def do_change_avatar_fields(
def do_scrub_avatar_images(user: UserProfile, *, acting_user: UserProfile | None) -> None:
old_version = user.avatar_version
+ # Note: while scrubbing, no need to generate and upload
+ # avatar when default_avatar_source is jdenticon.
do_change_avatar_fields(
- user, UserProfile.AVATAR_FROM_GRAVATAR, skip_notify=True, acting_user=acting_user
+ user, user.realm.default_avatar_source, skip_notify=True, acting_user=acting_user
)
for version in range(1, old_version + 1):
delete_avatar_image(user, version)
+def set_avatar_to_default(user_profile: UserProfile, *, acting_user: UserProfile | None) -> None:
+ default_avatar_source = user_profile.realm.default_avatar_source
+
+ if user_profile.avatar_source == default_avatar_source: # nocoverage
+ return
+
+ if default_avatar_source == UserProfile.AVATAR_FROM_JDENTICON:
+ generate_and_upload_jdenticon_avatar(
+ user_profile, realm_uuid=str(user_profile.realm.uuid), future=True
+ )
+ do_change_avatar_fields(user_profile, default_avatar_source, acting_user=acting_user)
+
+
def update_scheduled_email_notifications_time(
user_profile: UserProfile, old_batching_period: int, new_batching_period: int
) -> None:
diff --git a/zerver/lib/avatar.py b/zerver/lib/avatar.py
index 91d78b8b4e3..5424e253d8c 100644
--- a/zerver/lib/avatar.py
+++ b/zerver/lib/avatar.py
@@ -1,3 +1,6 @@
+import logging
+import os
+import subprocess
from urllib.parse import urljoin
from django.conf import settings
@@ -7,9 +10,10 @@ from zerver.lib.avatar_hash import (
gravatar_hash,
user_avatar_base_path_from_ids,
user_avatar_content_hash,
+ user_avatar_path,
)
-from zerver.lib.thumbnail import MEDIUM_AVATAR_SIZE
-from zerver.lib.upload import get_avatar_url
+from zerver.lib.thumbnail import DEFAULT_AVATAR_SIZE, MEDIUM_AVATAR_SIZE
+from zerver.lib.upload import get_avatar_url, write_jdenticon_avatars
from zerver.lib.url_encoding import append_url_query_string
from zerver.models import UserProfile
from zerver.models.users import is_cross_realm_bot_email
@@ -18,6 +22,8 @@ STATIC_AVATARS_DIR = "images/static_avatars/"
DEFAULT_AVATAR_FILE = "images/default-avatar.png"
+logger = logging.getLogger(__name__)
+
def avatar_url(
user_profile: UserProfile, medium: bool = False, client_gravatar: bool = False
@@ -106,11 +112,11 @@ def get_avatar_field(
return None
"""
- If we get this far, we'll compute an avatar URL that may be
- either user-uploaded or a gravatar, and then we'll add version
- info to try to avoid stale caches.
+ If we get this far, we'll compute an avatar URL based on the
+ avatar source, and then we'll add version info to try to avoid
+ stale caches.
"""
- if avatar_source == "U":
+ if avatar_source in [UserProfile.AVATAR_FROM_USER, UserProfile.AVATAR_FROM_JDENTICON]:
hash_key = user_avatar_base_path_from_ids(user_id, avatar_version, realm_id)
return get_avatar_url(hash_key, medium=medium)
@@ -173,3 +179,51 @@ def is_avatar_new(ldap_avatar: bytes, user_profile: UserProfile) -> bool:
def get_avatar_for_inaccessible_user() -> str:
return staticfiles_storage.url("images/unknown-user-avatar.png")
+
+
+def generate_avatar_jdenticon(input: str, medium: bool) -> bytes:
+ from zerver.lib.storage import static_path
+
+ jdenticon_path = (
+ static_path("webpack-bundles/jdenticon.js")
+ if settings.PRODUCTION
+ else os.path.join(settings.DEPLOY_ROOT, "node_modules/jdenticon/bin/jdenticon.js")
+ )
+ size = str(MEDIUM_AVATAR_SIZE if medium else DEFAULT_AVATAR_SIZE)
+ command = ["node", jdenticon_path, input, "-s", size, "-p", "0"]
+ try:
+ stdout = subprocess.check_output(command)
+ return stdout
+ except subprocess.CalledProcessError as error: # nocoverage
+ logger.exception("Jdenticon generation failed for user_id:{input}")
+ raise error
+
+
+def generate_and_upload_jdenticon_avatar(
+ user_profile: UserProfile,
+ realm_uuid: str,
+ future: bool,
+) -> None:
+ # We use a combination of user ID and realm_uuid (salt) as the key
+ # for Jdenticon generation, so that clients that prefer to use computation
+ # instead of network to provide default avatars for users can do that
+ # in the future.
+ #
+ # Using only user ID (no salt) can result in situations where a person is
+ # part of multiple zulip servers, and they find same avatar for different
+ # people in different servers.
+ #
+ # Note: The key effectively changes when user IDs are renumbered when
+ # migrating between Zulip servers,
+ jdenticon_key = f"{realm_uuid}:{user_profile.id}"
+ image_data = generate_avatar_jdenticon(jdenticon_key, medium=False)
+ image_data_medium = generate_avatar_jdenticon(jdenticon_key, medium=True)
+ file_path = user_avatar_path(user_profile, future)
+
+ write_jdenticon_avatars(
+ file_path,
+ user_profile,
+ image_data=image_data,
+ image_data_medium=image_data_medium,
+ future=future,
+ )
diff --git a/zerver/lib/bulk_create.py b/zerver/lib/bulk_create.py
index 42d37f5edc6..a9c56828b83 100644
--- a/zerver/lib/bulk_create.py
+++ b/zerver/lib/bulk_create.py
@@ -4,6 +4,7 @@ from typing import Any
from django.db.models import Model, QuerySet
from django.utils.timezone import now as timezone_now
+from zerver.lib.avatar import generate_and_upload_jdenticon_avatar
from zerver.lib.create_user import create_user_profile, get_display_email_address
from zerver.lib.initial_password import initial_password
from zerver.lib.streams import (
@@ -95,6 +96,9 @@ def bulk_create_users(
user_profile.email = get_display_email_address(user_profile)
UserProfile.objects.bulk_update(profiles_to_create, ["email"])
+ for user_profile in profiles_to_create:
+ generate_and_upload_jdenticon_avatar(user_profile, str(realm.uuid), future=False)
+
user_ids = {user.id for user in profiles_to_create}
RealmAuditLog.objects.bulk_create(
diff --git a/zerver/lib/create_user.py b/zerver/lib/create_user.py
index 6585ac97091..afe5980dc47 100644
--- a/zerver/lib/create_user.py
+++ b/zerver/lib/create_user.py
@@ -162,7 +162,7 @@ def create_user(
bot_owner: UserProfile | None = None,
tos_version: str | None = None,
timezone: str = "",
- avatar_source: str = UserProfile.AVATAR_FROM_GRAVATAR,
+ avatar_source: str | None = None,
is_mirror_dummy: bool = False,
default_language: str | None = None,
default_sending_stream: Stream | None = None,
@@ -205,6 +205,8 @@ def create_user(
force_date_joined=force_date_joined,
email_address_visibility=user_email_address_visibility,
)
+ if avatar_source is None:
+ avatar_source = realm.default_avatar_source
user_profile.avatar_source = avatar_source
user_profile.timezone = timezone
user_profile.default_sending_stream = default_sending_stream
diff --git a/zerver/lib/export.py b/zerver/lib/export.py
index 2801578fc99..c1fe03c4d57 100644
--- a/zerver/lib/export.py
+++ b/zerver/lib/export.py
@@ -2084,6 +2084,13 @@ def export_uploads_and_avatars(
avatar_hash_values = set()
for avatar_user in users:
+ # We don't export Jdenticon avatar because it is deterministically
+ # generated using a combination of user ID and realm UUID as input
+ # value. Since user ID may change on import, the resulting Jdenticon
+ # would differ. Instead, we regenerate it during import using the new user ID.
+ if avatar_user.avatar_source != UserProfile.AVATAR_FROM_USER:
+ continue
+
avatar_path = user_avatar_base_path_from_ids(
avatar_user.id, avatar_user.avatar_version, realm.id
)
@@ -2364,7 +2371,7 @@ def export_avatars_from_local(
]
for user in users:
- if user.avatar_source == UserProfile.AVATAR_FROM_GRAVATAR:
+ if user.avatar_source != UserProfile.AVATAR_FROM_USER:
continue
avatar_path = user_avatar_base_path_from_ids(user.id, user.avatar_version, realm.id)
diff --git a/zerver/lib/import_realm.py b/zerver/lib/import_realm.py
index 59d6ff5fe4a..bb13c3fe2d4 100644
--- a/zerver/lib/import_realm.py
+++ b/zerver/lib/import_realm.py
@@ -29,7 +29,8 @@ from zerver.actions.realm_settings import (
do_set_realm_new_stream_announcements_stream,
do_set_realm_zulip_update_announcements_stream,
)
-from zerver.actions.user_settings import do_change_avatar_fields
+from zerver.actions.user_settings import set_avatar_to_default
+from zerver.lib.avatar import generate_and_upload_jdenticon_avatar
from zerver.lib.avatar_hash import user_avatar_base_path_from_ids
from zerver.lib.bulk_create import bulk_set_users_or_streams_recipient_fields
from zerver.lib.export import DATE_FIELDS, Field, Path, Record, TableName
@@ -937,7 +938,7 @@ def process_avatars(record: dict[str, Any]) -> None:
user_profile.id,
)
# Delete the record of the avatar to avoid 404s.
- do_change_avatar_fields(user_profile, UserProfile.AVATAR_FROM_GRAVATAR, acting_user=None)
+ set_avatar_to_default(user_profile, acting_user=None)
def process_emojis(
@@ -1759,6 +1760,14 @@ def do_import_realm(import_dir: Path, subdomain: str, processes: int = 1) -> Rea
default_user_profile_id=None, # Fail if there is no user set
)
+ # We need to generate Jdenticon avatars while importing Zulip export data
+ # as well because the export data doesn't include them. Jdenticon avatar
+ # is deterministically generated using a combination of user ID and realm UUID
+ # as input value. Since user ID possibly changes on import, the resulting
+ # Jdenticon would differ. We regenerate it here using the current user ID.
+ for user_profile in UserProfile.objects.filter(avatar_source=UserProfile.AVATAR_FROM_JDENTICON):
+ generate_and_upload_jdenticon_avatar(user_profile, str(realm.uuid), future=False)
+
# We need to have this check as the emoji files may not
# be present in import data from other services.
if os.path.exists(os.path.join(import_dir, "emoji")):
diff --git a/zerver/lib/transfer.py b/zerver/lib/transfer.py
index 758ba657aa4..2835b7f6f52 100644
--- a/zerver/lib/transfer.py
+++ b/zerver/lib/transfer.py
@@ -9,7 +9,7 @@ from zerver.lib.avatar_hash import user_avatar_path
from zerver.lib.mime_types import guess_type
from zerver.lib.parallel import run_parallel
from zerver.lib.thumbnail import BadImageError
-from zerver.lib.upload import upload_emoji_image, write_avatar_images
+from zerver.lib.upload import upload_emoji_image, write_avatar_images, write_jdenticon_avatars
from zerver.lib.upload.s3 import S3UploadBackend, upload_content_to_s3
from zerver.models import Attachment, RealmEmoji, UserProfile
@@ -30,20 +30,35 @@ def _transfer_avatar_to_s3(user: UserProfile) -> None:
assert settings.LOCAL_AVATARS_DIR is not None
file_path = os.path.join(settings.LOCAL_AVATARS_DIR, avatar_path)
try:
- with open(file_path + ".original", "rb") as f:
- # We call write_avatar_images directly to walk around the
- # content-type checking in upload_avatar_image. We don't
- # know the original file format, and we don't need to know
- # it because we never serve them directly.
- write_avatar_images(
- user_avatar_path(user, future=False),
- user,
- f.read(),
- content_type="application/octet-stream",
- backend=s3backend,
- future=False,
- )
- logging.info("Uploaded avatar for %s in realm %s", user.id, user.realm.name)
+ if user.avatar_source == UserProfile.AVATAR_FROM_USER:
+ with open(file_path + ".original", "rb") as f:
+ # We call write_avatar_images directly to walk around the
+ # content-type checking in upload_avatar_image. We don't
+ # know the original file format, and we don't need to know
+ # it because we never serve them directly.
+ write_avatar_images(
+ user_avatar_path(user, future=False),
+ user,
+ f.read(),
+ content_type="application/octet-stream",
+ backend=s3backend,
+ future=False,
+ )
+ else:
+ assert user.avatar_source == UserProfile.AVATAR_FROM_JDENTICON
+ with (
+ open(file_path + ".png", "rb") as f,
+ open(file_path + "-medium.png", "rb") as f_medium,
+ ):
+ write_jdenticon_avatars(
+ user_avatar_path(user, future=False),
+ user,
+ image_data=f.read(),
+ image_data_medium=f_medium.read(),
+ backend=s3backend,
+ future=False,
+ )
+ logging.info("Uploaded avatar for %s in realm %s", user.id, user.realm.name)
except FileNotFoundError:
pass
diff --git a/zerver/lib/upload/__init__.py b/zerver/lib/upload/__init__.py
index 58697512276..35bc7542609 100644
--- a/zerver/lib/upload/__init__.py
+++ b/zerver/lib/upload/__init__.py
@@ -339,6 +339,35 @@ def write_avatar_images(
)
+def write_jdenticon_avatars(
+ file_path: str,
+ user_profile: UserProfile,
+ *,
+ image_data: bytes,
+ image_data_medium: bytes,
+ backend: ZulipUploadBackend | None = None,
+ future: bool = True,
+) -> None:
+ if backend is None:
+ backend = upload_backend
+
+ backend.upload_single_avatar_image(
+ backend.get_avatar_path(file_path, medium=False),
+ user_profile=user_profile,
+ image_data=image_data,
+ content_type="image/png",
+ future=future,
+ )
+
+ backend.upload_single_avatar_image(
+ backend.get_avatar_path(file_path, medium=True),
+ user_profile=user_profile,
+ image_data=image_data_medium,
+ content_type="image/png",
+ future=future,
+ )
+
+
def upload_avatar_image(
user_file: IO[bytes],
user_profile: UserProfile,
@@ -367,7 +396,9 @@ def copy_avatar(source_profile: UserProfile, target_profile: UserProfile) -> Non
source_file_path = user_avatar_path(source_profile, future=False)
target_file_path = user_avatar_path(target_profile, future=True)
- image_data, content_type = upload_backend.get_avatar_contents(source_file_path)
+ image_data, content_type = upload_backend.get_avatar_contents(
+ source_file_path, source_profile.avatar_source
+ )
write_avatar_images(
target_file_path, target_profile, image_data, content_type=content_type, future=True
)
@@ -387,7 +418,7 @@ def ensure_avatar_image(user_profile: UserProfile, medium: bool = False) -> None
if os.path.isfile(output_path):
return
- image_data, _ = upload_backend.get_avatar_contents(file_path)
+ image_data, _ = upload_backend.get_avatar_contents(file_path, user_profile.avatar_source)
if medium:
resized_avatar = resize_avatar(image_data, MEDIUM_AVATAR_SIZE)
diff --git a/zerver/lib/upload/base.py b/zerver/lib/upload/base.py
index 6c9276766d4..cf3326e7191 100644
--- a/zerver/lib/upload/base.py
+++ b/zerver/lib/upload/base.py
@@ -66,7 +66,7 @@ class ZulipUploadBackend:
def get_avatar_url(self, hash_key: str, medium: bool = False) -> str:
raise NotImplementedError
- def get_avatar_contents(self, file_path: str) -> tuple[bytes, str]:
+ def get_avatar_contents(self, file_path: str, avatar_source: str) -> tuple[bytes, str]:
raise NotImplementedError
def get_avatar_path(self, hash_key: str, medium: bool = False) -> str:
diff --git a/zerver/lib/upload/local.py b/zerver/lib/upload/local.py
index a3bfb833aec..71fb0ca9f01 100644
--- a/zerver/lib/upload/local.py
+++ b/zerver/lib/upload/local.py
@@ -149,7 +149,10 @@ class LocalUploadBackend(ZulipUploadBackend):
return "/user_avatars/" + self.get_avatar_path(hash_key, medium)
@override
- def get_avatar_contents(self, file_path: str) -> tuple[bytes, str]:
+ def get_avatar_contents(self, file_path: str, avatar_source: str) -> tuple[bytes, str]:
+ # Currently, only used in codepaths where avatar_source = "U".
+ # We can extend it for avatar_source = "J", if required.
+ assert avatar_source is UserProfile.AVATAR_FROM_USER
image_data = b"".join(read_local_file("avatars", file_path + ".original"))
content_type = guess_type(file_path)[0]
return image_data, content_type or "application/octet-stream"
diff --git a/zerver/lib/upload/s3.py b/zerver/lib/upload/s3.py
index f83c0e488aa..790ce598ff9 100644
--- a/zerver/lib/upload/s3.py
+++ b/zerver/lib/upload/s3.py
@@ -332,7 +332,10 @@ class S3UploadBackend(ZulipUploadBackend):
return self.get_public_upload_url(self.get_avatar_path(hash_key, medium))
@override
- def get_avatar_contents(self, file_path: str) -> tuple[bytes, str]:
+ def get_avatar_contents(self, file_path: str, avatar_source: str) -> tuple[bytes, str]:
+ # Currently, only used in codepaths where avatar_source = "U".
+ # We can extend it for avatar_source = "J", if required.
+ assert avatar_source is UserProfile.AVATAR_FROM_USER
key = self.avatar_bucket.Object(file_path + ".original")
image_data = key.get()["Body"].read()
content_type = key.content_type
diff --git a/zerver/migrations/0001_squashed_0569.py b/zerver/migrations/0001_squashed_0569.py
index 7f95045f5fe..bd45779075b 100644
--- a/zerver/migrations/0001_squashed_0569.py
+++ b/zerver/migrations/0001_squashed_0569.py
@@ -1037,7 +1037,11 @@ class Migration(migrations.Migration):
(
"avatar_source",
models.CharField(
- choices=[("G", "Hosted by Gravatar"), ("U", "Uploaded by user")],
+ choices=[
+ ("G", "Hosted by Gravatar"),
+ ("J", "Generated using Jdenticon"),
+ ("U", "Uploaded by user"),
+ ],
default="G",
max_length=1,
),
diff --git a/zerver/migrations/0031_remove_system_avatar_source.py b/zerver/migrations/0031_remove_system_avatar_source.py
index 80e3ed63337..95d57dcbf1d 100644
--- a/zerver/migrations/0031_remove_system_avatar_source.py
+++ b/zerver/migrations/0031_remove_system_avatar_source.py
@@ -11,7 +11,11 @@ class Migration(migrations.Migration):
model_name="userprofile",
name="avatar_source",
field=models.CharField(
- choices=[("G", "Hosted by Gravatar"), ("U", "Uploaded by user")],
+ choices=[
+ ("G", "Hosted by Gravatar"),
+ ("J", "Generated using Jdenticon"),
+ ("U", "Uploaded by user"),
+ ],
max_length=1,
default="G",
),
diff --git a/zerver/models/users.py b/zerver/models/users.py
index c502f23cbf0..8ace2d46abb 100644
--- a/zerver/models/users.py
+++ b/zerver/models/users.py
@@ -653,9 +653,11 @@ class UserProfile(AbstractBaseUser, PermissionsMixin, UserBaseSettings):
timezone = models.CharField(max_length=40, default="")
AVATAR_FROM_GRAVATAR = "G"
+ AVATAR_FROM_JDENTICON = "J"
AVATAR_FROM_USER = "U"
AVATAR_SOURCES = (
(AVATAR_FROM_GRAVATAR, "Hosted by Gravatar"),
+ (AVATAR_FROM_JDENTICON, "Generated using Jdenticon"),
(AVATAR_FROM_USER, "Uploaded by user"),
)
avatar_source = models.CharField(
diff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yaml
index e5280c63421..776a16b85ec 100644
--- a/zerver/openapi/zulip.yaml
+++ b/zerver/openapi/zulip.yaml
@@ -355,9 +355,13 @@ paths:
avatar_source:
type: string
description: |
- The new avatar data source type for the user.
+ The new avatar data source type for the user. Valid values are:
- Valid values are `G` (gravatar) and `U` (uploaded by user).
+ - "G" = Hosted by Gravatar
+ - "J" = Generated using Jdenticon
+ - "U" = Uploaded by user
+
+ **Changes**: The "J" value is new in Zulip 12.0 (feature level 466).
avatar_url_medium:
type: string
description: |
@@ -4994,6 +4998,9 @@ paths:
- "G" = Hosted by Gravatar
- "J" = Generated using Jdenticon
+ Note that "U" is not a supported value here, since there is
+ no such thing as a "default" user-uploaded avatar.
+
**Changes**: New in Zulip 12.0 (feature level 456).
default_code_block_language:
type: string
@@ -19827,6 +19834,9 @@ paths:
- "G" = Hosted by Gravatar
- "J" = Generated using Jdenticon
+ Note that "U" is not a supported value here, since there is
+ no such thing as a "default" user-uploaded avatar.
+
**Changes**: New in Zulip 12.0 (feature level 456).
jitsi_server_url:
type: string
@@ -20753,9 +20763,14 @@ paths:
description: |
Present if `realm_user` is present in `fetch_event_types`.
- The avatar data source type for the current user.
+ The avatar data source type for the current user. Valid values are:
- Valid values are `G` (gravatar) and `U` (uploaded by user).
+ - "G" = Hosted by Gravatar
+ - "J" = Generated using Jdenticon
+ - "U" = Uploaded by user
+
+ **Changes**: The "J" value is new in Zulip 12.0 (feature level 466).
+ The avatar data source type for the current user.
avatar_url_medium:
type: string
description: |
diff --git a/zerver/tests/test_bots.py b/zerver/tests/test_bots.py
index a6b6809bc87..0c9c3e1d529 100644
--- a/zerver/tests/test_bots.py
+++ b/zerver/tests/test_bots.py
@@ -11,6 +11,7 @@ from zulip_bots.custom_exceptions import ConfigValidationError
from zerver.actions.bots import do_change_bot_owner, do_change_default_sending_stream
from zerver.actions.realm_settings import (
do_change_realm_permission_group_setting,
+ do_set_realm_property,
do_set_realm_user_default_setting,
)
from zerver.actions.streams import do_change_stream_permission
@@ -1514,6 +1515,10 @@ class BotTest(ZulipTestCase, UploadSerializeMixin):
def test_patch_bot_avatar(self) -> None:
self.login("hamlet")
+ bot_realm = get_realm("zulip")
+ do_set_realm_property(
+ bot_realm, "default_avatar_source", UserProfile.AVATAR_FROM_JDENTICON, acting_user=None
+ )
bot_info = {
"full_name": "The Bot of Hamlet",
"short_name": "hambot",
@@ -1522,9 +1527,9 @@ class BotTest(ZulipTestCase, UploadSerializeMixin):
self.assert_json_success(result)
bot_email = "[email protected]"
- bot_realm = get_realm("zulip")
profile = get_user(bot_email, bot_realm)
- self.assertEqual(profile.avatar_source, UserProfile.AVATAR_FROM_GRAVATAR)
+ self.assertEqual(profile.avatar_source, UserProfile.AVATAR_FROM_JDENTICON)
+ self.assertTrue(os.path.exists(avatar_disk_path(profile)))
# Try error case first (too many files):
@@ -1553,6 +1558,21 @@ class BotTest(ZulipTestCase, UploadSerializeMixin):
self.assertEqual(profile.avatar_source, UserProfile.AVATAR_FROM_USER)
self.assertTrue(os.path.exists(avatar_disk_path(profile)))
+ # Verify Bot's avatar when realm's default avatar source is Gravatar.
+ do_set_realm_property(
+ bot_realm, "default_avatar_source", UserProfile.AVATAR_FROM_GRAVATAR, acting_user=None
+ )
+ bot_info = {
+ "full_name": "Bot with gravatar",
+ "short_name": "gravatar",
+ }
+ result = self.client_post("/json/bots", bot_info)
+ self.assert_json_success(result)
+
+ bot_email = "[email protected]"
+ profile = get_user(bot_email, bot_realm)
+ self.assertEqual(profile.avatar_source, UserProfile.AVATAR_FROM_GRAVATAR)
+
def test_patch_bot_to_stream(self) -> None:
self.login("hamlet")
bot_info = {
diff --git a/zerver/tests/test_event_system.py b/zerver/tests/test_event_system.py
index 55d1c71f11a..525d25f13c4 100644
--- a/zerver/tests/test_event_system.py
+++ b/zerver/tests/test_event_system.py
@@ -16,7 +16,7 @@ from zerver.actions.custom_profile_fields import try_update_realm_custom_profile
from zerver.actions.message_send import check_send_message
from zerver.actions.presence import do_update_user_presence
from zerver.actions.streams import do_change_stream_folder
-from zerver.actions.user_settings import do_change_user_setting
+from zerver.actions.user_settings import do_change_avatar_fields, do_change_user_setting
from zerver.lib.event_schema import check_web_reload_client_event
from zerver.lib.events import fetch_initial_state_data, post_process_state
from zerver.lib.exceptions import AccessDeniedError
@@ -466,6 +466,9 @@ class GetEventsTest(ZulipTestCase):
user_profile = self.example_user("hamlet")
self.login_user(user_profile)
+ do_change_avatar_fields(user_profile, UserProfile.AVATAR_FROM_GRAVATAR, acting_user=None)
+ self.assertEqual(user_profile.avatar_source, UserProfile.AVATAR_FROM_GRAVATAR)
+
def get_message(apply_markdown: bool, client_gravatar: bool) -> dict[str, Any]:
result = self.tornado_call(
get_events,
@@ -729,6 +732,7 @@ class FetchInitialStateDataTest(ZulipTestCase):
def test_user_avatar_url_field_optional(self) -> None:
hamlet = self.example_user("hamlet")
+ aaron = self.example_user("aaron")
users = [
self.example_user("iago"),
self.example_user("cordelia"),
@@ -736,6 +740,9 @@ class FetchInitialStateDataTest(ZulipTestCase):
self.example_user("othello"),
]
+ do_change_avatar_fields(hamlet, UserProfile.AVATAR_FROM_GRAVATAR, acting_user=None)
+ do_change_avatar_fields(aaron, UserProfile.AVATAR_FROM_JDENTICON, acting_user=None)
+
for user in users:
user.long_term_idle = True
user.save()
@@ -778,8 +785,11 @@ class FetchInitialStateDataTest(ZulipTestCase):
for user_dict in raw_users.values():
if user_dict["user_id"] in gravatar_users_id:
self.assertIsNone(user_dict["avatar_url"])
- else:
+ elif user_dict["user_id"] in long_term_idle_users_ids:
self.assertFalse("avatar_url" in user_dict)
+ else:
+ # avatar source is Jdenticon
+ self.assertIsNotNone(user_dict["avatar_url"])
def test_realm_linkifiers_based_on_client_capabilities(self) -> None:
user = self.example_user("iago")
diff --git a/zerver/tests/test_events.py b/zerver/tests/test_events.py
index 09d2f646832..85a2b849f99 100644
--- a/zerver/tests/test_events.py
+++ b/zerver/tests/test_events.py
@@ -961,6 +961,8 @@ class NormalActionsTest(BaseAction):
UserProfile.EMAIL_ADDRESS_VISIBILITY_EVERYONE,
acting_user=None,
)
+ do_change_avatar_fields(hamlet, UserProfile.AVATAR_FROM_GRAVATAR, acting_user=None)
+ self.assertEqual(hamlet.avatar_source, UserProfile.AVATAR_FROM_GRAVATAR)
with self.verify_action(client_gravatar=True) as events:
self.send_stream_message(
@@ -1593,6 +1595,12 @@ class NormalActionsTest(BaseAction):
reset_email_visibility_to_everyone_in_zulip_realm()
self.user_profile = self.example_user("iago")
+ do_set_realm_property(
+ self.user_profile.realm,
+ "default_avatar_source",
+ Realm.AVATAR_FROM_GRAVATAR,
+ acting_user=None,
+ )
streams = [
get_stream(stream_name, self.user_profile.realm)
for stream_name in ["Denmark", "Scotland"]
@@ -2642,6 +2650,10 @@ class NormalActionsTest(BaseAction):
UserProfile.EMAIL_ADDRESS_VISIBILITY_ADMINS,
acting_user=None,
)
+ do_change_avatar_fields(
+ self.user_profile, UserProfile.AVATAR_FROM_GRAVATAR, acting_user=None
+ )
+ self.assertEqual(self.user_profile.avatar_source, UserProfile.AVATAR_FROM_GRAVATAR)
# Important: We need to refresh from the database here so that
# we don't have a stale UserProfile object with an old value
# for email being passed into this next function.
@@ -2663,6 +2675,10 @@ class NormalActionsTest(BaseAction):
UserProfile.EMAIL_ADDRESS_VISIBILITY_EVERYONE,
acting_user=None,
)
+ do_change_avatar_fields(
+ self.user_profile, UserProfile.AVATAR_FROM_GRAVATAR, acting_user=None
+ )
+ self.assertEqual(self.user_profile.avatar_source, UserProfile.AVATAR_FROM_GRAVATAR)
# Important: We need to refresh from the database here so that
# we don't have a stale UserProfile object with an old value
# for email being passed into this next function.
diff --git a/zerver/tests/test_message_fetch.py b/zerver/tests/test_message_fetch.py
index 3ae92064145..931b7b64926 100644
--- a/zerver/tests/test_message_fetch.py
+++ b/zerver/tests/test_message_fetch.py
@@ -19,7 +19,7 @@ from zerver.actions.reactions import check_add_reaction
from zerver.actions.realm_settings import do_set_realm_property
from zerver.actions.streams import do_deactivate_stream
from zerver.actions.uploads import do_claim_attachments
-from zerver.actions.user_settings import do_change_user_setting
+from zerver.actions.user_settings import do_change_avatar_fields, do_change_user_setting
from zerver.actions.users import do_deactivate_user
from zerver.lib.avatar import avatar_url
from zerver.lib.display_recipient import get_display_recipient
@@ -2454,6 +2454,9 @@ class GetOldMessagesTest(ZulipTestCase):
hamlet = self.example_user("hamlet")
self.login_user(hamlet)
+ do_change_avatar_fields(hamlet, UserProfile.AVATAR_FROM_GRAVATAR, acting_user=None)
+ self.assertEqual(hamlet.avatar_source, UserProfile.AVATAR_FROM_GRAVATAR)
+
do_change_user_setting(
hamlet,
"email_address_visibility",
diff --git a/zerver/tests/test_outgoing_webhook_interfaces.py b/zerver/tests/test_outgoing_webhook_interfaces.py
index 2e3121b0a99..c1424105867 100644
--- a/zerver/tests/test_outgoing_webhook_interfaces.py
+++ b/zerver/tests/test_outgoing_webhook_interfaces.py
@@ -5,7 +5,7 @@ from unittest import mock
import requests
from typing_extensions import override
-from zerver.lib.avatar import get_gravatar_url
+from zerver.lib.avatar import avatar_url
from zerver.lib.exceptions import JsonableError
from zerver.lib.message_cache import MessageDict
from zerver.lib.outgoing_webhook import get_service_interface_class, process_success_response
@@ -73,14 +73,8 @@ class TestGenericOutgoingWebhookService(ZulipTestCase):
message = Message.objects.get(id=message_id)
- gravatar_url = get_gravatar_url(
- othello.delivery_email,
- othello.avatar_version,
- get_realm("zulip").id,
- )
-
- expected_message_data = {
- "avatar_url": gravatar_url,
+ expected_message_data: dict[str, Any] = {
+ "avatar_url": avatar_url(othello),
"client": "test suite",
"content": "@**test**",
"content_type": "text/x-markdown",
diff --git a/zerver/tests/test_transfer.py b/zerver/tests/test_transfer.py
index 606a92227c7..53982f6e1f9 100644
--- a/zerver/tests/test_transfer.py
+++ b/zerver/tests/test_transfer.py
@@ -4,7 +4,9 @@ from unittest.mock import Mock, patch
from django.conf import settings
from moto.core.decorator import mock_aws
+from zerver.actions.create_user import do_create_user
from zerver.actions.realm_emoji import check_add_realm_emoji
+from zerver.actions.realm_settings import do_set_realm_property
from zerver.lib.avatar_hash import user_avatar_path
from zerver.lib.test_classes import ZulipTestCase
from zerver.lib.test_helpers import (
@@ -21,7 +23,7 @@ from zerver.lib.transfer import (
transfer_uploads_to_s3,
)
from zerver.lib.upload import upload_message_attachment
-from zerver.models import Attachment, RealmEmoji
+from zerver.models import Attachment, Realm, RealmEmoji, UserProfile
class TransferUploadsToS3Test(ZulipTestCase):
@@ -37,29 +39,45 @@ class TransferUploadsToS3Test(ZulipTestCase):
@mock_aws
def test_transfer_avatars_to_s3(self) -> None:
+ """Verify user uploaded avatar and Jdenticon generated avatar gets transferred"""
bucket = create_s3_buckets(settings.S3_AVATAR_BUCKET)[0]
self.login("hamlet")
+ hamlet = self.example_user("hamlet")
+ do_set_realm_property(
+ hamlet.realm, "default_avatar_source", Realm.AVATAR_FROM_JDENTICON, acting_user=None
+ )
+ jerry = do_create_user("email1", "password", hamlet.realm, "jerry", acting_user=None)
with get_test_image_file("img.png") as image_file:
self.client_post("/json/users/me/avatar", {"file": image_file})
- user = self.example_user("hamlet")
+ hamlet.refresh_from_db()
+ self.assertEqual(hamlet.avatar_source, UserProfile.AVATAR_FROM_USER)
+ self.assertEqual(jerry.avatar_source, UserProfile.AVATAR_FROM_JDENTICON)
with self.assertLogs(level="INFO"):
transfer_avatars_to_s3(1)
- path_id = user_avatar_path(user)
- image_key = bucket.Object(path_id + ".png")
- original_image_key = bucket.Object(path_id + ".original")
- medium_image_key = bucket.Object(path_id + "-medium.png")
-
- self.assert_length(list(bucket.objects.all()), 3)
- with open(avatar_disk_path(user), "rb") as f:
- self.assertEqual(image_key.get()["Body"].read(), f.read())
- with open(avatar_disk_path(user, original=True), "rb") as f:
- self.assertEqual(original_image_key.get()["Body"].read(), f.read())
- with open(avatar_disk_path(user, medium=True), "rb") as f:
- self.assertEqual(medium_image_key.get()["Body"].read(), f.read())
+ path_id_hamlet = user_avatar_path(hamlet)
+ image_key_hamlet = bucket.Object(path_id_hamlet + ".png")
+ original_image_key_hamlet = bucket.Object(path_id_hamlet + ".original")
+ medium_image_key_hamlet = bucket.Object(path_id_hamlet + "-medium.png")
+
+ path_id_jerry = user_avatar_path(jerry)
+ image_key_jerry = bucket.Object(path_id_jerry + ".png")
+ medium_image_key_jerry = bucket.Object(path_id_jerry + "-medium.png")
+
+ self.assert_length(list(bucket.objects.all()), 5)
+ with open(avatar_disk_path(hamlet), "rb") as f:
+ self.assertEqual(image_key_hamlet.get()["Body"].read(), f.read())
+ with open(avatar_disk_path(hamlet, original=True), "rb") as f:
+ self.assertEqual(original_image_key_hamlet.get()["Body"].read(), f.read())
+ with open(avatar_disk_path(hamlet, medium=True), "rb") as f:
+ self.assertEqual(medium_image_key_hamlet.get()["Body"].read(), f.read())
+ with open(avatar_disk_path(jerry), "rb") as f:
+ self.assertEqual(image_key_jerry.get()["Body"].read(), f.read())
+ with open(avatar_disk_path(jerry, medium=True), "rb") as f:
+ self.assertEqual(medium_image_key_jerry.get()["Body"].read(), f.read())
@mock_aws
def test_transfer_message_files(self) -> None:
diff --git a/zerver/tests/test_upload.py b/zerver/tests/test_upload.py
index b2f0dd4587e..110246510de 100644
--- a/zerver/tests/test_upload.py
+++ b/zerver/tests/test_upload.py
@@ -1151,6 +1151,22 @@ class AvatarTest(UploadSerializeMixin, ZulipTestCase):
"/user_avatars/5/ff062b0fee41738b38c4312bb33bdf3fe2aad463-medium.png",
)
+ with self.settings(AVATAR_SALT="salt"):
+ url = get_avatar_field(
+ user_id=18,
+ realm_id=4,
+ avatar_source=UserProfile.AVATAR_FROM_JDENTICON,
+ avatar_version=2,
+ medium=True,
+ client_gravatar=False,
+ )
+
+ self.assertEqual(
+ url,
+ "/user_avatars/4/899f0055b9b2d23cd53c9370c681ccee3d50da7a-medium.png",
+ )
+
url = get_avatar_field(
user_id=9999,
realm_id=9999,
@@ -1295,6 +1311,7 @@ class AvatarTest(UploadSerializeMixin, ZulipTestCase):
self.login("hamlet")
cordelia = self.example_user("cordelia")
cordelia.email = cordelia.delivery_email
+ cordelia.avatar_source = UserProfile.AVATAR_FROM_GRAVATAR
cordelia.save()
with self.settings(
ENABLE_GRAVATAR=False, DEFAULT_AVATAR_URI="http://other.server/avatar.svg"
@@ -1303,7 +1320,7 @@ class AvatarTest(UploadSerializeMixin, ZulipTestCase):
redirect_url = response["Location"]
self.assertEqual(redirect_url, "http://other.server/avatar.svg?version=1&foo=bar")
- def test_get_user_avatar(self) -> None:
+ def _test_get_avatar(self) -> None:
hamlet = self.example_user("hamlet")
self.login_user(hamlet)
cordelia = self.example_user("cordelia")
@@ -1313,8 +1330,6 @@ class AvatarTest(UploadSerializeMixin, ZulipTestCase):
internal_realm = get_realm(settings.SYSTEM_BOT_REALM)
cross_realm_bot = get_system_bot(settings.WELCOME_BOT, internal_realm.id)
- cordelia.avatar_source = UserProfile.AVATAR_FROM_USER
- cordelia.save()
response = self.client_get("/avatar/[email protected]", {"foo": "bar"})
redirect_url = response["Location"]
self.assertTrue(redirect_url.endswith(str(avatar_url(cordelia)) + "?foo=bar"))
@@ -1395,15 +1410,27 @@ class AvatarTest(UploadSerializeMixin, ZulipTestCase):
redirect_url = response["Location"]
self.assertTrue(redirect_url.endswith("images/unknown-user-avatar.png?foo=bar"))
- def test_get_user_avatar_medium(self) -> None:
+ def test_get_user_avatar(self) -> None:
+ cordelia = self.example_user("cordelia")
+ cordelia.avatar_source = UserProfile.AVATAR_FROM_USER
+ cordelia.save()
+
+ self._test_get_avatar()
+
+ def test_get_jdenticon_avatar(self) -> None:
+ cordelia = self.example_user("cordelia")
+ cordelia.avatar_source = UserProfile.AVATAR_FROM_JDENTICON
+ cordelia.save()
+
+ self._test_get_avatar()
+
+ def _test_get_avatar_medium(self) -> None:
hamlet = self.example_user("hamlet")
self.login_user(hamlet)
cordelia = self.example_user("cordelia")
cordelia.email = cordelia.delivery_email
cordelia.save()
- cordelia.avatar_source = UserProfile.AVATAR_FROM_USER
- cordelia.save()
response = self.client_get("/avatar/[email protected]/medium", {"foo": "bar"})
redirect_url = response["Location"]
self.assertTrue(redirect_url.endswith(str(avatar_url(cordelia, True)) + "?foo=bar"))
@@ -1454,6 +1481,20 @@ class AvatarTest(UploadSerializeMixin, ZulipTestCase):
response = self.client_get(f"/avatar/{cordelia.id}/medium", {"foo": "bar"})
self.assertEqual(429, response.status_code)
+ def test_get_user_avatar_medium(self) -> None:
+ cordelia = self.example_user("cordelia")
+ cordelia.avatar_source = UserProfile.AVATAR_FROM_USER
+ cordelia.save()
+
+ self._test_get_avatar_medium()
+
+ def test_get_jdenticon_avatar_medium(self) -> None:
+ cordelia = self.example_user("cordelia")
+ cordelia.avatar_source = UserProfile.AVATAR_FROM_JDENTICON
+ cordelia.save()
+
+ self._test_get_avatar_medium()
+
def test_non_valid_user_avatar(self) -> None:
# It's debatable whether we should generate avatars for non-users,
# but this test just validates the current code's behavior.
@@ -1606,27 +1647,52 @@ class AvatarTest(UploadSerializeMixin, ZulipTestCase):
def test_delete_avatar(self) -> None:
"""
- A DELETE request to /json/users/me/avatar should delete the profile picture and return gravatar URL
+ A DELETE request to /json/users/me/avatar should delete the profile picture
+ and return URL corresponding to the realm's default avatar source.
"""
self.login("cordelia")
cordelia = self.example_user("cordelia")
+ realm = cordelia.realm
cordelia.avatar_source = UserProfile.AVATAR_FROM_USER
cordelia.save()
- do_set_realm_property(cordelia.realm, "avatar_changes_disabled", True, acting_user=None)
+ # On deletion, cordelia's avatar should be Jdenticon generated.
+ do_set_realm_property(
+ realm, "default_avatar_source", Realm.AVATAR_FROM_JDENTICON, acting_user=None
+ )
+ self.assertEqual(realm.default_avatar_source, Realm.AVATAR_FROM_JDENTICON)
+
+ do_set_realm_property(realm, "avatar_changes_disabled", True, acting_user=None)
result = self.client_delete("/json/users/me/avatar")
self.assert_json_error(result, "Avatar changes are disabled in this organization.", 400)
- do_set_realm_property(cordelia.realm, "avatar_changes_disabled", False, acting_user=None)
+ do_set_realm_property(realm, "avatar_changes_disabled", False, acting_user=None)
result = self.client_delete("/json/users/me/avatar")
- user_profile = self.example_user("cordelia")
-
response_dict = self.assert_json_success(result)
+
+ cordelia.refresh_from_db()
self.assertIn("avatar_url", response_dict)
- self.assertEqual(response_dict["avatar_url"], avatar_url(user_profile))
+ self.assertEqual(response_dict["avatar_url"], avatar_url(cordelia))
+ self.assertEqual(cordelia.avatar_source, UserProfile.AVATAR_FROM_JDENTICON)
+ self.assertEqual(cordelia.avatar_version, 2)
+
+ # On deletion, hamlet's avatar should be a Gravatar.
+ do_set_realm_property(
+ realm, "default_avatar_source", Realm.AVATAR_FROM_GRAVATAR, acting_user=None
+ )
+
+ self.login("hamlet")
+ hamlet = self.example_user("hamlet")
+ hamlet.avatar_source = UserProfile.AVATAR_FROM_USER
+ hamlet.save(update_fields=["avatar_source"])
+
+ result = self.client_delete("/json/users/me/avatar")
+ response_dict = self.assert_json_success(result)
- self.assertEqual(user_profile.avatar_source, UserProfile.AVATAR_FROM_GRAVATAR)
- self.assertEqual(user_profile.avatar_version, 2)
+ hamlet.refresh_from_db()
+ self.assertEqual(hamlet.avatar_source, UserProfile.AVATAR_FROM_GRAVATAR)
+ self.assertEqual(response_dict["avatar_url"], avatar_url(hamlet))
+ self.assertEqual(hamlet.avatar_version, 2)
def test_avatar_upload_file_size_error(self) -> None:
self.login("hamlet")
diff --git a/zerver/tests/test_upload_local.py b/zerver/tests/test_upload_local.py
index 2d6ee55128b..46a158d57a3 100644
--- a/zerver/tests/test_upload_local.py
+++ b/zerver/tests/test_upload_local.py
@@ -31,7 +31,7 @@ from zerver.lib.upload.base import StreamingSourceWithSize
from zerver.lib.upload.local import write_local_file
from zerver.models import Attachment, RealmEmoji
from zerver.models.realms import get_realm
-from zerver.models.users import get_system_bot
+from zerver.models.users import UserProfile, get_system_bot
class LocalStorageTest(UploadSerializeMixin, ZulipTestCase):
@@ -206,6 +206,8 @@ class LocalStorageTest(UploadSerializeMixin, ZulipTestCase):
file_path = user_avatar_path(user_profile)
write_local_file("avatars", file_path + ".original", read_test_image_file("img.png"))
+ user_profile.avatar_source = UserProfile.AVATAR_FROM_USER
+ user_profile.save()
assert settings.LOCAL_UPLOADS_DIR is not None
assert settings.LOCAL_AVATARS_DIR is not None
diff --git a/zerver/tests/test_upload_s3.py b/zerver/tests/test_upload_s3.py
index dbf00fe2b9e..16bf8bfc1c5 100644
--- a/zerver/tests/test_upload_s3.py
+++ b/zerver/tests/test_upload_s3.py
@@ -417,6 +417,8 @@ class S3Test(ZulipTestCase):
with get_test_image_file("img.png") as image_file:
zerver.lib.upload.upload_avatar_image(image_file, user_profile, future=False)
+ user_profile.avatar_source = UserProfile.AVATAR_FROM_USER
+ user_profile.save()
test_image_data = read_test_image_file("img.png")
test_medium_image_data = resize_avatar(test_image_data, MEDIUM_AVATAR_SIZE)
@@ -501,6 +503,8 @@ class S3Test(ZulipTestCase):
with get_test_image_file("img.png") as image_file:
zerver.lib.upload.upload_avatar_image(image_file, user_profile, future=False)
+ user_profile.avatar_source = UserProfile.AVATAR_FROM_USER
+ user_profile.save()
key = bucket.Object(original_file_path)
image_data = key.get()["Body"].read()
diff --git a/zerver/tests/test_users.py b/zerver/tests/test_users.py
index 8b62fc38123..f0c701be3f4 100644
--- a/zerver/tests/test_users.py
+++ b/zerver/tests/test_users.py
@@ -24,6 +24,7 @@ from zerver.actions.realm_settings import (
)
from zerver.actions.user_settings import (
bulk_regenerate_api_keys,
+ do_change_avatar_fields,
do_change_full_name,
do_change_user_setting,
)
@@ -361,6 +362,9 @@ class PermissionTest(ZulipTestCase):
admin = self.example_user("iago")
self.login_user(user)
+ do_change_avatar_fields(user, UserProfile.AVATAR_FROM_GRAVATAR, acting_user=None)
+ self.assertEqual(user.avatar_source, UserProfile.AVATAR_FROM_GRAVATAR)
+
# First, verify client_gravatar works normally
result = self.client_get("/json/users", {"client_gravatar": "true"})
members = self.assert_json_success(result)["members"]
@@ -393,7 +397,8 @@ class PermissionTest(ZulipTestCase):
hamlet = find_dict(members, "user_id", user.id)
self.assertEqual(hamlet["email"], f"user{user.id}@zulip.testserver")
self.assertEqual(
- hamlet["avatar_url"], get_gravatar_url(user.delivery_email, 1, get_realm("zulip").id)
+ hamlet["avatar_url"],
+ get_gravatar_url(user.delivery_email, user.avatar_version, get_realm("zulip").id),
)
# client_gravatar is still turned off for admins. In theory,
@@ -408,7 +413,8 @@ class PermissionTest(ZulipTestCase):
hamlet = find_dict(members, "user_id", user.id)
self.assertEqual(hamlet["email"], f"user{user.id}@zulip.testserver")
self.assertEqual(
- hamlet["avatar_url"], get_gravatar_url(user.delivery_email, 1, get_realm("zulip").id)
+ hamlet["avatar_url"],
+ get_gravatar_url(user.delivery_email, user.avatar_version, get_realm("zulip").id),
)
self.assertEqual(hamlet["delivery_email"], self.example_email("hamlet"))
@@ -3230,6 +3236,8 @@ class BulkUsersTest(ZulipTestCase):
self.login("cordelia")
hamlet = self.example_user("hamlet")
+ do_change_avatar_fields(hamlet, UserProfile.AVATAR_FROM_GRAVATAR, acting_user=None)
+ self.assertEqual(hamlet.avatar_source, UserProfile.AVATAR_FROM_GRAVATAR)
def get_hamlet_avatar(client_gravatar: bool) -> str | None:
data = dict(client_gravatar=orjson.dumps(client_gravatar).decode())
diff --git a/zerver/views/user_settings.py b/zerver/views/user_settings.py
index 573637b4e91..58843eafd61 100644
--- a/zerver/views/user_settings.py
+++ b/zerver/views/user_settings.py
@@ -33,6 +33,7 @@ from zerver.actions.user_settings import (
do_change_user_setting,
do_regenerate_api_key,
do_start_email_change_process,
+ set_avatar_to_default,
)
from zerver.actions.users import generate_password_reset_url
from zerver.decorator import human_users_only, require_post
@@ -577,13 +578,11 @@ def delete_avatar_backend(request: HttpRequest, user_profile: UserProfile) -> Ht
raise JsonableError(str(AVATAR_CHANGES_DISABLED_ERROR))
if user_profile.avatar_source == UserProfile.AVATAR_FROM_USER:
- do_change_avatar_fields(
- user_profile, UserProfile.AVATAR_FROM_GRAVATAR, acting_user=user_profile
- )
+ set_avatar_to_default(user_profile, acting_user=user_profile)
- gravatar_url = avatar_url(user_profile)
+ default_avatar_url = avatar_url(user_profile)
json_result = dict(
- avatar_url=gravatar_url,
+ avatar_url=default_avatar_url,
)
return json_success(request, data=json_result)
diff --git a/zerver/views/users.py b/zerver/views/users.py
index 23182b31a2d..a598ec4cce4 100644
--- a/zerver/views/users.py
+++ b/zerver/views/users.py
@@ -693,12 +693,11 @@ def add_bot_backend(
check_valid_bot_type(user_profile, bot_type)
check_valid_interface_type(interface_type)
- if len(request.FILES) == 0:
- avatar_source = UserProfile.AVATAR_FROM_GRAVATAR
- elif len(request.FILES) != 1:
- raise JsonableError(_("You may only upload one file at a time"))
- else:
+ avatar_source = None
+ if len(request.FILES) == 1:
avatar_source = UserProfile.AVATAR_FROM_USER
+ elif len(request.FILES) > 1:
+ raise JsonableError(_("You may only upload one file at a time"))
default_sending_stream = None
if default_sending_stream_name is not None: