response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
To be expansive, we include audit log entries for events that either modified the target user or where the target user modified something (E.g. if they changed the settings for a stream).
def custom_fetch_realm_audit_logs_for_user(response: TableData, context: Context) -> None: """To be expansive, we include audit log entries for events that either modified the target user or where the target user modified something (E.g. if they changed the settings for a stream). """ user = context...
Simple custom fetch function to fetch only the ScheduledMessage objects that we're allowed to.
def custom_fetch_scheduled_messages(response: TableData, context: Context) -> None: """ Simple custom fetch function to fetch only the ScheduledMessage objects that we're allowed to. """ realm = context["realm"] exportable_scheduled_message_ids = context["exportable_scheduled_message_ids"] quer...
Simple custom fetch function to fix up .acting_user for some RealmAuditLog objects. Certain RealmAuditLog objects have an acting_user that is in a different .realm, due to the possibility of server administrators (typically with the .is_staff permission) taking certain actions to modify UserProfiles or Realms, which w...
def custom_fetch_realm_audit_logs_for_realm(response: TableData, context: Context) -> None: """ Simple custom fetch function to fix up .acting_user for some RealmAuditLog objects. Certain RealmAuditLog objects have an acting_user that is in a different .realm, due to the possibility of server administr...
As part of the system for doing parallel exports, this runs on one batch of Message objects and adds the corresponding UserMessage objects. (This is called by the export_usermessage_batch management command). See write_message_partial_for_query for more context.
def export_usermessages_batch( input_path: Path, output_path: Path, consent_message_id: Optional[int] = None ) -> None: """As part of the system for doing parallel exports, this runs on one batch of Message objects and adds the corresponding UserMessage objects. (This is called by the export_usermessage...
Scheduled messages are private to the sender, so which ones we export depends on the public/consent/full export mode.
def get_exportable_scheduled_message_ids( realm: Realm, public_only: bool = False, consent_message_id: Optional[int] = None ) -> Set[int]: """ Scheduled messages are private to the sender, so which ones we export depends on the public/consent/full export mode. """ if public_only: return...
Use this function if you need a HUGE number of ids from the database, and you don't mind a few extra trips. Particularly for exports, we don't really care about a little extra time to finish the export--the much bigger concern is that we don't want to overload our database all at once, nor do we want to keep a whole b...
def get_id_list_gently_from_database(*, base_query: Any, id_field: str) -> List[int]: """ Use this function if you need a HUGE number of ids from the database, and you don't mind a few extra trips. Particularly for exports, we don't really care about a little extra time to finish the export--the mu...
This function computes page_params for when we load the home page. The page_params data structure gets sent to the client.
def build_page_params_for_home_page_load( request: HttpRequest, user_profile: Optional[UserProfile], realm: Realm, insecure_desktop_app: bool, narrow: List[NarrowTerm], narrow_stream: Optional[Stream], narrow_topic_name: Optional[str], needs_tutorial: bool, ) -> Tuple[int, Dict[str, obje...
Because the URLs for uploaded files encode the realm ID of the organization being imported (which is only determined at import time), we need to rewrite the URLs of links to uploaded files during the import process.
def fix_upload_links(data: TableData, message_table: TableName) -> None: """ Because the URLs for uploaded files encode the realm ID of the organization being imported (which is only determined at import time), we need to rewrite the URLs of links to uploaded files during the import process. """...
When the export data doesn't contain the table `zerver_realmauditlog`, this function creates RealmAuditLog objects for `subscription_created` type event for all the existing Stream subscriptions. This is needed for all the export tools which do not include the table `zerver_realmauditlog` (Slack, Gitter, etc.) because...
def create_subscription_events(data: TableData, realm_id: int) -> None: """ When the export data doesn't contain the table `zerver_realmauditlog`, this function creates RealmAuditLog objects for `subscription_created` type event for all the existing Stream subscriptions. This is needed for all the ...
The tokens in the services are created by 'generate_api_key'. As the tokens are unique, they should be re-created for the imports.
def fix_service_tokens(data: TableData, table: TableName) -> None: """ The tokens in the services are created by 'generate_api_key'. As the tokens are unique, they should be re-created for the imports. """ for item in data[table]: item["token"] = generate_api_key()
Build new huddle hashes with the updated ids of the users
def process_huddle_hash(data: TableData, table: TableName) -> None: """ Build new huddle hashes with the updated ids of the users """ for huddle in data[table]: user_id_list = id_map_to_list["huddle_to_user_list"][huddle["id"]] huddle["huddle_hash"] = get_huddle_hash(user_id_list)
Extract the IDs of the user_profiles involved in a huddle from the subscription object This helps to generate a unique huddle hash from the updated user_profile ids
def get_huddles_from_subscription(data: TableData, table: TableName) -> None: """ Extract the IDs of the user_profiles involved in a huddle from the subscription object This helps to generate a unique huddle hash from the updated user_profile ids """ id_map_to_list["huddle_to_user_list"] = { ...
In CustomProfileField with 'field_type' like 'USER', the IDs need to be re-mapped.
def fix_customprofilefield(data: TableData) -> None: """ In CustomProfileField with 'field_type' like 'USER', the IDs need to be re-mapped. """ field_type_USER_ids = { item["id"] for item in data["zerver_customprofilefield"] if item["field_type"] == CustomProfileField.USER ...
This function sets the rendered_content of all the messages after the messages have been imported from a non-Zulip platform.
def fix_message_rendered_content( realm: Realm, sender_map: Dict[int, Record], messages: List[Record] ) -> None: """ This function sets the rendered_content of all the messages after the messages have been imported from a non-Zulip platform. """ for message in messages: if message["rend...
Returns the ids present in the current table
def current_table_ids(data: TableData, table: TableName) -> List[int]: """ Returns the ids present in the current table """ return [item["id"] for item in data[table]]
Increases the sequence number for a given table by the amount of objects being imported into that table. Hence, this gives a reserved range of IDs to import the converted Slack objects into the tables.
def allocate_ids(model_class: Any, count: int) -> List[int]: """ Increases the sequence number for a given table by the amount of objects being imported into that table. Hence, this gives a reserved range of IDs to import the converted Slack objects into the tables. """ conn = connection.cursor(...
When Django gives us dict objects via model_to_dict, the foreign key fields are `foo`, but we want `foo_id` for the bulk insert. This function handles the simple case where we simply rename the fields. For cases where we need to munge ids in the database, see re_map_foreign_keys.
def convert_to_id_fields(data: TableData, table: TableName, field_name: Field) -> None: """ When Django gives us dict objects via model_to_dict, the foreign key fields are `foo`, but we want `foo_id` for the bulk insert. This function handles the simple case where we simply rename the fields. For c...
This is a wrapper function for all the realm data tables and only avatar and attachment records need to be passed through the internal function because of the difference in data format (TableData corresponding to realm data tables and List[Record] corresponding to the avatar and attachment records)
def re_map_foreign_keys( data: TableData, table: TableName, field_name: Field, related_table: TableName, verbose: bool = False, id_field: bool = False, recipient_field: bool = False, ) -> None: """ This is a wrapper function for all the realm data tables and only avatar and attac...
We occasionally need to assign new ids to rows during the import/export process, to accommodate things like existing rows already being in tables. See bulk_import_client for more context. The tricky part is making sure that foreign key references are in sync with the new ids, and this fixer function does the re-mappi...
def re_map_foreign_keys_internal( data_table: List[Record], table: TableName, field_name: Field, related_table: TableName, verbose: bool = False, id_field: bool = False, recipient_field: bool = False, ) -> None: """ We occasionally need to assign new ids to rows during the import...
Some tables, including Reaction and UserStatus, contain a form of foreign key reference to the RealmEmoji table in the form of `str(realm_emoji.id)` when `reaction_type="realm_emoji"`. See the block comment for emoji_code in the AbstractEmoji definition for more details.
def re_map_realm_emoji_codes(data: TableData, *, table_name: str) -> None: """ Some tables, including Reaction and UserStatus, contain a form of foreign key reference to the RealmEmoji table in the form of `str(realm_emoji.id)` when `reaction_type="realm_emoji"`. See the block comment for emoji_cod...
We need to assign new ids to rows during the import/export process. The tricky part is making sure that foreign key references are in sync with the new ids, and this wrapper function does the re-mapping only for ManyToMany fields.
def re_map_foreign_keys_many_to_many( data: TableData, table: TableName, field_name: Field, related_table: TableName, verbose: bool = False, ) -> None: """ We need to assign new ids to rows during the import/export process. The tricky part is making sure that foreign key references ...
This is an internal function for tables with ManyToMany fields, which takes the old ID list of the ManyToMany relation and returns the new updated ID list.
def re_map_foreign_keys_many_to_many_internal( table: TableName, field_name: Field, related_table: TableName, old_id_list: List[int], verbose: bool = False, ) -> List[int]: """ This is an internal function for tables with ManyToMany fields, which takes the old ID list of the ManyToMany r...
The recipient column shouldn't be imported, we'll set the correct values when Recipient table gets imported.
def remove_denormalized_recipient_column_from_data(data: TableData) -> None: """ The recipient column shouldn't be imported, we'll set the correct values when Recipient table gets imported. """ for stream_dict in data["zerver_stream"]: if "recipient" in stream_dict: del stream_d...
E.g. (RealmDomain -> 'zerver_realmdomain')
def get_db_table(model_class: Any) -> str: """E.g. (RealmDomain -> 'zerver_realmdomain')""" return model_class._meta.db_table
Should run only with settings.BILLING_ENABLED. Ensures that we only enable authentication methods that are available without needing a plan. If the organization upgrades to a paid plan, or gets a sponsorship, they can enable the restricted authentication methods in their settings.
def disable_restricted_authentication_methods(data: TableData) -> None: """ Should run only with settings.BILLING_ENABLED. Ensures that we only enable authentication methods that are available without needing a plan. If the organization upgrades to a paid plan, or gets a sponsorship, they can enable...
This function reads in our entire collection of message ids, which can be millions of integers for some installations. And then we sort the list. This is necessary to ensure that the sort order of incoming ids matches the sort order of date_sent, which isn't always guaranteed by our utilities that convert third party ...
def get_incoming_message_ids(import_dir: Path, sort_by_date: bool) -> List[int]: """ This function reads in our entire collection of message ids, which can be millions of integers for some installations. And then we sort the list. This is necessary to ensure that the sort order of incoming ids matc...
Given an email address, returns the initial password for that account, as created by populate_db.
def initial_password(email: str) -> Optional[str]: """Given an email address, returns the initial password for that account, as created by populate_db.""" if settings.INITIAL_PASSWORD_SALT is not None: # We check settings.DEVELOPMENT, not settings.PRODUCTION, # because some tests mock setti...
Find the module name corresponding to where this record was logged. Sadly `record.module` is just the innermost component of the full module name, so we have to go reconstruct this ourselves.
def find_log_caller_module(record: logging.LogRecord) -> Optional[str]: """Find the module name corresponding to where this record was logged. Sadly `record.module` is just the innermost component of the full module name, so we have to go reconstruct this ourselves. """ # Repeat a search similar to...
Note: `filename` should be declared in zproject/computed_settings.py with zulip_path.
def log_to_file( logger: Logger, filename: str, log_format: str = "%(asctime)s %(levelname)-8s %(message)s", ) -> None: """Note: `filename` should be declared in zproject/computed_settings.py with zulip_path.""" formatter = logging.Formatter(log_format) handler = logging.FileHandler(filename) ...
You can access a message by ID in our APIs that either: (1) You received or have previously accessed via starring (aka have a UserMessage row for). (2) Was sent to a public stream in your realm. We produce consistent, boring error messages to avoid leaking any information from a security perspective. The lock_mes...
def access_message( user_profile: UserProfile, message_id: int, lock_message: bool = False, ) -> Message: """You can access a message by ID in our APIs that either: (1) You received or have previously accessed via starring (aka have a UserMessage row for). (2) Was sent to a public stream...
As access_message, but also returns the usermessage, if any.
def access_message_and_usermessage( user_profile: UserProfile, message_id: int, lock_message: bool = False, ) -> Tuple[Message, Optional[UserMessage]]: """As access_message, but also returns the usermessage, if any.""" try: base_query = Message.objects.select_related(*Message.DEFAULT_SELECT_...
Access control method for unauthenticated requests interacting with a message in web-public streams.
def access_web_public_message( realm: Realm, message_id: int, ) -> Message: """Access control method for unauthenticated requests interacting with a message in web-public streams. """ # We throw a MissingAuthenticationError for all errors in this # code path, to avoid potentially leaking in...
Returns whether a user has access to a given message. * The user_message parameter must be provided if the user has a UserMessage row for the target message. * The optional stream parameter is validated; is_subscribed is not.
def has_message_access( user_profile: UserProfile, message: Message, *, has_user_message: Callable[[], bool], stream: Optional[Stream] = None, is_subscribed: Optional[bool] = None, ) -> bool: """ Returns whether a user has access to a given message. * The user_message parameter must...
This function does the full has_message_access check for each message. If stream is provided, it is used to avoid unnecessary database queries, and will use exactly 2 bulk queries instead. Throws AssertionError if stream is passed and any of the messages were not sent to that stream.
def bulk_access_messages( user_profile: UserProfile, messages: Collection[Message] | QuerySet[Message], *, stream: Optional[Stream] = None, ) -> List[Message]: """This function does the full has_message_access check for each message. If stream is provided, it is used to avoid unnecessary da...
This function mirrors bulk_access_messages, above, but applies the limits to a QuerySet and returns a new QuerySet which only contains messages in the given stream which the user can access. Note that this only works with streams. It may return an empty QuerySet if the user has access to no messages (for instance, for...
def bulk_access_stream_messages_query( user_profile: UserProfile, messages: QuerySet[Message], stream: Stream ) -> QuerySet[Message]: """This function mirrors bulk_access_messages, above, but applies the limits to a QuerySet and returns a new QuerySet which only contains messages in the given stream whi...
Returns a subset of `message_ids` containing only messages the user has a UserMessage for. Makes O(1) database queries. Note that this is not sufficient for access verification for stream messages. See `access_message`, `bulk_access_messages` for proper message access checks that follow our security model.
def get_messages_with_usermessage_rows_for_user( user_profile_id: int, message_ids: Sequence[int] ) -> ValuesQuerySet[UserMessage, int]: """ Returns a subset of `message_ids` containing only messages the user has a UserMessage for. Makes O(1) database queries. Note that this is not sufficient for a...
Helper for doing lookups of the recipient_id that get_recent_private_conversations would have used to record that message in its data structure.
def get_recent_conversations_recipient_id( user_profile: UserProfile, recipient_id: int, sender_id: int ) -> int: """Helper for doing lookups of the recipient_id that get_recent_private_conversations would have used to record that message in its data structure. """ my_recipient_id = user_profile...
This function uses some carefully optimized SQL queries, designed to use the UserMessage index on private_messages. It is somewhat complicated by the fact that for 1:1 direct messages, we store the message against a recipient_id of whichever user was the recipient, and thus for 1:1 direct messages sent directly to us,...
def get_recent_private_conversations(user_profile: UserProfile) -> Dict[int, Dict[str, Any]]: """This function uses some carefully optimized SQL queries, designed to use the UserMessage index on private_messages. It is somewhat complicated by the fact that for 1:1 direct messages, we store the message ...
Helper function for 'topic_wildcard_mention_allowed' and 'stream_wildcard_mention_allowed' to check if the sender is allowed to use wildcard mentions based on the 'wildcard_mention_policy' setting of that realm. This check is used only if the participants count in the topic or the subscribers count in the stream is gre...
def wildcard_mention_policy_authorizes_user(sender: UserProfile, realm: Realm) -> bool: """Helper function for 'topic_wildcard_mention_allowed' and 'stream_wildcard_mention_allowed' to check if the sender is allowed to use wildcard mentions based on the 'wildcard_mention_policy' setting of that realm. T...
This function determines the visibility policy to set when a user participates in a topic, depending on the 'automatically_follow_topics_policy' and 'automatically_unmute_topics_in_muted_streams_policy' settings.
def visibility_policy_for_participation( sender: UserProfile, is_stream_muted: Optional[bool], ) -> Optional[int]: """ This function determines the visibility policy to set when a user participates in a topic, depending on the 'automatically_follow_topics_policy' and 'automatically_unmute_topics...
This function determines the visibility policy to set when a message is sent to a topic, depending on the 'automatically_follow_topics_policy' and 'automatically_unmute_topics_in_muted_streams_policy' settings. It returns None when the policies can't make it more visible than the current visibility policy.
def visibility_policy_for_send_message( sender: UserProfile, message: Message, stream: Stream, is_stream_muted: Optional[bool], current_visibility_policy: int, ) -> Optional[int]: """ This function determines the visibility policy to set when a message is sent to a topic, depending on th...
If the user can set a visibility policy.
def set_visibility_policy_possible(user_profile: UserProfile, message: Message) -> bool: """If the user can set a visibility policy.""" if not message.is_stream_message(): return False if user_profile.is_bot: return False if user_profile.realm != message.get_realm(): return Fal...
Given a iterable of messages and reactions stitch reactions into messages.
def sew_messages_and_reactions( messages: List[Dict[str, Any]], reactions: List[Dict[str, Any]] ) -> List[Dict[str, Any]]: """Given a iterable of messages and reactions stitch reactions into messages. """ # Add all messages with empty reaction item for message in messages: message["react...
Updates the message as stored in the to_dict cache (for serving messages).
def update_message_cache( changed_messages: Iterable[Message], realm_id: Optional[int] = None ) -> List[int]: """Updates the message as stored in the to_dict cache (for serving messages).""" items_for_remote_cache = {} message_ids = [] changed_messages_to_dict = MessageDict.messages_to_encoded_c...
Given two hex strings of equal length, return a hex string with the bitwise xor of the two hex strings.
def xor_hex_strings(bytes_a: str, bytes_b: str) -> str: """Given two hex strings of equal length, return a hex string with the bitwise xor of the two hex strings.""" assert len(bytes_a) == len(bytes_b) return "".join(f"{int(x, 16) ^ int(y, 16):x}" for x, y in zip(bytes_a, bytes_b))
Given an ascii string, encode it as a hex string
def ascii_to_hex(input_string: str) -> str: """Given an ascii string, encode it as a hex string""" return input_string.encode().hex()
Given a hex array, decode it back to a string
def hex_to_ascii(input_string: str) -> str: """Given a hex array, decode it back to a string""" return bytes.fromhex(input_string).decode()
This is kind of the inverse of `get_user_mutes` above. While `get_user_mutes` is mainly used for event system work, this is used in the message send codepath, to get a list of IDs of users who have muted a particular user. The result will also include deactivated users.
def get_muting_users(muted_user_id: int) -> Set[int]: """ This is kind of the inverse of `get_user_mutes` above. While `get_user_mutes` is mainly used for event system work, this is used in the message send codepath, to get a list of IDs of users who have muted a particular user. The result will...
Given the anchor and use_first_unread_anchor parameters passed by the client, computes what anchor value the client requested, handling backwards-compatibility and the various string-valued fields. We encode use_first_unread_anchor as anchor=None.
def parse_anchor_value(anchor_val: Optional[str], use_first_unread_anchor: bool) -> Optional[int]: """Given the anchor and use_first_unread_anchor parameters passed by the client, computes what anchor value the client requested, handling backwards-compatibility and the various string-valued fields. We ...
This code is actually generic enough that we could move it to a library, but our only caller for now is message search.
def limit_query_to_range( query: Select, num_before: int, num_after: int, anchor: int, include_anchor: bool, anchored_to_left: bool, anchored_to_right: bool, id_col: ColumnElement[Integer], first_visible_message_id: int, ) -> SelectBase: """ This code is actually generic enou...
This method assumes that the callers are in our event-handling codepath, and therefore as of summer 2023, they do not yet support the "negated" flag.
def narrow_dataclasses_from_tuples(tups: Collection[Sequence[str]]) -> Collection[NarrowTerm]: """ This method assumes that the callers are in our event-handling codepath, and therefore as of summer 2023, they do not yet support the "negated" flag. """ return [NarrowTerm(operator=tup[0], operand=tup...
Changes to this function should come with corresponding changes to NarrowLibraryTest.
def build_narrow_predicate( narrow: Collection[NarrowTerm], ) -> NarrowPredicate: """Changes to this function should come with corresponding changes to NarrowLibraryTest.""" check_narrow_for_events(narrow) def narrow_predicate(*, message: Dict[str, Any], flags: List[str]) -> bool: def satis...
Captures the hierarchy of notification settings, where visibility policy is considered first, followed by stream-specific settings, and the global-setting in the UserProfile is the fallback.
def user_allows_notifications_in_StreamTopic( stream_is_muted: bool, visibility_policy: int, stream_specific_setting: Optional[bool], global_setting: bool, ) -> bool: """ Captures the hierarchy of notification settings, where visibility policy is considered first, followed by stream-specific...
Returns the user group name to display in the email notification if user group(s) are mentioned. This implements the same algorithm as get_user_group_mentions_data in zerver/lib/notification_data.py, but we're passed a list of messages instead.
def get_mentioned_user_group( messages: List[Dict[str, Any]], user_profile: UserProfile ) -> Optional[MentionedUserGroup]: """Returns the user group name to display in the email notification if user group(s) are mentioned. This implements the same algorithm as get_user_group_mentions_data in zerver...
This checks if there is any realm internal bot missing. If that is the case, it creates the missing realm internal bots.
def create_if_missing_realm_internal_bots() -> None: """This checks if there is any realm internal bot missing. If that is the case, it creates the missing realm internal bots. """ if missing_any_realm_internal_bots(): for realm in Realm.objects.all(): setup_realm_internal_bots(rea...
Given the send_request object for a direct message from the user to welcome-bot, trigger the welcome-bot reply.
def send_welcome_bot_response(send_request: SendMessageRequest) -> None: """Given the send_request object for a direct message from the user to welcome-bot, trigger the welcome-bot reply.""" welcome_bot = get_system_bot(settings.WELCOME_BOT, send_request.realm.id) human_response_lower = send_request.mes...
bot_id is the user_id of the bot sending the response message_info is used to address the message and should have these fields: type - "stream" or "private" display_recipient - like we have in other message events topic - see get_topic_from_message_info response_data is what the bot wants to send back and...
def send_response_message( bot_id: int, message_info: Dict[str, Any], response_data: Dict[str, Any] ) -> None: """ bot_id is the user_id of the bot sending the response message_info is used to address the message and should have these fields: type - "stream" or "private" display_recipie...
Returns response of call if no exception occurs.
def do_rest_call( base_url: str, event: Dict[str, Any], service_handler: OutgoingWebhookServiceInterface, ) -> Optional[Response]: """Returns response of call if no exception occurs.""" try: start_time = perf_counter() bot_profile = service_handler.user_profile response = ser...
Our data models support UserPresence objects not having None values for last_active_time/last_connected_time. The legacy API however has always sent timestamps, so for backward compatibility we cannot send such values through the API and need to default to a sane This helper functions expects to take a last_active_tim...
def user_presence_datetime_with_date_joined_default( dt: Optional[datetime], date_joined: datetime ) -> datetime: """ Our data models support UserPresence objects not having None values for last_active_time/last_connected_time. The legacy API however has always sent timestamps, so for backward c...
Reformats the modern UserPresence data structure so that legacy API clients can still access presence data. We expect this code to remain mostly unchanged until we can delete it.
def get_legacy_user_presence_info( last_active_time: datetime, last_connected_time: datetime ) -> Dict[str, Any]: """ Reformats the modern UserPresence data structure so that legacy API clients can still access presence data. We expect this code to remain mostly unchanged until we can delete it. ...
This function assumes it's being called right after the presence object was updated, and is not meant to be used on old presence data.
def format_legacy_presence_dict( last_active_time: datetime, last_connected_time: datetime ) -> Dict[str, Any]: """ This function assumes it's being called right after the presence object was updated, and is not meant to be used on old presence data. """ if ( last_active_time + t...
This decorator should obviously be used only in a dev environment. It works best when surrounding a function that you expect to be called once. One strategy is to write a backend test and wrap the test case with the profiled decorator. You can run a single test case like this: # edit zerver/tests/test_external.p...
def profiled(func: Callable[ParamT, ReturnT]) -> Callable[ParamT, ReturnT]: """ This decorator should obviously be used only in a dev environment. It works best when surrounding a function that you expect to be called once. One strategy is to write a backend test and wrap the test case with the pro...
Never use this function outside of the push-notifications codepath. Most of our code knows how to get streams up front in a more efficient manner.
def get_message_stream_name_from_database(message: Message) -> str: """ Never use this function outside of the push-notifications codepath. Most of our code knows how to get streams up front in a more efficient manner. """ stream_id = message.recipient.type_id return Stream.objects.get(id=st...
Take a payload in an unknown Zulip version's format, and return in current format.
def modernize_apns_payload(data: Mapping[str, Any]) -> Mapping[str, Any]: """Take a payload in an unknown Zulip version's format, and return in current format.""" # TODO this isn't super robust as is -- if a buggy remote server # sends a malformed payload, we are likely to raise an exception. if "messag...
Parse GCM options, supplying defaults, and raising an error if invalid. The options permitted here form part of the Zulip notification bouncer's API. They are: `priority`: Passed through to GCM; see upstream doc linked below. Zulip servers should always set this; when unset, we guess a value based on the beh...
def parse_gcm_options(options: Dict[str, Any], data: Dict[str, Any]) -> str: """ Parse GCM options, supplying defaults, and raising an error if invalid. The options permitted here form part of the Zulip notification bouncer's API. They are: `priority`: Passed through to GCM; see upstream doc link...
Send a GCM message to the given devices. See https://firebase.google.com/docs/cloud-messaging/http-server-ref for the GCM upstream API which this talks to. data: The JSON object (decoded) to send as the 'data' parameter of the GCM message. options: Additional options to control the GCM message sent. For detai...
def send_android_push_notification( user_identity: UserPushIdentityCompat, devices: Sequence[DeviceToken], data: Dict[str, Any], options: Dict[str, Any], remote: Optional["RemoteZulipServer"] = None, ) -> int: """ Send a GCM message to the given devices. See https://firebase.google.com/...
True just if this server has configured a way to send push notifications.
def push_notifications_configured() -> bool: """True just if this server has configured a way to send push notifications.""" if ( uses_notification_bouncer() and settings.ZULIP_ORG_KEY is not None and settings.ZULIP_ORG_ID is not None ): # nocoverage # We have the needed con...
Called during startup of the push notifications worker to check whether we expect mobile push notifications to work on this server and update state accordingly.
def initialize_push_notifications() -> None: """Called during startup of the push notifications worker to check whether we expect mobile push notifications to work on this server and update state accordingly. """ if sends_notifications_directly(): # This server sends push notifications dire...
Common fields for all notification payloads.
def get_base_payload(user_profile: UserProfile) -> Dict[str, Any]: """Common fields for all notification payloads.""" data: Dict[str, Any] = {} # These will let the app support logging into multiple realms and servers. data["server"] = settings.EXTERNAL_HOST data["realm_id"] = user_profile.realm.id...
Common fields for `message` payloads, for all platforms.
def get_message_payload( user_profile: UserProfile, message: Message, mentioned_user_group_id: Optional[int] = None, mentioned_user_group_name: Optional[str] = None, can_access_sender: bool = True, ) -> Dict[str, Any]: """Common fields for `message` payloads, for all platforms.""" data = get...
On an iOS notification, this is the first bolded line.
def get_apns_alert_title(message: Message) -> str: """ On an iOS notification, this is the first bolded line. """ if message.recipient.type == Recipient.DIRECT_MESSAGE_GROUP: recipients = get_display_recipient(message.recipient) assert isinstance(recipients, list) return ", ".joi...
On an iOS notification, this is the second bolded line.
def get_apns_alert_subtitle( message: Message, trigger: str, user_profile: UserProfile, mentioned_user_group_name: Optional[str] = None, can_access_sender: bool = True, ) -> str: """ On an iOS notification, this is the second bolded line. """ sender_name = message.sender.full_name ...
A `message` payload for iOS, via APNs.
def get_message_payload_apns( user_profile: UserProfile, message: Message, trigger: str, mentioned_user_group_id: Optional[int] = None, mentioned_user_group_name: Optional[str] = None, can_access_sender: bool = True, ) -> Dict[str, Any]: """A `message` payload for iOS, via APNs.""" zulip...
A `message` payload + options, for Android via GCM/FCM.
def get_message_payload_gcm( user_profile: UserProfile, message: Message, mentioned_user_group_id: Optional[int] = None, mentioned_user_group_name: Optional[str] = None, can_access_sender: bool = True, ) -> Tuple[Dict[str, Any], Dict[str, Any]]: """A `message` payload + options, for Android via ...
A `remove` payload + options, for Android via GCM/FCM.
def get_remove_payload_gcm( user_profile: UserProfile, message_ids: List[int], ) -> Tuple[Dict[str, Any], Dict[str, Any]]: """A `remove` payload + options, for Android via GCM/FCM.""" gcm_payload = get_base_payload(user_profile) gcm_payload.update( event="remove", zulip_message_ids="...
This should be called when a message that previously had a mobile push notification executed is read. This triggers a push to the mobile app, when the message is read on the server, to remove the message from the notification.
def handle_remove_push_notification(user_profile_id: int, message_ids: List[int]) -> None: """This should be called when a message that previously had a mobile push notification executed is read. This triggers a push to the mobile app, when the message is read on the server, to remove the message from ...
missed_message is the event received by the zerver.worker.missedmessage_mobile_notifications.PushNotificationWorker.consume function.
def handle_push_notification(user_profile_id: int, missed_message: Dict[str, Any]) -> None: """ missed_message is the event received by the zerver.worker.missedmessage_mobile_notifications.PushNotificationWorker.consume function. """ if not push_notifications_configured(): return user_pr...
This function optimizes searches of the form `user_profile_id in (1, 2, 3, 4)` by quickly building the where clauses. Profiling shows significant speedups over the normal Django-based approach. Use this very carefully! Also, the caller should guard against empty lists of user_ids.
def query_for_ids( query: ValuesQuerySet[ModelT, RowT], user_ids: List[int], field: str, ) -> ValuesQuerySet[ModelT, RowT]: """ This function optimizes searches of the form `user_profile_id in (1, 2, 3, 4)` by quickly building the where clauses. Profiling shows significant speedups over...
Returns whether or not a user was rate limited. Will raise a RateLimitedError exception if the user has been rate limited, otherwise returns and modifies request to contain the rate limit information
def rate_limit_user(request: HttpRequest, user: UserProfile, domain: str) -> None: """Returns whether or not a user was rate limited. Will raise a RateLimitedError exception if the user has been rate limited, otherwise returns and modifies request to contain the rate limit information""" if not should_...
While it does actually send the notice, this function has a lot of code and comments around error handling for the push notifications bouncer. There are several classes of failures, each with its own potential solution: * Network errors with requests.request. We raise an exception to signal it to the callers. * 5...
def send_to_push_bouncer( method: str, endpoint: str, post_data: Union[bytes, Mapping[str, Union[str, int, None, bytes]]], extra_headers: Mapping[str, str] = {}, ) -> Dict[str, object]: """While it does actually send the notice, this function has a lot of code and comments around error handling ...
This should only be needed in middleware; in app code, just raise. When app code raises a JsonableError, the JsonErrorHandler middleware takes care of transforming it into a response by calling this function.
def json_response_from_error(exception: JsonableError) -> MutableJsonResponse: """ This should only be needed in middleware; in app code, just raise. When app code raises a JsonableError, the JsonErrorHandler middleware takes care of transforming it into a response by calling this function. """...
Patched version of the standard Django never_cache_responses decorator that adds headers to a response so that it will never be cached, unless the view code has already set a Cache-Control header.
def default_never_cache_responses( view_func: Callable[Concatenate[HttpRequest, ParamT], HttpResponse], ) -> Callable[Concatenate[HttpRequest, ParamT], HttpResponse]: """Patched version of the standard Django never_cache_responses decorator that adds headers to a response so that it will never be cached...
Helper for REST API request dispatch. The rest_dispatch_kwargs parameter is expected to be a dictionary mapping HTTP methods to a mix of view functions and (view_function, {view_flags}) tuples. * Returns an error HttpResponse for unsupported HTTP methods. * Otherwise, returns a tuple containing the view function co...
def get_target_view_function_or_response( request: HttpRequest, rest_dispatch_kwargs: Dict[str, object] ) -> Union[Tuple[Callable[..., HttpResponse], Set[str]], HttpResponse]: """Helper for REST API request dispatch. The rest_dispatch_kwargs parameter is expected to be a dictionary mapping HTTP methods to ...
Dispatch to a REST API endpoint. Authentication is verified in the following ways: * for paths beginning with /api, HTTP basic auth * for paths beginning with /json (used by the web client), the session token Unauthenticated requests may use this endpoint only with the allow_anonymous_user_web view flag. Thi...
def rest_dispatch(request: HttpRequest, /, **kwargs: object) -> HttpResponse: """Dispatch to a REST API endpoint. Authentication is verified in the following ways: * for paths beginning with /api, HTTP basic auth * for paths beginning with /json (used by the web client), the session token ...
Core helper for bulk moving rows between a table and its archive table
def move_rows( base_model: Type[Model], raw_query: SQL, *, src_db_table: Optional[str] = None, returning_id: bool = False, **kwargs: Composable, ) -> List[int]: """Core helper for bulk moving rows between a table and its archive table""" if src_db_table is None: # Use base_model'...
This function constructs a list of (realm, streams_of_the_realm) tuples where each realm is a Realm that requires calling the archiving functions on it, and streams_of_the_realm is a list of streams of the realm to call archive_stream_messages with. The purpose of this is performance - for servers with thousands of re...
def get_realms_and_streams_for_archiving() -> List[Tuple[Realm, List[Stream]]]: """ This function constructs a list of (realm, streams_of_the_realm) tuples where each realm is a Realm that requires calling the archiving functions on it, and streams_of_the_realm is a list of streams of the realm to call ...
Utility function for calling in the Django shell if a stream's policy was set to something too aggressive and the administrator wants to restore the messages deleted as a result.
def restore_retention_policy_deletions_for_stream(stream: Stream) -> None: """ Utility function for calling in the Django shell if a stream's policy was set to something too aggressive and the administrator wants to restore the messages deleted as a result. """ relevant_transactions = ArchiveTra...
This function deletes archived data that was archived at least settings.ARCHIVED_DATA_VACUUMING_DELAY_DAYS days ago. It works by deleting ArchiveTransaction objects that are sufficiently old. We've configured most archive tables, like ArchiveMessage, with on_delete=CASCADE, so that deleting an ArchiveTransaction entai...
def clean_archived_data() -> None: """This function deletes archived data that was archived at least settings.ARCHIVED_DATA_VACUUMING_DELAY_DAYS days ago. It works by deleting ArchiveTransaction objects that are sufficiently old. We've configured most archive tables, like ArchiveMessage, with on_de...
Registered as GET_EXTRA_MODEL_FILTER_KWARGS_GETTER in our SCIM configuration. Returns a function which generates additional kwargs to add to QuerySet's .filter() when fetching a UserProfile corresponding to the requested SCIM User from the database. It's *crucial* for security that we filter by realm_id (based on the...
def get_extra_model_filter_kwargs_getter( model: Type[models.Model], ) -> Callable[[HttpRequest, Any, Any], Dict[str, object]]: """Registered as GET_EXTRA_MODEL_FILTER_KWARGS_GETTER in our SCIM configuration. Returns a function which generates additional kwargs to add to QuerySet's .filter() when f...
Used as the base url for constructing the Location of a SCIM resource. Since SCIM synchronization is scoped to an individual realm, we need these locations to be namespaced within the realm's domain namespace, which is conveniently accessed via realm.uri.
def base_scim_location_getter(request: HttpRequest, *args: Any, **kwargs: Any) -> str: """Used as the base url for constructing the Location of a SCIM resource. Since SCIM synchronization is scoped to an individual realm, we need these locations to be namespaced within the realm's domain namespace, whi...
Unlike most scheduled emails, invitation emails don't have an existing user object to key off of, so we filter by address here.
def clear_scheduled_invitation_emails(email: str) -> None: """Unlike most scheduled emails, invitation emails don't have an existing user object to key off of, so we filter by address here.""" items = ScheduledEmail.objects.filter( address__iexact=email, type=ScheduledEmail.INVITATION_REMINDER )...
Helper for `manage.py send_custom_email`. Can be used directly with from a management shell with send_custom_email(user_profile_list, dict( markdown_template_path="/path/to/markdown/file.md", subject="Email subject", from_name="Sender Name") )
def send_custom_email( users: QuerySet[UserProfile], *, dry_run: bool, options: Dict[str, str], add_context: Optional[Callable[[Dict[str, object], UserProfile], None]] = None, distinct_email: bool = False, ) -> QuerySet[UserProfile]: """ Helper for `manage.py send_custom_email`. Can...
The purpose of this function is to log (potential) config errors, but without raising an exception.
def log_email_config_errors() -> None: """ The purpose of this function is to log (potential) config errors, but without raising an exception. """ if settings.EMAIL_HOST_USER and settings.EMAIL_HOST_PASSWORD is None: logger.error( "An SMTP username was set (EMAIL_HOST_USER), but ...
This function takes a soft-deactivated user, and computes and adds to the database any UserMessage rows that were not created while the user was soft-deactivated. The end result is that from the perspective of the message database, it should be impossible to tell that the user was soft-deactivated at all. At a high l...
def add_missing_messages(user_profile: UserProfile) -> None: """This function takes a soft-deactivated user, and computes and adds to the database any UserMessage rows that were not created while the user was soft-deactivated. The end result is that from the perspective of the message database, it shou...
When we're about to send an email/push notification to a long_term_idle user, it's very likely that the user will try to return to Zulip. As a result, it makes sense to optimistically soft-reactivate that user, to give them a good return experience. It's important that we do nothing for stream wildcard or large group ...
def soft_reactivate_if_personal_notification( user_profile: UserProfile, unique_triggers: Set[str], mentioned_user_group_members_count: Optional[int], ) -> None: """When we're about to send an email/push notification to a long_term_idle user, it's very likely that the user will try to return to ...
Note that stream_dict["name"] is assumed to already be stripped of whitespace
def create_streams_if_needed( realm: Realm, stream_dicts: List[StreamDict], acting_user: Optional[UserProfile] = None ) -> Tuple[List[Stream], List[Stream]]: """Note that stream_dict["name"] is assumed to already be stripped of whitespace""" added_streams: List[Stream] = [] existing_streams: List[St...
Common function for backend code where the target use attempts to access the target stream, returning all the data fetched along the way. If that user does not have permission to access that stream, we throw an exception. A design goal is that the error message is the same for streams you can't access and streams tha...
def access_stream_common( user_profile: UserProfile, stream: Stream, error: str, require_active: bool = True, allow_realm_admin: bool = False, ) -> Optional[Subscription]: """Common function for backend code where the target use attempts to access the target stream, returning all the data fe...
It may seem a little silly to have this helper function for unmuting topics, but it gets around a linter warning, and it helps to be able to review all security-related stuff in one place. Our policy for accessing streams when you unmute a topic is that you don't necessarily need to have an active subscription or even...
def access_stream_to_remove_visibility_policy_by_name( user_profile: UserProfile, stream_name: str, error: str ) -> Stream: """ It may seem a little silly to have this helper function for unmuting topics, but it gets around a linter warning, and it helps to be able to review all security-related stu...
Determine whether the provided user is allowed to access the history of the target stream. This is used by the caller to determine whether this user can get historical messages before they joined for a narrowing search. Because of the way our search is currently structured, we may be passed an invalid stream here. W...
def can_access_stream_history(user_profile: UserProfile, stream: Stream) -> bool: """Determine whether the provided user is allowed to access the history of the target stream. This is used by the caller to determine whether this user can get historical messages before they joined for a narrowing search...
Converts list of dicts to a list of Streams, validating input in the process For each stream name, we validate it to ensure it meets our requirements for a proper stream name using check_stream_name. This function in autocreate mode should be atomic: either an exception will be raised during a precheck, or all the st...
def list_to_streams( streams_raw: Collection[StreamDict], user_profile: UserProfile, autocreate: bool = False, unsubscribing_others: bool = False, is_default_stream: bool = False, ) -> Tuple[List[Stream], List[Stream]]: """Converts list of dicts to a list of Streams, validating input in the proc...