response stringlengths 1 33.1k | instruction stringlengths 22 582k |
|---|---|
Checks that the data sent is well-formed. Does not handle editability, permissions etc. | def validate_message_edit_payload(
message: Message,
stream_id: Optional[int],
topic_name: Optional[str],
propagate_mode: Optional[str],
content: Optional[str],
) -> None:
"""
Checks that the data sent is well-formed. Does not handle editability, permissions etc.
"""
if topic_name is... |
Checks if the user has the permission to edit the message. | def validate_user_can_edit_message(
user_profile: UserProfile, message: Message, edit_limit_buffer: int
) -> None:
"""
Checks if the user has the permission to edit the message.
"""
if not user_profile.realm.allow_message_editing:
raise JsonableError(_("Your organization has turned off messa... |
Returns resolved_topic_message_id if resolve topic notifications were in fact sent. | def maybe_send_resolve_topic_notifications(
*,
user_profile: UserProfile,
stream: Stream,
old_topic_name: str,
new_topic_name: str,
changed_messages: QuerySet[Message],
) -> Optional[int]:
"""Returns resolved_topic_message_id if resolve topic notifications were in fact sent."""
# Note th... |
The main function for message editing. A message edit event can
modify:
* the message's content (in which case the caller will have
set both content and rendered_content),
* the topic, in which case the caller will have set topic_name
* or both message's content and the topic
* or stream and/or topic, in which case ... | def do_update_message(
user_profile: UserProfile,
target_message: Message,
new_stream: Optional[Stream],
topic_name: Optional[str],
propagate_mode: Optional[str],
send_notification_to_old_thread: bool,
send_notification_to_new_thread: bool,
content: Optional[str],
rendering_result: O... |
This will update a message given the message id and user profile.
It checks whether the user profile has the permission to edit the message
and raises a JsonableError if otherwise.
It returns the number changed. | def check_update_message(
user_profile: UserProfile,
message_id: int,
stream_id: Optional[int] = None,
topic_name: Optional[str] = None,
propagate_mode: str = "change_one",
send_notification_to_old_thread: bool = True,
send_notification_to_new_thread: bool = True,
content: Optional[str] ... |
Returns a dictionary that can be passed into do_send_messages. In
production, this is always called by check_message, but some
testing code paths call it directly. | def build_message_send_dict(
message: Message,
stream: Optional[Stream] = None,
local_id: Optional[str] = None,
sender_queue_id: Optional[str] = None,
widget_content_dict: Optional[Dict[str, Any]] = None,
email_gateway: bool = False,
mention_backend: Optional[MentionBackend] = None,
limi... |
Given a list of active_user_ids, we build up a subset
of those users who fit these criteria:
* They are likely to receive push or email notifications.
* They are no longer "present" according to the
UserPresence table. | def get_active_presence_idle_user_ids(
realm: Realm,
sender_id: int,
user_notifications_data_list: List[UserMessageNotificationsData],
) -> List[int]:
"""
Given a list of active_user_ids, we build up a subset
of those users who fit these criteria:
* They are likely to receive push or em... |
See
https://zulip.readthedocs.io/en/latest/subsystems/sending-messages.html
for high-level documentation on this subsystem. | def do_send_messages(
send_message_requests_maybe_none: Sequence[Optional[SendMessageRequest]],
*,
mark_as_read: Sequence[int] = [],
) -> List[SentMessageResult]:
"""See
https://zulip.readthedocs.io/en/latest/subsystems/sending-messages.html
for high-level documentation on this subsystem.
""... |
Sends a direct message error notification to a bot's owner if one
hasn't already been sent in the last 5 minutes. | def send_rate_limited_pm_notification_to_bot_owner(
sender: UserProfile, realm: Realm, content: str
) -> None:
"""
Sends a direct message error notification to a bot's owner if one
hasn't already been sent in the last 5 minutes.
"""
if sender.realm.is_zephyr_mirror_realm or sender.realm.deactiva... |
If a bot sends a message to a stream that doesn't exist or has no
subscribers, sends a notification to the bot owner (if not a
cross-realm bot) so that the owner can correct the issue. | def send_pm_if_empty_stream(
stream: Optional[Stream],
realm: Realm,
sender: UserProfile,
stream_name: Optional[str] = None,
stream_id: Optional[int] = None,
) -> None:
"""If a bot sends a message to a stream that doesn't exist or has no
subscribers, sends a notification to the bot owner (if... |
This function returns a dictionary with data about which users would
receive stream creation events due to gaining access to a user.
The key of the dictionary is a user object and the value is a set of
user_ids that would gain access to that user. | def get_recipients_for_user_creation_events(
realm: Realm, sender: UserProfile, user_profiles: Sequence[UserProfile]
) -> Dict[UserProfile, Set[int]]:
"""
This function returns a dictionary with data about which users would
receive stream creation events due to gaining access to a user.
The key of t... |
See
https://zulip.readthedocs.io/en/latest/subsystems/sending-messages.html
for high-level documentation on this subsystem. | def check_message(
sender: UserProfile,
client: Client,
addressee: Addressee,
message_content_raw: str,
realm: Optional[Realm] = None,
forged: bool = False,
forged_timestamp: Optional[float] = None,
forwarder_user_profile: Optional[UserProfile] = None,
local_id: Optional[str] = None,... |
Create a message object and checks it, but doesn't send it or save it to the database.
The internal function that calls this can therefore batch send a bunch of created
messages together as one database query.
Call do_send_messages with a list of the return values of this method. | def _internal_prep_message(
realm: Realm,
sender: UserProfile,
addressee: Addressee,
content: str,
*,
email_gateway: bool = False,
mention_backend: Optional[MentionBackend] = None,
limit_unread_user_ids: Optional[Set[int]] = None,
disable_external_notifications: bool = False,
) -> Op... |
See _internal_prep_message for details of how this works. | def internal_prep_stream_message(
sender: UserProfile,
stream: Stream,
topic_name: str,
content: str,
*,
email_gateway: bool = False,
limit_unread_user_ids: Optional[Set[int]] = None,
) -> Optional[SendMessageRequest]:
"""
See _internal_prep_message for details of how this works.
... |
See _internal_prep_message for details of how this works. | def internal_prep_stream_message_by_name(
realm: Realm,
sender: UserProfile,
stream_name: str,
topic_name: str,
content: str,
) -> Optional[SendMessageRequest]:
"""
See _internal_prep_message for details of how this works.
"""
addressee = Addressee.for_stream_name(stream_name, topic_... |
See _internal_prep_message for details of how this works. | def internal_prep_private_message(
sender: UserProfile,
recipient_user: UserProfile,
content: str,
*,
mention_backend: Optional[MentionBackend] = None,
disable_external_notifications: bool = False,
) -> Optional[SendMessageRequest]:
"""
See _internal_prep_message for details of how this ... |
Should be called while holding a SELECT FOR UPDATE lock
(e.g. via access_message(..., lock_message=True)) on the
Message row, to prevent race conditions. | def do_add_reaction(
user_profile: UserProfile,
message: Message,
emoji_name: str,
emoji_code: str,
reaction_type: str,
) -> None:
"""Should be called while holding a SELECT FOR UPDATE lock
(e.g. via access_message(..., lock_message=True)) on the
Message row, to prevent race conditions.
... |
Should be called while holding a SELECT FOR UPDATE lock
(e.g. via access_message(..., lock_message=True)) on the
Message row, to prevent race conditions. | def do_remove_reaction(
user_profile: UserProfile, message: Message, emoji_code: str, reaction_type: str
) -> None:
"""Should be called while holding a SELECT FOR UPDATE lock
(e.g. via access_message(..., lock_message=True)) on the
Message row, to prevent race conditions.
"""
reaction = Reaction... |
ordered_linkifier_ids should contain ids of all existing linkifiers.
In the rare situation when any of the linkifier gets deleted that more ids
are passed, the checks below are sufficient to detect inconsistencies most of
the time. | def check_reorder_linkifiers(
realm: Realm, ordered_linkifier_ids: List[int], *, acting_user: Optional[UserProfile]
) -> None:
"""ordered_linkifier_ids should contain ids of all existing linkifiers.
In the rare situation when any of the linkifier gets deleted that more ids
are passed, the checks below a... |
Takes in a realm object, the name of an attribute to update, the
value to update and and the user who initiated the update. | def do_set_realm_property(
realm: Realm, name: str, value: Any, *, acting_user: Optional[UserProfile]
) -> None:
"""Takes in a realm object, the name of an attribute to update, the
value to update and and the user who initiated the update.
"""
property_type = Realm.property_types[name]
assert is... |
Takes in a realm object, the name of an attribute to update, the
user_group to update and and the user who initiated the update. | def do_change_realm_permission_group_setting(
realm: Realm, setting_name: str, user_group: UserGroup, *, acting_user: Optional[UserProfile]
) -> None:
"""Takes in a realm object, the name of an attribute to update, the
user_group to update and and the user who initiated the update.
"""
assert settin... |
Deactivate this realm. Do NOT deactivate the users -- we need to be able to
tell the difference between users that were intentionally deactivated,
e.g. by a realm admin, and users who can't currently use Zulip because their
realm has been deactivated. | def do_deactivate_realm(realm: Realm, *, acting_user: Optional[UserProfile]) -> None:
"""
Deactivate this realm. Do NOT deactivate the users -- we need to be able to
tell the difference between users that were intentionally deactivated,
e.g. by a realm admin, and users who can't currently use Zulip beca... |
Even though our submessage architecture is geared toward
collaboration among all message readers, we still enforce
the the first person to attach a submessage to the message
must be the original sender of the message. | def verify_submessage_sender(
*,
message_id: int,
message_sender_id: int,
submessage_sender_id: int,
) -> None:
"""Even though our submessage architecture is geared toward
collaboration among all message readers, we still enforce
the the first person to attach a submessage to the message
... |
Should be called while holding a SELECT FOR UPDATE lock
(e.g. via access_message(..., lock_message=True)) on the
Message row, to prevent race conditions. | def do_add_submessage(
realm: Realm,
sender_id: int,
message_id: int,
msg_type: str,
content: str,
) -> None:
"""Should be called while holding a SELECT FOR UPDATE lock
(e.g. via access_message(..., lock_message=True)) on the
Message row, to prevent race conditions.
"""
submessag... |
This is a version of do_delete_user which does not delete messages
that the user was a participant in, and thus is less potentially
disruptive to other users.
The code is a bit tricky, because we want to, at some point, call
user_profile.delete() to trigger cascading deletions of related
models - but we need to avoid ... | def do_delete_user_preserving_messages(user_profile: UserProfile) -> None:
"""This is a version of do_delete_user which does not delete messages
that the user was a participant in, and thus is less potentially
disruptive to other users.
The code is a bit tricky, because we want to, at some point, call
... |
Helper function for changing the .is_active field. Not meant as a standalone function
in production code as properly activating/deactivating users requires more steps.
This changes the is_active value and saves it, while ensuring
Subscription.is_user_active values are updated in the same db transaction. | def change_user_is_active(user_profile: UserProfile, value: bool) -> None:
"""
Helper function for changing the .is_active field. Not meant as a standalone function
in production code as properly activating/deactivating users requires more steps.
This changes the is_active value and saves it, while ensu... |
Verifies that the user's proposed full name is valid. The caller
is responsible for checking check permissions. Returns the new
full name, which may differ from what was passed in (because this
function strips whitespace). | def check_change_full_name(
user_profile: UserProfile, full_name_raw: str, acting_user: Optional[UserProfile]
) -> str:
"""Verifies that the user's proposed full name is valid. The caller
is responsible for checking check permissions. Returns the new
full name, which may differ from what was passed in... |
Returns:
1. realm, converted realm data
2. avatars, which is list to map avatars to Zulip avatar records.json
3. user_map, which is a dictionary to map from Gitter user id to Zulip user id
4. stream_map, which is a dictionary to map from Gitter rooms to Zulip stream id | def gitter_workspace_to_realm(
domain_name: str, gitter_data: GitterDataT, realm_subdomain: str
) -> Tuple[ZerverFieldsT, List[ZerverFieldsT], Dict[str, int], Dict[str, int]]:
"""
Returns:
1. realm, converted realm data
2. avatars, which is list to map avatars to Zulip avatar records.json
3. use... |
Returns:
1. zerver_userprofile, which is a list of user profile
2. avatar_list, which is list to map avatars to Zulip avatars records.json
3. added_users, which is a dictionary to map from Gitter user id to Zulip id | def build_userprofile(
timestamp: Any, domain_name: str, gitter_data: GitterDataT
) -> Tuple[List[ZerverFieldsT], List[ZerverFieldsT], Dict[str, int]]:
"""
Returns:
1. zerver_userprofile, which is a list of user profile
2. avatar_list, which is list to map avatars to Zulip avatars records.json
3... |
Returns:
1. stream, which is the list of streams
2. defaultstreams, which is the list of default streams
3. stream_map, which is a dictionary to map from Gitter rooms to Zulip stream id | def build_stream_map(
timestamp: Any, gitter_data: GitterDataT
) -> Tuple[List[ZerverFieldsT], List[ZerverFieldsT], Dict[str, int]]:
"""
Returns:
1. stream, which is the list of streams
2. defaultstreams, which is the list of default streams
3. stream_map, which is a dictionary to map from Gitte... |
Assumes that there is at least one stream with 'stream_id' = 0,
and that this stream is the only defaultstream, with 'defaultstream_id' = 0
Returns:
1. zerver_recipient, which is a list of mapped recipient
2. zerver_subscription, which is a list of mapped subscription | def build_recipient_and_subscription(
zerver_userprofile: List[ZerverFieldsT], zerver_stream: List[ZerverFieldsT]
) -> Tuple[List[ZerverFieldsT], List[ZerverFieldsT]]:
"""
Assumes that there is at least one stream with 'stream_id' = 0,
and that this stream is the only defaultstream, with 'defaultstrea... |
Messages are stored in batches | def convert_gitter_workspace_messages(
gitter_data: GitterDataT,
output_dir: str,
subscriber_map: Dict[int, Set[int]],
user_map: Dict[str, int],
stream_map: Dict[str, int],
user_short_name_to_full_name: Dict[str, str],
zerver_userprofile: List[ZerverFieldsT],
realm_id: int,
chunk_siz... |
This can be convenient for building up UserMessage
rows. | def make_subscriber_map(zerver_subscription: List[ZerverFieldsT]) -> Dict[int, Set[int]]:
"""
This can be convenient for building up UserMessage
rows.
"""
subscriber_map: Dict[int, Set[int]] = {}
for sub in zerver_subscription:
user_id = sub["user_profile"]
recipient_id = sub["re... |
This function was only used HipChat import, this function may be
required for future conversions. The Slack and Gitter conversions do it more
tightly integrated with creating other objects. | def build_recipients(
zerver_userprofile: Iterable[ZerverFieldsT],
zerver_stream: Iterable[ZerverFieldsT],
zerver_huddle: Iterable[ZerverFieldsT] = [],
) -> List[ZerverFieldsT]:
"""
This function was only used HipChat import, this function may be
required for future conversions. The Slack and Gi... |
This function should be passed a 'fileinfo' dictionary, which contains
information about 'size', 'created' (created time) and ['name'] (filename). | def build_attachment(
realm_id: int,
message_ids: Set[int],
user_id: int,
fileinfo: ZerverFieldsT,
s3_path: str,
zerver_attachment: List[ZerverFieldsT],
) -> None:
"""
This function should be passed a 'fileinfo' dictionary, which contains
information about 'size', 'created' (created ... |
This function gets the avatar of the user and saves it in the
user's avatar directory with both the extensions '.png' and '.original'
Required parameters:
1. avatar_list: List of avatars to be mapped in avatars records.json file
2. avatar_dir: Folder where the downloaded avatars are saved
3. realm_id: Realm ID.
We us... | def process_avatars(
avatar_list: List[ZerverFieldsT],
avatar_dir: str,
realm_id: int,
threads: int,
size_url_suffix: str = "",
) -> List[ZerverFieldsT]:
"""
This function gets the avatar of the user and saves it in the
user's avatar directory with both the extensions '.png' and '.origin... |
This function downloads the uploads and saves it in the realm's upload directory.
Required parameters:
1. upload_list: List of uploads to be mapped in uploads records.json file
2. upload_dir: Folder where the downloaded uploads are saved | def process_uploads(
upload_list: List[ZerverFieldsT], upload_dir: str, threads: int
) -> List[ZerverFieldsT]:
"""
This function downloads the uploads and saves it in the realm's upload directory.
Required parameters:
1. upload_list: List of uploads to be mapped in uploads records.json file
2. ... |
This function downloads the custom emojis and saves in the output emoji folder.
Required parameters:
1. zerver_realmemoji: List of all RealmEmoji objects to be imported
2. emoji_dir: Folder where the downloaded emojis are saved
3. emoji_url_map: Maps emoji name to its url | def process_emojis(
zerver_realmemoji: List[ZerverFieldsT],
emoji_dir: str,
emoji_url_map: ZerverFieldsT,
threads: int,
) -> List[ZerverFieldsT]:
"""
This function downloads the custom emojis and saves in the output emoji folder.
Required parameters:
1. zerver_realmemoji: List of all Re... |
Algorithmically, we treat users who have sent at least 10 messages
or have sent a message within the last 60 days as active.
Everyone else is treated as long-term idle, which means they will
have a slightly slower first page load when coming back to
Zulip. | def long_term_idle_helper(
message_iterator: Iterator[ZerverFieldsT],
user_from_message: Callable[[ZerverFieldsT], Optional[ExternalId]],
timestamp_from_message: Callable[[ZerverFieldsT], float],
zulip_user_id_from_user: Callable[[ExternalId], int],
all_user_ids_iterator: Iterator[ExternalId],
z... |
This function does most of the work for processing emoticons, the bulk
of which is copying files. We also write a json file with metadata.
Finally, we return a list of RealmEmoji dicts to our caller.
In our data_dir we have a pretty simple setup:
The exported JSON file will have emoji rows if it contains any cus... | def write_emoticon_data(
realm_id: int, custom_emoji_data: List[Dict[str, Any]], data_dir: str, output_dir: str
) -> List[ZerverFieldsT]:
"""
This function does most of the work for processing emoticons, the bulk
of which is copying files. We also write a json file with metadata.
Finally, we return... |
Use like this:
NEXT_ID = sequencer()
message_id = NEXT_ID('message') | def sequencer() -> Callable[[str], int]:
"""
Use like this:
NEXT_ID = sequencer()
message_id = NEXT_ID('message')
"""
seq_dict: Dict[str, Callable[[], int]] = {}
def next_one(name: str) -> int:
if name not in seq_dict:
seq_dict[name] = _seq()
seq = seq_dict[name... |
Returns:
1. realm, converted realm data
2. slack_user_id_to_zulip_user_id, which is a dictionary to map from Slack user id to Zulip user id
3. slack_recipient_name_to_zulip_recipient_id, which is a dictionary to map from Slack recipient
name(channel names, mpim names, usernames, etc) to Zulip recipient id
4. added_c... | def slack_workspace_to_realm(
domain_name: str,
realm_id: int,
user_list: List[ZerverFieldsT],
realm_subdomain: str,
slack_data_dir: str,
custom_emoji_list: ZerverFieldsT,
) -> Tuple[
ZerverFieldsT,
SlackToZulipUserIDT,
SlackToZulipRecipientT,
AddedChannelsT,
AddedMPIMsT,
... |
Returns:
1. zerver_userprofile, which is a list of user profile
2. avatar_list, which is list to map avatars to Zulip avatar records.json
3. slack_user_id_to_zulip_user_id, which is a dictionary to map from Slack user ID to Zulip
user id
4. zerver_customprofilefield, which is a list of all custom profile fields
5. z... | def users_to_zerver_userprofile(
slack_data_dir: str, users: List[ZerverFieldsT], realm_id: int, timestamp: Any, domain_name: str
) -> Tuple[
List[ZerverFieldsT],
List[ZerverFieldsT],
SlackToZulipUserIDT,
List[ZerverFieldsT],
List[ZerverFieldsT],
]:
"""
Returns:
1. zerver_userprofile... |
Returns:
1. realm, converted realm data
2. added_channels, which is a dictionary to map from channel name to channel id, Zulip stream_id
3. added_mpims, which is a dictionary to map from MPIM(multiparty IM) name to MPIM id, Zulip huddle_id
4. dm_members, which is a dictionary to map from DM id to tuple of DM participan... | def channels_to_zerver_stream(
slack_data_dir: str,
realm_id: int,
realm: Dict[str, Any],
slack_user_id_to_zulip_user_id: SlackToZulipUserIDT,
zerver_userprofile: List[ZerverFieldsT],
) -> Tuple[
Dict[str, List[ZerverFieldsT]], AddedChannelsT, AddedMPIMsT, DMMembersT, SlackToZulipRecipientT
]:
... |
Returns:
1. reactions, which is a list of the reactions
2. uploads, which is a list of uploads to be mapped in uploads records.json
3. attachment, which is a list of the attachments | def convert_slack_workspace_messages(
slack_data_dir: str,
users: List[ZerverFieldsT],
realm_id: int,
slack_user_id_to_zulip_user_id: SlackToZulipUserIDT,
slack_recipient_name_to_zulip_recipient_id: SlackToZulipRecipientT,
added_channels: AddedChannelsT,
added_mpims: AddedMPIMsT,
dm_memb... |
This function is an iterator that returns all the messages across
all Slack channels, in order by timestamp. It's important to
not read all the messages into memory at once, because for
large imports that can OOM kill. | def get_messages_iterator(
slack_data_dir: str,
added_channels: Dict[str, Any],
added_mpims: AddedMPIMsT,
dm_members: DMMembersT,
) -> Iterator[ZerverFieldsT]:
"""This function is an iterator that returns all the messages across
all Slack channels, in order by timestamp. It's important to
n... |
Returns:
1. zerver_message, which is a list of the messages
2. zerver_usermessage, which is a list of the usermessages
3. zerver_attachment, which is a list of the attachments
4. uploads_list, which is a list of uploads to be mapped in uploads records.json
5. reaction_list, which is a list of all user reactions | def channel_message_to_zerver_message(
realm_id: int,
users: List[ZerverFieldsT],
slack_user_id_to_zulip_user_id: SlackToZulipUserIDT,
slack_recipient_name_to_zulip_recipient_id: SlackToZulipRecipientT,
all_messages: List[ZerverFieldsT],
zerver_realmemoji: List[ZerverFieldsT],
subscriber_map... |
Returns:
1. For strikethrough formatting: This maps Slack's '~strike~' to Zulip's '~~strike~~'
2. For bold formatting: This maps Slack's '*bold*' to Zulip's '**bold**'
3. For italic formatting: This maps Slack's '_italic_' to Zulip's '*italic*' | def convert_markdown_syntax(text: str, regex: str, zulip_keyword: str) -> str:
"""
Returns:
1. For strikethrough formatting: This maps Slack's '~strike~' to Zulip's '~~strike~~'
2. For bold formatting: This maps Slack's '*bold*' to Zulip's '**bold**'
3. For italic formatting: This maps Slack's '_ita... |
1. Converts '<https://foo.com>' to 'https://foo.com'
2. Converts '<https://foo.com|foo>' to 'https://foo.com|foo' | def convert_link_format(text: str) -> Tuple[str, bool]:
"""
1. Converts '<https://foo.com>' to 'https://foo.com'
2. Converts '<https://foo.com|foo>' to 'https://foo.com|foo'
"""
has_link = False
for match in re.finditer(LINK_REGEX, text, re.VERBOSE):
converted_text = match.group(0).repla... |
1. Converts '<mailto:foo@foo.com>' to 'mailto:foo@foo.com'
2. Converts '<mailto:foo@foo.com|foo@foo.com>' to 'mailto:foo@foo.com' | def convert_mailto_format(text: str) -> Tuple[str, bool]:
"""
1. Converts '<mailto:foo@foo.com>' to 'mailto:foo@foo.com'
2. Converts '<mailto:foo@foo.com|foo@foo.com>' to 'mailto:foo@foo.com'
"""
has_link = False
for match in re.finditer(SLACK_MAILTO_REGEX, text, re.VERBOSE):
has_link = ... |
The logic in this function is fairly tricky. The essence is that
a file should be cleaned up if and only if it not referenced by any
Message, ScheduledMessage or ArchivedMessage. The way to find that out is through the
Attachment and ArchivedAttachment tables.
The queries are complicated by the fact that an uploaded fi... | def get_old_unclaimed_attachments(
weeks_ago: int,
) -> Tuple[QuerySet[Attachment], QuerySet[ArchivedAttachment]]:
"""
The logic in this function is fairly tricky. The essence is that
a file should be cleaned up if and only if it not referenced by any
Message, ScheduledMessage or ArchivedMessage. Th... |
DEPRECATED: We should start using
get_avatar_field to populate users,
particularly for codepaths where the
client can compute gravatar URLs
on the client side. | def avatar_url_from_dict(userdict: Dict[str, Any], medium: bool = False) -> str:
"""
DEPRECATED: We should start using
get_avatar_field to populate users,
particularly for codepaths where the
client can compute gravatar URLs
on the client side.
... |
Most of the parameters to this function map to fields
by the same name in UserProfile (avatar_source, realm_id,
email, etc.).
Then there are these:
medium - This means we want a medium-sized avatar. This can
affect the "s" parameter for gravatar avatars, or it
can give us something like foo-medium... | def get_avatar_field(
user_id: int,
realm_id: int,
email: str,
avatar_source: str,
avatar_version: int,
medium: bool,
client_gravatar: bool,
) -> Optional[str]:
"""
Most of the parameters to this function map to fields
by the same name in UserProfile (avatar_source, realm_id,
... |
Absolute URLs are used to simplify logic for applications that
won't be served by browsers, such as rendering GCM notifications. | def absolute_avatar_url(user_profile: UserProfile) -> str:
"""
Absolute URLs are used to simplify logic for applications that
won't be served by browsers, such as rendering GCM notifications.
"""
avatar = avatar_url(user_profile)
# avatar_url can return None if client_gravatar=True, however here... |
Compute the Gravatar hash for an email address. | def gravatar_hash(email: str) -> str:
"""Compute the Gravatar hash for an email address."""
# Non-ASCII characters aren't permitted by the currently active e-mail
# RFCs. However, the IETF has published https://tools.ietf.org/html/rfc4952,
# outlining internationalization of email addresses, and regardl... |
Creates and saves a UserProfile with the given email.
Has some code based off of UserManage.create_user, but doesn't .save() | def bulk_create_users(
realm: Realm,
users_raw: Set[Tuple[str, str, bool]],
bot_type: Optional[int] = None,
bot_owner: Optional[UserProfile] = None,
tos_version: Optional[str] = None,
timezone: str = "",
) -> None:
"""
Creates and saves a UserProfile with the given email.
Has some co... |
Decorator which applies Django caching to a function.
Decorator argument is a function which computes a cache key
from the original function's arguments. You are responsible
for avoiding collisions with other uses of this decorator or
other uses of caching. | def cache_with_key(
keyfunc: Callable[ParamT, str],
cache_name: Optional[str] = None,
timeout: Optional[int] = None,
) -> Callable[[Callable[ParamT, ReturnT]], Callable[ParamT, ReturnT]]:
"""Decorator which applies Django caching to a function.
Decorator argument is a function which computes a cach... |
Variant of cache_get_many that drops any keys that fail
validation, rather than throwing an exception visible to the
caller. | def safe_cache_get_many(keys: List[str], cache_name: Optional[str] = None) -> Dict[str, Any]:
"""Variant of cache_get_many that drops any keys that fail
validation, rather than throwing an exception visible to the
caller."""
try:
# Almost always the keys will all be correct, so we just try
... |
Variant of cache_set_many that drops saving any keys that fail
validation, rather than throwing an exception visible to the
caller. | def safe_cache_set_many(
items: Dict[str, Any], cache_name: Optional[str] = None, timeout: Optional[int] = None
) -> None:
"""Variant of cache_set_many that drops saving any keys that fail
validation, rather than throwing an exception visible to the
caller."""
try:
# Almost always the keys w... |
This is a wrapper over lru_cache function. It adds following features on
top of lru_cache:
* It will not cache result of functions with unhashable arguments.
* It will clear cache whenever zerver.lib.cache.KEY_PREFIX changes. | def ignore_unhashable_lru_cache(
maxsize: int = 128, typed: bool = False
) -> Callable[[Callable[ParamT, ReturnT]], IgnoreUnhashableLruCacheWrapper[ParamT, ReturnT]]:
"""
This is a wrapper over lru_cache function. It adds following features on
top of lru_cache:
* It will not cache result of fun... |
Wrapper that converts any dict args to dict item tuples. | def dict_to_items_tuple(user_function: Callable[..., Any]) -> Callable[..., Any]:
"""Wrapper that converts any dict args to dict item tuples."""
def dict_to_tuple(arg: Any) -> Any:
if isinstance(arg, dict):
return tuple(sorted(arg.items()))
return arg
def wrapper(*args: Any, **... |
Wrapper that converts any dict items tuple args to dicts. | def items_tuple_to_dict(user_function: Callable[..., Any]) -> Callable[..., Any]:
"""Wrapper that converts any dict items tuple args to dicts."""
def dict_items_to_dict(arg: Any) -> Any:
if isinstance(arg, tuple):
try:
return dict(arg)
except TypeError:
... |
For installations like Zulip Cloud hosting a lot of realms, it only makes
sense to do cache-filling work for realms that have any currently
active users/clients. Otherwise, we end up with every single-user
trial organization that has ever been created costing us N streams
worth of cache work (where N is the number of ... | def get_active_realm_ids() -> ValuesQuerySet[RealmCount, int]:
"""For installations like Zulip Cloud hosting a lot of realms, it only makes
sense to do cache-filling work for realms that have any currently
active users/clients. Otherwise, we end up with every single-user
trial organization that has eve... |
Compare two Zulip-style version strings.
Versions are dot-separated sequences of decimal integers,
followed by arbitrary trailing decoration. Comparison is
lexicographic on the integer sequences, and refuses to
guess how any trailing decoration compares to any other,
to further numerals, or to nothing.
Returns:
Tr... | def version_lt(ver1: str, ver2: str) -> Optional[bool]:
"""
Compare two Zulip-style version strings.
Versions are dot-separated sequences of decimal integers,
followed by arbitrary trailing decoration. Comparison is
lexicographic on the integer sequences, and refuses to
guess how any trailing ... |
Lock a file object using flock(2) for the duration of a 'with' statement.
If shared is True, use a LOCK_SH lock, otherwise LOCK_EX. | def flock(lockfile: Union[int, IO[Any]], shared: bool = False) -> Iterator[None]:
"""Lock a file object using flock(2) for the duration of a 'with' statement.
If shared is True, use a LOCK_SH lock, otherwise LOCK_EX."""
fcntl.flock(lockfile, fcntl.LOCK_SH if shared else fcntl.LOCK_EX)
try:
yie... |
Lock a file using flock(2) for the duration of a 'with' statement.
If shared is True, use a LOCK_SH lock, otherwise LOCK_EX.
The file is given by name and will be created if it does not exist. | def lockfile(filename: str, shared: bool = False) -> Iterator[None]:
"""Lock a file using flock(2) for the duration of a 'with' statement.
If shared is True, use a LOCK_SH lock, otherwise LOCK_EX.
The file is given by name and will be created if it does not exist."""
with open(filename, "w") as lock:
... |
Lock a file using flock(2) for the duration of a 'with' statement.
Doesn't block, yields False immediately if the lock can't be acquired. | def lockfile_nonblocking(filename: str) -> Iterator[bool]: # nocoverage
"""Lock a file using flock(2) for the duration of a 'with' statement.
Doesn't block, yields False immediately if the lock can't be acquired."""
with open(filename, "w") as f:
lock_acquired = False
try:
fcnt... |
This is just a tiny wrapper on DictType, but it provides
some minor benefits:
- mark clearly that the schema is for a Zulip event
- make sure there's a type field
- add id field automatically
- sanity check that we have no duplicate keys | def event_dict_type(
required_keys: Sequence[Tuple[str, Any]],
optional_keys: Sequence[Tuple[str, Any]] = [],
) -> DictType:
"""
This is just a tiny wrapper on DictType, but it provides
some minor benefits:
- mark clearly that the schema is for a Zulip event
- make sure there's a ty... |
Returns a YAML-like string for our data type; these are used for
pretty-printing and comparison between the OpenAPI type
definitions and these Python data types, as part of
schema is a glorified repr of a data type, but it also includes a
var_name you pass in, plus we dumb things down a bit to match our
current OpenAP... | def schema(
var_name: str,
data_type: Any,
) -> str:
"""Returns a YAML-like string for our data type; these are used for
pretty-printing and comparison between the OpenAPI type
definitions and these Python data types, as part of
schema is a glorified repr of a data type, but it also includes a
... |
Check that val conforms to our data_type | def check_data(
data_type: Any,
var_name: str,
val: Any,
) -> None:
"""Check that val conforms to our data_type"""
if hasattr(data_type, "check_data"):
data_type.check_data(var_name, val)
return
if not isinstance(val, data_type):
raise AssertionError(f"{var_name} is not t... |
Interrupt running process, and provide a python prompt for
interactive debugging. | def interactive_debug(sig: int, frame: Optional[FrameType]) -> None:
"""Interrupt running process, and provide a python prompt for
interactive debugging."""
d = {"_frame": frame} # Allow access to frame object.
if frame is not None:
d.update(frame.f_globals) # Unless shadowed by global
... |
If tracemalloc tracing enabled, listen for requests to dump a snapshot.
To trigger once this is listening:
echo | socat -u stdin unix-sendto:/var/log/zulip/tracemalloc/tracemalloc.$pid
To enable in the Zulip web server: edit /etc/zulip/uwsgi.ini ,
and add e.g. ` PYTHONTRACEMALLOC=5` to the `env=` line.
This functio... | def maybe_tracemalloc_listen() -> None:
"""If tracemalloc tracing enabled, listen for requests to dump a snapshot.
To trigger once this is listening:
echo | socat -u stdin unix-sendto:/var/log/zulip/tracemalloc/tracemalloc.$pid
To enable in the Zulip web server: edit /etc/zulip/uwsgi.ini ,
and a... |
Return all the default streams for a realm using a list of dictionaries sorted
by stream name. | def get_default_streams_for_realm_as_dicts(realm_id: int) -> List[DefaultStreamDict]:
"""
Return all the default streams for a realm using a list of dictionaries sorted
by stream name.
"""
streams = get_slim_realm_default_streams(realm_id)
stream_dicts = [stream.to_dict() for stream in streams]
... |
Skipping streams where the user's subscription status has changed
when constructing digests is critical to ensure correctness for
streams without shared history, guest users, and long-term idle
users, because it means that every user has the same view of the
history of a given stream whose message history is being incl... | def get_user_stream_map(user_ids: List[int], cutoff_date: datetime) -> Dict[int, Set[int]]:
"""Skipping streams where the user's subscription status has changed
when constructing digests is critical to ensure correctness for
streams without shared history, guest users, and long-term idle
users, because ... |
This returns an appropriate object describing the recipient of a
direct message (whether individual or group).
It will be an array of dicts for each recipient.
Do not use this for streams. | def get_display_recipient_remote_cache(
recipient_id: int, recipient_type: int, recipient_type_id: Optional[int]
) -> List[UserDisplayRecipient]:
"""
This returns an appropriate object describing the recipient of a
direct message (whether individual or group).
It will be an array of dicts for each ... |
Takes set of tuples of the form (recipient_id, recipient_type, recipient_type_id)
Returns dict mapping recipient_id to corresponding display_recipient | def bulk_fetch_stream_names(
recipient_tuples: Set[Tuple[int, int, int]],
) -> Dict[int, str]:
"""
Takes set of tuples of the form (recipient_id, recipient_type, recipient_type_id)
Returns dict mapping recipient_id to corresponding display_recipient
"""
from zerver.models import Stream
if ... |
Takes set of tuples of the form (recipient_id, recipient_type, recipient_type_id)
Returns dict mapping recipient_id to corresponding display_recipient | def bulk_fetch_user_display_recipients(
recipient_tuples: Set[Tuple[int, int, int]],
) -> Dict[int, List[UserDisplayRecipient]]:
"""
Takes set of tuples of the form (recipient_id, recipient_type, recipient_type_id)
Returns dict mapping recipient_id to corresponding display_recipient
"""
from ze... |
Takes set of tuples of the form (recipient_id, recipient_type, recipient_type_id)
Returns dict mapping recipient_id to corresponding display_recipient | def bulk_fetch_display_recipients(
recipient_tuples: Set[Tuple[int, int, int]],
) -> Dict[int, DisplayRecipientT]:
"""
Takes set of tuples of the form (recipient_id, recipient_type, recipient_type_id)
Returns dict mapping recipient_id to corresponding display_recipient
"""
from zerver.models im... |
returns: an object describing the recipient (using a cache).
If the type is a stream, the type_id must be an int; a string is returned.
Otherwise, type_id may be None; an array of recipient dicts is returned. | def get_display_recipient_by_id(
recipient_id: int, recipient_type: int, recipient_type_id: Optional[int]
) -> List[UserDisplayRecipient]:
"""
returns: an object describing the recipient (using a cache).
If the type is a stream, the type_id must be an int; a string is returned.
Otherwise, type_id ma... |
Take a DraftData object that was already validated by the @typed_endpoint
decorator then further sanitize, validate, and transform it.
Ultimately return this "further validated" draft dict.
It will have a slightly different set of keys the values
for which can be used to directly create a Draft object. | def further_validated_draft_dict(
draft_dict: DraftData, user_profile: UserProfile
) -> Dict[str, Any]:
"""Take a DraftData object that was already validated by the @typed_endpoint
decorator then further sanitize, validate, and transform it.
Ultimately return this "further validated" draft dict.
It ... |
Create drafts in bulk for a given user based on the DraftData objects. Since
currently, the only place this method is being used (apart from tests) is from
the create_draft view, we assume that these are syntactically valid
(i.e. they satisfy the @typed_endpoint validation for DraftData). | def do_create_drafts(drafts: List[DraftData], user_profile: UserProfile) -> List[Draft]:
"""Create drafts in bulk for a given user based on the DraftData objects. Since
currently, the only place this method is being used (apart from tests) is from
the create_draft view, we assume that these are syntacticall... |
Edit/update a single draft for a given user. Since the only place this method is being
used from (apart from tests) is the edit_draft view, we assume that the DraftData object
is syntactically valid (i.e. it satisfies the @typed_endpoint validation for DraftData). | def do_edit_draft(draft_id: int, draft: DraftData, user_profile: UserProfile) -> None:
"""Edit/update a single draft for a given user. Since the only place this method is being
used from (apart from tests) is the edit_draft view, we assume that the DraftData object
is syntactically valid (i.e. it satisfies ... |
Delete a draft belonging to a particular user. | def do_delete_draft(draft_id: int, user_profile: UserProfile) -> None:
"""Delete a draft belonging to a particular user."""
try:
draft_object = Draft.objects.get(id=draft_id, user_profile=user_profile)
except Draft.DoesNotExist:
raise ResourceNotFoundError(_("Draft does not exist"))
dra... |
Missed message strings are formatted with a little "mm" prefix
followed by a randomly generated 32-character string. | def is_mm_32_format(msg_string: Optional[str]) -> bool:
"""
Missed message strings are formatted with a little "mm" prefix
followed by a randomly generated 32-character string.
"""
return msg_string is not None and msg_string.startswith("mm") and len(msg_string) == 34 |
We add quote prefix ">" to each line of the message in plain text
format, such that email clients render the message as quote. | def add_quote_prefix_in_text(content: str) -> str:
"""
We add quote prefix ">" to each line of the message in plain text
format, such that email clients render the message as quote.
"""
lines = content.split("\n")
output = []
for line in lines:
quoted_line = f"> {line}"
outpu... |
Builds the message list object for the message notification email template.
The messages are collapsed into per-recipient and per-sender blocks, like
our web interface | def build_message_list(
user: UserProfile,
messages: List[Message],
stream_id_map: Optional[Dict[int, Stream]] = None, # only needs id, name
) -> List[Dict[str, Any]]:
"""
Builds the message list object for the message notification email template.
The messages are collapsed into per-recipient a... |
Send a reminder email to a user if she's missed some direct messages
by being offline.
The email will have its reply to address set to a limited used email
address that will send a Zulip message to the correct recipient. This
allows the user to respond to missed direct messages, huddles, and
@-mentions directly from t... | def do_send_missedmessage_events_reply_in_zulip(
user_profile: UserProfile, missed_messages: List[Dict[str, Any]], message_count: int
) -> None:
"""
Send a reminder email to a user if she's missed some direct messages
by being offline.
The email will have its reply to address set to a limited used ... |
Avoid calling this in a loop!
Instead, call get_realm_email_validator()
outside of the loop. | def email_allowed_for_realm(email: str, realm: Realm) -> None:
"""
Avoid calling this in a loop!
Instead, call get_realm_email_validator()
outside of the loop.
"""
get_realm_email_validator(realm)(email) |
We use this function even for a list of one emails.
It checks "new" emails to make sure that they don't
already exist. There's a bit of fiddly logic related
to cross-realm bots and mirror dummies too. | def get_existing_user_errors(
target_realm: Realm,
emails: Set[str],
verbose: bool = False,
) -> Dict[str, Tuple[str, bool]]:
"""
We use this function even for a list of one emails.
It checks "new" emails to make sure that they don't
already exist. There's a bit of fiddly logic related
... |
NOTE:
Only use this to validate that a single email
is not already used in the realm.
We should start using bulk_check_new_emails()
for any endpoint that takes multiple emails,
such as the "invite" interface. | def validate_email_not_already_in_realm(
target_realm: Realm, email: str, verbose: bool = True
) -> None:
"""
NOTE:
Only use this to validate that a single email
is not already used in the realm.
We should start using bulk_check_new_emails()
for any endpoint that takes multi... |
This function is used as a helper in
fetch_initial_state_data, when the user passes
in None for event_types, and we want to fetch
info for every event type. Defining this at module
level makes it easier to mock. | def always_want(msg_type: str) -> bool:
"""
This function is used as a helper in
fetch_initial_state_data, when the user passes
in None for event_types, and we want to fetch
info for every event type. Defining this at module
level makes it easier to mock.
"""
return True |
When `event_types` is None, fetches the core data powering the
web app's `page_params` and `/api/v1/register` (for mobile/terminal
apps). Can also fetch a subset as determined by `event_types`.
The user_profile=None code path is used for logged-out public
access to streams with is_web_public=True.
Whenever you add n... | def fetch_initial_state_data(
user_profile: Optional[UserProfile],
*,
realm: Optional[Realm] = None,
event_types: Optional[Iterable[str]] = None,
queue_id: Optional[str] = "",
client_gravatar: bool = False,
user_avatar_url_field_optional: bool = False,
user_settings_object: bool = False,... |
NOTE:
Below is an example of post-processing initial state data AFTER we
apply events. For large payloads like `unread_msgs`, it's helpful
to have an intermediate data structure that is easy to manipulate
with O(1)-type operations as we apply events.
Then, only at the end, we put it in the form that's more appropria... | def post_process_state(
user_profile: Optional[UserProfile], ret: Dict[str, Any], notification_settings_null: bool
) -> None:
"""
NOTE:
Below is an example of post-processing initial state data AFTER we
apply events. For large payloads like `unread_msgs`, it's helpful
to have an intermediate d... |
The way we send realm emojis is kinda clumsy--we
send a dict mapping the emoji id to a sub_dict with
the fields (including the id). Ideally we can streamline
this and just send a list of dicts. The clients can make
a Map as needed. | def check_realm_emoji_update(var_name: str, event: Dict[str, object]) -> None:
"""
The way we send realm emojis is kinda clumsy--we
send a dict mapping the emoji id to a sub_dict with
the fields (including the id). Ideally we can streamline
this and just send a list of dicts. The clients can make
... |
Realm updates have these two fields:
property
value
We check not only the basic schema, but also that
the value people actually matches the type from
Realm.property_types that we have configured
for the property. | def check_realm_update(
var_name: str,
event: Dict[str, object],
prop: str,
) -> None:
"""
Realm updates have these two fields:
property
value
We check not only the basic schema, but also that
the value people actually matches the type from
Realm.property_types that we ... |
Display setting events have a "setting" field that
is more specifically typed according to the
UserProfile.property_types dictionary. | def check_update_display_settings(
var_name: str,
event: Dict[str, object],
) -> None:
"""
Display setting events have a "setting" field that
is more specifically typed according to the
UserProfile.property_types dictionary.
"""
_check_update_display_settings(var_name, event)
setting... |
See UserProfile.notification_settings_legacy for
more details. | def check_update_global_notifications(
var_name: str,
event: Dict[str, object],
desired_val: Union[bool, int, str],
) -> None:
"""
See UserProfile.notification_settings_legacy for
more details.
"""
_check_update_global_notifications(var_name, event)
setting_name = event["notification... |
IMPORTANT: You generally don't want to call this directly.
Instead use one of the higher level helpers:
write_table_data
write_records_json_file
The one place we call this directly is for message partials. | def write_data_to_file(output_file: Path, data: Any) -> None:
"""
IMPORTANT: You generally don't want to call this directly.
Instead use one of the higher level helpers:
write_table_data
write_records_json_file
The one place we call this directly is for message partials.
"""
w... |
Takes a Django query and returns a JSONable list
of dictionaries corresponding to the database rows. | def make_raw(query: Any, exclude: Optional[List[Field]] = None) -> List[Record]:
"""
Takes a Django query and returns a JSONable list
of dictionaries corresponding to the database rows.
"""
rows = []
for instance in query:
data = model_to_dict(instance, exclude=exclude)
"""
... |
We add tables here that are keyed by user, and for which
we fetch rows using the same scheme whether we are
exporting a realm or a single user.
For any table where there is nuance between how you
fetch for realms vs. single users, it's best to just
keep things simple and have each caller maintain its
own slightly diff... | def add_user_profile_child_configs(user_profile_config: Config) -> None:
"""
We add tables here that are keyed by user, and for which
we fetch rows using the same scheme whether we are
exporting a realm or a single user.
For any table where there is nuance between how you
fetch for realms vs. s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.