response stringlengths 1 33.1k | instruction stringlengths 22 582k |
|---|---|
This is required over access_stream_* in certain cases where
we need the stream data only to prepare a response that user can access
and not send it out to unauthorized recipients. | def get_stream_by_narrow_operand_access_unchecked(operand: Union[str, int], realm: Realm) -> Stream:
"""This is required over access_stream_* in certain cases where
we need the stream data only to prepare a response that user can access
and not send it out to unauthorized recipients.
"""
if isinstan... |
Get streams with subscribers | def get_occupied_streams(realm: Realm) -> QuerySet[Stream]:
"""Get streams with subscribers"""
exists_expression = Exists(
Subscription.objects.filter(
active=True,
is_user_active=True,
user_profile__realm=realm,
recipient_id=OuterRef("recipient_id"),
... |
Fetch which stream colors have already been used for each user in
user_ids. Uses an optimized query designed to support picking
colors when bulk-adding users to streams, which requires
inspecting all Subscription objects for the users, which can often
end up being all Subscription objects in the realm. | def get_used_colors_for_user_ids(user_ids: List[int]) -> Dict[int, Set[str]]:
"""Fetch which stream colors have already been used for each user in
user_ids. Uses an optimized query designed to support picking
colors when bulk-adding users to streams, which requires
inspecting all Subscription objects fo... |
Glossary:
subscribed_ids:
This shows the users who are actually subscribed to the
stream, which we generally send to the person subscribing
to the stream.
private_peer_dict:
These are the folks that need to know about a new subscriber.
It's usually a superset of the sub... | def bulk_get_subscriber_peer_info(
realm: Realm,
streams: Collection[Stream] | QuerySet[Stream],
) -> SubscriberPeerInfo:
"""
Glossary:
subscribed_ids:
This shows the users who are actually subscribed to the
stream, which we generally send to the person subscribing
... |
Returns the set of active user IDs who can access any message
history on this stream (regardless of whether they have a
UserMessage) based on the stream's configuration.
1. if !history_public_to_subscribers:
History is not available to anyone
2. if history_public_to_subscribers:
All subscribers can access ... | def subscriber_ids_with_stream_history_access(stream: Stream) -> Set[int]:
"""Returns the set of active user IDs who can access any message
history on this stream (regardless of whether they have a
UserMessage) based on the stream's configuration.
1. if !history_public_to_subscribers:
History... |
This function optimizes an important use case for large
streams. Open realms often have many long_term_idle users, which
can result in 10,000s of long_term_idle recipients in default
streams. do_send_messages has an optimization to avoid doing work
for long_term_idle unless message flags or notifications should be
gene... | def get_subscriptions_for_send_message(
*,
realm_id: int,
stream_id: int,
topic_name: str,
possible_stream_wildcard_mention: bool,
topic_participant_user_ids: AbstractSet[int],
possibly_mentioned_user_ids: AbstractSet[int],
) -> QuerySet[Subscription]:
"""This function optimizes an impor... |
Validates whether the user can view the subscribers of a stream. Raises a JsonableError if:
* The user and the stream are in different realms
* The realm is MIT and the stream is not invite only.
* The stream is invite only, requesting_user is passed, and that user
does not subscribe to the stream. | def validate_user_access_to_subscribers(
user_profile: Optional[UserProfile], stream: Stream
) -> None:
"""Validates whether the user can view the subscribers of a stream. Raises a JsonableError if:
* The user and the stream are in different realms
* The realm is MIT and the stream is not invite only.
... |
Helper for validate_user_access_to_subscribers that doesn't require
a full stream object. This function is a bit hard to read,
because it is carefully optimized for performance in the two code
paths we call it from:
* In `bulk_get_subscriber_user_ids`, we already know whether the
user was subscribed via `sub_dict`, a... | def validate_user_access_to_subscribers_helper(
user_profile: Optional[UserProfile],
stream_dict: Mapping[str, Any],
check_user_subscribed: Callable[[UserProfile], bool],
) -> None:
"""Helper for validate_user_access_to_subscribers that doesn't require
a full stream object. This function is a bit h... |
sub_dict maps stream_id => whether the user is subscribed to that stream. | def bulk_get_subscriber_user_ids(
stream_dicts: Collection[Mapping[str, Any]],
user_profile: UserProfile,
subscribed_stream_ids: Set[int],
) -> Dict[int, List[int]]:
"""sub_dict maps stream_id => whether the user is subscribed to that stream."""
target_stream_dicts = []
is_subscribed: bool
c... |
Build a query to get the subscribers list for a stream, raising a JsonableError if:
'realm' is optional in stream.
The caller can refine this query with select_related(), values(), etc. depending
on whether it wants objects or just certain fields | def get_subscribers_query(
stream: Stream, requesting_user: Optional[UserProfile]
) -> QuerySet[Subscription]:
"""Build a query to get the subscribers list for a stream, raising a JsonableError if:
'realm' is optional in stream.
The caller can refine this query with select_related(), values(), etc. de... |
Given a list of values, return a string nicely formatting those values,
summarizing when you have more than `display_limit`. Eg, for a
`display_limit` of 3 we get the following possible cases:
Jessica
Jessica and Waseem
Jessica, Waseem, and Tim
Jessica, Waseem, Tim, and 1 other
Jessica, Waseem, Tim, and 2 others | def display_list(values: List[str], display_limit: int) -> str:
"""
Given a list of values, return a string nicely formatting those values,
summarizing when you have more than `display_limit`. Eg, for a
`display_limit` of 3 we get the following possible cases:
Jessica
Jessica and Waseem
Jes... |
Given a path to a Markdown file, return the rendered HTML.
Note that this assumes that any HTML in the Markdown file is
trusted; it is intended to be used for documentation, not user
data. | def render_markdown_path(
markdown_file_path: str,
context: Optional[Dict[str, Any]] = None,
integration_doc: bool = False,
help_center: bool = False,
) -> str:
"""Given a path to a Markdown file, return the rendered HTML.
Note that this assumes that any HTML in the Markdown file is
trusted... |
Checks whether the zulip_test_template database template, is
consistent with our database migrations; if not, it updates it
in the fastest way possible:
* If all we need to do is add some migrations, just runs those
migrations on the template database.
* Otherwise, we rebuild the test template database from scratch.... | def update_test_databases_if_required(rebuild_test_database: bool = False) -> None:
"""Checks whether the zulip_test_template database template, is
consistent with our database migrations; if not, it updates it
in the fastest way possible:
* If all we need to do is add some migrations, just runs those
... |
The logic in zerver/lib/test_runner.py tries to delete all the
temporary test databases generated by test-backend threads, but it
cannot guarantee it handles all race conditions correctly. This
is a catch-all function designed to delete any that might have
been leaked due to crashes (etc.). The high-level algorithm i... | def destroy_leaked_test_databases(expiry_time: int = 60 * 60) -> int:
"""The logic in zerver/lib/test_runner.py tries to delete all the
temporary test databases generated by test-backend threads, but it
cannot guarantee it handles all race conditions correctly. This
is a catch-all function designed to ... |
This function is used to reset the zulip_test database fastest way possible,
i.e. First, it deletes the database and then clones it from zulip_test_template.
This function is used with puppeteer tests, so it can quickly reset the test
database after each run. | def reset_zulip_test_database() -> None:
"""
This function is used to reset the zulip_test database fastest way possible,
i.e. First, it deletes the database and then clones it from zulip_test_template.
This function is used with puppeteer tests, so it can quickly reset the test
database after each ... |
Allow a user to capture just the queries executed during
the with statement. | def queries_captured(
include_savepoints: bool = False, keep_cache_warm: bool = False
) -> Iterator[List[CapturedQuery]]:
"""
Allow a user to capture just the queries executed during
the with statement.
"""
queries: List[CapturedQuery] = []
def cursor_execute(self: TimeTrackingCursor, sql:... |
Redirect stdout to /dev/null. | def stdout_suppressed() -> Iterator[IO[str]]:
"""Redirect stdout to /dev/null."""
with open(os.devnull, "a") as devnull:
stdout, sys.stdout = sys.stdout, devnull
try:
yield stdout
finally:
sys.stdout = stdout |
This function is used to reset email visibility for all users and
RealmUserDefault object in the zulip realm in development environment
to "EMAIL_ADDRESS_VISIBILITY_EVERYONE" since the default value is
"EMAIL_ADDRESS_VISIBILITY_ADMINS". This function is needed in
tests that want "email" field of users to be set to thei... | def reset_email_visibility_to_everyone_in_zulip_realm() -> None:
"""
This function is used to reset email visibility for all users and
RealmUserDefault object in the zulip realm in development environment
to "EMAIL_ADDRESS_VISIBILITY_EVERYONE" since the default value is
"EMAIL_ADDRESS_VISIBILITY_ADM... |
Temporarily add a rate-limiting rule to the ratelimiter | def ratelimit_rule(
range_seconds: int,
num_requests: int,
domain: str = "api_by_user",
) -> Iterator[None]:
"""Temporarily add a rate-limiting rule to the ratelimiter"""
RateLimitedIPAddr("127.0.0.1", domain=domain).clear_history()
domain_rules = rules.get(domain, []).copy()
domain_rules.a... |
This function runs only under parallel mode. It initializes the
individual processes which are also called workers. | def init_worker(
counter: "multiprocessing.sharedctypes.Synchronized[int]",
initial_settings: Optional[Dict[str, Any]] = None,
serialized_contents: Optional[Dict[str, str]] = None,
process_setup: Optional[Callable[..., None]] = None,
process_setup_args: Optional[Tuple[Any, ...]] = None,
debug_mo... |
Render a TeX string into HTML using KaTeX
Returns the HTML string, or None if there was some error in the TeX syntax
Keyword arguments:
tex -- Text string with the TeX to render
Don't include delimiters ('$$', '\[ \]', etc.)
is_inline -- Boolean setting that indicates whether the render should be
... | def render_tex(tex: str, is_inline: bool = True) -> Optional[str]:
r"""Render a TeX string into HTML using KaTeX
Returns the HTML string, or None if there was some error in the TeX syntax
Keyword arguments:
tex -- Text string with the TeX to render
Don't include delimiters ('$$', '\[ \]', e... |
Call the function in a separate thread.
Return its return value, or raise an exception,
within approximately 'timeout' seconds.
The function may receive a TimeoutExpiredError exception
anywhere in its code, which could have arbitrary
unsafe effects (resources not released, etc.).
It might also fail to receive the exce... | def unsafe_timeout(timeout: float, func: Callable[[], ResultT]) -> ResultT:
"""Call the function in a separate thread.
Return its return value, or raise an exception,
within approximately 'timeout' seconds.
The function may receive a TimeoutExpiredError exception
anywhere in its code, which could h... |
Use this where you are getting dicts that are based off of messages
that may come from the outside world, especially from third party
APIs and bots.
We prefer 'topic' to 'subject' here. We expect at least one field
to be present (or the caller must know how to handle KeyError). | def get_topic_from_message_info(message_info: Dict[str, Any]) -> str:
"""
Use this where you are getting dicts that are based off of messages
that may come from the outside world, especially from third party
APIs and bots.
We prefer 'topic' to 'subject' here. We expect at least one field
to be... |
Resolved topics are denoted only by a title change, not by a boolean toggle in a database column. This
method inspects the topic name and returns a tuple of:
- Whether the topic has been resolved
- The topic name with the resolution prefix, if present in stored_name, removed | def get_topic_resolution_and_bare_name(stored_name: str) -> Tuple[bool, str]:
"""
Resolved topics are denoted only by a title change, not by a boolean toggle in a database column. This
method inspects the topic name and returns a tuple of:
- Whether the topic has been resolved
- The topic name with... |
Users who either sent or reacted to the messages in the topic.
The function is expensive for large numbers of messages in the topic. | def participants_for_topic(realm_id: int, recipient_id: int, topic_name: str) -> Set[int]:
"""
Users who either sent or reacted to the messages in the topic.
The function is expensive for large numbers of messages in the topic.
"""
messages = Message.objects.filter(
# Uses index: zerver_mess... |
This is responsible for inspecting the function signature and getting the
metadata from the parameters. We want to keep this function as pure as
possible not leaking side effects to the global state. Side effects should
be executed separately after the ViewFuncInfo is returned. | def parse_view_func_signature(
view_func: Callable[Concatenate[HttpRequest, ParamT], object],
) -> ViewFuncInfo:
"""This is responsible for inspecting the function signature and getting the
metadata from the parameters. We want to keep this function as pure as
possible not leaking side effects to the gl... |
Master function for accessing another user by ID in API code;
verifies the user ID is in the same realm, and if requested checks
for administrative privileges, with flags for various special
cases. | def access_user_by_id(
user_profile: UserProfile,
target_user_id: int,
*,
allow_deactivated: bool = False,
allow_bots: bool = False,
for_admin: bool,
) -> UserProfile:
"""Master function for accessing another user by ID in API code;
verifies the user ID is in the same realm, and if reque... |
Variant of access_user_by_id allowing cross-realm bots to be accessed. | def access_user_by_id_including_cross_realm(
user_profile: UserProfile,
target_user_id: int,
*,
allow_deactivated: bool = False,
allow_bots: bool = False,
for_admin: bool,
) -> UserProfile:
"""Variant of access_user_by_id allowing cross-realm bots to be accessed."""
try:
target =... |
Formats a user row returned by a database fetch using
.values(*realm_user_dict_fields) into a dictionary representation
of that user for API delivery to clients. The acting_user
argument is used for permissions checks. | def format_user_row(
realm_id: int,
acting_user: Optional[UserProfile],
row: RawUserDict,
client_gravatar: bool,
user_avatar_url_field_optional: bool,
custom_profile_field_data: Optional[Dict[str, Any]] = None,
) -> APIUserDict:
"""Formats a user row returned by a database fetch using
.v... |
Fetches data about the target user(s) appropriate for sending to
acting_user via the standard format for the Zulip API. If
target_user is None, we fetch all users in the realm. | def get_users_for_api(
realm: Realm,
acting_user: Optional[UserProfile],
*,
target_user: Optional[UserProfile] = None,
client_gravatar: bool,
user_avatar_url_field_optional: bool,
include_custom_profile_fields: bool = True,
user_list_incomplete: bool = False,
) -> Dict[int, APIUserDict]:... |
It is generally unsafe to call is_verified directly on `request.user` since
the attribute `otp_device` does not exist on an `AnonymousUser`, and `is_verified`
does not make sense without 2FA being enabled.
This wraps the checks for all these assumptions to make sure the call is safe. | def is_2fa_verified(user: UserProfile) -> bool:
"""
It is generally unsafe to call is_verified directly on `request.user` since
the attribute `otp_device` does not exist on an `AnonymousUser`, and `is_verified`
does not make sense without 2FA being enabled.
This wraps the checks for all these assum... |
This locks the user groups with the given potential_subgroup_ids, as well
as their indirect subgroups, followed by the potential supergroup. It
ensures that we lock the user groups in a consistent order topologically to
avoid unnecessary deadlocks on non-conflicting queries.
Regardless of whether the user groups retur... | def lock_subgroups_with_respect_to_supergroup(
potential_subgroup_ids: Collection[int], potential_supergroup_id: int, acting_user: UserProfile
) -> Iterator[LockedUserGroupContext]:
"""This locks the user groups with the given potential_subgroup_ids, as well
as their indirect subgroups, followed by the pote... |
This function is used in do_events_register code path so this code
should be performant. We need to do 2 database queries because
Django's ORM doesn't properly support the left join between
UserGroup and UserGroupMembership that we need. | def user_groups_in_realm_serialized(realm: Realm) -> List[UserGroupDict]:
"""This function is used in do_events_register code path so this code
should be performant. We need to do 2 database queries because
Django's ORM doesn't properly support the left join between
UserGroup and UserGroupMembership th... |
Any changes to this function likely require a migration to adjust
existing realms. See e.g. migration 0382_create_role_based_system_groups.py,
which is a copy of this function from when we introduced system groups. | def create_system_user_groups_for_realm(realm: Realm) -> Dict[int, NamedUserGroup]:
"""Any changes to this function likely require a migration to adjust
existing realms. See e.g. migration 0382_create_role_based_system_groups.py,
which is a copy of this function from when we introduced system groups.
"... |
Doing bulk inserts this way is much faster than using Django,
since we don't have any ORM overhead. Profiling with 1000
users shows a speedup of 0.436 -> 0.027 seconds, so we're
talking about a 15x speedup. | def bulk_insert_ums(ums: List[UserMessageLite]) -> None:
"""
Doing bulk inserts this way is much faster than using Django,
since we don't have any ORM overhead. Profiling with 1000
users shows a speedup of 0.436 -> 0.027 seconds, so we're
talking about a 15x speedup.
"""
if not ums:
... |
Fetches UserTopic objects associated with the target user.
* include_deactivated: Whether to include those associated with
deactivated streams.
* include_stream_name: Whether to include stream names in the
returned dictionaries.
* visibility_policy: If specified, returns only UserTopic objects
with the specified ... | def get_user_topics(
user_profile: UserProfile,
include_deactivated: bool = False,
include_stream_name: bool = False,
visibility_policy: Optional[int] = None,
) -> List[UserTopicDict]:
"""
Fetches UserTopic objects associated with the target user.
* include_deactivated: Whether to include th... |
This is only used in tests. | def set_topic_visibility_policy(
user_profile: UserProfile,
topics: List[List[str]],
visibility_policy: int,
last_updated: Optional[datetime] = None,
) -> None:
"""
This is only used in tests.
"""
UserTopic.objects.filter(
user_profile=user_profile,
visibility_policy=vis... |
Prefetch the visibility policies the user has configured for
various topics.
The prefetching helps to avoid the db queries later in the loop
to determine the user's visibility policy for a topic. | def build_get_topic_visibility_policy(
user_profile: UserProfile,
) -> Callable[[int, str], int]:
"""Prefetch the visibility policies the user has configured for
various topics.
The prefetching helps to avoid the db queries later in the loop
to determine the user's visibility policy for a topic.
... |
Assert that the input is an integer and is contained in `possible_values`. If the input is not in
`possible_values`, a `ValidationError` is raised containing the failing field's name. | def check_int_in(possible_values: List[int]) -> Validator[int]:
"""
Assert that the input is an integer and is contained in `possible_values`. If the input is not in
`possible_values`, a `ValidationError` is raised containing the failing field's name.
"""
def validator(var_name: str, val: object) -... |
Use this validator if an argument is of a variable type (e.g. processing
properties that might be strings or booleans).
`allowed_type_funcs`: the check_* validator functions for the possible data
types for this variable. | def check_union(allowed_type_funcs: Collection[Validator[ResultT]]) -> Validator[ResultT]:
"""
Use this validator if an argument is of a variable type (e.g. processing
properties that might be strings or booleans).
`allowed_type_funcs`: the check_* validator functions for the possible data
types fo... |
This function is used to validate the data sent to the server while
creating/editing choices of the choice field in Organization settings. | def validate_select_field_data(field_data: ProfileFieldData) -> Dict[str, Dict[str, str]]:
"""
This function is used to validate the data sent to the server while
creating/editing choices of the choice field in Organization settings.
"""
validator = check_dict_only(
[
("text", ch... |
This function is used to validate the value selected by the user against a
choice field. This is not used to validate admin data. | def validate_select_field(var_name: str, field_data: str, value: object) -> str:
"""
This function is used to validate the value selected by the user against a
choice field. This is not used to validate admin data.
"""
s = check_string(var_name, value)
field_data_dict = orjson.loads(field_data)
... |
This code works with the web app; mobile and other
clients should also start supporting this soon. | def do_widget_post_save_actions(send_request: SendMessageRequest) -> None:
"""
This code works with the web app; mobile and other
clients should also start supporting this soon.
"""
message_content = send_request.message.content
sender_id = send_request.message.sender_id
message_id = send_re... |
If the link points to a local destination (e.g. #narrow/...),
generate a relative link that will open it in the current window. | def rewrite_local_links_to_relative(db_data: Optional[DbData], link: str) -> str:
"""If the link points to a local destination (e.g. #narrow/...),
generate a relative link that will open it in the current window.
"""
if db_data:
realm_uri_prefix = db_data.realm_uri + "/"
if link.starts... |
Sanitize a URL against XSS attacks.
See the docstring on markdown.inlinepatterns.LinkPattern.sanitize_url. | def sanitize_url(url: str) -> Optional[str]:
"""
Sanitize a URL against XSS attacks.
See the docstring on markdown.inlinepatterns.LinkPattern.sanitize_url.
"""
try:
parts = urlsplit(url.replace(" ", "%20"))
scheme, netloc, path, query, fragment = parts
except ValueError:
... |
Augment a linkifier so it only matches after start-of-string,
whitespace, or opening delimiters, won't match if there are word
characters directly after, and saves what was matched as
OUTER_CAPTURE_GROUP. | def prepare_linkifier_pattern(source: str) -> str:
"""Augment a linkifier so it only matches after start-of-string,
whitespace, or opening delimiters, won't match if there are word
characters directly after, and saves what was matched as
OUTER_CAPTURE_GROUP."""
# This NEL character (0x85) is interp... |
Convert Markdown to HTML, with Zulip-specific settings and hacks. | def do_convert(
content: str,
realm_alert_words_automaton: Optional[ahocorasick.Automaton] = None,
message: Optional[Message] = None,
message_realm: Optional[Realm] = None,
sent_by_bot: bool = False,
translate_emoticons: bool = False,
url_embed_data: Optional[Dict[str, Optional[UrlEmbedData]... |
This is basically just a wrapper for do_render_markdown. | def render_message_markdown(
message: Message,
content: str,
realm: Optional[Realm] = None,
realm_alert_words_automaton: Optional[ahocorasick.Automaton] = None,
url_embed_data: Optional[Dict[str, Optional[UrlEmbedData]]] = None,
mention_data: Optional[MentionData] = None,
email_gateway: bool... |
Sanitizes a value to be safe to store in a Linux filesystem, in
S3, and in a URL. So Unicode is allowed, but not special
characters other than ".", "-", and "_".
This implementation is based on django.utils.text.slugify; it is
modified by:
* adding '.' to the list of allowed characters.
* preserving the case of the v... | def sanitize_name(value: str) -> str:
"""
Sanitizes a value to be safe to store in a Linux filesystem, in
S3, and in a URL. So Unicode is allowed, but not special
characters other than ".", "-", and "_".
This implementation is based on django.utils.text.slugify; it is
modified by:
* adding... |
Verify that we are only reading and writing files under the
expected paths. This is expected to be already enforced at other
layers, via cleaning of user input, but we assert it here for
defense in depth. | def assert_is_local_storage_path(type: Literal["avatars", "files"], full_path: str) -> None:
"""
Verify that we are only reading and writing files under the
expected paths. This is expected to be already enforced at other
layers, via cleaning of user input, but we assert it here for
defense in dept... |
This method can be used to standardize a dictionary of headers with
the standard format that Django expects. For reference, refer to:
https://docs.djangoproject.com/en/3.2/ref/request-response/#django.http.HttpRequest.headers
NOTE: Historically, Django's headers were not case-insensitive. We're still
capitalizing our ... | def standardize_headers(input_headers: Union[None, Dict[str, Any]]) -> Dict[str, str]:
"""This method can be used to standardize a dictionary of headers with
the standard format that Django expects. For reference, refer to:
https://docs.djangoproject.com/en/3.2/ref/request-response/#django.http.HttpRequest.... |
For integrations that require custom HTTP headers for some (or all)
of their test fixtures, this method will call a specially named
function from the target integration module to determine what set
of HTTP headers goes with the given test fixture. | def get_fixture_http_headers(integration_name: str, fixture_name: str) -> Dict["str", "str"]:
"""For integrations that require custom HTTP headers for some (or all)
of their test fixtures, this method will call a specially named
function from the target integration module to determine what set
of HTTP h... |
If an integration requires an event type kind of HTTP header which can
be easily (statically) determined, then name the fixtures in the format
of "header_value__other_details" or even "header_value" and the use this
method in the headers.py file for the integration. | def get_http_headers_from_filename(http_header_key: str) -> Callable[[str], Dict[str, str]]:
"""If an integration requires an event type kind of HTTP header which can
be easily (statically) determined, then name the fixtures in the format
of "header_value__other_details" or even "header_value" and the use t... |
If an integration requires time input in unix milliseconds, this helper
checks to ensure correct type and will catch any errors related to type or
value and raise a JsonableError.
Returns a datetime representing the time. | def unix_milliseconds_to_timestamp(milliseconds: Any, webhook: str) -> datetime:
"""If an integration requires time input in unix milliseconds, this helper
checks to ensure correct type and will catch any errors related to type or
value and raise a JsonableError.
Returns a datetime representing the time... |
Migration 0041 had a bug, where if multiple messages referenced the
same attachment, rather than creating a single attachment object
for all of them, we would incorrectly create one for each message.
This results in exceptions looking up the Attachment object
corresponding to a file that was used in multiple messages t... | def fix_duplicate_attachments(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None:
"""Migration 0041 had a bug, where if multiple messages referenced the
same attachment, rather than creating a single attachment object
for all of them, we would incorrectly create one for each message.
This... |
Delete any old scheduled jobs, to handle changes in the format of
that table. Ideally, we'd translate the jobs, but it's not really
worth the development effort to save a few invitation reminders
and day2 followup emails. | def delete_old_scheduled_jobs(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None:
"""Delete any old scheduled jobs, to handle changes in the format of
that table. Ideally, we'd translate the jobs, but it's not really
worth the development effort to save a few invitation reminders
and day... |
Delete any old scheduled jobs, to handle changes in the format of
send_email. Ideally, we'd translate the jobs, but it's not really
worth the development effort to save a few invitation reminders
and day2 followup emails. | def delete_old_scheduled_jobs(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None:
"""Delete any old scheduled jobs, to handle changes in the format of
send_email. Ideally, we'd translate the jobs, but it's not really
worth the development effort to save a few invitation reminders
and day2... |
Fixes UserProfile objects that incorrectly had a bot_owner set | def migrate_fix_invalid_bot_owner_values(
apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
) -> None:
"""Fixes UserProfile objects that incorrectly had a bot_owner set"""
UserProfile = apps.get_model("zerver", "UserProfile")
UserProfile.objects.filter(is_bot=False).exclude(bot_owner=None).update... |
With CVE-2019-18933, it was possible for certain users created
using social login (e.g. Google/GitHub auth) to have the empty
string as their password in the Zulip database, rather than
Django's "unusable password" (i.e. no password at all). This was a
serious security issue for organizations with both password and
Go... | def ensure_no_empty_passwords(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None:
"""With CVE-2019-18933, it was possible for certain users created
using social login (e.g. Google/GitHub auth) to have the empty
string as their password in the Zulip database, rather than
Django's "unusable... |
This migration fixes any PreregistrationUser objects that might
have been already corrupted to have the administrator role by the
buggy original version of migration
0198_preregistrationuser_invited_as.
Since invitations that create new users as administrators are
rare, it is cleaner to just remove the role from all
P... | def clear_preregistrationuser_invited_as_admin(
apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
) -> None:
"""This migration fixes any PreregistrationUser objects that might
have been already corrupted to have the administrator role by the
buggy original version of migration
0198_preregistr... |
Conceptually, this migration cleans up the old NEW_USER_BOT and FEEDBACK_BOT
UserProfile objects (their implementations were removed long ago).
We do this by:
* Changing their sent messages to have been sent by NOTIFICATION_BOT.
* Changing their 1:1 PMs to be PMs with NOTIFICATION_BOT and deleting their
PM recipient... | def fix_messages(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None:
"""Conceptually, this migration cleans up the old NEW_USER_BOT and FEEDBACK_BOT
UserProfile objects (their implementations were removed long ago).
We do this by:
* Changing their sent messages to have been sent by NOTIF... |
Zulip's data model for reactions has enforced via code,
nontransactionally, that they can only react with one emoji_code
for a given reaction_type. This fixes any that were stored in the
database via a race; the next migration will add the appropriate
database-level unique constraint. | def clear_duplicate_reactions(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None:
"""Zulip's data model for reactions has enforced via code,
nontransactionally, that they can only react with one emoji_code
for a given reaction_type. This fixes any that were stored in the
database via a r... |
This migration fixes two issues with the RealmAuditLog format for certain event types:
* The notifications_stream and signup_notifications_stream fields had the
Stream objects passed into `ujson.dumps()` and thus marshalled as a giant
JSON object, when the intent was to store the stream ID.
* The default_sending_st... | def update_realmauditlog_values(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None:
"""
This migration fixes two issues with the RealmAuditLog format for certain event types:
* The notifications_stream and signup_notifications_stream fields had the
Stream objects passed into `ujson.dump... |
Taken from zerver.models. Adjusted to work in a migration without changing
behavior. | def get_fake_email_domain(realm: Any) -> str:
"""
Taken from zerver.models. Adjusted to work in a migration without changing
behavior.
"""
try:
# Check that realm.host can be used to form valid email addresses.
realm_host = host_for_subdomain(realm.string_id)
validate_email(A... |
do_delete_users had two bugs:
1. Creating the replacement dummy users with active=True
2. Creating the replacement dummy users with email domain set to realm.uri,
which may not be a valid email domain.
Prior commits fixed the bugs, and this migration fixes the pre-existing objects. | def fix_dummy_users(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None:
"""
do_delete_users had two bugs:
1. Creating the replacement dummy users with active=True
2. Creating the replacement dummy users with email domain set to realm.uri,
which may not be a valid email domain.
Pri... |
This migration establishes the invariant that all RealmEmoji objects have .author set
and queues events for reuploading all RealmEmoji. | def set_emoji_author(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None:
"""
This migration establishes the invariant that all RealmEmoji objects have .author set
and queues events for reuploading all RealmEmoji.
"""
RealmEmoji = apps.get_model("zerver", "RealmEmoji")
UserProfile... |
Migrate edit history events for the messages in the provided range to:
* Rename prev_subject => prev_topic.
* Provide topic and stream fields with the current values.
The range of message IDs to be processed is inclusive on both ends. | def backfill_message_edit_history_chunk(
first_id: int, last_id: int, message_model: Type[Any]
) -> None:
"""
Migrate edit history events for the messages in the provided range to:
* Rename prev_subject => prev_topic.
* Provide topic and stream fields with the current values.
The range of messa... |
As detailed in https://github.com/zulip/zulip/issues/21608, it is
possible for the deferred_work queue from Zulip 4.x to have been
started up by puppet during the deployment before migrations were
run on Zulip 5.0.
This means that the deferred_work events originally produced by
migration 0376 might have been processed... | def reupload_realm_emoji(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None:
"""As detailed in https://github.com/zulip/zulip/issues/21608, it is
possible for the deferred_work queue from Zulip 4.x to have been
started up by puppet during the deployment before migrations were
run on Zulip... |
Migration 0400_realmreactivationstatus changed REALM_REACTIVATION Confirmation
to have a RealmReactivationStatus instance as .content_object. Now we need to migrate
pre-existing REALM_REACTIVATION Confirmations to follow this format.
The process is a bit fiddly because Confirmation.content_object is a GenericForeignKe... | def fix_old_realm_reactivation_confirmations(
apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
) -> None:
"""
Migration 0400_realmreactivationstatus changed REALM_REACTIVATION Confirmation
to have a RealmReactivationStatus instance as .content_object. Now we need to migrate
pre-existing REAL... |
This migration updates the emoji style for users who are using the
deprecated Google blob style. Unless they are part of an organization
which has Google blob as an organization default, these users will
now use the modern Google emoji style. | def update_deprecated_emoji_style(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None:
"""
This migration updates the emoji style for users who are using the
deprecated Google blob style. Unless they are part of an organization
which has Google blob as an organization default, these users ... |
This adds the property_name field to any STREAM_GROUP_BASED_SETTING_CHANGED
audit log entries that were created before the previous commit. | def fix_audit_log_objects_for_group_based_stream_settings(
apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
) -> None:
"""
This adds the property_name field to any STREAM_GROUP_BASED_SETTING_CHANGED
audit log entries that were created before the previous commit.
"""
RealmAuditLog = apps.... |
Find deleted users prior to the fix in 208c0c303405, which have
invalid delivery_email values; fixing them allows them to survive
an export/import. | def fix_invalid_emails(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None:
"""Find deleted users prior to the fix in 208c0c303405, which have
invalid delivery_email values; fixing them allows them to survive
an export/import.
"""
UserProfile = apps.get_model("zerver", "UserProfile")
... |
Backfill subscription realm audit log events for users which are
currently subscribed but don't have any, presumably due to some
historical bug. This is important because those rows are
necessary when reactivating a user who is currently
soft-deactivated.
For each stream, we find the subscribed users who have no rele... | def backfill_missing_subscriptions(
apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
) -> None:
"""Backfill subscription realm audit log events for users which are
currently subscribed but don't have any, presumably due to some
historical bug. This is important because those rows are
necess... |
This is a copy of zerver.lib.utils.generate_api_key. Importing code that's prone
to change in a migration is something we generally avoid, to ensure predictable,
consistent behavior of the migration across time. | def generate_api_key() -> str:
"""
This is a copy of zerver.lib.utils.generate_api_key. Importing code that's prone
to change in a migration is something we generally avoid, to ensure predictable,
consistent behavior of the migration across time.
"""
api_key = ""
while len(api_key) < 32:
... |
Because 'topic_wildcard_mentioned' and 'group_mentioned' flags are
reused flag slots (ref: c37871a) in the 'flags' bitfield, we're not
confident that their value is in 0 state on very old servers, and this
migration is to ensure that's the case.
Additionally, we are clearing 'force_expand' and 'force_collapse' unused
f... | def clear_old_data_for_unused_usermessage_flags(
apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
) -> None:
"""Because 'topic_wildcard_mentioned' and 'group_mentioned' flags are
reused flag slots (ref: c37871a) in the 'flags' bitfield, we're not
confident that their value is in 0 state on very ... |
Validate as a URL template | def url_template_validator(value: str) -> None:
"""Validate as a URL template"""
if not uri_template.validate(value):
raise ValidationError(_("Invalid URL template.")) |
If invite_expires_in_days is specified, we return only those PreregistrationUser
objects that were created at most that many days in the past. | def filter_to_valid_prereg_users(
query: QuerySet[PreregistrationUser],
invite_expires_in_minutes: Union[Optional[int], UnspecifiedValue] = UnspecifiedValue(),
) -> QuerySet[PreregistrationUser]:
"""
If invite_expires_in_days is specified, we return only those PreregistrationUser
objects that were c... |
Takes a list of huddle-type recipient_ids, returns a dict
mapping recipient id to list of user ids in the huddle.
We rely on our caller to pass us recipient_ids that correspond
to huddles, but technically this function is valid for any type
of subscription. | def bulk_get_huddle_user_ids(recipient_ids: List[int]) -> Dict[int, Set[int]]:
"""
Takes a list of huddle-type recipient_ids, returns a dict
mapping recipient id to list of user ids in the huddle.
We rely on our caller to pass us recipient_ids that correspond
to huddles, but technically this functi... |
Takes a list of user IDs and returns the Huddle object for the
group consisting of these users. If the Huddle object does not
yet exist, it will be transparently created. | def get_or_create_huddle(id_list: List[int]) -> Huddle:
"""
Takes a list of user IDs and returns the Huddle object for the
group consisting of these users. If the Huddle object does not
yet exist, it will be transparently created.
"""
from zerver.models import Subscription, UserProfile
hudd... |
Return all streams (including invite-only streams) that have not been deactivated. | def get_active_streams(realm: Realm) -> QuerySet[Stream]:
"""
Return all streams (including invite-only streams) that have not been deactivated.
"""
return Stream.objects.filter(realm=realm, deactivated=False) |
This returns the streams that we are allowed to linkify using
something like "#frontend" in our markup. For now the business
rule is that you can link any stream in the realm that hasn't
been deactivated (similar to how get_active_streams works). | def get_linkable_streams(realm_id: int) -> QuerySet[Stream]:
"""
This returns the streams that we are allowed to linkify using
something like "#frontend" in our markup. For now the business
rule is that you can link any stream in the realm that hasn't
been deactivated (similar to how get_active_stre... |
Callers that don't have a Realm object already available should use
get_realm_stream directly, to avoid unnecessarily fetching the
Realm object. | def get_stream(stream_name: str, realm: Realm) -> Stream:
"""
Callers that don't have a Realm object already available should use
get_realm_stream directly, to avoid unnecessarily fetching the
Realm object.
"""
return get_realm_stream(stream_name, realm.id) |
This function is intended to be used for
manual manage.py shell work; robust code must use get_user or
get_user_by_delivery_email instead, because Zulip supports
multiple users with a given (delivery) email address existing on a
single server (in different realms). | def get_user_profile_by_email(email: str) -> UserProfile:
"""This function is intended to be used for
manual manage.py shell work; robust code must use get_user or
get_user_by_delivery_email instead, because Zulip supports
multiple users with a given (delivery) email address existing on a
single ser... |
Fetches a user given their delivery email. For use in
authentication/registration contexts. Do not use for user-facing
views (e.g. Zulip API endpoints) as doing so would violate the
EMAIL_ADDRESS_VISIBILITY_ADMINS security model. Use get_user in
those code paths. | def get_user_by_delivery_email(email: str, realm: "Realm") -> UserProfile:
"""Fetches a user given their delivery email. For use in
authentication/registration contexts. Do not use for user-facing
views (e.g. Zulip API endpoints) as doing so would violate the
EMAIL_ADDRESS_VISIBILITY_ADMINS security m... |
This is similar to get_user_by_delivery_email, and
it has the same security caveats. It gets multiple
users and returns a QuerySet, since most callers
will only need two or three fields.
If you are using this to get large UserProfile objects, you are
probably making a mistake, but if you must,
then use `select_relate... | def get_users_by_delivery_email(emails: Set[str], realm: "Realm") -> QuerySet[UserProfile]:
"""This is similar to get_user_by_delivery_email, and
it has the same security caveats. It gets multiple
users and returns a QuerySet, since most callers
will only need two or three fields.
If you are using... |
Fetches the user by its visible-to-other users username (in the
`email` field). For use in API contexts; do not use in
authentication/registration contexts as doing so will break
authentication in organizations using
EMAIL_ADDRESS_VISIBILITY_ADMINS. In those code paths, use
get_user_by_delivery_email. | def get_user(email: str, realm: "Realm") -> UserProfile:
"""Fetches the user by its visible-to-other users username (in the
`email` field). For use in API contexts; do not use in
authentication/registration contexts as doing so will break
authentication in organizations using
EMAIL_ADDRESS_VISIBILI... |
Variant of get_user_by_email that excludes deactivated users.
See get_user docstring for important usage notes. | def get_active_user(email: str, realm: "Realm") -> UserProfile:
"""Variant of get_user_by_email that excludes deactivated users.
See get_user docstring for important usage notes."""
user_profile = get_user(email, realm)
if not user_profile.is_active:
raise UserProfile.DoesNotExist
return use... |
This function doesn't use the realm_id argument yet, but requires
passing it as preparation for adding system bots to each realm instead
of having them all in a separate system bot realm.
If you're calling this function, use the id of the realm in which the system
bot will be after that migration. If the bot is suppose... | def get_system_bot(email: str, realm_id: int) -> UserProfile:
"""
This function doesn't use the realm_id argument yet, but requires
passing it as preparation for adding system bots to each realm instead
of having them all in a separate system bot realm.
If you're calling this function, use the id of... |
This decorator is used to register OpenAPI param value generator functions
with endpoints. Example usage:
@openapi_param_value_generator(["/messages/render:post"])
def ... | def openapi_param_value_generator(
endpoints: List[str],
) -> Callable[[Callable[[], Dict[str, object]]], Callable[[], Dict[str, object]]]:
"""This decorator is used to register OpenAPI param value generator functions
with endpoints. Example usage:
@openapi_param_value_generator(["/messages/render:post... |
Throws an exception if any registered helpers were not called by tests | def assert_all_helper_functions_called() -> None:
"""Throws an exception if any registered helpers were not called by tests"""
if REGISTERED_GENERATOR_FUNCTIONS == CALLED_GENERATOR_FUNCTIONS:
return
uncalled_functions = str(REGISTERED_GENERATOR_FUNCTIONS - CALLED_GENERATOR_FUNCTIONS)
raise Exc... |
A simple wrapper around generate_curl_example. | def render_curl_example(
function: str,
api_url: str,
admin_config: bool = False,
) -> List[str]:
"""A simple wrapper around generate_curl_example."""
parts = function.split(":")
endpoint = parts[0]
method = parts[1]
kwargs: Dict[str, Any] = {}
if len(parts) > 2:
kwargs["auth... |
Fetch a fixture from the full spec object. | def get_openapi_fixture(endpoint: str, method: str, status_code: str = "200") -> Dict[str, Any]:
"""Fetch a fixture from the full spec object."""
return get_schema(endpoint, method, status_code)["example"] |
Fetch a fixture from the full spec object. | def get_openapi_fixture_description(endpoint: str, method: str, status_code: str = "200") -> str:
"""Fetch a fixture from the full spec object."""
return get_schema(endpoint, method, status_code)["description"] |
Fetch all the kinds of parameters required for curl examples. | def get_curl_include_exclude(endpoint: str, method: str) -> List[Dict[str, Any]]:
"""Fetch all the kinds of parameters required for curl examples."""
if (
"x-curl-examples-parameters"
not in openapi_spec.openapi()["paths"][endpoint][method.lower()]
):
return [{"type": "exclude", "par... |
Fetch if the endpoint requires admin config. | def check_requires_administrator(endpoint: str, method: str) -> bool:
"""Fetch if the endpoint requires admin config."""
return openapi_spec.openapi()["paths"][endpoint][method.lower()].get(
"x-requires-administrator", False
) |
Fetch the additional imports required for an endpoint. | def check_additional_imports(endpoint: str, method: str) -> Optional[List[str]]:
"""Fetch the additional imports required for an endpoint."""
return openapi_spec.openapi()["paths"][endpoint][method.lower()].get(
"x-python-examples-extra-imports", None
) |
Fetch responses description of an endpoint. | def get_responses_description(endpoint: str, method: str) -> str:
"""Fetch responses description of an endpoint."""
return openapi_spec.openapi()["paths"][endpoint][method.lower()].get(
"x-response-description", ""
) |
Fetch parameters description of an endpoint. | def get_parameters_description(endpoint: str, method: str) -> str:
"""Fetch parameters description of an endpoint."""
return openapi_spec.openapi()["paths"][endpoint][method.lower()].get(
"x-parameter-description", ""
) |
Generate fixture to be rendered | def generate_openapi_fixture(endpoint: str, method: str) -> List[str]:
"""Generate fixture to be rendered"""
fixture = []
for status_code in sorted(
openapi_spec.openapi()["paths"][endpoint][method.lower()]["responses"]
):
if (
"oneOf"
in openapi_spec.openapi()["... |
Fetch a description from the full spec object. | def get_openapi_description(endpoint: str, method: str) -> str:
"""Fetch a description from the full spec object."""
endpoint_documentation = openapi_spec.openapi()["paths"][endpoint][method.lower()]
endpoint_description = endpoint_documentation["description"]
check_deprecated_consistency(
endpo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.