response stringlengths 1 33.1k | instruction stringlengths 22 582k |
|---|---|
Fetch a summary from the full spec object. | def get_openapi_summary(endpoint: str, method: str) -> str:
"""Fetch a summary from the full spec object."""
return openapi_spec.openapi()["paths"][endpoint][method.lower()]["summary"] |
Compare a "content" dict with the defined schema for a specific method
in an endpoint. Return true if validated and false if skipped. | def validate_test_response(request: Request, response: Response) -> bool:
"""Compare a "content" dict with the defined schema for a specific method
in an endpoint. Return true if validated and false if skipped.
"""
if request.path.startswith("/json/"):
path = request.path[len("/json") :]
e... |
Check if opaque objects are present in the OpenAPI spec; this is an
important part of our policy for ensuring every detail of Zulip's
API responses is correct.
This is done by checking for the presence of the
`additionalProperties` attribute for all objects (dictionaries). | def validate_schema(schema: Dict[str, Any]) -> None:
"""Check if opaque objects are present in the OpenAPI spec; this is an
important part of our policy for ensuring every detail of Zulip's
API responses is correct.
This is done by checking for the presence of the
`additionalProperties` attribute f... |
This decorator is used to register an OpenAPI test function with
its endpoint. Example usage:
@openapi_test_function("/messages/render:post")
def ... | def openapi_test_function(
endpoint: str,
) -> Callable[[Callable[ParamT, ReturnT]], Callable[ParamT, ReturnT]]:
"""This decorator is used to register an OpenAPI test function with
its endpoint. Example usage:
@openapi_test_function("/messages/render:post")
def ...
"""
def wrapper(test_fun... |
The has_alert_word flag can be ignored for most tests. | def check_flags(flags: List[str], expected: Set[str]) -> None:
"""
The has_alert_word flag can be ignored for most tests.
"""
assert "has_alert_word" not in expected
flag_set = set(flags)
flag_set.discard("has_alert_word")
if flag_set != expected:
raise AssertionError(f"expected flag... |
A helper to let us ignore the view function's signature | def call_endpoint(
view: Callable[..., T], request: HttpRequest, *args: object, **kwargs: object
) -> T:
"""A helper to let us ignore the view function's signature"""
return view(request, *args, **kwargs) |
`users` is a list of user IDs, or in some special cases like message
send/update or embeds, dictionaries containing extra data. | def send_event(
realm: Realm, event: Mapping[str, Any], users: Union[Iterable[int], Iterable[Mapping[str, Any]]]
) -> None:
"""`users` is a list of user IDs, or in some special cases like message
send/update or embeds, dictionaries containing extra data."""
realm_ports = get_realm_tornado_ports(realm)
... |
Prunes the internal_data data structures, which are not intended to
be exposed to API clients. | def prune_internal_data(events: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Prunes the internal_data data structures, which are not intended to
be exposed to API clients.
"""
events = copy.deepcopy(events)
for event in events:
if event["type"] == "message" and "internal_data" in event... |
The receiver_is_off_zulip logic used to determine whether a user
has no active client suffers from a somewhat fundamental race
condition. If the client is no longer on the Internet,
receiver_is_off_zulip will still return False for
DEFAULT_EVENT_QUEUE_TIMEOUT_SECS, until the queue is
garbage-collected. This would cau... | def missedmessage_hook(
user_profile_id: int, client: ClientDescriptor, last_for_client: bool
) -> None:
"""The receiver_is_off_zulip logic used to determine whether a user
has no active client suffers from a somewhat fundamental race
condition. If the client is no longer on the Internet,
receiver_... |
This function has a complete unit test suite in
`test_enqueue_notifications` that should be expanded as we add
more features here.
See https://zulip.readthedocs.io/en/latest/subsystems/notifications.html
for high-level design documentation. | def maybe_enqueue_notifications(
*,
user_notifications_data: UserMessageNotificationsData,
acting_user_id: int,
message_id: int,
mentioned_user_group_id: Optional[int],
idle: bool,
already_notified: Dict[str, bool],
) -> Dict[str, bool]:
"""This function has a complete unit test suite in... |
Return client info for all the clients interested in a message.
This basically includes clients for users who are recipients
of the message, with some nuances for bots that auto-subscribe
to all streams, plus users who may be mentioned, etc. | def get_client_info_for_message_event(
event_template: Mapping[str, Any], users: Iterable[Mapping[str, Any]]
) -> Dict[str, ClientInfo]:
"""
Return client info for all the clients interested in a message.
This basically includes clients for users who are recipients
of the message, with some nuances ... |
See
https://zulip.readthedocs.io/en/latest/subsystems/sending-messages.html
for high-level documentation on this subsystem. | def process_message_event(
event_template: Mapping[str, Any], users: Collection[Mapping[str, Any]]
) -> None:
"""See
https://zulip.readthedocs.io/en/latest/subsystems/sending-messages.html
for high-level documentation on this subsystem.
"""
send_to_clients = get_client_info_for_message_event(eve... |
Given a successful authentication for an email address (i.e. we've
confirmed the user controls the email address) that does not
currently have a Zulip account in the target realm, send them to
the registration flow or the "continue to registration" flow,
depending on is_signup, whether the email address can join the
or... | def maybe_send_to_registration(
request: HttpRequest,
email: str,
full_name: str = "",
mobile_flow_otp: Optional[str] = None,
desktop_flow_otp: Optional[str] = None,
is_signup: bool = False,
multiuse_object_key: str = "",
full_name_validated: bool = False,
params_to_store_in_authenti... |
Given a successful authentication showing the user controls given
email address (email) and potentially a UserProfile
object (if the user already has a Zulip account), redirect the
browser to the appropriate place:
* The logged-in app if the user already has a Zulip account and is
trying to log in, potentially to an... | def login_or_register_remote_user(request: HttpRequest, result: ExternalAuthResult) -> HttpResponse:
"""Given a successful authentication showing the user controls given
email address (email) and potentially a UserProfile
object (if the user already has a Zulip account), redirect the
browser to the appr... |
The desktop otp flow returns to the app (through the clipboard)
a token that allows obtaining (through log_into_subdomain) a logged in session
for the user account we authenticated in this flow.
The token can only be used once and within ExternalAuthResult.LOGIN_KEY_EXPIRATION_SECONDS
of being created, as nothing more ... | def finish_desktop_flow(
request: HttpRequest,
user_profile: UserProfile,
otp: str,
params_to_store_in_authenticated_session: Optional[Dict[str, str]] = None,
) -> HttpResponse:
"""
The desktop otp flow returns to the app (through the clipboard)
a token that allows obtaining (through log_int... |
The purpose of this endpoint is to provide an initial step in the flow
on which we can handle the special behavior for the desktop app.
/accounts/login/sso may have Apache intercepting requests to it
to do authentication, so we need this additional endpoint. | def start_remote_user_sso(request: HttpRequest) -> HttpResponse:
"""
The purpose of this endpoint is to provide an initial step in the flow
on which we can handle the special behavior for the desktop app.
/accounts/login/sso may have Apache intercepting requests to it
to do authentication, so we nee... |
Given a valid authentication token (generated by
redirect_and_log_into_subdomain called on auth.zulip.example.com),
call login_or_register_remote_user, passing all the authentication
result data that has been stored in Redis, associated with this token. | def log_into_subdomain(request: HttpRequest, token: str) -> HttpResponse:
"""Given a valid authentication token (generated by
redirect_and_log_into_subdomain called on auth.zulip.example.com),
call login_or_register_remote_user, passing all the authentication
result data that has been stored in Redis, a... |
Returns which authentication methods are enabled on the server | def get_auth_backends_data(request: HttpRequest) -> Dict[str, Any]:
"""Returns which authentication methods are enabled on the server"""
subdomain = get_subdomain(request)
try:
realm = Realm.objects.get(string_id=subdomain)
except Realm.DoesNotExist:
# If not the root subdomain, this is ... |
This is the view function for generating our SP metadata
for SAML authentication. It's meant for helping check the correctness
of the configuration when setting up SAML, or for obtaining the XML metadata
if the IdP requires it.
Taken from https://python-social-auth.readthedocs.io/en/latest/backends/saml.html | def saml_sp_metadata(request: HttpRequest) -> HttpResponse: # nocoverage
"""
This is the view function for generating our SP metadata
for SAML authentication. It's meant for helping check the correctness
of the configuration when setting up SAML, or for obtaining the XML metadata
if the IdP requir... |
This function implements Zulip's support for a mini Zulip window
that just handles messages from a single narrow | def detect_narrowed_window(
request: HttpRequest, user_profile: Optional[UserProfile]
) -> Tuple[List[NarrowTerm], Optional[Stream], Optional[str]]:
"""This function implements Zulip's support for a mini Zulip window
that just handles messages from a single narrow"""
if user_profile is None:
ret... |
Reset our don't-spam-users-with-email counter since the
user has since logged in | def update_last_reminder(user_profile: Optional[UserProfile]) -> None:
"""Reset our don't-spam-users-with-email counter since the
user has since logged in
"""
if user_profile is None:
return
if user_profile.last_reminder is not None: # nocoverage
# TODO: Look into the history of la... |
This fills out the message edit history entries from the database
to have the current topic + content as of that time, plus data on
whatever changed. This makes it much simpler to do future
processing. | def fill_edit_history_entries(
raw_edit_history: List[EditHistoryEvent], message: Message
) -> List[FormattedEditHistoryEvent]:
"""
This fills out the message edit history entries from the database
to have the current topic + content as of that time, plus data on
whatever changed. This makes it much... |
This endpoint is used by the web app running in the browser. We serve HTML
error pages, and in case of success a simple redirect to the remote billing
access link received from the bouncer. | def self_hosting_auth_redirect_endpoint(
request: HttpRequest,
*,
next_page: Optional[str] = None,
) -> HttpResponse:
"""
This endpoint is used by the web app running in the browser. We serve HTML
error pages, and in case of success a simple redirect to the remote billing
access link receive... |
This endpoint is used by the desktop application. It makes an API request here,
expecting a JSON response with either the billing access link, or appropriate
error information. | def self_hosting_auth_json_endpoint(
request: HttpRequest,
user_profile: UserProfile,
*,
next_page: Optional[str] = None,
) -> HttpResponse:
"""
This endpoint is used by the desktop application. It makes an API request here,
expecting a JSON response with either the billing access link, or a... |
The purpose of this little endpoint is primarily to take a GET
request to a long URL containing a confirmation key, and render
a page that will via JavaScript immediately do a POST request to
/accounts/register, so that the user can create their account on
a page with a cleaner URL (and with the browser security and UX... | def get_prereg_key_and_redirect(
request: HttpRequest, confirmation_key: str, full_name: Optional[str] = REQ(default=None)
) -> HttpResponse:
"""
The purpose of this little endpoint is primarily to take a GET
request to a long URL containing a confirmation key, and render
a page that will via JavaSc... |
Checks if the Confirmation key is valid, returning the PreregistrationUser or
PreregistrationRealm object in case of success and raising an appropriate
ConfirmationKeyError otherwise. | def check_prereg_key(
request: HttpRequest, confirmation_key: str
) -> Tuple[Union[PreregistrationUser, PreregistrationRealm], bool]:
"""
Checks if the Confirmation key is valid, returning the PreregistrationUser or
PreregistrationRealm object in case of success and raising an appropriate
Confirmati... |
Send an email with a confirmation link to the provided e-mail so the user
can complete their registration. | def prepare_activation_url(
email: str,
session: SessionBase,
*,
realm: Optional[Realm],
streams: Optional[Iterable[Stream]] = None,
invited_as: Optional[int] = None,
multiuse_invite: Optional[MultiuseInvite] = None,
) -> str:
"""
Send an email with a confirmation link to the provide... |
Returns whether the target user is either the current user or a bot
owned by the current user | def user_directly_controls_user(user_profile: UserProfile, target: UserProfile) -> bool:
"""Returns whether the target user is either the current user or a bot
owned by the current user"""
if user_profile == target:
return True
if target.is_bot and target.bot_owner_id == user_profile.id:
... |
This takes a series of thunks and calls them in sequence, and it
smushes all the json results into a single response when
everything goes right. (This helps clients avoid extra latency
hops.) It rolls back the transaction when things go wrong in any
one of the composed methods. | def compose_views(thunks: List[Callable[[], HttpResponse]]) -> Dict[str, Any]:
"""
This takes a series of thunks and calls them in sequence, and it
smushes all the json results into a single response when
everything goes right. (This helps clients avoid extra latency
hops.) It rolls back the trans... |
If you are subscribing lots of new users to new streams,
this function can be pretty expensive in terms of generating
lots of queries and sending lots of messages. We isolate
the code partly to make it easier to test things like
excessive query counts by mocking this function so that it
doesn't drown out query counts ... | def send_messages_for_new_subscribers(
user_profile: UserProfile,
subscribers: Set[UserProfile],
new_subscriptions: Dict[str, List[str]],
email_to_user_profile: Dict[str, UserProfile],
created_streams: List[Stream],
announce: bool,
) -> None:
"""
If you are subscribing lots of new users ... |
This is the entry point to changing subscription properties. This
is a bulk endpoint: requesters always provide a subscription_data
list containing dictionaries for each stream of interest.
Requests are of the form:
[{"stream_id": "1", "property": "is_muted", "value": False},
{"stream_id": "1", "property": "color", ... | def update_subscription_properties_backend(
request: HttpRequest,
user_profile: UserProfile,
subscription_data: List[Dict[str, Any]] = REQ(
json_validator=check_list(
check_dict(
[
("stream_id", check_int),
("property", check_string... |
We should return a signed, short-lived URL
that the client can use for native mobile download, rather than serving a redirect. | def serve_file_url_backend(
request: HttpRequest, user_profile: UserProfile, realm_id_str: str, filename: str
) -> HttpResponseBase:
"""
We should return a signed, short-lived URL
that the client can use for native mobile download, rather than serving a redirect.
"""
return serve_file(request, ... |
Serves avatar images off disk, via nginx (or directly in dev), with no auth.
This is done unauthed because these need to be accessed from HTML
emails, where the client does not have any auth. We rely on the
URL being generated using the AVATAR_SALT secret. | def serve_local_avatar_unauthed(request: HttpRequest, path: str) -> HttpResponseBase:
"""Serves avatar images off disk, via nginx (or directly in dev), with no auth.
This is done unauthed because these need to be accessed from HTML
emails, where the client does not have any auth. We rely on the
URL be... |
Accepts an email address or user ID and returns the avatar | def avatar(
request: HttpRequest,
maybe_user_profile: Union[UserProfile, AnonymousUser],
email_or_id: str,
medium: bool = False,
) -> HttpResponse:
"""Accepts an email address or user ID and returns the avatar"""
is_email = False
try:
int(email_or_id)
except ValueError:
i... |
The client_gravatar field here is set to True by default assuming that clients
can compute their own gravatars, which saves bandwidth. This is more important of
an optimization than it might seem because gravatar URLs contain MD5 hashes that
compress very poorly compared to other data. | def get_user_data(
user_profile: UserProfile,
include_custom_profile_fields: bool,
client_gravatar: bool,
target_user: Optional[UserProfile] = None,
) -> Dict[str, Any]:
"""
The client_gravatar field here is set to True by default assuming that clients
can compute their own gravatars, which ... |
This function allows logging in without a password on the Zulip
mobile apps when connecting to a Zulip development environment. It
requires DevAuthBackend to be included in settings.AUTHENTICATION_BACKENDS. | def api_dev_fetch_api_key(request: HttpRequest, username: str = REQ()) -> HttpResponse:
"""This function allows logging in without a password on the Zulip
mobile apps when connecting to a Zulip development environment. It
requires DevAuthBackend to be included in settings.AUTHENTICATION_BACKENDS.
"""
... |
Construct a response to a webhook event from a Thinkst canarytoken from
canarytokens.org. Canarytokens from Thinkst's paid product have a different
schema and should use the "thinkst" integration. See linked documentation
below for a schema:
https://help.canary.tools/hc/en-gb/articles/360002426577-How-do-I-configure-n... | def api_canarytoken_webhook(
request: HttpRequest,
user_profile: UserProfile,
*,
message: JsonBodyPayload[WildValue],
user_specified_topic: OptionalUserSpecifiedTopicStr = None,
) -> HttpResponse:
"""
Construct a response to a webhook event from a Thinkst canarytoken from
canarytokens.or... |
The Freshdesk API is currently pretty broken: statuses are customizable
but the API will only tell you the number associated with the status, not
the name. While we engage the Freshdesk developers about exposing this
information through the API, since only FlightCar uses this integration,
hardcode their statuses. | def property_name(property: str, index: int) -> str:
"""The Freshdesk API is currently pretty broken: statuses are customizable
but the API will only tell you the number associated with the status, not
the name. While we engage the Freshdesk developers about exposing this
information through the API, si... |
These are always of the form "{ticket_action:created}" or
"{status:{from:4,to:6}}". Note the lack of string quoting: this isn't
valid JSON so we have to parse it ourselves. | def parse_freshdesk_event(event_string: str) -> List[str]:
"""These are always of the form "{ticket_action:created}" or
"{status:{from:4,to:6}}". Note the lack of string quoting: this isn't
valid JSON so we have to parse it ourselves.
"""
data = event_string.replace("{", "").replace("}", "").replace... |
There are public (visible to customers) and private note types. | def format_freshdesk_note_message(ticket: WildValue, event_info: List[str]) -> str:
"""There are public (visible to customers) and private note types."""
note_type = event_info[1]
content = NOTE_TEMPLATE.format(
name=ticket["requester_name"].tame(check_string),
email=ticket["requester_email"... |
Freshdesk will only tell us the first event to match our webhook
configuration, so if we change multiple properties, we only get the before
and after data for the first one. | def format_freshdesk_property_change_message(ticket: WildValue, event_info: List[str]) -> str:
"""Freshdesk will only tell us the first event to match our webhook
configuration, so if we change multiple properties, we only get the before
and after data for the first one.
"""
content = PROPERTY_CHANG... |
They send us the description as HTML. | def format_freshdesk_ticket_creation_message(ticket: WildValue) -> str:
"""They send us the description as HTML."""
cleaned_description = convert_html_to_markdown(ticket["ticket_description"].tame(check_string))
content = TICKET_CREATION_TEMPLATE.format(
name=ticket["requester_name"].tame(check_stri... |
GitHub sends the event as an HTTP header. We have our
own Zulip-specific concept of an event that often maps
directly to the X-GitHub-Event header's event, but we sometimes
refine it based on the payload. | def api_github_webhook(
request: HttpRequest,
user_profile: UserProfile,
*,
payload: JsonBodyPayload[WildValue],
branches: Optional[str] = None,
user_specified_topic: OptionalUserSpecifiedTopicStr = None,
) -> HttpResponse:
"""
GitHub sends the event as an HTTP header. We have our
o... |
Usually, we return an event name that is a key in EVENT_FUNCTION_MAPPER.
We return None for an event that we know we don't want to handle. | def get_zulip_event_name(
header_event: str,
payload: WildValue,
branches: Optional[str],
) -> Optional[str]:
"""
Usually, we return an event name that is a key in EVENT_FUNCTION_MAPPER.
We return None for an event that we know we don't want to handle.
"""
if header_event == "pull_reque... |
Replace the username of each assignee with their (full) name.
This is a hack-like adaptor so that when assignees are passed to
`get_pull_request_event_message` we can use the assignee's name
and not their username (for more consistency). | def replace_assignees_username_with_name(
assignees: Union[List[WildValue], WildValue],
) -> List[Dict[str, str]]:
"""Replace the username of each assignee with their (full) name.
This is a hack-like adaptor so that when assignees are passed to
`get_pull_request_event_message` we can use the assignee's... |
This uses the subject name from opbeat to make the topic,
and the summary from Opbeat as the message body, with
details about the object mentioned. | def api_opbeat_webhook(
request: HttpRequest,
user_profile: UserProfile,
*,
payload: JsonBodyPayload[WildValue],
) -> HttpResponse:
"""
This uses the subject name from opbeat to make the topic,
and the summary from Opbeat as the message body, with
details about the object mentioned.
... |
Usually, we return an event name that is a key in EVENT_FUNCTION_MAPPER.
We return None for an event that we know we don't want to handle. | def get_zulip_event_name(
header_event: str,
payload: WildValue,
) -> Optional[str]:
"""
Usually, we return an event name that is a key in EVENT_FUNCTION_MAPPER.
We return None for an event that we know we don't want to handle.
"""
if header_event in EVENT_FUNCTION_MAPPER:
return hea... |
Creates a stat chunk about total occurrences and users affected for the
error.
Example: usersAffected: 2, totalOccurrences: 10
Output: 2 users affected with 10 total occurrences
:param error_dict: The error dictionary containing the error keys and
values
:returns: A message chunk that will be added to the main messag... | def make_user_stats_chunk(error_dict: WildValue) -> str:
"""Creates a stat chunk about total occurrences and users affected for the
error.
Example: usersAffected: 2, totalOccurrences: 10
Output: 2 users affected with 10 total occurrences
:param error_dict: The error dictionary containing the error... |
Creates a time message chunk.
Example: firstOccurredOn: "X", lastOccurredOn: "Y"
Output:
First occurred: X
Last occurred: Y
:param error_dict: The error dictionary containing the error keys and
values
:returns: A message chunk that will be added to the main message | def make_time_chunk(error_dict: WildValue) -> str:
"""Creates a time message chunk.
Example: firstOccurredOn: "X", lastOccurredOn: "Y"
Output:
First occurred: X
Last occurred: Y
:param error_dict: The error dictionary containing the error keys and
values
:returns: A message chunk that ... |
Creates a message chunk if exists.
Example: message: "This is an example message" returns "Message: This is an
example message". Whereas message: "" returns "".
:param message: The value of message inside of the error dictionary
:returns: A message chunk if there exists an additional message, otherwise
returns an emp... | def make_message_chunk(message: str) -> str:
"""Creates a message chunk if exists.
Example: message: "This is an example message" returns "Message: This is an
example message". Whereas message: "" returns "".
:param message: The value of message inside of the error dictionary
:returns: A message c... |
Creates a message chunk that contains the application info and the link
to the Raygun dashboard about the application.
:param app_dict: The application dictionary obtained from the payload
:returns: A message chunk that will be added to the main message | def make_app_info_chunk(app_dict: WildValue) -> str:
"""Creates a message chunk that contains the application info and the link
to the Raygun dashboard about the application.
:param app_dict: The application dictionary obtained from the payload
:returns: A message chunk that will be added to the main m... |
Creates a message for a repeating error follow up
:param payload: Raygun payload
:return: Returns the message, somewhat beautifully formatted | def notification_message_follow_up(payload: WildValue) -> str:
"""Creates a message for a repeating error follow up
:param payload: Raygun payload
:return: Returns the message, somewhat beautifully formatted
"""
message = ""
# Link to Raygun about the follow up
followup_link_md = "[follow-... |
Creates a message for a new error or reoccurred error
:param payload: Raygun payload
:return: Returns the message, somewhat beautifully formatted | def notification_message_error_occurred(payload: WildValue) -> str:
"""Creates a message for a new error or reoccurred error
:param payload: Raygun payload
:return: Returns the message, somewhat beautifully formatted
"""
message = ""
# Provide a clickable link that goes to Raygun about this er... |
Composes a message that contains information on the error
:param payload: Raygun payload
:return: Returns a response message | def compose_notification_message(payload: WildValue) -> str:
"""Composes a message that contains information on the error
:param payload: Raygun payload
:return: Returns a response message
"""
# Get the event type of the error. This can be "NewErrorOccurred",
# "ErrorReoccurred", "OneMinuteFol... |
Creates a message from an activity that is being taken for an error
:param payload: Raygun payload
:return: Returns the message, somewhat beautifully formatted | def activity_message(payload: WildValue) -> str:
"""Creates a message from an activity that is being taken for an error
:param payload: Raygun payload
:return: Returns the message, somewhat beautifully formatted
"""
message = ""
error_link_md = "[Error]({})".format(payload["error"]["url"].tame... |
Composes a message that contains an activity that is being taken to
an error, such as commenting, assigning an error to a user, ignoring the
error, etc.
:param payload: Raygun payload
:return: Returns a response message | def compose_activity_message(payload: WildValue) -> str:
"""Composes a message that contains an activity that is being taken to
an error, such as commenting, assigning an error to a user, ignoring the
error, etc.
:param payload: Raygun payload
:return: Returns a response message
"""
event_... |
Parses and returns the timestamp provided
:param timestamp: The timestamp provided by the payload
:returns: A string containing the time | def parse_time(timestamp: str) -> str:
"""Parses and returns the timestamp provided
:param timestamp: The timestamp provided by the payload
:returns: A string containing the time
"""
# Raygun provides two timestamp format, one with the Z at the end,
# and one without the Z.
format = "%Y-%... |
Handle either an exception type event or a message type event payload. | def handle_event_payload(event: Dict[str, Any]) -> Tuple[str, str]:
"""Handle either an exception type event or a message type event payload."""
topic_name = event["title"]
platform_name = event["platform"]
syntax_highlight_as = syntax_highlight_as_map.get(platform_name, "")
if syntax_highlight_as ... |
Handle either an issue type event. | def handle_issue_payload(
action: str, issue: Dict[str, Any], actor: Dict[str, Any]
) -> Tuple[str, str]:
"""Handle either an issue type event."""
topic_name = issue["title"]
datetime = issue["lastSeen"].split(".")[0].replace("T", " ")
if issue["assignedTo"]:
if issue["assignedTo"]["type"]... |
Attempt to use webhook payload for the notification.
When the integration is configured as a webhook, instead of being added as
an internal integration, the payload is slightly different, but has all the
required information for sending a notification. We transform this payload to
look like the payload from a "properl... | def transform_webhook_payload(payload: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""Attempt to use webhook payload for the notification.
When the integration is configured as a webhook, instead of being added as
an internal integration, the payload is slightly different, but has all the
required inf... |
Parses the payload and finds previous and current value of change_type. | def get_old_and_new_values(change_type: str, message: WildValue) -> ReturnType:
"""Parses the payload and finds previous and current value of change_type."""
old = message["change"]["diff"][change_type].get("from")
new = message["change"]["diff"][change_type].get("to")
return old, new |
Parses the comment to issue, task or US. | def parse_comment(
message: WildValue,
) -> EventType:
"""Parses the comment to issue, task or US."""
return {
"event": "commented",
"type": message["type"].tame(check_string),
"values": {
"user": get_owner_name(message),
"user_link": get_owner_link(message),
... |
Parses create or delete event. | def parse_create_or_delete(
message: WildValue,
) -> EventType:
"""Parses create or delete event."""
if message["type"].tame(check_string) == "relateduserstory":
return {
"type": message["type"].tame(check_string),
"event": message["action"].tame(check_string),
"v... |
Parses change event. | def parse_change_event(change_type: str, message: WildValue) -> Optional[EventType]:
"""Parses change event."""
evt: EventType = {}
values: Dict[str, Optional[Union[str, bool]]] = {
"user": get_owner_name(message),
"user_link": get_owner_link(message),
"subject": get_subject(message)... |
Parses the payload by delegating to specialized functions. | def parse_message(
message: WildValue,
) -> List[EventType]:
"""Parses the payload by delegating to specialized functions."""
events: List[EventType] = []
if message["action"].tame(check_string) in ["create", "delete"]:
events.append(parse_create_or_delete(message))
elif message["action"].t... |
Gets the template string and formats it with parsed data. | def generate_content(data: EventType) -> str:
"""Gets the template string and formats it with parsed data."""
assert isinstance(data["type"], str) and isinstance(data["event"], str)
template = templates[data["type"]][data["event"]]
assert isinstance(data["values"], dict)
content = template.format(*... |
Requests sent from Thinkst canaries are either from canarytokens or
canaries, which can be differentiated by the value of the `AlertType`
field. | def is_canarytoken(message: WildValue) -> bool:
"""
Requests sent from Thinkst canaries are either from canarytokens or
canaries, which can be differentiated by the value of the `AlertType`
field.
"""
return message["AlertType"].tame(check_string) == "CanarytokenIncident" |
Returns the name of the canary or canarytoken. | def canary_name(message: WildValue) -> str:
"""
Returns the name of the canary or canarytoken.
"""
if is_canarytoken(message):
return message["Reminder"].tame(check_string)
else:
return message["CanaryName"].tame(check_string) |
Returns a description of the kind of request - canary or canarytoken. | def canary_kind(message: WildValue) -> str:
"""
Returns a description of the kind of request - canary or canarytoken.
"""
if is_canarytoken(message):
return "canarytoken"
else:
return "canary" |
Extract the source IP and reverse DNS information from a canary request. | def source_ip_and_reverse_dns(message: WildValue) -> Tuple[Optional[str], Optional[str]]:
"""
Extract the source IP and reverse DNS information from a canary request.
"""
reverse_dns, source_ip = (None, None)
if "SourceIP" in message:
source_ip = message["SourceIP"].tame(check_string)
#... |
Construct the response to a canary or canarytoken request. | def body(message: WildValue) -> str:
"""
Construct the response to a canary or canarytoken request.
"""
title = canary_kind(message).title()
name = canary_name(message)
body = f"**:alert: {title} *{name}* has been triggered!**\n\n{message['Intro'].tame(check_string)}\n\n"
if "IncidentHash"... |
Construct a response to a webhook event from a Thinkst canary or canarytoken.
Thinkst offers public canarytokens with canarytokens.org and with their canary
product, but the schema returned by these identically named services are
completely different - canarytokens from canarytokens.org are handled by a
different Zuli... | def api_thinkst_webhook(
request: HttpRequest,
user_profile: UserProfile,
*,
message: JsonBodyPayload[WildValue],
user_specified_topic: OptionalUserSpecifiedTopicStr = None,
) -> HttpResponse:
"""
Construct a response to a webhook event from a Thinkst canary or canarytoken.
Thinkst offe... |
Zendesk uses triggers with message templates. This webhook uses the
ticket_id and ticket_title to create a topic. And passes with zendesk
user's configured message to zulip. | def api_zendesk_webhook(
request: HttpRequest,
user_profile: UserProfile,
*,
ticket_title: str,
ticket_id: str,
message: str,
) -> HttpResponse:
"""
Zendesk uses triggers with message templates. This webhook uses the
ticket_id and ticket_title to create a topic. And passes with zende... |
Returns all (either test, or real) worker queues. | def get_active_worker_queues(only_test_queues: bool = False) -> List[str]:
"""Returns all (either test, or real) worker queues."""
for module_info in pkgutil.iter_modules(zerver.worker.__path__, "zerver.worker."):
importlib.import_module(module_info.name)
return [
queue_name
for que... |
When migrating to support registration by UUID, we introduced a bug where duplicate
registrations for the same device+user could be created - one by user_id and one by
user_uuid. Given no good way of detecting these duplicates at database level, we need to
take advantage of the fact that when a remote server sends a pu... | def delete_duplicate_registrations(
registrations: List[RemotePushDeviceToken], server_id: int, user_id: int, user_uuid: str
) -> List[RemotePushDeviceToken]:
"""
When migrating to support registration by UUID, we introduced a bug where duplicate
registrations for the same device+user could be created -... |
Tries to fetch RemoteRealm for the given realm_uuid and server. Otherwise,
returns None and logs what happened using request and user_uuid args to make
the output more informative. | def get_remote_realm_helper(
request: HttpRequest, server: RemoteZulipServer, realm_uuid: str, user_uuid: str
) -> Optional[RemoteRealm]:
"""
Tries to fetch RemoteRealm for the given realm_uuid and server. Otherwise,
returns None and logs what happened using request and user_uuid args to make
the ou... |
The remote server sends us a list of (tokens of) devices that it
believes it has registered. However some of them may have been
deleted by us due to errors received in the low level code
responsible for directly sending push notifications.
Query the database for the RemotePushDeviceTokens from these lists
that we do i... | def get_deleted_devices(
user_identity: UserPushIdentityCompat,
server: RemoteZulipServer,
android_devices: List[str],
apple_devices: List[str],
) -> DevicesToCleanUpDict:
"""The remote server sends us a list of (tokens of) devices that it
believes it has registered. However some of them may hav... |
Finds the RemoteRealmCount and RemoteRealmAuditLog entries without .remote_realm
set and sets it based on the "realms" data received from the remote server,
if possible. | def fix_remote_realm_foreign_keys(
server: RemoteZulipServer, realms: List[RealmDataForAnalytics]
) -> None:
"""
Finds the RemoteRealmCount and RemoteRealmAuditLog entries without .remote_realm
set and sets it based on the "realms" data received from the remote server,
if possible.
"""
if ... |
We want to keep these flags mostly intact after we create
messages. The is_private flag, for example, would be bad to overwrite.
So we're careful to only toggle the read flag.
We exclude marking messages as read for bots, since bots, by
default, never mark messages as read. | def mark_all_messages_as_read() -> None:
"""
We want to keep these flags mostly intact after we create
messages. The is_private flag, for example, would be bad to overwrite.
So we're careful to only toggle the read flag.
We exclude marking messages as read for bots, since bots, by
default, nev... |
Clean up duplicated RemoteRealmCount and RemoteInstallationCount rows.
This is the equivalent of analytics' 0015_clear_duplicate_counts
migration -- but it also has additional duplicates if there are
multiple servers submitting information with the same UUID.
We drop the behaviour of rolling up and updating the value... | def clear_duplicate_counts(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None:
"""Clean up duplicated RemoteRealmCount and RemoteInstallationCount rows.
This is the equivalent of analytics' 0015_clear_duplicate_counts
migration -- but it also has additional duplicates if there are
multip... |
Pads an authentication methods dict to contain all auth backends
supported by the software, regardless of whether they are
configured on this server | def pad_method_dict(method_dict: Dict[str, bool]) -> Dict[str, bool]:
"""Pads an authentication methods dict to contain all auth backends
supported by the software, regardless of whether they are
configured on this server"""
for key in AUTH_BACKEND_NAME_MAP:
if key not in method_dict:
... |
realm_authentication_methods can be passed if already fetched to avoid
a database query. | def auth_enabled_helper(
backends_to_check: List[str],
realm: Optional[Realm],
realm_authentication_methods: Optional[Dict[str, bool]] = None,
) -> bool:
"""
realm_authentication_methods can be passed if already fetched to avoid
a database query.
"""
if realm is not None:
if rea... |
This is the core common function used by essentially all
authentication backends to check if there's an active user account
with a given email address in the organization, handling both
user-level and realm-level deactivation correctly. | def common_get_active_user(
email: str, realm: Realm, return_data: Optional[Dict[str, Any]] = None
) -> Optional[UserProfile]:
"""This is the core common function used by essentially all
authentication backends to check if there's an active user account
with a given email address in the organization, ha... |
Returns True if the password is strong enough,
False otherwise. | def check_password_strength(password: str) -> bool:
"""
Returns True if the password is strong enough,
False otherwise.
"""
if len(password) < settings.PASSWORD_MIN_LENGTH:
return False
if password == "":
# zxcvbn throws an exception when passed the empty string, so
# we... |
Returns list of _LDAPUsers matching the email search | def find_ldap_users_by_email(email: str) -> List[_LDAPUser]:
"""
Returns list of _LDAPUsers matching the email search
"""
return LDAPReverseEmailSearch().search_for_users(email) |
Used to make determinations on whether a user's email address is
managed by LDAP. For environments using both LDAP and
Email+Password authentication, we do not allow EmailAuthBackend
authentication for email addresses managed by LDAP (to avoid a
security issue where one create separate credentials for an LDAP
user), a... | def email_belongs_to_ldap(realm: Realm, email: str) -> bool:
"""Used to make determinations on whether a user's email address is
managed by LDAP. For environments using both LDAP and
Email+Password authentication, we do not allow EmailAuthBackend
authentication for email addresses managed by LDAP (to a... |
Inside django_auth_ldap populate_user(), if LDAPError is raised,
e.g. due to invalid connection credentials, the function catches it
and emits a signal (ldap_error) to communicate this error to others.
We normally don't use signals, but here there's no choice, so in this function
we essentially convert the signal to a ... | def catch_ldap_error(signal: Signal, **kwargs: Any) -> None:
"""
Inside django_auth_ldap populate_user(), if LDAPError is raised,
e.g. due to invalid connection credentials, the function catches it
and emits a signal (ldap_error) to communicate this error to others.
We normally don't use signals, bu... |
Responsible for doing the Zulip account lookup and validation parts
of the Zulip social auth pipeline (similar to the authenticate()
methods in most other auth backends in this file).
Returns a UserProfile object for successful authentication, and None otherwise. | def social_associate_user_helper(
backend: BaseAuth, return_data: Dict[str, Any], *args: Any, **kwargs: Any
) -> Union[HttpResponse, Optional[UserProfile]]:
"""Responsible for doing the Zulip account lookup and validation parts
of the Zulip social auth pipeline (similar to the authenticate()
methods in ... |
A simple wrapper function to reformat the return data from
social_associate_user_helper as a dictionary. The
python-social-auth infrastructure will then pass those values into
later stages of settings.SOCIAL_AUTH_PIPELINE, such as
social_auth_finish, as kwargs. | def social_auth_associate_user(
backend: BaseAuth, *args: Any, **kwargs: Any
) -> Union[HttpResponse, Dict[str, Any]]:
"""A simple wrapper function to reformat the return data from
social_associate_user_helper as a dictionary. The
python-social-auth infrastructure will then pass those values into
l... |
Given the determination in social_auth_associate_user for whether
the user should be authenticated, this takes care of actually
logging in the user (if appropriate) and redirecting the browser
to the appropriate next page depending on the situation. Read the
comments below as well as login_or_register_remote_user in
`... | def social_auth_finish(
backend: Any, details: Dict[str, Any], response: HttpResponse, *args: Any, **kwargs: Any
) -> Optional[HttpResponse]:
"""Given the determination in social_auth_associate_user for whether
the user should be authenticated, this takes care of actually
logging in the user (if appropr... |
wantMessagesSigned controls whether requests processed by this saml auth
object need to be signed. The default of False is often not acceptable,
because we don't want anyone to be able to submit such a request.
Callers should use this to enforce the requirement of signatures. | def patch_saml_auth_require_messages_signed(auth: OneLogin_Saml2_Auth) -> None:
"""
wantMessagesSigned controls whether requests processed by this saml auth
object need to be signed. The default of False is often not acceptable,
because we don't want anyone to be able to submit such a request.
Calle... |
Returns a list of dictionaries that represent social backends, sorted
in the order in which they should be displayed. | def get_external_method_dicts(realm: Optional[Realm] = None) -> List[ExternalAuthMethodDictT]:
"""
Returns a list of dictionaries that represent social backends, sorted
in the order in which they should be displayed.
"""
result: List[ExternalAuthMethodDictT] = []
for backend in EXTERNAL_AUTH_MET... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.