repo
stringclasses
856 values
pull_number
int64
3
127k
instance_id
stringlengths
12
58
issue_numbers
sequencelengths
1
5
base_commit
stringlengths
40
40
patch
stringlengths
67
1.54M
test_patch
stringlengths
0
107M
problem_statement
stringlengths
3
307k
hints_text
stringlengths
0
908k
created_at
timestamp[s]
zulip/zulip
23,554
zulip__zulip-23554
[ "23530" ]
a09014f1de54bb9747960d5d2384d05565bce822
diff --git a/zerver/lib/markdown/tabbed_sections.py b/zerver/lib/markdown/tabbed_sections.py --- a/zerver/lib/markdown/tabbed_sections.py +++ b/zerver/lib/markdown/tabbed_sections.py @@ -75,7 +75,7 @@ "public-streams": "Public streams", "private-streams": "Private streams", "web-public-streams": "Web-public streams", - "via-user-profile": "Via the user's profile", + "via-user-card": "Via user card", "via-organization-settings": "Via organization settings", "via-personal-settings": "Via personal settings", "default-subdomain": "Default subdomain",
Use consistent naming for user (profile) menus As [discussed on CZO](https://chat.zulip.org/#narrow/stream/101-design/topic/terms.20for.20user.20profiles), we should develop consistent naming for the pop-up you seen when you click on a user avatar, as well as the detailed user profile. Specifically, the naming we want to implement is: 1. "User card" for the initial user view. ![Screen-Shot-2022-11-03-at-4 03 01-PM](https://user-images.githubusercontent.com/2090066/201202788-1a7311cc-a4ce-4042-8d95-5a5b2c50339e.png) 2. "User profile" for the detailed profile. ![Screen-Shot-2022-11-03-at-4 03 09-PM](https://user-images.githubusercontent.com/2090066/201202848-cbaa4a53-759f-4de7-a92f-0ebb87877286.png) Known places where changes need to be made: - [ ] Tooltip on user avatar: "View user profile (u)" -> "View user card (u)" - [ ] Menu option on user card: "View full profile" -> "View profile" - Custom profile fields: - [ ] "Summary" column name -> "Card" - [ ] "Display in profile summary" -> "Display on user card" We should also check whether any other places are affected. Help center: - [ ] Whenever instructions mention opening the profile card, we should name it explicitly, e.g.,: > Click on the ellipsis () to the right of their name. -> Click on the ellipsis () to the right of their name to open their **user card**. - [ ] Some pages known to be affected: https://zulip.com/help/view-someones-profile, https://zulip.com/help/custom-profile-fields, any pages that have "Via the user's profile" instructions. We should do an overall audit to make sure the terminology is consistent (can be done as a follow-up).
@laurynmm Would you be up for taking this one? It's not *critical* for the release, but would be nice to include. Hello @zulip/server-settings members, this issue was labeled with the "area: settings (admin/org)" label, so you may want to check it out! <!-- areaLabelAddition -->
2022-11-14T17:54:35
zulip/zulip
23,555
zulip__zulip-23555
[ "23552" ]
a09014f1de54bb9747960d5d2384d05565bce822
diff --git a/zerver/data_import/slack.py b/zerver/data_import/slack.py --- a/zerver/data_import/slack.py +++ b/zerver/data_import/slack.py @@ -1146,6 +1146,10 @@ def build_reactions( continue for slack_user_id in slack_reaction["users"]: + if slack_user_id not in slack_user_id_to_zulip_user_id: + # Deleted users still have reaction references but no profile, so we skip + continue + reaction_id = NEXT_ID("reaction") reaction = Reaction( id=reaction_id,
Slack imports containing reactions from users who no longer exist throw stack Easy to fix manually, but we shouldn't fault. Stub issue that I'll fix but don't want to forget. ```python Traceback (most recent call last): File "./manage.py", line 151, in <module> execute_from_command_line(sys.argv) File "./manage.py", line 116, in execute_from_command_line utility.execute() File "/srv/zulip-venv-cache/7bce584675a91f5ea66d1f1814748fdac0d2084b/zulip-py3-venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/srv/zulip-venv-cache/7bce584675a91f5ea66d1f1814748fdac0d2084b/zulip-py3-venv/lib/python3.8/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/srv/zulip-venv-cache/7bce584675a91f5ea66d1f1814748fdac0d2084b/zulip-py3-venv/lib/python3.8/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/home/zulip/deployments/2022-11-10-06-08-39/zerver/management/commands/convert_slack_data.py", line 59, in handle do_convert_data(path, output_dir, token, threads=num_threads) File "/home/zulip/deployments/2022-11-10-06-08-39/zerver/data_import/slack.py", line 1343, in do_convert_data reactions, uploads_list, zerver_attachment = convert_slack_workspace_messages( File "/home/zulip/deployments/2022-11-10-06-08-39/zerver/data_import/slack.py", line 750, in convert_slack_workspace_messages ) = channel_message_to_zerver_message( File "/home/zulip/deployments/2022-11-10-06-08-39/zerver/data_import/slack.py", line 914, in channel_message_to_zerver_message build_reactions( File "/home/zulip/deployments/2022-11-10-06-08-39/zerver/data_import/slack.py", line 1159, in build_reactions reaction_dict["user_profile"] = slack_user_id_to_zulip_user_id[slack_user_id] KeyError: 'BLAHBLAHBLAH' ```
Hello @zulip/server-misc members, this issue was labeled with the "area: export/import" label, so you may want to check it out! <!-- areaLabelAddition -->
2022-11-14T19:30:59
zulip/zulip
23,565
zulip__zulip-23565
[ "21709" ]
f14dde1a64b84123628ff57683b943a0781868a1
diff --git a/zerver/actions/users.py b/zerver/actions/users.py --- a/zerver/actions/users.py +++ b/zerver/actions/users.py @@ -160,21 +160,30 @@ def do_deactivate_user( if settings.BILLING_ENABLED: update_license_ledger_if_needed(user_profile.realm, event_time) - delete_user_sessions(user_profile) - event = dict( - type="realm_user", - op="remove", - person=dict(user_id=user_profile.id, full_name=user_profile.full_name), - ) - send_event(user_profile.realm, event, active_user_ids(user_profile.realm_id)) + transaction.on_commit(lambda: delete_user_sessions(user_profile)) - if user_profile.is_bot: - event = dict( - type="realm_bot", + event_remove_user = dict( + type="realm_user", op="remove", - bot=dict(user_id=user_profile.id, full_name=user_profile.full_name), + person=dict(user_id=user_profile.id, full_name=user_profile.full_name), ) - send_event(user_profile.realm, event, bot_owner_user_ids(user_profile)) + transaction.on_commit( + lambda: send_event( + user_profile.realm, event_remove_user, active_user_ids(user_profile.realm_id) + ) + ) + + if user_profile.is_bot: + event_remove_bot = dict( + type="realm_bot", + op="remove", + bot=dict(user_id=user_profile.id, full_name=user_profile.full_name), + ) + transaction.on_commit( + lambda: send_event( + user_profile.realm, event_remove_bot, bot_owner_user_ids(user_profile) + ) + ) @transaction.atomic(durable=True)
diff --git a/zerver/tests/test_decorators.py b/zerver/tests/test_decorators.py --- a/zerver/tests/test_decorators.py +++ b/zerver/tests/test_decorators.py @@ -1216,7 +1216,8 @@ def test_send_deactivated_user(self) -> None: """ user_profile = self.example_user("hamlet") self.login_user(user_profile) - do_deactivate_user(user_profile, acting_user=None) + with self.captureOnCommitCallbacks(execute=True): + do_deactivate_user(user_profile, acting_user=None) result = self.client_post( "/json/messages", diff --git a/zerver/tests/test_users.py b/zerver/tests/test_users.py --- a/zerver/tests/test_users.py +++ b/zerver/tests/test_users.py @@ -1579,7 +1579,8 @@ def test_clear_sessions(self) -> None: self.assert_json_success(result) self.assertEqual(Session.objects.filter(pk=session_key).count(), 1) - do_deactivate_user(user, acting_user=None) + with self.captureOnCommitCallbacks(execute=True): + do_deactivate_user(user, acting_user=None) self.assertEqual(Session.objects.filter(pk=session_key).count(), 0) result = self.client_get("/json/users")
sync_ldap_user_data error It seems that after switching to version 5.1, the `LDAP_DEACTIVATE_NON_MATCHING_USERS` setting stopped working correctly for me. ``` root@zserver:/home/zulip/deployments/current# ./scripts/get-django-setting LDAP_DEACTIVATE_NON_MATCHING_USERS True ``` Sync command `root@zserver:/home/zulip/deployments/current# su zulip -c './manage.py sync_ldap_user_data'` ends with an error. I replaced the real username and domain for privacy reasons. ``` 2022-04-06 17:11:01.106 DEBG [django_auth_ldap] search_s('OU=MyOU,DC=MyDC', 2, '(sAMAccountName=%(user)s)') returned 0 objects: 2022-04-06 17:11:01.317 ERR [zulip.sync_ldap_user_data] LDAP sync failed Traceback (most recent call last): File "/home/zulip/deployments/2022-04-03-15-35-19/zproject/backends.py", line 1099, in sync_user_from_ldap ldap_username = backend.django_to_ldap_username(user_profile.delivery_email) File "/home/zulip/deployments/2022-04-03-15-35-19/zproject/backends.py", line 668, in django_to_ldap_username raise ZulipLDAPExceptionNoMatchingLDAPUser( zproject.backends.ZulipLDAPExceptionNoMatchingLDAPUser: No LDAP user matching django_to_ldap_username result: myusername. Input username: [email protected] During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/zulip/deployments/2022-04-03-15-35-19/zerver/management/commands/sync_ldap_user_data.py", line 30, in sync_ldap_user_data sync_user_from_ldap(u, logger) File "/home/zulip/deployments/2022-04-03-15-35-19/zproject/backends.py", line 1106, in sync_user_from_ldap do_deactivate_user(user_profile, acting_user=None) File "/home/zulip/deployments/2022-04-03-15-35-19/zerver/lib/actions.py", line 1463, in do_deactivate_user delete_user_sessions(user_profile) File "/home/zulip/deployments/2022-04-03-15-35-19/zerver/lib/sessions.py", line 47, in delete_user_sessions delete_session(session) File "/home/zulip/deployments/2022-04-03-15-35-19/zerver/lib/sessions.py", line 41, in delete_session session_engine.SessionStore(session.session_key).delete() File "/home/zulip/deployments/2022-04-03-15-35-19/zerver/lib/safe_session_cached_db.py", line 24, in delete assert not get_connection().in_atomic_block AssertionError Traceback (most recent call last): File "/home/zulip/deployments/2022-04-03-15-35-19/zproject/backends.py", line 1099, in sync_user_from_ldap ldap_username = backend.django_to_ldap_username(user_profile.delivery_email) File "/home/zulip/deployments/2022-04-03-15-35-19/zproject/backends.py", line 668, in django_to_ldap_username raise ZulipLDAPExceptionNoMatchingLDAPUser( zproject.backends.ZulipLDAPExceptionNoMatchingLDAPUser: No LDAP user matching django_to_ldap_username result: myusername. Input username: [email protected] During handling of the above exception, another exception occurred: Traceback (most recent call last): File "./manage.py", line 157, in <module> execute_from_command_line(sys.argv) File "./manage.py", line 122, in execute_from_command_line utility.execute() File "/srv/zulip-venv-cache/726c7d1d35d9cd61bb4b70e98167a1db7b0c524d/zulip-py3-venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/srv/zulip-venv-cache/726c7d1d35d9cd61bb4b70e98167a1db7b0c524d/zulip-py3-venv/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/srv/zulip-venv-cache/726c7d1d35d9cd61bb4b70e98167a1db7b0c524d/zulip-py3-venv/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/zulip/deployments/2022-04-03-15-35-19/zerver/management/commands/sync_ldap_user_data.py", line 80, in handle sync_ldap_user_data(user_profiles, not options["force"]) File "/usr/lib/python3.8/contextlib.py", line 75, in inner return func(*args, **kwds) File "/home/zulip/deployments/2022-04-03-15-35-19/zerver/management/commands/sync_ldap_user_data.py", line 30, in sync_ldap_user_data sync_user_from_ldap(u, logger) File "/home/zulip/deployments/2022-04-03-15-35-19/zproject/backends.py", line 1106, in sync_user_from_ldap do_deactivate_user(user_profile, acting_user=None) File "/home/zulip/deployments/2022-04-03-15-35-19/zerver/lib/actions.py", line 1463, in do_deactivate_user delete_user_sessions(user_profile) File "/home/zulip/deployments/2022-04-03-15-35-19/zerver/lib/sessions.py", line 47, in delete_user_sessions delete_session(session) File "/home/zulip/deployments/2022-04-03-15-35-19/zerver/lib/sessions.py", line 41, in delete_session session_engine.SessionStore(session.session_key).delete() File "/home/zulip/deployments/2022-04-03-15-35-19/zerver/lib/safe_session_cached_db.py", line 24, in delete assert not get_connection().in_atomic_block AssertionError ``` As a result, the user remains active.
Thanks for the report! I [posted this on chat.zulip.org](https://chat.zulip.org/#narrow/stream/31-production-help/topic/sync_ldap_user_data.20error.20.2321709/near/1361750) for more interactive discussion. We're hitting this as well on our production instance. Happened on 4.11 and now on 5.1 as well. sync_ldap_user_data never completes, same trace back in ``safe_session_cached_db.py", line 24`` Happens regardless of ``LDAP_DEACTIVATE_NON_MATCHING_USERS`` true or false, both config settings trigger the same traceback. Any ideas on a fix/workaround? Zulip chat has a workaround, documenting here so it's discoverable (Zulip chats are not indexed by search engines seemingly) Carrying this patch in our local branch for now and testing. ```quote For a short-term fix, @Aggr, you can remove the @transaction.atomic line in zerver/management/commands/sync_ldap_user_data.py and re-run the import. ``` Hello @zulip/server-authentication members, this issue was labeled with the "area: authentication" label, so you may want to check it out! <!-- areaLabelAddition -->
2022-11-14T22:19:01
zulip/zulip
23,579
zulip__zulip-23579
[ "14053" ]
af00d20402884101cc3c9c6910c5ad157a17d47a
diff --git a/zerver/tornado/event_queue.py b/zerver/tornado/event_queue.py --- a/zerver/tornado/event_queue.py +++ b/zerver/tornado/event_queue.py @@ -350,10 +350,28 @@ def push(self, orig_event: Mapping[str, Any]) -> None: event["id"] = self.next_event_id self.next_event_id += 1 full_event_type = compute_full_event_type(event) - if full_event_type == "restart" or full_event_type.startswith("flags/"): + if full_event_type == "restart" or ( + full_event_type.startswith("flags/") + and not full_event_type.startswith("flags/remove/read") + ): + # virtual_events are an optimization that allows certain + # simple events, such as update_message_flags events that + # simply contain a list of message IDs to operate on, to + # be compressed together. This is primarily useful for + # flags/add/read, where normal Zulip usage will result in + # many small flags/add/read events as users scroll. + # + # We need to exclude flags/remove/read, because it has an + # extra message_details field that cannot be compressed. + # + # BUG: This compression algorithm is incorrect in the + # presence of mark-as-unread, since it does not respect + # the ordering of "mark as read" and "mark as unread" + # updates for a given message. if full_event_type not in self.virtual_events: self.virtual_events[full_event_type] = copy.deepcopy(event) return + # Update the virtual event with the values from the event virtual_event = self.virtual_events[full_event_type] virtual_event["id"] = event["id"]
diff --git a/frontend_tests/node_tests/popovers.js b/frontend_tests/node_tests/popovers.js --- a/frontend_tests/node_tests/popovers.js +++ b/frontend_tests/node_tests/popovers.js @@ -27,11 +27,6 @@ const message_lists = mock_esm("../../static/js/message_lists", { view: { message_containers: {}, }, - data: { - fetch_status: { - has_found_newest: () => true, - }, - }, }, }); mock_esm("../../static/js/message_viewport", {
Unread message clearing issue I logged into zulip after years. The dialog box showed 50K unread messages with an option to clear the unread messages. After clicking on the option 'clear unread message' (i don't remember exact words), the dialog box didn't show any progress or count, as result, I was waiting for the box to disappear. Meanwhile, the unread count on the streams section kept changing in the left sidebar, after a while, the stream count change wasn't visible. Now I reloaded the page. The stream counts were gone, the home page was still showing the threads from a long back. There is no 'go the latest' link on the page. I'm scrolling for several minutes and unable to go to the latest thread by date. What could be helpful? 1. While clearing the unread message, show how completion status. 2. Add a link to go the latest message after choosing the clear the unread message or anywhere from the UI. [Edit]: Clicking on, one of the streams, on the left sidebar takes to the latest place and from there it's possible to go in reverse chronological order.
Hello @zulip/server-sidebars members, this issue was labeled with the "area: left-sidebar" label, so you may want to check it out! <!-- areaLabelAddition --> I think this is a duplicate issue, but I agree and thanks for reraising this.
2022-11-15T14:58:05
zulip/zulip
23,652
zulip__zulip-23652
[ "23625" ]
ca835ec943cf6a2d1aa50e48ae14831bf9096b47
diff --git a/tools/setup/emoji/emoji_names.py b/tools/setup/emoji/emoji_names.py --- a/tools/setup/emoji/emoji_names.py +++ b/tools/setup/emoji/emoji_names.py @@ -524,7 +524,11 @@ "1f3ca-200d-2640": {"canonical_name": "woman_swimming", "aliases": []}, "1f3ca-200d-2642": {"canonical_name": "man_swimming", "aliases": []}, "1f3ca": {"canonical_name": "swim", "aliases": []}, + "1f3cb-fe0f-200d-2640-fe0f": {"canonical_name": "woman_lifting_weights", "aliases": []}, + "1f3cb-fe0f-200d-2642-fe0f": {"canonical_name": "man_lifting_weights", "aliases": []}, "1f3cb": {"canonical_name": "lift", "aliases": ["work_out", "weight_lift", "gym"]}, + "1f3cc-fe0f-200d-2640-fe0f": {"canonical_name": "woman_golfing", "aliases": []}, + "1f3cc-fe0f-200d-2642-fe0f": {"canonical_name": "man_golfing", "aliases": []}, "1f3cc": {"canonical_name": "golf", "aliases": []}, "1f3cd": {"canonical_name": "motorcycle", "aliases": []}, "1f3ce": {"canonical_name": "racecar", "aliases": []}, @@ -563,6 +567,10 @@ "1f3ef": {"canonical_name": "shiro", "aliases": []}, "1f3f0": {"canonical_name": "castle", "aliases": []}, "1f3f3-200d-1f308": {"canonical_name": "rainbow_flag", "aliases": []}, + "1f3f3-fe0f-200d-26a7-fe0f": { + "canonical_name": "transgender_flag", + "aliases": ["light_blue", "pink"], + }, "1f3f3": {"canonical_name": "white_flag", "aliases": ["surrender"]}, "1f3f4-200d-2620": {"canonical_name": "pirate_flag", "aliases": ["jolly_roger", "plunder"]}, "1f3f4-e0067-e0062-e0065-e006e-e0067-e007f": {"canonical_name": "flag_england", "aliases": []}, @@ -642,6 +650,10 @@ "1f43e": {"canonical_name": "paw_prints", "aliases": ["paws"]}, "1f43f": {"canonical_name": "chipmunk", "aliases": []}, "1f440": {"canonical_name": "eyes", "aliases": ["looking"]}, + "1f441-fe0f-200d-1f5e8-fe0f": { + "canonical_name": "eye_in_speech_bubble", + "aliases": ["speech", "witness"], + }, "1f441": {"canonical_name": "eye", "aliases": []}, "1f442": {"canonical_name": "ear", "aliases": []}, "1f443": {"canonical_name": "nose", "aliases": []}, @@ -1046,6 +1058,8 @@ "1f570": {"canonical_name": "mantelpiece_clock", "aliases": []}, "1f573": {"canonical_name": "hole", "aliases": []}, "1f574": {"canonical_name": "levitating", "aliases": ["hover"]}, + "1f575-fe0f-200d-2640-fe0f": {"canonical_name": "woman_detective", "aliases": []}, + "1f575-fe0f-200d-2642-fe0f": {"canonical_name": "man_detective", "aliases": []}, "1f575": {"canonical_name": "detective", "aliases": ["spy", "sleuth", "agent", "sneaky"]}, "1f576": {"canonical_name": "dark_sunglasses", "aliases": []}, "1f577": {"canonical_name": "spider", "aliases": []}, @@ -1580,7 +1594,7 @@ "1f9c8": {"canonical_name": "butter", "aliases": ["dairy"]}, "1f9c9": {"canonical_name": "mate", "aliases": []}, "1f9ca": {"canonical_name": "ice", "aliases": ["ice_cube", "iceberg"]}, - "1f9cb": {"canonical_name": "bubble_tea", "aliases": ["bubble"]}, + "1f9cb": {"canonical_name": "bubble_tea", "aliases": []}, "1f9cc": {"canonical_name": "troll", "aliases": ["fairy_tale", "fantasy", "monster"]}, "1f9cd-200d-2640": {"canonical_name": "woman_standing", "aliases": []}, "1f9cd-200d-2642": {"canonical_name": "man_standing", "aliases": []}, @@ -1950,7 +1964,7 @@ "269c": {"canonical_name": "fleur_de_lis", "aliases": []}, "26a0": {"canonical_name": "warning", "aliases": ["caution", "danger"]}, "26a1": {"canonical_name": "high_voltage", "aliases": ["zap"]}, - "26a7": {"canonical_name": "transgender_symbol", "aliases": ["transgender"]}, + "26a7": {"canonical_name": "transgender_symbol", "aliases": []}, "26aa": {"canonical_name": "white_circle", "aliases": []}, "26ab": {"canonical_name": "black_circle", "aliases": []}, "26b0": {"canonical_name": "coffin", "aliases": ["burial", "grave"]}, @@ -1978,6 +1992,8 @@ "26f5": {"canonical_name": "boat", "aliases": ["sailboat"]}, "26f7": {"canonical_name": "skier", "aliases": []}, "26f8": {"canonical_name": "ice_skate", "aliases": []}, + "26f9-fe0f-200d-2640-fe0f": {"canonical_name": "woman_bouncing_ball", "aliases": []}, + "26f9-fe0f-200d-2642-fe0f": {"canonical_name": "man_bouncing_ball", "aliases": []}, "26f9": {"canonical_name": "ball", "aliases": ["sports"]}, "26fa": {"canonical_name": "tent", "aliases": ["camping"]}, "26fd": {"canonical_name": "fuel_pump", "aliases": ["gas_pump", "petrol_pump"]},
diff --git a/frontend_tests/node_tests/emoji_picker.js b/frontend_tests/node_tests/emoji_picker.js --- a/frontend_tests/node_tests/emoji_picker.js +++ b/frontend_tests/node_tests/emoji_picker.js @@ -21,7 +21,7 @@ run_test("initialize", () => { const complete_emoji_catalog = _.sortBy(emoji_picker.complete_emoji_catalog, "name"); assert.equal(complete_emoji_catalog.length, 11); - assert.equal(emoji.emojis_by_name.size, 1817); + assert.equal(emoji.emojis_by_name.size, 1827); let total_emoji_in_categories = 0; @@ -44,12 +44,12 @@ run_test("initialize", () => { const zulip_emoji_count = 1; assert_emoji_category(complete_emoji_catalog.pop(), "fa-car", 195); assert_emoji_category(complete_emoji_catalog.pop(), "fa-hashtag", 221); - assert_emoji_category(complete_emoji_catalog.pop(), "fa-smile-o", 162); + assert_emoji_category(complete_emoji_catalog.pop(), "fa-smile-o", 163); assert_emoji_category(complete_emoji_catalog.pop(), "fa-star-o", popular_emoji_count); - assert_emoji_category(complete_emoji_catalog.pop(), "fa-thumbs-o-up", 353); + assert_emoji_category(complete_emoji_catalog.pop(), "fa-thumbs-o-up", 361); assert_emoji_category(complete_emoji_catalog.pop(), "fa-lightbulb-o", 255); assert_emoji_category(complete_emoji_catalog.pop(), "fa-cutlery", 132); - assert_emoji_category(complete_emoji_catalog.pop(), "fa-flag", 268); + assert_emoji_category(complete_emoji_catalog.pop(), "fa-flag", 269); assert_emoji_category(complete_emoji_catalog.pop(), "fa-cog", 1); assert_emoji_category(complete_emoji_catalog.pop(), "fa-leaf", 144); assert_emoji_category(complete_emoji_catalog.pop(), "fa-soccer-ball-o", 86);
Transgender Flag missing in reaction in Zulip 6.0 Hi, All of the new unicode 14 flags are showing in the reaction picker except, as far as I can tell, the transgender flag (🏳️‍⚧️). Steps to reproduce: * Go to react to a message
Hello @zulip/server-emoji members, this issue was labeled with the "area: emoji" label, so you may want to check it out! <!-- areaLabelAddition --> Hm, @evykassirer , could you please take a look at this one?
2022-11-23T00:21:59
zulip/zulip
23,677
zulip__zulip-23677
[ "23654" ]
911b3b5365d9bfd935b04b5406bb302616c02783
diff --git a/zerver/views/user_settings.py b/zerver/views/user_settings.py --- a/zerver/views/user_settings.py +++ b/zerver/views/user_settings.py @@ -1,3 +1,4 @@ +from email.headerregistry import Address from typing import Any, Dict, Optional from django.conf import settings @@ -96,13 +97,14 @@ def confirm_email_change(request: HttpRequest, confirmation_key: str) -> HttpRes context=context, realm=user_profile.realm, ) - + old_email_address = Address(addr_spec=old_email) + new_email_address = Address(addr_spec=new_email) ctx = { "new_email_html_tag": SafeString( - f'<a href="mailto:{escape(new_email)}">{escape(new_email)}</a>' + f'<a href="mailto:{escape(new_email)}">{escape(new_email_address.username)}@<wbr>{escape(new_email_address.domain)}</wbr></a>' ), "old_email_html_tag": SafeString( - f'<a href="mailto:{escape(old_email)}">{escape(old_email)}</a>' + f'<a href="mailto:{escape(old_email)}">{escape(old_email_address.username)}@<wbr>{escape(old_email_address.domain)}</wbr></a>' ), } return render(request, "confirmation/confirm_email_change.html", context=ctx)
diff --git a/zerver/tests/test_email_change.py b/zerver/tests/test_email_change.py --- a/zerver/tests/test_email_change.py +++ b/zerver/tests/test_email_change.py @@ -1,8 +1,10 @@ import datetime +from email.headerregistry import Address from unittest import mock from django.conf import settings from django.core import mail +from django.utils.html import escape from django.utils.timezone import now from confirmation.models import ( @@ -95,7 +97,8 @@ def test_confirm_email_change(self) -> None: ) old_email = user_profile.delivery_email - new_email = "[email protected]" + new_email = '"<li>hamlet-new<li>"@zulip.com' + new_email_address = Address(addr_spec=new_email) new_realm = get_realm("zulip") self.login("hamlet") obj = EmailChangeStatus.objects.create( @@ -109,7 +112,11 @@ def test_confirm_email_change(self) -> None: self.assertEqual(response.status_code, 200) self.assert_in_success_response( - ["This confirms that the email address for your Zulip"], response + [ + "This confirms that the email address for your Zulip", + f'<a href="mailto:{escape(new_email)}">{escape(new_email_address.username)}@<wbr>{escape(new_email_address.domain)}</wbr></a>', + ], + response, ) user_profile = get_user_by_delivery_email(new_email, new_realm) self.assertTrue(bool(user_profile))
Long email spills out on email change confirmation page <img width="970" alt="Screen Shot 2022-11-22 at 4 37 11 PM" src="https://user-images.githubusercontent.com/2090066/203448558-bd7a4c3a-ccdc-4f5d-81b8-3093ba52a8d3.png"> We would ideally break up the email to multiple lines, but abbreviating would also be better than the current situation.
@amanagr FYI, in case this is a quick one for you to fix. Hello @zulip/server-misc members, this issue was labeled with the "area: misc" label, so you may want to check it out! <!-- areaLabelAddition --> @zulipbot claim Welcome to Zulip, @cloudier1337! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! hey @alya I'm on this but unfortunately I can not reproduce this behaviour - I understand it happened on Edit Profile -> Change Email, but as I do it on dev environment, I get no such notice - only to check my mail and confirm. You get the notice after you click on `confirm` button. @cloudier1337 please take a look at the [Zulip contributor guide](https://zulip.readthedocs.io/en/latest/overview/contributing.html), and keep in mind the following guideline: > Before you claim an issue, you should be confident that you will be able to tackle it effectively. I will go ahead and unassign this issue, and you should feel free to re-claim it once you have figured out how to reproduce (following @amanagr's advice above) and how to approach making a fix. Thanks! @zulipbot claim Hello @Ujjawal3, it looks like you've currently claimed 1 issue in this repository. We encourage new contributors to focus their efforts on at most 1 issue at a time, so please complete your work on your other claimed issues before trying to claim this issue again. We look forward to your valuable contributions! @zulipbot claim > @cloudier1337 please take a look at the [Zulip contributor guide](https://zulip.readthedocs.io/en/latest/overview/contributing.html), and keep in mind the following guideline: > > > Before you claim an issue, you should be confident that you will be able to tackle it effectively. > > I will go ahead and unassign this issue, and you should feel free to re-claim it once you have figured out how to reproduce (following @amanagr's advice above) and how to approach making a fix. > > Thanks! Thanks for your answer, I am confident I can solve it (I just did not think I would have trouble reproducing it). My bad. Will find another one, now that this one has been claimed.
2022-11-27T22:16:01
zulip/zulip
23,731
zulip__zulip-23731
[ "23715" ]
1fea98499d20ecbfcecd7648113ef292483fd40c
diff --git a/zerver/lib/markdown/__init__.py b/zerver/lib/markdown/__init__.py --- a/zerver/lib/markdown/__init__.py +++ b/zerver/lib/markdown/__init__.py @@ -2372,13 +2372,22 @@ def percent_escape_format_string(format_string: str) -> str: return re.sub(r"(?<!%)(%%)*%([a-fA-F0-9][a-fA-F0-9])", r"\1%%\2", format_string) +@dataclass +class TopicLinkMatch: + url: str + text: str + index: int + precedence: Optional[int] + + # Security note: We don't do any HTML escaping in this # function on the URLs; they are expected to be HTML-escaped when # rendered by clients (just as links rendered into message bodies # are validated and escaped inside `url_to_a`). def topic_links(linkifiers_key: int, topic_name: str) -> List[Dict[str, str]]: - matches: List[Dict[str, Union[str, int]]] = [] + matches: List[TopicLinkMatch] = [] linkifiers = linkifiers_for_realm(linkifiers_key) + precedence = 0 options = re2.Options() options.log_errors = False @@ -2411,16 +2420,29 @@ def topic_links(linkifiers_key: int, topic_name: str) -> List[Dict[str, str]]: # Also, we include the matched text in the response, so that our clients # don't have to implement any logic of their own to get back the text. matches += [ - dict( + TopicLinkMatch( url=url_format_string % match_details, text=match_text, - index=topic_name.find(match_text), + index=m.start(), + precedence=precedence, ) ] + precedence += 1 + + # Sort the matches beforehand so we favor the match with a higher priority and tie-break with the starting index. + # Note that we sort it before processing the raw URLs so that linkifiers will be prioritized over them. + matches.sort(key=lambda k: (k.precedence, k.index)) + pos = 0 # Also make raw URLs navigable. - for sub_string in basic_link_splitter.split(topic_name): - link_match = re.match(get_web_link_regex(), sub_string) + while pos < len(topic_name): + # Assuming that basic_link_splitter matches 1 character, + # we match segments of the string for URL divided by the matched character. + next_split = basic_link_splitter.search(topic_name, pos) + end = next_split.start() if next_split is not None else len(topic_name) + # We have to match the substring because LINK_REGEX + # matches the start of the entire string with "^" + link_match = re.match(get_web_link_regex(), topic_name[pos:end]) if link_match: actual_match_url = link_match.group("url") result = urlsplit(actual_match_url) @@ -2432,13 +2454,40 @@ def topic_links(linkifiers_key: int, topic_name: str) -> List[Dict[str, str]]: else: url = actual_match_url matches.append( - dict(url=url, text=actual_match_url, index=topic_name.find(actual_match_url)) + TopicLinkMatch( + url=url, + text=actual_match_url, + index=pos, + precedence=None, + ) ) + # Move pass the next split point, and start matching the URL from there + pos = end + 1 + + def are_matches_overlapping(match_a: TopicLinkMatch, match_b: TopicLinkMatch) -> bool: + return (match_b.index <= match_a.index < match_b.index + len(match_b.text)) or ( + match_a.index <= match_b.index < match_a.index + len(match_a.text) + ) - # In order to preserve the order in which the links occur, we sort the matched text - # based on its starting index in the topic. We pop the index field before returning. - matches = sorted(matches, key=lambda k: k["index"]) - return [{k: str(v) for k, v in match.items() if k != "index"} for match in matches] + # The following removes overlapping intervals depending on the precedence of linkifier patterns. + # This uses the same algorithm implemented in static/js/markdown.js. + # To avoid mutating matches inside the loop, the final output gets appended to another list. + applied_matches: List[TopicLinkMatch] = [] + for current_match in matches: + # When the current match does not overlap with all existing matches, + # we are confident that the link should present in the final output because + # 1. Given that the links are sorted by precedence, the current match has the highest priority + # among the matches to be checked. + # 2. None of the matches with higher priority overlaps with the current match. + # This might be optimized to search for overlapping matches in O(logn) time, + # but it is kept as-is since performance is not critical for this codepath and for simplicity. + if all( + not are_matches_overlapping(old_match, current_match) for old_match in applied_matches + ): + applied_matches.append(current_match) + # We need to sort applied_matches again because the links were previously ordered by precedence. + applied_matches.sort(key=lambda v: v.index) + return [{"url": match.url, "text": match.text} for match in applied_matches] def maybe_update_markdown_engines(linkifiers_key: int, email_gateway: bool) -> None: diff --git a/zerver/models.py b/zerver/models.py --- a/zerver/models.py +++ b/zerver/models.py @@ -1338,7 +1338,7 @@ def realm_filters_for_realm(realm_id: int) -> List[Tuple[str, str, int]]: @cache_with_key(get_linkifiers_cache_key, timeout=3600 * 24 * 7) def linkifiers_for_realm_remote_cache(realm_id: int) -> List[LinkifierDict]: linkifiers = [] - for linkifier in RealmFilter.objects.filter(realm_id=realm_id): + for linkifier in RealmFilter.objects.filter(realm_id=realm_id).order_by("id"): linkifiers.append( LinkifierDict( pattern=linkifier.pattern,
diff --git a/frontend_tests/node_tests/markdown_parse.js b/frontend_tests/node_tests/markdown_parse.js --- a/frontend_tests/node_tests/markdown_parse.js +++ b/frontend_tests/node_tests/markdown_parse.js @@ -6,6 +6,7 @@ const {zrequire} = require("../zjsunit/namespace"); const {run_test} = require("../zjsunit/test"); const markdown = zrequire("markdown"); +const linkifiers = zrequire("linkifiers"); const my_id = 101; @@ -216,10 +217,54 @@ run_test("linkifiers", () => { ); }); +function assert_topic_links(topic, expected_links) { + const topic_links = markdown.get_topic_links({ + topic, + get_linkifier_map: linkifiers.get_linkifier_map, + }); + assert.deepEqual(topic_links, expected_links); +} + run_test("topic links", () => { - const topic = "progress on #foo101 and #foo102"; - const topic_links = markdown.get_topic_links({topic, get_linkifier_map}); - assert.deepEqual(topic_links, [ + linkifiers.initialize([{pattern: "#foo(?P<id>\\d+)", url_format: "http://foo.com/%(id)s"}]); + assert_topic_links("progress on #foo101 and #foo102", [ + { + text: "#foo101", + url: "http://foo.com/101", + }, + { + text: "#foo102", + url: "http://foo.com/102", + }, + ]); +}); + +run_test("topic links repeated", () => { + // Links generated from repeated patterns should preserve the order. + const topic = + "#foo101 https://google.com #foo102 #foo103 https://google.com #foo101 #foo102 #foo103"; + linkifiers.initialize([{pattern: "#foo(?P<id>\\d+)", url_format: "http://foo.com/%(id)s"}]); + assert_topic_links(topic, [ + { + text: "#foo101", + url: "http://foo.com/101", + }, + { + text: "https://google.com", + url: "https://google.com", + }, + { + text: "#foo102", + url: "http://foo.com/102", + }, + { + text: "#foo103", + url: "http://foo.com/103", + }, + { + text: "https://google.com", + url: "https://google.com", + }, { text: "#foo101", url: "http://foo.com/101", @@ -228,5 +273,106 @@ run_test("topic links", () => { text: "#foo102", url: "http://foo.com/102", }, + { + text: "#foo103", + url: "http://foo.com/103", + }, + ]); +}); + +run_test("topic links overlapping", () => { + linkifiers.initialize([ + {pattern: "[a-z]+(?P<id>1\\d+) #[a-z]+", url_format: "http://a.com/%(id)s"}, + {pattern: "[a-z]+(?P<id>1\\d+)", url_format: "http://b.com/%(id)s"}, + {pattern: ".+#(?P<id>[a-z]+)", url_format: "http://wildcard.com/%(id)s"}, + {pattern: "#(?P<id>[a-z]+)", url_format: "http://c.com/%(id)s"}, + ]); + // b.com's pattern should be matched while it overlaps with c.com's. + assert_topic_links("#foo100", [ + { + text: "foo100", + url: "http://b.com/100", + }, + ]); + // a.com's pattern should be matched while it overlaps with b.com's, wildcard.com's and c.com's. + assert_topic_links("#asd123 #asd", [ + { + text: "asd123 #asd", + url: "http://a.com/123", + }, + ]); + // a.com's pattern do not match, wildcard.com's and b.com's patterns should match + // and the links are ordered by the matched index. + assert_topic_links("/#asd #foo100", [ + { + text: "/#asd", + url: "http://wildcard.com/asd", + }, + { + text: "foo100", + url: "http://b.com/100", + }, + ]); + assert_topic_links("foo.anything/#asd", [ + { + text: "foo.anything/#asd", + url: "http://wildcard.com/asd", + }, + ]); + + // While the raw URL "http://foo.com/foo100" appears before b.com's match "foo100", + // we prioritize the linkifier match first. + assert_topic_links("http://foo.com/foo100", [ + { + text: "foo100", + url: "http://b.com/100", + }, + ]); + + // Here the raw URL "https://foo.com/#asd" appears after wildcard.com's match "something https://foo.com/#asd". + // The latter is prioritized and the raw URL does not get included. + assert_topic_links("something https://foo.com/#asd", [ + { + text: "something https://foo.com/#asd", + url: "http://wildcard.com/asd", + }, + ]); +}); + +run_test("topic links ordering by priority", () => { + // The same test case is also implemented in zerver/tests/test_markdown.py + linkifiers.initialize([ + {pattern: "http", url_format: "http://example.com/"}, + {pattern: "b#(?P<id>[a-z]+)", url_format: "http://example.com/b/%(id)s"}, + { + pattern: "a#(?P<aid>[a-z]+) b#(?P<bid>[a-z]+)", + url_format: "http://example.com/a/%(aid)s/b/%(bid)", + }, + {pattern: "a#(?P<id>[a-z]+)", url_format: "http://example.com/a/%(id)s"}, + ]); + + // There should be 5 link matches in the topic, if ordered from the most priortized to the least: + // 1. "http" (linkifier) + // 2. "b#bar" (linkifier) + // 3. "a#asd b#bar" (linkifier) + // 4. "a#asd" (linkifier) + // 5. "http://foo.com" (raw URL) + // When there are overlapping matches, the one that appears earlier in the list should + // have a topic link generated. + // For this test case, while "a#asd" and "a#asd b#bar" both match and they overlap, + // there is a match "b#bar" with a higher priority, preventing "a#asd b#bar" from being matched. + assert_topic_links("http://foo.com a#asd b#bar", [ + { + text: "http", + url: "http://example.com/", + }, + { + text: "a#asd", + url: "http://example.com/a/asd", + }, + { + text: "b#bar", + url: "http://example.com/b/bar", + }, ]); }); diff --git a/zerver/tests/test_markdown.py b/zerver/tests/test_markdown.py --- a/zerver/tests/test_markdown.py +++ b/zerver/tests/test_markdown.py @@ -1301,16 +1301,26 @@ def test_links_in_topic_name(self) -> None: ], ) + def check_add_linkifiers( + self, linkifiers: List[RealmFilter], expected_linkifier_strs: List[str] + ) -> None: + self.assert_length(linkifiers, len(expected_linkifier_strs)) + for linkifier, expected_linkifier_str in zip(linkifiers, expected_linkifier_strs): + linkifier.clean() + linkifier.save() + self.assertEqual(str(linkifier), expected_linkifier_str) + def test_realm_patterns(self) -> None: realm = get_realm("zulip") - url_format_string = r"https://trac.example.com/ticket/%(id)s" - linkifier = RealmFilter( - realm=realm, pattern=r"#(?P<id>[0-9]{2,8})", url_format_string=url_format_string - ) - linkifier.save() - self.assertEqual( - str(linkifier), - "<RealmFilter(zulip): #(?P<id>[0-9]{2,8}) https://trac.example.com/ticket/%(id)s>", + self.check_add_linkifiers( + [ + RealmFilter( + realm=realm, + pattern=r"#(?P<id>[0-9]{2,8})", + url_format_string=r"https://trac.example.com/ticket/%(id)s", + ) + ], + ["<RealmFilter(zulip): #(?P<id>[0-9]{2,8}) https://trac.example.com/ticket/%(id)s>"], ) msg = Message(sender=self.example_user("othello")) @@ -1340,6 +1350,21 @@ def test_realm_patterns(self) -> None: ], ) + msg.set_topic_name("#111 https://google.com #111 #222 #111 https://google.com #222") + converted_topic = topic_links(realm.id, msg.topic_name()) + self.assertEqual( + converted_topic, + [ + {"url": "https://trac.example.com/ticket/111", "text": "#111"}, + {"url": "https://google.com", "text": "https://google.com"}, + {"url": "https://trac.example.com/ticket/111", "text": "#111"}, + {"url": "https://trac.example.com/ticket/222", "text": "#222"}, + {"url": "https://trac.example.com/ticket/111", "text": "#111"}, + {"url": "https://google.com", "text": "https://google.com"}, + {"url": "https://trac.example.com/ticket/222", "text": "#222"}, + ], + ) + msg.set_topic_name("#444 #555 #666") converted_topic = topic_links(realm.id, msg.topic_name()) self.assertEqual( @@ -1443,29 +1468,29 @@ def assert_conversion(content: str, should_have_converted: bool = True) -> None: def test_multiple_matching_realm_patterns(self) -> None: realm = get_realm("zulip") - url_format_string = r"https://trac.example.com/ticket/%(id)s" - linkifier_1 = RealmFilter( - realm=realm, - pattern=r"(?P<id>ABC\-[0-9]+)", - url_format_string=url_format_string, - ) - linkifier_1.save() - self.assertEqual( - str(linkifier_1), - r"<RealmFilter(zulip): (?P<id>ABC\-[0-9]+) https://trac.example.com/ticket/%(id)s>", - ) - - url_format_string = r"https://other-trac.example.com/ticket/%(id)s" - linkifier_2 = RealmFilter( - realm=realm, - pattern=r"(?P<id>[A-Z][A-Z0-9]*\-[0-9]+)", - url_format_string=url_format_string, - ) - linkifier_2.save() - self.assertEqual( - str(linkifier_2), - r"<RealmFilter(zulip): (?P<id>[A-Z][A-Z0-9]*\-[0-9]+)" - " https://other-trac.example.com/ticket/%(id)s>", + self.check_add_linkifiers( + [ + RealmFilter( + realm=realm, + pattern="(?P<id>ABC-[0-9]+)", + url_format_string="https://trac.example.com/ticket/%(id)s", + ), + RealmFilter( + realm=realm, + pattern="(?P<id>[A-Z][A-Z0-9]*-[0-9]+)", + url_format_string="https://other-trac.example.com/ticket/%(id)s", + ), + RealmFilter( + realm=realm, + pattern="(?P<id>[A-Z][A-Z0-9]+)", + url_format_string="https://yet-another-trac.example.com/ticket/%(id)s", + ), + ], + [ + "<RealmFilter(zulip): (?P<id>ABC-[0-9]+) https://trac.example.com/ticket/%(id)s>", + "<RealmFilter(zulip): (?P<id>[A-Z][A-Z0-9]*-[0-9]+) https://other-trac.example.com/ticket/%(id)s>", + "<RealmFilter(zulip): (?P<id>[A-Z][A-Z0-9]+) https://yet-another-trac.example.com/ticket/%(id)s>", + ], ) msg = Message(sender=self.example_user("othello")) @@ -1485,12 +1510,136 @@ def test_multiple_matching_realm_patterns(self) -> None: converted.rendered_content, '<p>We should fix <a href="https://trac.example.com/ticket/ABC-123">ABC-123</a> or <a href="https://trac.example.com/ticket/16">trac ABC-123</a> today.</p>', ) - # But both the links should be generated in topics. + # Only the older linkifier should be used in the topic, because the two patterns overlap. self.assertEqual( converted_topic, [ {"url": "https://trac.example.com/ticket/ABC-123", "text": "ABC-123"}, - {"url": "https://other-trac.example.com/ticket/ABC-123", "text": "ABC-123"}, + ], + ) + + # linkifier 3 matches ASD, ABC and QWE, but because it has lower priority + # than linkifier 1 and linkifier 2 because it is created last, the former + # two matches will not be chosen. + # Both linkifier 1 and linkifier 2 matches ABC-123, similarly, as linkifier 2 + # has a lower priority, only linkifier 1's URL will be generated. + converted_topic = topic_links(realm.id, "ASD-123 ABC-123 QWE") + self.assertEqual( + converted_topic, + [ + {"url": "https://other-trac.example.com/ticket/ASD-123", "text": "ASD-123"}, + {"url": "https://trac.example.com/ticket/ABC-123", "text": "ABC-123"}, + {"url": "https://yet-another-trac.example.com/ticket/QWE", "text": "QWE"}, + ], + ) + + def test_links_and_linkifiers_in_topic_name(self) -> None: + realm = get_realm("zulip") + self.check_add_linkifiers( + [ + RealmFilter( + realm=realm, + pattern="ABC-42", + url_format_string="https://google.com", + ), + RealmFilter( + realm=realm, + pattern=r"com.+(?P<id>ABC\-[0-9]+)", + url_format_string="https://trac.example.com/ticket/%(id)s", + ), + ], + [ + "<RealmFilter(zulip): ABC-42 https://google.com>", + r"<RealmFilter(zulip): com.+(?P<id>ABC\-[0-9]+) https://trac.example.com/ticket/%(id)s>", + ], + ) + + # This verifies that second linkifier has a lower priority than the first one. + # It helps us to later ensure that even with a low priority, the linkifier can take effect + # when it appears earlier than a raw URL. + converted_topic = topic_links(realm.id, "com ABC-42") + self.assertEqual( + converted_topic, + [{"url": "https://google.com", "text": "ABC-42"}], + ) + # The linkifier matches "com/ABC-123", which is after where the raw URL starts + converted_topic = topic_links(realm.id, "https://foo.com/ABC-123") + self.assertEqual( + converted_topic, + [{"url": "https://foo.com/ABC-123", "text": "https://foo.com/ABC-123"}], + ) + + # The linkifier matches "com https://foo.com/ABC-123", which is before where the raw URL starts + converted_topic = topic_links(realm.id, "com https://foo.com/ABC-123") + self.assertEqual( + converted_topic, + [ + { + "url": "https://trac.example.com/ticket/ABC-123", + "text": "com https://foo.com/ABC-123", + } + ], + ) + + def test_topic_links_ordering_by_priority(self) -> None: + # The same test case is also implemented in frontend_tests/node_tests/markdown_parse.js + realm = get_realm("zulip") + self.check_add_linkifiers( + [ + RealmFilter( + realm=realm, + pattern="http", + url_format_string="http://example.com/", + ), + RealmFilter( + realm=realm, + pattern="b#(?P<id>[a-z]+)", + url_format_string="http://example.com/b/%(id)s", + ), + RealmFilter( + realm=realm, + pattern="a#(?P<aid>[a-z]+) b#(?P<bid>[a-z]+)", + url_format_string="http://example.com/a/%(aid)s/b/%(bid)s", + ), + RealmFilter( + realm=realm, + pattern="a#(?P<id>[a-z]+)", + url_format_string="http://example.com/a/%(id)s", + ), + ], + [ + "<RealmFilter(zulip): http http://example.com/>", + "<RealmFilter(zulip): b#(?P<id>[a-z]+) http://example.com/b/%(id)s>", + "<RealmFilter(zulip): a#(?P<aid>[a-z]+) b#(?P<bid>[a-z]+) http://example.com/a/%(aid)s/b/%(bid)s>", + "<RealmFilter(zulip): a#(?P<id>[a-z]+) http://example.com/a/%(id)s>", + ], + ) + # There should be 5 link matches in the topic, if ordered from the most priortized to the least: + # 1. "http" (linkifier) + # 2. "b#bar" (linkifier) + # 3. "a#asd b#bar" (linkifier) + # 4. "a#asd" (linkifier) + # 5. "http://foo.com" (raw URL) + # When there are overlapping matches, the one that appears earlier in the list should + # have a topic link generated. + # For this test case, while "a#asd" and "a#asd b#bar" both match and they overlap, + # there is a match "b#bar" with a higher priority, preventing "a#asd b#bar" from being matched. + converted_topic = topic_links(realm.id, "http://foo.com a#asd b#bar") + self.assertEqual( + converted_topic, + [ + { + "text": "http", + "url": "http://example.com/", + }, + { + "text": "a#asd", + "url": "http://example.com/a/asd", + }, + { + "text": "b#bar", + "url": "http://example.com/b/bar", + }, ], ) @@ -1531,6 +1680,23 @@ def save_new_linkifier() -> None: flush() self.assertFalse(realm_in_local_linkifiers_cache(realm.id)) + def test_linkifier_precedence(self) -> None: + realm = self.example_user("hamlet").realm + # The insertion order should not affect the fact that the linkifiers are ordered by id. + # Note that we might later switch to a different field to order the linkifiers. + sequence = (10, 3, 11, 2, 4, 5, 6) + for cur_precedence in sequence: + linkifier = RealmFilter( + id=cur_precedence, + realm=realm, + pattern=f"abc{cur_precedence}", + url_format_string="http://foo.com", + ) + linkifier.save() + linkifiers = linkifiers_for_realm(realm.id) + for index, cur_precedence in enumerate(sorted(sequence)): + self.assertEqual(linkifiers[index]["id"], cur_precedence) + def test_realm_patterns_negative(self) -> None: realm = get_realm("zulip") RealmFilter(
Make behavior of overlapping linkifiers clear and consistent To make the behavior of overlapping linkifiers clear, consistent and predictable, we should: - [ ] Add an order_by on linkifier ID, so that linkifiers shown higher in the settings list take priority over overlapping linkfiers that are lower on the list. - [ ] Document the above behavior on https://zulip.com/help/add-a-custom-linkifier - [ ] Make linkifiers in topics work like linkifiers in messages. Currently, if multiple linkifiers match, multiple links are show in the topic bar, which causes confusion. The third point can be addressed independently from the first two. Follow-up issue to make the system more flexible: #23716 [CZO discussion](https://chat.zulip.org/#narrow/stream/9-issues/topic/linkifiers/near/1467435)
@zulipbot claim
2022-12-02T09:24:51
zulip/zulip
23,817
zulip__zulip-23817
[ "23720", "23720" ]
fd221efc68992043e13545e4c9b24c2aa0821593
diff --git a/zerver/data_import/mattermost.py b/zerver/data_import/mattermost.py --- a/zerver/data_import/mattermost.py +++ b/zerver/data_import/mattermost.py @@ -70,6 +70,14 @@ def is_team_admin(user_dict: Dict[str, Any]) -> bool: for team in user_dict["teams"] ) + def is_team_guest(user_dict: Dict[str, Any]) -> bool: + if user_dict["teams"] is None: + return False + for team in user_dict["teams"]: + if team["name"] == team_name and "team_guest" in team["roles"]: + return True + return False + def get_full_name(user_dict: Dict[str, Any]) -> str: full_name = "{} {}".format(user_dict["first_name"], user_dict["last_name"]) if full_name.strip(): @@ -85,9 +93,12 @@ def get_full_name(user_dict: Dict[str, Any]) -> str: date_joined = int(timezone_now().timestamp()) timezone = "UTC" - role = UserProfile.ROLE_MEMBER if is_team_admin(user_dict): role = UserProfile.ROLE_REALM_OWNER + elif is_team_guest(user_dict): + role = UserProfile.ROLE_GUEST + else: + role = UserProfile.ROLE_MEMBER if user_dict["is_mirror_dummy"]: is_active = False
diff --git a/zerver/tests/fixtures/mattermost_fixtures/guestExport.json b/zerver/tests/fixtures/mattermost_fixtures/guestExport.json new file mode 100644 --- /dev/null +++ b/zerver/tests/fixtures/mattermost_fixtures/guestExport.json @@ -0,0 +1,36 @@ +{"type":"version","version":1} +{"type":"team","team":{"name":"gryffindor","display_name":"Iago Realm","type":"O","description":"","allow_open_invite":true}} +{"type":"team","team":{"name":"slytherin","display_name":"Othello Team","type":"O","description":"","allow_open_invite":true}} +{"type":"channel","channel":{"team":"gryffindor","name":"gryffindor-common-room","display_name":"Gryffindor common room","type":"O","header":"","purpose":"A place for talking about Gryffindor common room"}} +{"type":"channel","channel":{"team":"gryffindor","name":"gryffindor-quidditch-team","display_name":"Gryffindor quidditch team","type":"O","header":"","purpose":"A place for talking about Gryffindor quidditch team"}} +{"type":"channel","channel":{"team":"slytherin","name":"slytherin-common-room","display_name":"Slytherin common room","type":"O","header":"","purpose":""}} +{"type":"channel","channel":{"team":"gryffindor","name":"dumbledores-army","display_name":"Dumbledores army","type":"P","header":"https//:github.com/zulip/zulip","purpose":"A place for talking about Dumbledores army"}} +{"type":"channel","channel":{"team":"slytherin","name":"slytherin-quidditch-team","display_name":"Slytherin quidditch team","type":"O","header":"","purpose":""}} +{"type":"user","user":{"username":"ron","email":"[email protected]","auth_service":"","nickname":"","first_name":"Ron","last_name":"Weasley","position":"","roles":"system_user","locale":"en","teams":[{"name":"gryffindor","roles":"team_user","channels":[{"name":"gryffindor-quidditch-team","roles":"channel_user","notify_props":{"desktop":"default","mobile":"default","mark_unread":"all"},"favorite":false},{"name":"gryffindor-common-room","roles":"channel_user","notify_props":{"desktop":"default","mobile":"default","mark_unread":"all"},"favorite":false},{"name":"dumbledores-army","roles":"channel_user","notify_props":{"desktop":"default","mobile":"default","mark_unread":"all"},"favorite":false}]}],"notify_props":{"desktop":"mention","desktop_sound":"true","email":"true","mobile":"mention","mobile_push_status":"away","channel":"true","comments":"never","mention_keys":"ron,@ron"}}} +{"type":"user","user":{"username":"harry","email":"[email protected]","auth_service":"","nickname":"","first_name":"Harry","last_name":"Potter","position":"","roles":"system_admin system_user","locale":"en","teams":[{"name":"gryffindor","roles":"team_admin team_user","channels":[{"name":"dumbledores-army","roles":"channel_admin channel_user","notify_props":{"desktop":"default","mobile":"default","mark_unread":"all"},"favorite":false},{"name":"gryffindor-common-room","roles":"channel_admin channel_user","notify_props":{"desktop":"default","mobile":"default","mark_unread":"all"},"favorite":false},{"name":"gryffindor-quidditch-team","roles":"channel_admin channel_user","notify_props":{"desktop":"default","mobile":"default","mark_unread":"all"},"favorite":false}]}],"notify_props":{"desktop":"mention","desktop_sound":"true","email":"true","mobile":"mention","mobile_push_status":"away","channel":"true","comments":"never","mention_keys":"harry,@harry"}}} +{"type":"user","user":{"username":"malfoy","email":"[email protected]","auth_service":"","nickname":"","first_name":"","last_name":"","position":"","roles":"system_user","locale":"en","teams":[{"name":"slytherin","roles":"team_admin team_user","channels":[{"name":"slytherin-common-room","roles":"channel_admin channel_user","notify_props":{"desktop":"default","mobile":"default","mark_unread":"all"},"favorite":false},{"name":"slytherin-quidditch-team","roles":"channel_admin channel_user","notify_props":{"desktop":"default","mobile":"default","mark_unread":"all"},"favorite":false}]}],"notify_props":{"desktop":"mention","desktop_sound":"true","email":"true","mobile":"mention","mobile_push_status":"away","channel":"true","comments":"never","mention_keys":"malfoy,@malfoy"}}} +{"type":"user","user":{"username":"pansy","email":"[email protected]","auth_service":"","nickname":"","first_name":"","last_name":"","position":"","roles":"system_user","locale":"en","teams":[{"name":"slytherin","roles":"team_admin team_user","channels":[{"name":"slytherin-common-room","roles":"channel_admin channel_user","notify_props":{"desktop":"default","mobile":"default","mark_unread":"all"},"favorite":false},{"name":"slytherin-quidditch-team","roles":"channel_admin channel_user","notify_props":{"desktop":"default","mobile":"default","mark_unread":"all"},"favorite":false}]}],"notify_props":{"desktop":"mention","desktop_sound":"true","email":"true","mobile":"mention","mobile_push_status":"away","channel":"true","comments":"never","mention_keys":"malfoy,@malfoy"}}} +{"type":"user","user":{"username":"snape","email":"[email protected]","auth_service":"","nickname":"","first_name":"Severus","last_name":"Snape","position":"","roles":"system_user","locale":"en","teams":[{"name":"slytherin","roles":"team_user","channels":[{"name":"slytherin-common-room","roles":"channel_user","notify_props":{"desktop":"default","mobile":"default","mark_unread":"all"},"favorite":false}]}],"notify_props":{"desktop":"mention","desktop_sound":"true","email":"true","mobile":"mention","mobile_push_status":"away","channel":"true","comments":"never","mention_keys":"snape,@snape"}}} +{"type":"user","user":{"username":"sirius","email":"[email protected]","auth_service":"","nickname":"","first_name":"Sirius","last_name":"Black","position":"","roles":"system_guest","locale":"en","teams":[{"name":"slytherin","roles":"team_guest","channels":[{"name":"slytherin-common-room","roles":"channel_guest","notify_props":{"desktop":"default","mobile":"default","mark_unread":"all"},"favorite":false}]}],"notify_props":{"desktop":"mention","desktop_sound":"true","email":"true","mobile":"mention","mobile_push_status":"away","channel":"true","comments":"never","mention_keys":"sirius,@sirius"}}} +{"type":"post","post":{"team":"gryffindor","channel":"dumbledores-army","user":"harry","message":"harry joined the channel.","create_at":1553166657086,"reactions":null,"replies":[{"user":"ron","message":"The weather is so hot!","create_at":1553166584976}]}} +{"type":"post","post":{"team":"gryffindor","channel":"gryffindor-common-room","user":"ron","message":"ron joined the channel.","create_at":1553166512493,"reactions":null,"replies":null}} +{"type":"post","post":{"team":"gryffindor","channel":"gryffindor-quidditch-team","user":"harry","message":"harry joined the team.","create_at":1553165141670,"reactions":null,"replies":null}} +{"type":"post","post":{"team":"gryffindor","channel":"gryffindor-quidditch-team","user":"harry","message":"Awesome!","create_at":1553166557928,"reactions":[{"user":"malfoy","create_at":1553166812156,"emoji_name":"tick"}],"replies":null}} +{"type":"post","post":{"team":"slytherin","channel":"slytherin-quidditch-team","user":"malfoy","message":"malfoy joined the team.","create_at":1553166852598,"reactions":null,"replies":null}} +{"type":"post","post":{"team":"gryffindor","channel":"gryffindor-quidditch-team","user":"ron","message":"ron joined the team.","create_at":1553166512482,"reactions":null,"replies":null}} +{"type":"post","post":{"team":"gryffindor","channel":"gryffindor-quidditch-team","user":"ron","message":"Hey folks","create_at":1553166519720,"reactions":null,"replies":null}} +{"type":"post","post":{"team":"gryffindor","channel":"gryffindor-quidditch-team","user":"harry","message":"@ron Welcome mate!","create_at":1553166519726,"reactions":null,"replies":null}} +{"type":"post","post":{"team":"gryffindor","channel":"dumbledores-army","user":"harry","message":"ron added to the channel by harry.","create_at":1553166681045,"reactions":null,"replies":null}} +{"type":"post","post":{"team":"gryffindor","channel":"gryffindor-quidditch-team","user":"harry","message":"Hello world","create_at":1553165193242,"reactions":[{"user":"harry","create_at":1553165521410,"emoji_name":"tick"},{"user":"ron","create_at":1553166530805,"emoji_name":"smile"},{"user":"ron","create_at":1553166540953,"emoji_name":"world_map"}],"replies":null}} +{"type":"post","post":{"team":"gryffindor","channel":"gryffindor-common-room","user":"harry","message":"Looks like this channel is empty","create_at":1553166567370,"reactions":[{"user":"ron","create_at":1553166584976,"emoji_name":"rocket"}],"replies":null}} +{"type":"post","post":{"team":"gryffindor","channel":"gryffindor-quidditch-team","user":"ron","message":"How is everything going","create_at":1553166525124,"reactions":[{"user":"harry","create_at":1553166552827,"emoji_name":"apple"}],"replies":null}} +{"type":"post","post":{"team":"gryffindor","channel":"gryffindor-common-room","user":"ron","message":"Not really","create_at":1553166593455,"reactions":null,"replies":null}} +{"type":"post","post":{"team":"gryffindor","channel":"dumbledores-army","user":"ron","message":"hello","create_at":1553166686344,"reactions":null,"replies":null}} +{"type":"post","post":{"team":"gryffindor","channel":"dumbledores-army","user":"harry","message":"hey everyone","create_at":1553166668668,"reactions":[{"user":"ron","create_at":1553166695260,"emoji_name":"grin"}],"replies":null}} +{"type":"post","post":{"team":"slytherin","channel":"slytherin-common-room","user":"malfoy","message":"malfoy joined the channel.","create_at":1553166852612,"reactions":null,"replies":null}} +{"type":"post","post":{"team":"slytherin","channel":"slytherin-quidditch-team","user":"malfoy","message":":rofl:4","create_at":1553166916448,"reactions":[{"user":"harry","create_at":1553167016056,"emoji_name":"peerdium"}],"replies":null}} +{"type":"post","post":{"team":"slytherin","channel":"slytherin-quidditch-team","user":"malfoy","message":"Hello folks","create_at":1553166858280,"reactions":[{"user":"harry","create_at":1553166903980,"emoji_name":"joy"}],"replies":null}} +{"type":"post","post":{"team":"gryffindor","channel":"gryffindor-common-room","user":"harry","message":"harry joined the channel.","create_at":1553165141689,"reactions":null,"replies":null}} +{"type":"post","post":{"team":"gryffindor","channel":"gryffindor-quidditch-team","user":"snape","message":"Hey folks! I was always in your team. Time to go now.","create_at":1553166740759,"reactions":null,"replies":null}} +{"type":"emoji","emoji":{"name":"peerdium","image":"exported_emoji/h15ni7kf1bnj7jeua4qhmctsdo/image.png"}} +{"type":"emoji","emoji":{"name":"tick","image":"exported_emoji/7u7x8ytgp78q8jir81o9ejwwnr/image.png"}} diff --git a/zerver/tests/test_mattermost_importer.py b/zerver/tests/test_mattermost_importer.py --- a/zerver/tests/test_mattermost_importer.py +++ b/zerver/tests/test_mattermost_importer.py @@ -127,6 +127,37 @@ def test_process_user(self) -> None: self.assertEqual(user["short_name"], "snape") self.assertEqual(user["timezone"], "UTC") + def test_process_guest_user(self) -> None: + user_id_mapper = IdMapper() + fixture_file_name = self.fixture_file_name("guestExport.json", "mattermost_fixtures") + mattermost_data = mattermost_data_file_to_dict(fixture_file_name) + username_to_user = create_username_to_user_mapping(mattermost_data["user"]) + reset_mirror_dummy_users(username_to_user) + + sirius_dict = username_to_user["sirius"] + sirius_dict["is_mirror_dummy"] = False + + realm_id = 3 + + team_name = "slytherin" + user = process_user(sirius_dict, realm_id, team_name, user_id_mapper) + self.assertEqual(user["avatar_source"], "G") + self.assertEqual(user["delivery_email"], "[email protected]") + self.assertEqual(user["email"], "[email protected]") + self.assertEqual(user["full_name"], "Sirius Black") + self.assertEqual(user["role"], UserProfile.ROLE_GUEST) + self.assertEqual(user["is_mirror_dummy"], False) + self.assertEqual(user["realm"], 3) + self.assertEqual(user["short_name"], "sirius") + self.assertEqual(user["timezone"], "UTC") + + # A guest user with a `null` team value should be a regular + # user. (It's a bit of a mystery why the Mattermost export + # tool generates such `teams` lists). + sirius_dict["teams"] = None + user = process_user(sirius_dict, realm_id, team_name, user_id_mapper) + self.assertEqual(user["role"], UserProfile.ROLE_MEMBER) + def test_convert_user_data(self) -> None: user_id_mapper = IdMapper() realm_id = 3
Mattermost import - support importing Guests In our Mattermost import system, we currently import all users who aren't Team Admin as Zulip Members. That's not quite right, because per https://docs.mattermost.com/welcome/about-user-roles.html, we're not respecting Guest user status properly - a Mattermost Guest should be imported as a Zulip Guest too. This should be relatively simple to do: in `process_user` in `zerver/data_import/mattermost.py` we have these two lines at the time of writing this, where user `role` is determined: ``` role = UserProfile.ROLE_MEMBER if is_team_admin(user_dict): role = UserProfile.ROLE_REALM_OWNER ``` Similarly to `is_team_admin`, the code should inspect the `user_dict` here to check if this might be a guest user, and if so, set `role = UserProfile.ROLE_GUEST`. For reference, https://docs.mattermost.com/manage/bulk-export-tool.html has some documentation about the data format of the export. Though it doesn't seem to explain how exactly Guest status is encoded, so that might require looking up somewhere else or just manually generating a Mattermost export with a guest user and inspecting the data to determine how it's marked. Mattermost import - support importing Guests In our Mattermost import system, we currently import all users who aren't Team Admin as Zulip Members. That's not quite right, because per https://docs.mattermost.com/welcome/about-user-roles.html, we're not respecting Guest user status properly - a Mattermost Guest should be imported as a Zulip Guest too. This should be relatively simple to do: in `process_user` in `zerver/data_import/mattermost.py` we have these two lines at the time of writing this, where user `role` is determined: ``` role = UserProfile.ROLE_MEMBER if is_team_admin(user_dict): role = UserProfile.ROLE_REALM_OWNER ``` Similarly to `is_team_admin`, the code should inspect the `user_dict` here to check if this might be a guest user, and if so, set `role = UserProfile.ROLE_GUEST`. For reference, https://docs.mattermost.com/manage/bulk-export-tool.html has some documentation about the data format of the export. Though it doesn't seem to explain how exactly Guest status is encoded, so that might require looking up somewhere else or just manually generating a Mattermost export with a guest user and inspecting the data to determine how it's marked.
Hello @zulip/server-misc members, this issue was labeled with the "area: export/import" label, so you may want to check it out! <!-- areaLabelAddition --> @zulipbot claim Hello @mpedro12, it looks like you've currently claimed 1 issue in this repository. We encourage new contributors to focus their efforts on at most 1 issue at a time, so please complete your work on your other claimed issues before trying to claim this issue again. We look forward to your valuable contributions! @zulipbot claim Hello @zulip/server-misc members, this issue was labeled with the "area: export/import" label, so you may want to check it out! <!-- areaLabelAddition --> @zulipbot claim Hello @mpedro12, it looks like you've currently claimed 1 issue in this repository. We encourage new contributors to focus their efforts on at most 1 issue at a time, so please complete your work on your other claimed issues before trying to claim this issue again. We look forward to your valuable contributions! @zulipbot claim
2022-12-10T21:23:46
zulip/zulip
23,981
zulip__zulip-23981
[ "22228" ]
d1bb100a2d21ca407efb8d7a767222b381ed9b44
diff --git a/zerver/webhooks/slack_incoming/view.py b/zerver/webhooks/slack_incoming/view.py --- a/zerver/webhooks/slack_incoming/view.py +++ b/zerver/webhooks/slack_incoming/view.py @@ -1,6 +1,7 @@ # Webhooks for external integrations. import re -from typing import Optional +from itertools import zip_longest +from typing import Literal, Optional, TypedDict, cast from django.http import HttpRequest, HttpResponse from django.utils.translation import gettext as _ @@ -14,6 +15,7 @@ WildValue, check_dict, check_int, + check_list, check_string, check_string_in, check_url, @@ -98,17 +100,17 @@ def render_block(block: WildValue) -> str: if element_type == "image": pieces.append(render_block_element(element)) else: - pieces.append(element.tame(check_text_block())) + pieces.append(element.tame(check_text_block())["text"]) return "\n\n".join(piece.strip() for piece in pieces if piece.strip() != "") elif block_type == "divider": return "----" elif block_type == "header": - return "## " + block["text"].tame(check_text_block(plain_text_only=True)) + return "## " + block["text"].tame(check_text_block(plain_text_only=True))["text"] elif block_type == "image": image_url = block["image_url"].tame(check_url) alt_text = block["alt_text"].tame(check_string) if "title" in block: - alt_text = block["title"].tame(check_text_block(plain_text_only=True)) + alt_text = block["title"].tame(check_text_block(plain_text_only=True))["text"] return f"[{alt_text}]({image_url})" elif block_type == "input": # Unhandled @@ -116,30 +118,50 @@ def render_block(block: WildValue) -> str: elif block_type == "section": pieces = [] if "text" in block: - pieces.append(block["text"].tame(check_text_block())) + pieces.append(block["text"].tame(check_text_block())["text"]) if "accessory" in block: pieces.append(render_block_element(block["accessory"])) if "fields" in block: - # TODO -- these should be rendered in two columns, - # left-to-right. We could render them sequentially, - # except some may be Title1 / Title2 / value1 / value2, - # which would be nonsensical when rendered sequentially. - pass + fields = block["fields"].tame(check_list(check_text_block())) + if len(fields) == 1: + # Special-case a single field to display a bit more + # nicely, without extraneous borders and limitations + # on its contents. + pieces.append(fields[0]["text"]) + else: + # It is not possible to have newlines in a table, nor + # escape the pipes that make it up; replace them with + # whitespace. + field_text = [f["text"].replace("\n", " ").replace("|", " ") for f in fields] + # Because Slack formats this as two columns, but not + # necessarily a table with a bold header, we emit a + # blank header row first. + table = "| | |\n|-|-|\n" + # Then take the fields two-at-a-time to make the table + iters = [iter(field_text)] * 2 + for left, right in zip_longest(*iters, fillvalue=""): + table += f"| {left} | {right} |\n" + pieces.append(table) return "\n\n".join(piece.strip() for piece in pieces if piece.strip() != "") return "" -def check_text_block(plain_text_only: bool = False) -> Validator[str]: +class TextField(TypedDict): + text: str + type: Literal["plain_text", "mrkdwn"] + + +def check_text_block(plain_text_only: bool = False) -> Validator[TextField]: if plain_text_only: type_validator = check_string_in(["plain_text"]) else: - type_validator = check_string + type_validator = check_string_in(["plain_text", "mrkdwn"]) - def f(var_name: str, val: object) -> str: + def f(var_name: str, val: object) -> TextField: block = check_dict( [ ("type", type_validator), @@ -147,15 +169,7 @@ def f(var_name: str, val: object) -> str: ], )(var_name, val) - # We can't use `value_validator=check_string` above to let - # mypy know this is a str, because there's an optional boolean - # `emoji` key which can appear -- hence the assert. - text = block["text"] - assert isinstance(text, str) - - # Ideally we would escape the content if it was plain text, - # but out flavor of Markdown doesn't support escapes. :( - return text + return cast(TextField, block) return f
diff --git a/zerver/webhooks/slack_incoming/tests.py b/zerver/webhooks/slack_incoming/tests.py --- a/zerver/webhooks/slack_incoming/tests.py +++ b/zerver/webhooks/slack_incoming/tests.py @@ -74,6 +74,9 @@ def test_message_with_actions(self) -> None: [Overlook Hotel](https://google.com) \n :star: \n Doors had too many axe holes, guest in room 237 was far too rowdy, whole place felt stuck in the 1920s. [Haunted hotel image](https://is5-ssl.mzstatic.com/image/thumb/Purple3/v4/d3/72/5c/d3725c8f-c642-5d69-1904-aa36e4297885/source/256x256bb.jpg) + +**Average Rating** +1.0 """.strip() self.check_webhook( @@ -90,6 +93,9 @@ def test_message_with_blocks(self) -> None: [Overlook Hotel](https://example.com) \n :star: \n Doors had too many axe holes, guest in room 237 was far too rowdy, whole place felt stuck in the 1920s. [Haunted hotel image](https://is5-ssl.mzstatic.com/image/thumb/Purple3/v4/d3/72/5c/d3725c8f-c642-5d69-1904-aa36e4297885/source/256x256bb.jpg) + +**Average Rating** +1.0 """.strip() self.check_webhook( @@ -175,6 +181,12 @@ def test_attachment_blocks(self) -> None: [cute cat](https://pbs.twimg.com/profile_images/625633822235693056/lNGUneLX_400x400.jpg) This is a section block with a button. + +| | | +|-|-| +| one | two | +| three | four | +| five | | """.strip() self.check_webhook(
Slack Incoming integration ignores fields I am trying to use a Slack integration from Uptime Kuma and when the message comes in it seems to post only the main text and none of the blocks. I decided to try the example from Slack's website and, in-particular, it seems that the `fields` portion is getting skipped over. Here is the example JSON I'm using ```json { "text": "Message", "blocks": [ { "type": "header", "text": { "type": "plain_text", "text": "New request" } }, { "type": "section", "fields": [ { "type": "mrkdwn", "text": "*Type:*\nPaid Time Off" }, { "type": "mrkdwn", "text": "*Created by:*\n<example.com|Fred Enriquez>" } ] }, { "type": "section", "fields": [ { "type": "mrkdwn", "text": "*When:*\nAug 10 - Aug 13" } ] }, { "type": "section", "text": { "type": "mrkdwn", "text": "<https://example.com|View request>" } } ] } ``` The message it posts is simply this <img width="191" alt="CleanShot 2022-06-09 at 07 44 16@2x" src="https://user-images.githubusercontent.com/125599/172838959-09217b8e-1eef-4d19-9883-c88227dafdf6.png"> It's only getting the last section where it has a `text` set. All the previous sections where it includes `fields` don't show up. I tried to convert the prior section from this ```json { "type": "section", "fields": [ { "type": "mrkdwn", "text": "*When:*\nAug 10 - Aug 13" } ] }, ``` to this ```json { "type": "section", "text": { "type": "mrkdwn", "text": "*When:*\nAug 10 - Aug 13" } }, ``` and it properly posted that text as well <img width="120" alt="CleanShot 2022-06-09 at 07 45 41@2x" src="https://user-images.githubusercontent.com/125599/172839156-eeb3c427-441f-400a-ab6c-292fb5ba7d16.png"> So it feels like those with `fields` are getting skipped over. Uptime Kuma is posting all the relevant information in sections with fields, so I'm not getting much of a message when it tries to post. ```javascript { "type": "section", "fields": [{ "type": "mrkdwn", "text": "*Message*\n" + msg, }, { "type": "mrkdwn", "text": "*Time (UTC)*\n" + time, }], }], ``` Let me know if I can provide more information or where I can help. Thanks.
Zulip currently does skip over `fields`, only handling `text` and `accessory` pieces: https://github.com/zulip/zulip/blob/d0c5389d60c7232405d3e01710983f46ab245ff5/zerver/webhooks/slack_incoming/view.py#L76-L87 I pushed #22258 recently, which adds more supported syntax, but still doesn't address `fields`. The difficulty with the [`fields` of the `section` type](https://api.slack.com/reference/block-kit/blocks#section) is that they're laid out two-columns wide, side-by-side. We can't easily replicate that layout with Zulip's markdown. We can render them sequentially, but that means that people that are using them as _columns_ will get nonsense. That is, if the user intends: | *Severity* | *Component* | |-----------|---------------| | Critical | Web | rendering them sequentially will yield the garbled: > *Severity* > *Component* > Critical > Web And it's impossible to know, a priori, if the webhook is trying to read across or down. Actually, the help popup says you can make tables in Zulip markdown. Zulip does support markdown tables, which are an extension to Markdown. Unfortunately, [Python's Markdown tables](https://python-markdown.github.io/extensions/tables/) _require_ a header, which means that if the user is intending the _left_ column to be the headers, the rendering will be misleading and wrong. You can see this with how Github renders the table, in that the first row is bold, and centered: | Severity: | Critical | |-----------|---------------| | Which component is affected: | Rending in desktop clients | You can hack around this by leaving the "header" row blank: | | | |-----------|---------------| | Severity: | Critical | | Which component is affected: | Rending in desktop clients | But the other issue is that line breaks are not possible in Markdown tables. So while Slack supports [this](https://api.slack.com/tools/block-kit-builder?blocks=%5B%7B%22type%22:%22section%22,%22fields%22:%5B%7B%22type%22:%22mrkdwn%22,%22text%22:%22*Severity*%22%7D,%7B%22type%22:%22mrkdwn%22,%22text%22:%22*Bad*%5CnAlso,%20worse%5CnAnd%20verry%20verry%20sad%22%7D,%7B%22type%22:%22mrkdwn%22,%22text%22:%22*Component*%22%7D,%7B%22type%22:%22mrkdwn%22,%22text%22:%22Web%22%7D%5D%7D%5D): ![Screen Shot 2022-06-20 at 3 48 37 PM](https://user-images.githubusercontent.com/28347/174686186-2026ba20-763a-4a29-9c12-a458be5d0f4a.png) You can't do the equivalent in Markdown -- note that we need to pad the left column with empty cells, effectively, which gets complicated pretty quickly. | | | |-----------|---------------| | *Severity* | *Bad* | | | Also, worse | | | And very, very sad | | *Component* | Rending in desktop clients | Yes, I see these are all valid concerns - but honestly I'd much prefer to have the information there at all, because currently the webhook is almost useless, and worry about the layout later. Hello @zulip/server-integrations members, this issue was labeled with the "area: integrations" label, so you may want to check it out! <!-- areaLabelAddition --> This issue has worsened: Now we just get "Uptime Kuma Alert" without _any_ information :/ Hm, sounds like it would be worth implementing something here, even if the formatting is flawed. @alexmv Would a table with a blank header + replacing `\n` with a space be an acceptable workaround, do you think?
2023-01-04T20:11:04
zulip/zulip
24,001
zulip__zulip-24001
[ "23912" ]
358a0dda5b91a3c8632f4315c31f6accba66bc58
diff --git a/zerver/decorator.py b/zerver/decorator.py --- a/zerver/decorator.py +++ b/zerver/decorator.py @@ -55,7 +55,7 @@ from zerver.lib.queue import queue_json_publish from zerver.lib.rate_limiter import is_local_addr, rate_limit_request_by_ip, rate_limit_user from zerver.lib.request import REQ, RequestNotes, has_request_variables -from zerver.lib.response import json_method_not_allowed, json_success +from zerver.lib.response import json_method_not_allowed from zerver.lib.subdomains import get_subdomain, user_matches_subdomain from zerver.lib.timestamp import datetime_to_timestamp, timestamp_to_datetime from zerver.lib.users import is_2fa_verified @@ -962,7 +962,7 @@ def _wrapped_view_func( request: HttpRequest, /, *args: ParamT.args, **kwargs: ParamT.kwargs ) -> HttpResponse: if request.method == "HEAD": - return json_success(request) + return HttpResponse() return view_func(request, *args, **kwargs) return _wrapped_view_func diff --git a/zerver/webhooks/intercom/view.py b/zerver/webhooks/intercom/view.py --- a/zerver/webhooks/intercom/view.py +++ b/zerver/webhooks/intercom/view.py @@ -4,7 +4,7 @@ from django.http import HttpRequest, HttpResponse -from zerver.decorator import webhook_view +from zerver.decorator import return_success_on_head_request, webhook_view from zerver.lib.exceptions import UnsupportedWebhookEventTypeError from zerver.lib.request import REQ, has_request_variables from zerver.lib.response import json_success @@ -325,6 +325,8 @@ def get_user_unsubscribed_message(payload: WildValue) -> Tuple[str, str]: @webhook_view("Intercom", all_event_types=ALL_EVENT_TYPES) +# Intercom sends a HEAD request to validate the webhook URL. In this case, we just assume success. +@return_success_on_head_request @has_request_variables def api_intercom_webhook( request: HttpRequest,
diff --git a/zerver/tests/test_decorators.py b/zerver/tests/test_decorators.py --- a/zerver/tests/test_decorators.py +++ b/zerver/tests/test_decorators.py @@ -1971,8 +1971,8 @@ def test_function(request: HttpRequest) -> HttpResponse: return json_response(msg="from_test_function") # nocoverage. isn't meant to be called response = test_function(request) - self.assert_json_success(response) - self.assertNotEqual(orjson.loads(response.content).get("msg"), "from_test_function") + self.assertEqual(response.status_code, 200) + self.assertEqual(response.content, b"") def test_returns_normal_response_if_request_method_is_not_head(self) -> None: class HeadRequest(HostRequestMock): diff --git a/zerver/webhooks/intercom/tests.py b/zerver/webhooks/intercom/tests.py --- a/zerver/webhooks/intercom/tests.py +++ b/zerver/webhooks/intercom/tests.py @@ -265,3 +265,7 @@ def test_user_unsubscribed(self) -> None: "Contact: Eeshan Garg", "User unsubscribed from emails.", ) + + def test_success_on_http_head(self) -> None: + result = self.client_head(self.url) + self.assertEqual(result.status_code, 200)
Not able to setup intercom integration Hi, I am using the intercom integration in our self hosted zulip workspace. I am receiving an error : "Hi there! It looks like you tried to set up the Zulip Intercom integration, but didn't correctly configure the webhook to send data in the JSON format that this integration expects!" I have checked the webhook from intercom and it seems to be working and sending data in a json format. The following is the ping message format : ``` { "data": { "item": { "type": "ping", "message": "This is a ping notification test message." }, "type": "notification_event_data" }, "delivery_attempts": 1, "first_sent_at": 1671643827, "topic": "ping", "created_at": 1671643827, "self": null, "links": {}, "id": null, "type": "notification_event", "app_id": "******", "delivered_at": 0, "delivery_status": null } ``` It appears to be a valid json response too
Hello @zulip/server-integrations members, this issue was labeled with the "area: integrations" label, so you may want to check it out! <!-- areaLabelAddition --> @PIG208 Would you be up for taking a look at this one? > @PIG208 Would you be up for taking a look at this one? OK, got it queued. This payload is working fine. The error message `Hi there! It looks like you tried to set up the Zulip Intercom integration, but didn't correctly configure the webhook to send data in the JSON format that this integration expects!` only gets sent when the payload is not valid JSON, which doesn't seem to be the case with "ping". Were you able to get messages for other topics? "ping" messages in particular are ignored by this integration (assuming that the request body is valid JSON). It might be the case that other requests trigger this error message, and the "ping" request gets correctly ignored. In the documentation, it was mentioned that [Intercom uses a HEAD request to validate the URL](https://developers.intercom.com/building-apps/docs/setting-up-webhooks#configuring-your-endpoint-url), which does trigger the error message here because HEAD is unexpected for the integration.
2023-01-06T11:33:50
zulip/zulip
24,216
zulip__zulip-24216
[ "24048" ]
d346b9bd1c5223c0cb2d5a3d7ec460affda14142
diff --git a/version.py b/version.py --- a/version.py +++ b/version.py @@ -33,7 +33,7 @@ # Changes should be accompanied by documentation explaining what the # new level means in api_docs/changelog.md, as well as "**Changes**" # entries in the endpoint's documentation in `zulip.yaml`. -API_FEATURE_LEVEL = 199 +API_FEATURE_LEVEL = 200 # Bump the minor PROVISION_VERSION to indicate that folks should provision # only when going from an old version of the code to a newer version. Bump diff --git a/zerver/lib/streams.py b/zerver/lib/streams.py --- a/zerver/lib/streams.py +++ b/zerver/lib/streams.py @@ -670,6 +670,7 @@ def list_to_streams( 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 process @@ -736,6 +737,10 @@ def list_to_streams( raise JsonableError(_("Insufficient permission")) if not invite_only and not user_profile.can_create_public_streams(): raise JsonableError(_("Insufficient permission")) + if is_default_stream and not user_profile.is_realm_admin: + raise JsonableError(_("Insufficient permission")) + if invite_only and is_default_stream: + raise JsonableError(_("A default stream cannot be private.")) if not autocreate: raise JsonableError( diff --git a/zerver/views/streams.py b/zerver/views/streams.py --- a/zerver/views/streams.py +++ b/zerver/views/streams.py @@ -262,6 +262,7 @@ def update_stream_backend( ), is_private: Optional[bool] = REQ(json_validator=check_bool, default=None), is_announcement_only: Optional[bool] = REQ(json_validator=check_bool, default=None), + is_default_stream: Optional[bool] = REQ(json_validator=check_bool, default=None), stream_post_policy: Optional[int] = REQ( json_validator=check_int_in(Stream.STREAM_POST_POLICY_TYPES), default=None ), @@ -290,6 +291,12 @@ def update_stream_backend( else: proposed_is_web_public = stream.is_web_public + if is_default_stream is not None: + proposed_is_default_stream = is_default_stream + else: + default_stream_ids = get_default_stream_ids_for_realm(stream.realm_id) + proposed_is_default_stream = stream.id in default_stream_ids + if stream.realm.is_zephyr_mirror_realm: # In the Zephyr mirroring model, history is unconditionally # not public to subscribers, even for public streams. @@ -319,12 +326,11 @@ def update_stream_backend( else: raise JsonableError(_("Invalid parameters")) - if is_private is not None: - # Default streams cannot be made private. - default_stream_ids = get_default_stream_ids_for_realm(stream.realm_id) - if is_private and stream.id in default_stream_ids: - raise JsonableError(_("Default streams cannot be made private.")) + # Ensure that a stream cannot be both a default stream for new users and private + if proposed_is_private and proposed_is_default_stream: + raise JsonableError(_("A default stream cannot be private.")) + if is_private is not None: # We require even realm administrators to be actually # subscribed to make a private stream public, via this # stricted access_stream check. @@ -352,6 +358,12 @@ def update_stream_backend( acting_user=user_profile, ) + if is_default_stream is not None: + if is_default_stream: + do_add_default_stream(stream) + else: + do_remove_default_stream(stream) + if message_retention_days is not None: if not user_profile.is_realm_owner: raise OrganizationOwnerRequiredError @@ -566,6 +578,7 @@ def add_subscriptions_backend( ), invite_only: bool = REQ(json_validator=check_bool, default=False), is_web_public: bool = REQ(json_validator=check_bool, default=False), + is_default_stream: bool = REQ(json_validator=check_bool, default=False), stream_post_policy: int = REQ( json_validator=check_int_in(Stream.STREAM_POST_POLICY_TYPES), default=Stream.STREAM_POST_POLICY_EVERYONE, @@ -648,7 +661,9 @@ def add_subscriptions_backend( # Validation of the streams arguments, including enforcement of # can_create_streams policy and check_stream_name policy is inside # list_to_streams. - existing_streams, created_streams = list_to_streams(stream_dicts, user_profile, autocreate=True) + existing_streams, created_streams = list_to_streams( + stream_dicts, user_profile, autocreate=True, is_default_stream=is_default_stream + ) authorized_streams, unauthorized_streams = filter_stream_authorization( user_profile, existing_streams ) @@ -670,6 +685,10 @@ def add_subscriptions_backend( _("You can only invite other Zephyr mirroring users to private streams.") ) + if is_default_stream: + for stream in created_streams: + do_add_default_stream(stream) + (subscribed, already_subscribed) = bulk_add_subscriptions( realm, streams, subscribers, acting_user=user_profile, color_map=color_map )
diff --git a/web/tests/dispatch.test.js b/web/tests/dispatch.test.js --- a/web/tests/dispatch.test.js +++ b/web/tests/dispatch.test.js @@ -293,6 +293,7 @@ run_test("custom profile fields", ({override}) => { run_test("default_streams", ({override}) => { const event = event_fixtures.default_streams; override(settings_streams, "update_default_streams_table", noop); + override(stream_settings_ui, "update_is_default_stream", noop); const stub = make_stub(); override(stream_data, "set_realm_default_streams", stub.f); dispatch(event); diff --git a/zerver/tests/test_subs.py b/zerver/tests/test_subs.py --- a/zerver/tests/test_subs.py +++ b/zerver/tests/test_subs.py @@ -383,6 +383,47 @@ def test_history_public_to_subscribers_on_stream_creation(self) -> None: if stream.name == "publictrywithouthistory": self.assertTrue(stream.history_public_to_subscribers) + def test_add_stream_as_default_on_stream_creation(self) -> None: + user_profile = self.example_user("hamlet") + self.login_user(user_profile) + realm = user_profile.realm + + post_data = { + "subscriptions": orjson.dumps( + [{"name": "default_stream", "description": "This stream is default for new users"}] + ).decode(), + "is_default_stream": orjson.dumps(True).decode(), + } + result = self.api_post( + user_profile, "/api/v1/users/me/subscriptions", post_data, subdomain="zulip" + ) + self.assert_json_error(result, "Insufficient permission") + + do_change_user_role(user_profile, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=None) + result = self.api_post( + user_profile, "/api/v1/users/me/subscriptions", post_data, subdomain="zulip" + ) + self.assert_json_success(result) + default_stream = get_stream("default_stream", realm) + self.assertTrue(default_stream.id in get_default_stream_ids_for_realm(realm.id)) + + post_data = { + "subscriptions": orjson.dumps( + [ + { + "name": "private_default_stream", + "description": "This stream is private and default for new users", + } + ] + ).decode(), + "invite_only": orjson.dumps(True).decode(), + "is_default_stream": orjson.dumps(True).decode(), + } + result = self.api_post( + user_profile, "/api/v1/users/me/subscriptions", post_data, subdomain="zulip" + ) + self.assert_json_error(result, "A default stream cannot be private.") + def test_history_public_to_subscribers_zephyr_realm(self) -> None: realm = get_realm("zephyr") @@ -714,7 +755,7 @@ def test_make_stream_private(self) -> None: "is_private": orjson.dumps(True).decode(), } result = self.client_patch(f"/json/streams/{default_stream.id}", params) - self.assert_json_error(result, "Default streams cannot be made private.") + self.assert_json_error(result, "A default stream cannot be private.") self.assertFalse(default_stream.invite_only) do_change_user_role(user_profile, UserProfile.ROLE_MEMBER, acting_user=None) @@ -1051,6 +1092,76 @@ def test_change_history_access_for_private_streams(self) -> None: ).decode() self.assertEqual(realm_audit_log.extra_data, expected_extra_data) + def test_add_and_remove_stream_as_default(self) -> None: + user_profile = self.example_user("hamlet") + self.login_user(user_profile) + realm = user_profile.realm + stream = self.make_stream("stream", realm=realm) + stream_id = self.subscribe(user_profile, "stream").id + + params = { + "is_default_stream": orjson.dumps(True).decode(), + } + result = self.client_patch(f"/json/streams/{stream_id}", params) + self.assert_json_error(result, "Must be an organization administrator") + self.assertFalse(stream_id in get_default_stream_ids_for_realm(realm.id)) + + do_change_user_role(user_profile, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=None) + result = self.client_patch(f"/json/streams/{stream_id}", params) + self.assert_json_success(result) + self.assertTrue(stream_id in get_default_stream_ids_for_realm(realm.id)) + + params = { + "is_private": orjson.dumps(True).decode(), + } + result = self.client_patch(f"/json/streams/{stream_id}", params) + self.assert_json_error(result, "A default stream cannot be private.") + stream.refresh_from_db() + self.assertFalse(stream.invite_only) + + params = { + "is_private": orjson.dumps(True).decode(), + "is_default_stream": orjson.dumps(False).decode(), + } + result = self.client_patch(f"/json/streams/{stream_id}", params) + self.assert_json_success(result) + stream.refresh_from_db() + self.assertTrue(stream.invite_only) + self.assertFalse(stream_id in get_default_stream_ids_for_realm(realm.id)) + + stream_2 = self.make_stream("stream_2", realm=realm) + stream_2_id = self.subscribe(user_profile, "stream_2").id + + bad_params = { + "is_default_stream": orjson.dumps(True).decode(), + "is_private": orjson.dumps(True).decode(), + } + result = self.client_patch(f"/json/streams/{stream_2_id}", bad_params) + self.assert_json_error(result, "A default stream cannot be private.") + stream.refresh_from_db() + self.assertFalse(stream_2.invite_only) + self.assertFalse(stream_2_id in get_default_stream_ids_for_realm(realm.id)) + + private_stream = self.make_stream("private_stream", realm=realm, invite_only=True) + private_stream_id = self.subscribe(user_profile, "private_stream").id + + params = { + "is_default_stream": orjson.dumps(True).decode(), + } + result = self.client_patch(f"/json/streams/{private_stream_id}", params) + self.assert_json_error(result, "A default stream cannot be private.") + self.assertFalse(private_stream_id in get_default_stream_ids_for_realm(realm.id)) + + params = { + "is_private": orjson.dumps(False).decode(), + "is_default_stream": orjson.dumps(True).decode(), + } + result = self.client_patch(f"/json/streams/{private_stream_id}", params) + self.assert_json_success(result) + private_stream.refresh_from_db() + self.assertFalse(private_stream.invite_only) + self.assertTrue(private_stream_id in get_default_stream_ids_for_realm(realm.id)) + def test_stream_permission_changes_updates_updates_attachments(self) -> None: self.login("desdemona") fp = StringIO("zulip!")
Add an option to make a stream default for new users in stream creation and editing UIs At present, default streams are configured via the Settings > Default streams panel. There is no indication in stream settings of whether a stream is on the default streams list. When creating a stream, a user has to navigate to a separate menu if they want to add it to the defaults. To address this, we should add a new setting to the stream creation and stream editing UI. - Setting: [checkbox] Default stream for new users, with a question mark linking to https://zulip.com/help/set-default-streams-for-new-users - Placement: - Just below "Announce stream" in stream creation UI - Just below "Who can access the stream?" in General stream panel - Set to "off" by default If user doesn't have permission to set it (currently, non-admin), the setting should be: - Not shown in stream creation UI - Shown but disabled in the General stream settings panel Additionally, https://zulip.com/help/set-default-streams-for-new-users should be updated to document this feature. This can be done as a follow-up.
Hello @zulip/server-streams members, this issue was labeled with the "area: stream settings" label, so you may want to check it out! <!-- areaLabelAddition --> @zulipbot claim Hello @Joelute, it looks like you've currently claimed 1 issue in this repository. We encourage new contributors to focus their efforts on at most 1 issue at a time, so please complete your work on your other claimed issues before trying to claim this issue again. We look forward to your valuable contributions! Hello @alya, may I be assigned to this issue? Currently my other two issues are under intergration/CZO review. I would like to work on this issue on the side while waiting. Claiming the issue since I think I can tackle it. @zulipbot claim @HemantUmre12 You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! Still working on it.
2023-01-28T20:09:24
zulip/zulip
24,219
zulip__zulip-24219
[ "23642" ]
84b4f498d58f6ee82110f24dabfb43fd7940c0d1
diff --git a/zerver/openapi/curl_param_value_generators.py b/zerver/openapi/curl_param_value_generators.py --- a/zerver/openapi/curl_param_value_generators.py +++ b/zerver/openapi/curl_param_value_generators.py @@ -126,7 +126,7 @@ def add_emoji_to_message() -> Dict[str, object]: # The message ID here is hardcoded based on the corresponding value # for the example message IDs we use in zulip.yaml. - message_id = 46 + message_id = 47 emoji_name = "octopus" emoji_code = "1f419" reaction_type = "unicode_emoji" diff --git a/zerver/views/user_groups.py b/zerver/views/user_groups.py --- a/zerver/views/user_groups.py +++ b/zerver/views/user_groups.py @@ -1,8 +1,11 @@ -from typing import Optional, Sequence +from typing import List, Optional, Sequence +from django.conf import settings from django.http import HttpRequest, HttpResponse from django.utils.translation import gettext as _ +from django.utils.translation import override as override_language +from zerver.actions.message_send import do_send_messages, internal_prep_private_message from zerver.actions.user_groups import ( add_subgroups_to_user_group, bulk_add_members_to_user_group, @@ -15,6 +18,7 @@ ) from zerver.decorator import require_member_or_admin, require_user_group_edit_permission from zerver.lib.exceptions import JsonableError +from zerver.lib.mention import MentionBackend, silent_mention_syntax_for_user from zerver.lib.request import REQ, has_request_variables from zerver.lib.response import json_success from zerver.lib.user_groups import ( @@ -29,7 +33,7 @@ ) from zerver.lib.users import access_user_by_id, user_ids_to_users from zerver.lib.validator import check_bool, check_int, check_list -from zerver.models import UserProfile +from zerver.models import UserGroup, UserProfile, get_system_bot from zerver.views.streams import compose_views @@ -115,6 +119,55 @@ def update_user_group_backend( return json_success(request, data) +def notify_for_user_group_subscription_changes( + acting_user: UserProfile, + recipient_users: List[UserProfile], + user_group: UserGroup, + *, + send_subscription_message: bool = False, + send_unsubscription_message: bool = False, +) -> None: + realm = acting_user.realm + mention_backend = MentionBackend(realm.id) + + notifications = [] + notification_bot = get_system_bot(settings.NOTIFICATION_BOT, realm.id) + for recipient_user in recipient_users: + if recipient_user.id == acting_user.id: + # Don't send notification message if you subscribed/unsubscribed yourself. + continue + if recipient_user.is_bot: + # Don't send notification message to bots. + continue + if not recipient_user.is_active: + # Don't send notification message to deactivated users. + continue + + with override_language(recipient_user.default_language): + if send_subscription_message: + message = _("{user_full_name} added you to the group {group_name}.").format( + user_full_name=silent_mention_syntax_for_user(acting_user), + group_name=f"@_*{user_group.name}*", + ) + if send_unsubscription_message: + message = _("{user_full_name} removed you from the group {group_name}.").format( + user_full_name=silent_mention_syntax_for_user(acting_user), + group_name=f"@_*{user_group.name}*", + ) + + notifications.append( + internal_prep_private_message( + sender=notification_bot, + recipient_user=recipient_user, + content=message, + mention_backend=mention_backend, + ) + ) + + if len(notifications) > 0: + do_send_messages(notifications) + + def add_members_to_group_backend( request: HttpRequest, user_profile: UserProfile, user_group_id: int, members: Sequence[int] ) -> HttpResponse: @@ -122,19 +175,25 @@ def add_members_to_group_backend( return json_success(request) user_group = access_user_group_by_id(user_group_id, user_profile) - user_profiles = user_ids_to_users(members, user_profile.realm) - existing_member_ids = set(get_direct_memberships_of_users(user_group, user_profiles)) + member_users = user_ids_to_users(members, user_profile.realm) + existing_member_ids = set(get_direct_memberships_of_users(user_group, member_users)) - for user_profile in user_profiles: - if user_profile.id in existing_member_ids: + for member_user in member_users: + if member_user.id in existing_member_ids: raise JsonableError( _("User {user_id} is already a member of this group").format( - user_id=user_profile.id, + user_id=member_user.id, ) ) - user_profile_ids = [user.id for user in user_profiles] - bulk_add_members_to_user_group(user_group, user_profile_ids, acting_user=user_profile) + member_user_ids = [member_user.id for member_user in member_users] + bulk_add_members_to_user_group(user_group, member_user_ids, acting_user=user_profile) + notify_for_user_group_subscription_changes( + acting_user=user_profile, + recipient_users=member_users, + user_group=user_group, + send_subscription_message=True, + ) return json_success(request) @@ -153,6 +212,12 @@ def remove_members_from_group_backend( user_profile_ids = [user.id for user in user_profiles] remove_members_from_user_group(user_group, user_profile_ids, acting_user=user_profile) + notify_for_user_group_subscription_changes( + acting_user=user_profile, + recipient_users=user_profiles, + user_group=user_group, + send_unsubscription_message=True, + ) return json_success(request)
diff --git a/zerver/tests/test_user_groups.py b/zerver/tests/test_user_groups.py --- a/zerver/tests/test_user_groups.py +++ b/zerver/tests/test_user_groups.py @@ -7,6 +7,8 @@ from zerver.actions.realm_settings import do_set_realm_property from zerver.actions.user_groups import check_add_user_group, promote_new_full_members +from zerver.actions.users import do_deactivate_user +from zerver.lib.mention import silent_mention_syntax_for_user from zerver.lib.streams import ensure_stream from zerver.lib.test_classes import ZulipTestCase from zerver.lib.test_helpers import most_recent_usermessage @@ -361,14 +363,27 @@ def test_update_members_of_user_group(self) -> None: self.assertEqual(UserGroupMembership.objects.filter(user_group=user_group).count(), 1) othello = self.example_user("othello") - add = [othello.id] - params = {"add": orjson.dumps(add).decode()} + # A bot + webhook_bot = self.example_user("webhook_bot") + # A deactivated user + iago = self.example_user("iago") + do_deactivate_user(iago, acting_user=None) + + params = {"add": orjson.dumps([othello.id]).decode()} + initial_last_message = self.get_last_message() result = self.client_post(f"/json/user_groups/{user_group.id}/members", info=params) self.assert_json_success(result) self.assertEqual(UserGroupMembership.objects.filter(user_group=user_group).count(), 2) members = get_direct_memberships_of_users(user_group, [hamlet, othello]) self.assert_length(members, 2) + # A notification message is sent for adding to user group. + self.assertNotEqual(self.get_last_message(), initial_last_message) + expected_notification = ( + f"{silent_mention_syntax_for_user(hamlet)} added you to the group @_*support*." + ) + self.assertEqual(self.get_last_message().content, expected_notification) + # Test adding a member already there. result = self.client_post(f"/json/user_groups/{user_group.id}/members", info=params) self.assert_json_error(result, f"User {othello.id} is already a member of this group") @@ -376,6 +391,24 @@ def test_update_members_of_user_group(self) -> None: members = get_direct_memberships_of_users(user_group, [hamlet, othello]) self.assert_length(members, 2) + # Test user adding itself,bot and deactivated user to user group. + desdemona = self.example_user("desdemona") + self.login_user(desdemona) + + params = {"add": orjson.dumps([desdemona.id, iago.id, webhook_bot.id]).decode()} + initial_last_message = self.get_last_message() + result = self.client_post(f"/json/user_groups/{user_group.id}/members", info=params) + self.assert_json_success(result) + + self.assertEqual(UserGroupMembership.objects.filter(user_group=user_group).count(), 5) + members = get_direct_memberships_of_users( + user_group, [hamlet, othello, desdemona, iago, webhook_bot] + ) + self.assert_length(members, 5) + + # No notification message is sent for adding to user group. + self.assertEqual(self.get_last_message(), initial_last_message) + aaron = self.example_user("aaron") # For normal testing we again log in with hamlet @@ -383,20 +416,44 @@ def test_update_members_of_user_group(self) -> None: self.login_user(hamlet) # Test remove members params = {"delete": orjson.dumps([othello.id]).decode()} + initial_last_message = self.get_last_message() result = self.client_post(f"/json/user_groups/{user_group.id}/members", info=params) self.assert_json_success(result) - self.assertEqual(UserGroupMembership.objects.filter(user_group=user_group).count(), 1) - members = get_direct_memberships_of_users(user_group, [hamlet, othello, aaron]) - self.assert_length(members, 1) + + self.assertEqual(UserGroupMembership.objects.filter(user_group=user_group).count(), 4) + members = get_direct_memberships_of_users( + user_group, [hamlet, othello, aaron, desdemona, webhook_bot, iago] + ) + self.assert_length(members, 4) + + # A notification message is sent for removing from user group. + self.assertNotEqual(self.get_last_message(), initial_last_message) + expected_notification = ( + f"{silent_mention_syntax_for_user(hamlet)} removed you from the group @_*support*." + ) + self.assertEqual(self.get_last_message().content, expected_notification) # Test remove a member that's already removed params = {"delete": orjson.dumps([othello.id]).decode()} result = self.client_post(f"/json/user_groups/{user_group.id}/members", info=params) self.assert_json_error(result, f"There is no member '{othello.id}' in this user group") + + # Test user remove itself,bot and deactivated user from user group. + desdemona = self.example_user("desdemona") + self.login_user(desdemona) + + params = {"delete": orjson.dumps([desdemona.id, iago.id, webhook_bot.id]).decode()} + initial_last_message = self.get_last_message() + result = self.client_post(f"/json/user_groups/{user_group.id}/members", info=params) + self.assert_json_success(result) + self.assertEqual(UserGroupMembership.objects.filter(user_group=user_group).count(), 1) - members = get_direct_memberships_of_users(user_group, [hamlet, othello, aaron]) + members = get_direct_memberships_of_users(user_group, [hamlet, othello, desdemona]) self.assert_length(members, 1) + # No notification message is sent for removing from user group. + self.assertEqual(self.get_last_message(), initial_last_message) + # Test when nothing is provided result = self.client_post(f"/json/user_groups/{user_group.id}/members", info={}) msg = 'Nothing to do. Specify at least one of "add" or "delete".'
Notify users when they are added to a group Just as we notify users when someone else adds them to a stream, we should also notify users when someone else adds them to a group, by sending a Notification Bot message. In parallel with the stream notification message ("{user_full_name} subscribed you to the stream {stream_name}."), the message text can be: "{user_full_name} subscribed you to the group @{group_name}." As the groups project (https://github.com/zulip/zulip/issues/19525) moves along, we may want to add more information to the notification, e.g. groups of which the new group is a subgroup, or something about associated permissions. [CZO discussion](https://chat.zulip.org/#narrow/stream/137-feedback/topic/inform.20user.20about.20changes.20to.20their.20profile/near/1468096)
Hello @zulip/server-bots members, this issue was labeled with the "area: bots" label, so you may want to check it out! <!-- areaLabelAddition --> @zulipbot claim Welcome to Zulip, @gopipate! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! Welcome to Zulip, @TanatornG! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @zulipbot claim @ntessi This issue cannot be claimed, as someone else is already working on it. Please see our [contributor guide](https://zulip.readthedocs.io/en/latest/overview/contributing.html#your-first-codebase-contribution) for advice on finding an issue to work on. Thanks! @gopipate, @TanatornG You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! PR has been made at [https://github.com/zulip/zulip/pull/23784](https://github.com/zulip/zulip/pull/23784) @zulipbot claim @msridhar1 This issue cannot be claimed, as someone else is already working on it. Please see our [contributor guide](https://zulip.readthedocs.io/en/latest/overview/contributing.html#your-first-codebase-contribution) for advice on finding an issue to work on. Thanks! @zulipbot claim Welcome to Zulip, @vishisht08! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @vishisht08 We noticed that you have not made any updates to this issue or linked PRs for 10 days. Please comment here if you are still actively working on it. Otherwise, we'd appreciate a quick `@zulipbot abandon` comment so that someone else can claim this issue and continue from where you left off. If we don't hear back, you will be automatically unassigned in 4 days. Thanks! <!-- inactiveWarning --> @zulipbot claim Hello @Ujjawal3, it looks like you've currently claimed 1 issue in this repository. We encourage new contributors to focus their efforts on at most 1 issue at a time, so please complete your work on your other claimed issues before trying to claim this issue again. We look forward to your valuable contributions!
2023-01-29T13:05:59
zulip/zulip
24,301
zulip__zulip-24301
[ "24082" ]
7a97ceab865b9217ec1549349ff51774aa6e5a4d
diff --git a/tools/lib/provision_inner.py b/tools/lib/provision_inner.py --- a/tools/lib/provision_inner.py +++ b/tools/lib/provision_inner.py @@ -65,6 +65,12 @@ def build_timezones_data_paths() -> List[str]: return paths +def build_landing_page_images_paths() -> List[str]: + paths = ["tools/setup/generate_landing_page_images.py"] + paths += glob.glob("static/images/landing-page/hello/original/*") + return paths + + def compilemessages_paths() -> List[str]: paths = ["zerver/management/commands/compilemessages.py"] paths += glob.glob("locale/*/LC_MESSAGES/*.po") @@ -159,6 +165,16 @@ def need_to_run_build_timezone_data() -> bool: ) +def need_to_regenerate_landing_page_images() -> bool: + if not os.path.exists("static/images/landing-page/hello/generated"): + return True + + return is_digest_obsolete( + "landing_page_images_hash", + build_landing_page_images_paths(), + ) + + def need_to_run_compilemessages() -> bool: if not os.path.exists("locale/language_name_map.json"): # User may have cleaned their Git checkout. @@ -227,6 +243,13 @@ def main(options: argparse.Namespace) -> int: else: print("No need to run `tools/setup/build_timezone_values`.") + if options.is_force or need_to_regenerate_landing_page_images(): + run(["tools/setup/generate_landing_page_images.py"]) + write_new_digest( + "landing_page_images_hash", + build_landing_page_images_paths(), + ) + if not options.is_build_release_tarball_only: # The following block is skipped when we just need the development # environment to build a release tarball. diff --git a/tools/setup/generate_landing_page_images.py b/tools/setup/generate_landing_page_images.py new file mode 100755 --- /dev/null +++ b/tools/setup/generate_landing_page_images.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +"""Generates versions of landing page images to be served in different conditions.""" + +import glob +import os +import sys +from pathlib import Path +from typing import Tuple + +from PIL import Image + +ZULIP_PATH = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +if ZULIP_PATH not in sys.path: + sys.path.append(ZULIP_PATH) + +LANDING_IMAGES_DIR = os.path.join(ZULIP_PATH, "static", "images", "landing-page", "hello") +ORIGINAL_IMAGES_DIR = os.path.join(LANDING_IMAGES_DIR, "original") +GENERATED_IMAGES_DIR = os.path.join(LANDING_IMAGES_DIR, "generated") + + +def get_x_size(size: Tuple[float, float], x: int) -> Tuple[int, int]: + return int(x / 3 * size[0]), int(x / 3 * size[1]) + + +def generate_landing_page_images() -> None: + if not os.path.exists(GENERATED_IMAGES_DIR): + os.mkdir(GENERATED_IMAGES_DIR) + + for image_file_path in glob.glob(f"{ORIGINAL_IMAGES_DIR}/*"): + file_name = Path(image_file_path).stem + with Image.open(image_file_path) as image: + size_2x = get_x_size(image.size, 2) + size_1x = get_x_size(image.size, 1) + + ## Generate WEBP images. + image.save(f"{GENERATED_IMAGES_DIR}/{file_name}-3x.webp", quality=50) + image_2x = image.resize(size_2x) + image_2x.save(f"{GENERATED_IMAGES_DIR}/{file_name}-2x.webp", quality=50) + image_1x = image.resize(size_1x) + image_1x.save(f"{GENERATED_IMAGES_DIR}/{file_name}-1x.webp", quality=70) + + ## Generate JPG images. + # Convert from RGBA to RGB since jpg doesn't support transparency. + rgb_image = image.convert("RGB") + rgb_image.save(f"{GENERATED_IMAGES_DIR}/{file_name}-3x.jpg", quality=19, optimize=True) + rgb_image_2x = rgb_image.resize(size_2x) + rgb_image_2x.save( + f"{GENERATED_IMAGES_DIR}/{file_name}-2x.jpg", quality=50, optimize=True + ) + rgb_image_1x = rgb_image.resize(size_1x) + rgb_image_1x.save( + f"{GENERATED_IMAGES_DIR}/{file_name}-1x.jpg", quality=70, optimize=True + ) + + +if __name__ == "__main__": + generate_landing_page_images()
diff --git a/zerver/tests/test_docs.py b/zerver/tests/test_docs.py --- a/zerver/tests/test_docs.py +++ b/zerver/tests/test_docs.py @@ -253,7 +253,7 @@ def test_corporate_portico_endpoints(self) -> None: # Test the i18n version of one of these pages. self._test("/en/history/", ["Zulip released as open source!"]) self._test("/values/", ["designed our company"]) - self._test("/hello/", ["Chat for distributed teams"]) + self._test("/hello/", ["your mission-critical communications with Zulip"]) self._test("/communities/", ["Open communities directory"]) self._test("/development-community/", ["Zulip development community"]) self._test("/features/", ["Beautiful messaging"]) diff --git a/zerver/tests/test_home.py b/zerver/tests/test_home.py --- a/zerver/tests/test_home.py +++ b/zerver/tests/test_home.py @@ -544,7 +544,7 @@ def test_terms_of_service_first_time_template(self) -> None: result = self.client_post("/accounts/accept_terms/") self.assertEqual(result.status_code, 200) self.assert_in_response("I agree to the", result) - self.assert_in_response("Chat for distributed teams", result) + self.assert_in_response("your mission-critical communications with Zulip", result) def test_accept_terms_of_service(self) -> None: self.login("hamlet") @@ -1045,7 +1045,7 @@ def test_subdomain_homepage(self) -> None: with patch("zerver.views.home.get_subdomain", return_value=""): result = self._get_home_page() self.assertEqual(result.status_code, 200) - self.assert_in_response("Chat for distributed teams", result) + self.assert_in_response("your mission-critical communications with Zulip", result) with patch("zerver.views.home.get_subdomain", return_value="subdomain"): result = self._get_home_page()
UI redesign: marketing /hello New design for the main page <img width="1109" alt="image" src="https://user-images.githubusercontent.com/1903309/212569694-bea47388-af85-480a-a2ce-f1d7fef0395a.png"> Repl it project, which you can fork (like a google doc copy) https://replit.com/@VladKorobov/zulip-hello-page Replit demo: https://zulip-hello-page.vladkorobov.repl.co (switch light/dark theme in your OS or in webdev tools) Video walk through: https://share.cleanshot.com/Bfqf275f **Notes**: - Favicon is updated - Links are not populated ( clarify with @alya ) - Css isn't optimized or has any styleguide - Desktop menu and mobile menu are 2 components - Probably separate Menu and Footer into separate components - Expect some changes about links/wording Archived code: [zulip-hello-page.zip](https://github.com/zulip/zulip/files/10421371/zulip-hello-page.12.zip)
Hello @zulip/design, @zulip/server-misc members, this issue was labeled with the "area: portico", "redesign" labels, so you may want to check it out! <!-- areaLabelAddition --> Hi @terpimost, I would like to collaborate and contribute to this UI redesign. PS: I am done with the installation and reading the important guides. Hey there !!! @terpimost @amanagr @technicalpickles After seeing the current interface app, I can assure you that I can give it a great makeover. please assign this to me Since this issue doesn't have a "help wanted" label, this is not open for new contributors. @Advide2001 and @Rish-it I'm not sure what exactly you are suggesting but I'm open to talk about that here https://chat.zulip.org/#narrow/pm-with/22433-Vlad-Korobov @terpimost I noticed that we need to change the "R&D org leads" privacy icon from a hash to a lock in the mobile screenshots. Could you please make that tweak? ![Screen Shot 2023-04-17 at 2 56 27 PM](https://user-images.githubusercontent.com/2090066/232619705-5f4a2be0-b772-4b6b-81ab-eb5a231a22d2.png) @amanagr You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks!
2023-02-06T04:12:18
zulip/zulip
24,659
zulip__zulip-24659
[ "24604" ]
d0dbdfa52dd35c33993b6d72647672e689a22143
diff --git a/zerver/actions/message_edit.py b/zerver/actions/message_edit.py --- a/zerver/actions/message_edit.py +++ b/zerver/actions/message_edit.py @@ -50,6 +50,7 @@ update_messages_for_topic_edit, ) from zerver.lib.types import EditHistoryEvent +from zerver.lib.url_encoding import near_stream_message_url from zerver.lib.user_message import UserMessageLite, bulk_insert_ums from zerver.lib.user_topics import get_users_with_user_topic_visibility_policy from zerver.lib.widget import is_widget_message @@ -187,6 +188,7 @@ def maybe_send_resolve_topic_notifications( def send_message_moved_breadcrumbs( + target_message: Message, user_profile: UserProfile, old_stream: Stream, old_topic: str, @@ -207,6 +209,13 @@ def send_message_moved_breadcrumbs( user_mention = silent_mention_syntax_for_user(user_profile) old_topic_link = f"#**{old_stream.name}>{old_topic}**" new_topic_link = f"#**{new_stream.name}>{new_topic}**" + message = { + "id": target_message.id, + "stream_id": new_stream.id, + "display_recipient": new_stream.name, + "topic": new_topic, + } + moved_message_link = near_stream_message_url(target_message.realm, message) if new_thread_notification_string is not None: with override_language(new_stream.realm.default_language): @@ -215,6 +224,7 @@ def send_message_moved_breadcrumbs( new_stream, new_topic, new_thread_notification_string.format( + message_link=moved_message_link, old_location=old_topic_link, user=user_mention, changed_messages_count=changed_messages_count, @@ -925,7 +935,7 @@ def user_info(um: UserMessage) -> Dict[str, Any]: else: if changed_messages_count == 1: new_thread_notification_string = gettext_lazy( - "A message was moved here from {old_location} by {user}." + "[A message]({message_link}) was moved here from {old_location} by {user}." ) else: new_thread_notification_string = gettext_lazy( @@ -933,6 +943,7 @@ def user_info(um: UserMessage) -> Dict[str, Any]: ) send_message_moved_breadcrumbs( + target_message, user_profile, stream_being_edited, orig_topic_name,
diff --git a/zerver/tests/test_message_edit.py b/zerver/tests/test_message_edit.py --- a/zerver/tests/test_message_edit.py +++ b/zerver/tests/test_message_edit.py @@ -21,6 +21,7 @@ from zerver.lib.test_classes import ZulipTestCase, get_topic_messages from zerver.lib.test_helpers import cache_tries_captured, queries_captured from zerver.lib.topic import RESOLVED_TOPIC_PREFIX, TOPIC_NAME +from zerver.lib.url_encoding import near_stream_message_url from zerver.lib.user_topics import ( get_users_with_user_topic_visibility_policy, set_topic_visibility_policy, @@ -2322,11 +2323,18 @@ def test_move_message_to_stream_change_one(self) -> None: ) messages = get_topic_messages(user_profile, new_stream, "test") + message = { + "id": msg_id_later, + "stream_id": new_stream.id, + "display_recipient": new_stream.name, + "topic": "test", + } + moved_message_link = near_stream_message_url(messages[1].realm, message) self.assert_length(messages, 2) self.assertEqual(messages[0].id, msg_id_later) self.assertEqual( messages[1].content, - f"A message was moved here from #**test move stream>test** by @_**Iago|{user_profile.id}**.", + f"[A message]({moved_message_link}) was moved here from #**test move stream>test** by @_**Iago|{user_profile.id}**.", ) def test_move_message_to_preexisting_topic_change_one(self) -> None: @@ -2360,11 +2368,18 @@ def test_move_message_to_preexisting_topic_change_one(self) -> None: ) messages = get_topic_messages(user_profile, new_stream, "test") + message = { + "id": msg_id_later, + "stream_id": new_stream.id, + "display_recipient": new_stream.name, + "topic": "test", + } + moved_message_link = near_stream_message_url(messages[2].realm, message) self.assert_length(messages, 3) self.assertEqual(messages[0].id, msg_id_later) self.assertEqual( messages[2].content, - f"A message was moved here from #**test move stream>test** by @_**Iago|{user_profile.id}**.", + f"[A message]({moved_message_link}) was moved here from #**test move stream>test** by @_**Iago|{user_profile.id}**.", ) def test_move_message_to_stream_change_all(self) -> None: @@ -3130,11 +3145,18 @@ def test_notify_new_topics_after_message_move(self) -> None: self.assertEqual(messages[1].content, "Third") messages = get_topic_messages(user_profile, stream, "edited") + message = { + "id": msg_id, + "stream_id": stream.id, + "display_recipient": stream.name, + "topic": "edited", + } + moved_message_link = near_stream_message_url(messages[1].realm, message) self.assert_length(messages, 2) self.assertEqual(messages[0].content, "First") self.assertEqual( messages[1].content, - f"A message was moved here from #**public stream>test** by @_**Iago|{user_profile.id}**.", + f"[A message]({moved_message_link}) was moved here from #**public stream>test** by @_**Iago|{user_profile.id}**.", ) def test_notify_old_topics_after_message_move(self) -> None: @@ -3206,11 +3228,18 @@ def test_notify_both_topics_after_message_move(self) -> None: ) messages = get_topic_messages(user_profile, stream, "edited") + message = { + "id": msg_id, + "stream_id": stream.id, + "display_recipient": stream.name, + "topic": "edited", + } + moved_message_link = near_stream_message_url(messages[0].realm, message) self.assert_length(messages, 2) self.assertEqual(messages[0].content, "First") self.assertEqual( messages[1].content, - f"A message was moved here from #**public stream>test** by @_**Iago|{user_profile.id}**.", + f"[A message]({moved_message_link}) was moved here from #**public stream>test** by @_**Iago|{user_profile.id}**.", ) def test_notify_no_topic_after_message_move(self) -> None:
Link to moved message As [suggested on CZO](https://chat.zulip.org/#narrow/stream/137-feedback/topic/Moving.20message.20link.20to.20message.28s.29.3F/near/1519423), when Notification Bot sends a noitce about a single moved message to the stream that it was moved to, it would be helpful to link to the new location of the message: > `"[A message](new message URL) was moved here from..."` (Currently there is no link on "A message".)
Hello @zulip/server-bots members, this issue was labeled with the "area: bots" label, so you may want to check it out! <!-- areaLabelAddition --> @zulipbot claim Hey, can i work on this issue? @KousikRoy-EC I’m working > @KousikRoy-EC I’m working How to download and run the code? Can you help?
2023-03-12T17:43:15
zulip/zulip
24,673
zulip__zulip-24673
[ "24536" ]
d693b53aa61d4aa39beec2cc5609602ee5ee2fc8
diff --git a/zerver/webhooks/github/view.py b/zerver/webhooks/github/view.py --- a/zerver/webhooks/github/view.py +++ b/zerver/webhooks/github/view.py @@ -73,13 +73,18 @@ def get_opened_or_update_pull_request_body(helper: Helper) -> str: changes = payload.get("changes", {}) if "body" in changes or action == "opened": description = pull_request["body"].tame(check_none_or(check_string)) + target_branch = None + base_branch = None + if action == "opened" or action == "merged": + target_branch = pull_request["head"]["label"].tame(check_string) + base_branch = pull_request["base"]["label"].tame(check_string) return get_pull_request_event_message( get_sender_name(payload), action, pull_request["html_url"].tame(check_string), - target_branch=pull_request["head"]["ref"].tame(check_string), - base_branch=pull_request["base"]["ref"].tame(check_string), + target_branch=target_branch, + base_branch=base_branch, message=description, assignee=assignee, number=pull_request["number"].tame(check_int),
diff --git a/zerver/webhooks/github/tests.py b/zerver/webhooks/github/tests.py --- a/zerver/webhooks/github/tests.py +++ b/zerver/webhooks/github/tests.py @@ -157,12 +157,12 @@ def test_member_msg(self) -> None: self.check_webhook("member", TOPIC_REPO, expected_message) def test_pull_request_opened_msg(self) -> None: - expected_message = "baxterthehacker opened [PR #1](https://github.com/baxterthehacker/public-repo/pull/1) from `changes` to `master`:\n\n~~~ quote\nThis is a pretty simple change that we need to pull into master.\n~~~" + expected_message = "baxterthehacker opened [PR #1](https://github.com/baxterthehacker/public-repo/pull/1) from `baxterthehacker:changes` to `baxterthehacker:master`:\n\n~~~ quote\nThis is a pretty simple change that we need to pull into master.\n~~~" self.check_webhook("pull_request__opened", TOPIC_PR, expected_message) def test_pull_request_opened_with_preassigned_assignee_msg(self) -> None: expected_topic = "Scheduler / PR #4 Improve README" - expected_message = "eeshangarg opened [PR #4](https://github.com/eeshangarg/Scheduler/pull/4) (assigned to eeshangarg) from `improve-readme-2` to `master`." + expected_message = "eeshangarg opened [PR #4](https://github.com/eeshangarg/Scheduler/pull/4) (assigned to eeshangarg) from `eeshangarg:improve-readme-2` to `eeshangarg:master`." self.check_webhook( "pull_request__opened_with_preassigned_assignee", expected_topic, expected_message ) @@ -170,11 +170,11 @@ def test_pull_request_opened_with_preassigned_assignee_msg(self) -> None: def test_pull_request_opened_msg_with_custom_topic_in_url(self) -> None: self.url = self.build_webhook_url(topic="notifications") expected_topic = "notifications" - expected_message = "baxterthehacker opened [PR #1 Update the README with new information](https://github.com/baxterthehacker/public-repo/pull/1) from `changes` to `master`:\n\n~~~ quote\nThis is a pretty simple change that we need to pull into master.\n~~~" + expected_message = "baxterthehacker opened [PR #1 Update the README with new information](https://github.com/baxterthehacker/public-repo/pull/1) from `baxterthehacker:changes` to `baxterthehacker:master`:\n\n~~~ quote\nThis is a pretty simple change that we need to pull into master.\n~~~" self.check_webhook("pull_request__opened", expected_topic, expected_message) def test_pull_request_synchronized_msg(self) -> None: - expected_message = "baxterthehacker updated [PR #1](https://github.com/baxterthehacker/public-repo/pull/1) from `changes` to `master`." + expected_message = "baxterthehacker updated [PR #1](https://github.com/baxterthehacker/public-repo/pull/1)." self.check_webhook("pull_request__synchronized", TOPIC_PR, expected_message) def test_pull_request_closed_msg(self) -> None: @@ -282,15 +282,17 @@ def test_push_tag_msg(self) -> None: self.check_webhook("push__tag", TOPIC_REPO, expected_message) def test_pull_request_edited_msg(self) -> None: - expected_message = "baxterthehacker edited [PR #1](https://github.com/baxterthehacker/public-repo/pull/1) from `changes` to `master`." + expected_message = ( + "baxterthehacker edited [PR #1](https://github.com/baxterthehacker/public-repo/pull/1)." + ) self.check_webhook("pull_request__edited", TOPIC_PR, expected_message) def test_pull_request_edited_with_body_change(self) -> None: - expected_message = "cozyrohan edited [PR #1](https://github.com/cozyrohan/public-repo/pull/1) from `issue-#1` to `main`:\n\n~~~ quote\nPR EDITED\n~~~" + expected_message = "cozyrohan edited [PR #1](https://github.com/cozyrohan/public-repo/pull/1):\n\n~~~ quote\nPR EDITED\n~~~" self.check_webhook("pull_request__edited_with_body_change", TOPIC_PR, expected_message) def test_pull_request_synchronized_with_body(self) -> None: - expected_message = "baxterthehacker updated [PR #1](https://github.com/baxterthehacker/public-repo/pull/1) from `changes` to `master`." + expected_message = "baxterthehacker updated [PR #1](https://github.com/baxterthehacker/public-repo/pull/1)." self.check_webhook("pull_request__synchronized_with_body", TOPIC_PR, expected_message) def test_pull_request_assigned_msg(self) -> None:
GitHub bot should leave out branch names on pull request events Here's an [example message](https://chat.zulip.org/#narrow/stream/243-mobile-team/topic/zulip-flutter/near/1515826) from the GitHub bot: > gnprice updated [PR #17 Start writing unit tests](https://github.com/zulip/zulip-flutter/pull/17) from `pr-tests` to `main`. This wording is confusing to the point of being wrong: despite the use of the verb "updated", it's not the case that in any sense the PR was `pr-tests`, and became `main` instead. We should remove these branch names from the pull-request events. The "from" branch is never interesting. The "to" branch could be relevant on the "PR created" events, but isn't essential there, and never belongs on any of the other events. @timabbott writes: > The only place we use that language is in the `get_pull_request_event_message`, with this block: and quotes: ```py PULL_REQUEST_BRANCH_INFO_TEMPLATE = "from `{target}` to `{base}`" if target_branch and base_branch: branch_info = PULL_REQUEST_BRANCH_INFO_TEMPLATE.format( target=target_branch, base=base_branch, ) main_message = f"{main_message} {branch_info}" ``` So the simplest fix is to just delete that code. See [chat thread](https://chat.zulip.org/#narrow/stream/9-issues/topic/GitHub.20bot.20wording/near/1515830).
@zulipbot claim Hello @Aryanryn09! Thanks for your interest in Zulip! You have attempted to claim an issue without the label "help wanted". You can only claim and submit pull requests for issues with the [help wanted](https://github.com/zulip/zulip/issues?q=is%3Aopen+is%3Aissue+no%3Aassignee+label%3A%22help+wanted%22) label. If this is your first time here, we recommend reading our [guide for new contributors](https://zulip.readthedocs.io/en/latest/overview/contributing.html) before getting started. Hey @gnprice **I want to contribute in it should I have to replace the main_message or remove this line form the code PULL_REQUEST_BRANCH_INFO_TEMPLATE = "from `{target}` to `{base}`" or should I have to delete these four all code including the if conditions to fix this problem ?** Please Guide me its my first time. > **should I have to replace the main_message or remove this line form the code PULL_REQUEST_BRANCH_INFO_TEMPLATE = "from `{target}` to `{base}`" or should I have to delete these four all code including the if conditions to fix this problem ?** Please Guide me its my first time. The goal is to stop including the text "from `…` to `…`" in the output. You should first make sure you have your development environment set up, and that you can reproduce the wrong behavior where it includes that text. Then make changes to the code mentioned above, and confirm that what you do causes it to stop having that behavior. See the [Zulip contributing guide](https://zulip.readthedocs.io/en/latest/contributing/contributing.html) for how to get help on any of that. @gnprice should I proceed for the PR? See our guide to picking an issue to work on: https://zulip.readthedocs.io/en/latest/contributing/contributing.html#picking-an-issue-to-work-on If you have questions, better to ask them [in chat](https://zulip.com/development-community/) — more people will be able to answer there, and it's a better place for discussions anyway. @zulipbot claim @zulipbot claim @Aryanryn09 This issue cannot be claimed, as someone else is already working on it. Please see our [contributor guide](https://zulip.readthedocs.io/en/latest/overview/contributing.html#your-first-codebase-contribution) for advice on finding an issue to work on. Thanks!
2023-03-13T21:32:37
zulip/zulip
24,711
zulip__zulip-24711
[ "24208" ]
64584557b296acd95c7c3e3cee301f5bd2c2e368
diff --git a/zerver/lib/markdown/tabbed_sections.py b/zerver/lib/markdown/tabbed_sections.py --- a/zerver/lib/markdown/tabbed_sections.py +++ b/zerver/lib/markdown/tabbed_sections.py @@ -93,6 +93,8 @@ "user": "User", "bot": "Bot", "on-sign-up": "On sign-up", + "via-markdown": "Via Markdown", + "via-compose-box-buttons": "Via compose box buttons", }
Add "Writing messages" section to help center In order to clearly document all the cool things you can do in a Zulip message, and make this information easy to find, we should add a new "Writing messages" help center section (just above "Sending messages"). Tasks: - [ ] Move the following pages from "Sending messages" to "Writing messages" (we can preserve the order): [Message formatting](https://zulip.com/help/format-your-message-using-markdown) [Mention a user or group](https://zulip.com/help/mention-a-user-or-group) [Emoji and emoticons](https://zulip.com/help/emoji-and-emoticons) [Start a video call](https://zulip.com/help/start-a-call) [Share and upload files](https://zulip.com/help/share-and-upload-files) [Quote and reply](https://zulip.com/help/quote-and-reply) [Code blocks](https://zulip.com/help/code-blocks) [Add GIFs in your message](https://zulip.com/help/animated-gifs-from-giphy) [Create a poll](https://zulip.com/help/create-a-poll) - [ ] Make sure the pages on that list that overlap with "Message formatting" use `include` blocks -- e.g., I noticed that "Code blocks" duplicates content. - [ ] Create a new page corresponding to each section of `/help/format-your-message-using-markdown` that currently doesn't have a page. - Use `include` blocks; we want to keep the all-in-one reference page as well. - Page names will be a bit different from section names, e.g., "Insert a link" for "Links". [CZO discussion](https://chat.zulip.org/#narrow/stream/19-documentation/topic/message.20formatting/near/1497280)
Hello @zulip/server-user-docs members, this issue was labeled with the "area: documentation (user)" label, so you may want to check it out! <!-- areaLabelAddition --> @drrosa Would you be up for taking this on? Follow-up issue: #24209 Hello Alya is it ok if I take up this issue ? @zulipbot claim Welcome to Zulip, @MashyBasker! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! Hi @MashyBasker , when do you plan to put up a PR for this issue? We'd like to get it done soon, so it would be best if @drrosa worked on it if it will be more than another couple of days. Thanks! > ok sure @zulipbot abandon @zulipbot claim
2023-03-15T23:18:43
zulip/zulip
24,900
zulip__zulip-24900
[ "24900" ]
16aa7c09238c893c5485eae33eb2133267a6a0ad
diff --git a/zerver/views/streams.py b/zerver/views/streams.py --- a/zerver/views/streams.py +++ b/zerver/views/streams.py @@ -619,6 +619,21 @@ def add_subscriptions_backend( stream_dicts.append(stream_dict_copy) + is_subscribing_other_users = False + if len(principals) > 0 and not all(user_id == user_profile.id for user_id in principals): + is_subscribing_other_users = True + + if is_subscribing_other_users: + if not user_profile.can_subscribe_other_users(): + # Guest users case will not be handled here as it will + # be handled by the decorator above. + raise JsonableError(_("Insufficient permission")) + subscribers = { + principal_to_user_profile(user_profile, principal) for principal in principals + } + else: + subscribers = {user_profile} + # Validation of the streams arguments, including enforcement of # can_create_streams policy and check_stream_name policy is inside # list_to_streams. @@ -635,20 +650,14 @@ def add_subscriptions_backend( # Newly created streams are also authorized for the creator streams = authorized_streams + created_streams - if len(principals) > 0: - if realm.is_zephyr_mirror_realm and not all(stream.invite_only for stream in streams): - raise JsonableError( - _("You can only invite other Zephyr mirroring users to private streams.") - ) - if not user_profile.can_subscribe_other_users(): - # Guest users case will not be handled here as it will - # be handled by the decorator above. - raise JsonableError(_("Insufficient permission")) - subscribers = { - principal_to_user_profile(user_profile, principal) for principal in principals - } - else: - subscribers = {user_profile} + if ( + is_subscribing_other_users + and realm.is_zephyr_mirror_realm + and not all(stream.invite_only for stream in streams) + ): + raise JsonableError( + _("You can only invite other Zephyr mirroring users to private streams.") + ) (subscribed, already_subscribed) = bulk_add_subscriptions( realm, streams, subscribers, acting_user=user_profile, color_map=color_map
diff --git a/zerver/tests/test_subs.py b/zerver/tests/test_subs.py --- a/zerver/tests/test_subs.py +++ b/zerver/tests/test_subs.py @@ -4422,7 +4422,7 @@ def test_multi_user_subscription(self) -> None: # Now add ourselves with self.capture_send_event_calls(expected_num_events=2) as events: - with self.assert_database_query_count(13): + with self.assert_database_query_count(12): self.common_subscribe_to_streams( self.test_user, streams_to_sub, @@ -4731,28 +4731,36 @@ def test_users_getting_remove_peer_event(self) -> None: def test_bulk_subscribe_MIT(self) -> None: mit_user = self.mit_user("starnine") + num_streams = 15 realm = get_realm("zephyr") - stream_names = [f"stream_{i}" for i in range(40)] + stream_names = [f"stream_{i}" for i in range(num_streams)] streams = [self.make_stream(stream_name, realm=realm) for stream_name in stream_names] for stream in streams: stream.is_in_zephyr_realm = True stream.save() - # Make sure Zephyr mirroring realms such as MIT do not get - # any tornado subscription events - with self.capture_send_event_calls(expected_num_events=0): - with self.assert_database_query_count(5): + # Verify that peer_event events are never sent in Zephyr + # realm. This does generate stream creation events from + # send_stream_creation_events_for_private_streams. + with self.capture_send_event_calls(expected_num_events=num_streams + 1) as events: + with self.assert_database_query_count(num_streams + 12): self.common_subscribe_to_streams( mit_user, stream_names, dict(principals=orjson.dumps([mit_user.id]).decode()), subdomain="zephyr", - allow_fail=True, ) + # num_streams stream creation events: + self.assertEqual( + {(event["event"]["type"], event["event"]["op"]) for event in events[0:num_streams]}, + {("stream", "create")}, + ) + # Followed by one subscription event: + self.assertEqual(events[num_streams]["event"]["type"], "subscription") - with self.capture_send_event_calls(expected_num_events=0): + with self.capture_send_event_calls(expected_num_events=1): bulk_remove_subscriptions( realm, users=[mit_user], @@ -4760,6 +4768,31 @@ def test_bulk_subscribe_MIT(self) -> None: acting_user=None, ) + def test_subscribe_others_to_public_stream_in_zephyr_realm(self) -> None: + """ + Users cannot be subscribed to public streams by other users in zephyr realm. + """ + starnine = self.mit_user("starnine") + espuser = self.mit_user("espuser") + + realm = get_realm("zephyr") + stream = self.make_stream("stream_1", realm=realm) + stream.is_in_zephyr_realm = True + stream.save() + + result = self.common_subscribe_to_streams( + starnine, + ["stream_1"], + dict(principals=orjson.dumps([starnine.id, espuser.id]).decode()), + subdomain="zephyr", + allow_fail=True, + ) + self.assert_json_error( + result, + "You can only invite other Zephyr mirroring users to private streams.", + status_code=400, + ) + def test_bulk_subscribe_many(self) -> None: # Create a whole bunch of streams streams = [f"stream_{i}" for i in range(30)]
streams: Fixes issue in stream creation. This PR fixes issue in stream creation. <!-- Describe your pull request here.--> [CZO discussion](https://chat.zulip.org/#narrow/stream/9-issues/topic/Issue.20in.20stream.20creation) <!-- If the PR makes UI changes, always include one or more still screenshots to demonstrate your changes. If it seems helpful, add a screen capture of the new functionality as well. Tooling tips: https://zulip.readthedocs.io/en/latest/tutorials/screenshot-and-gif-software.html --> **Screenshots and screen captures:** Stream Creation form when user cannot subscribe other users. ![Screenshot from 2023-05-11 13-23-55](https://github.com/zulip/zulip/assets/99073049/d290be46-455c-4176-aa69-87ec2916cc2d) ![Screenshot from 2023-05-11 13-23-52](https://github.com/zulip/zulip/assets/99073049/0585cdaa-e60a-4314-bdf7-bf641123c601) Stream edit when user cannot subscribe other users. ![Screenshot from 2023-05-11 13-24-11](https://github.com/zulip/zulip/assets/99073049/f954d24c-af36-4ea7-9ecb-ea1ee30b8e84) <details> <summary>Self-review checklist</summary> <!-- Prior to submitting a PR, follow our step-by-step guide to review your own code: https://zulip.readthedocs.io/en/latest/contributing/code-reviewing.html#how-to-review-code --> <!-- Once you create the PR, check off all the steps below that you have completed. If any of these steps are not relevant or you have not completed, leave them unchecked.--> - [x] [Self-reviewed](https://zulip.readthedocs.io/en/latest/contributing/code-reviewing.html#how-to-review-code) the changes for clarity and maintainability (variable names, code reuse, readability, etc.). Communicate decisions, questions, and potential concerns. - [x] Explains differences from previous plans (e.g., issue description). - [x] Highlights technical choices and bugs encountered. - [x] Calls out remaining decisions and concerns. - [x] Automated tests verify logic where appropriate. Individual commits are ready for review (see [commit discipline](https://zulip.readthedocs.io/en/latest/contributing/commit-discipline.html)). - [x] Each commit is a coherent idea. - [x] Commit message(s) explain reasoning and motivation for changes. Completed manual review and testing of the following: - [x] Visual appearance of the changes. - [x] Responsiveness and internationalization. - [x] Strings and tooltips. - [x] End-to-end functionality of buttons, interactions and flows. - [x] Corner cases, error conditions, and easily imagined bugs. </details>
@sahil839 please review this PR. > I am not sure we discussed about hiding or disabling the add subscribers widget in stream creation form. I like the idea of hiding it, but am not sure what is the best solution. @alya FYI. Hm, I think we need some way to communicate to the user that they don't have permissions to add subscribers. It's probably fine to disable the user input field, "Add" button, and the "Add all users" button, with the same tooltip as on the the "Edit stream" panel. That might be simplest, and then we won't have to adjust the filter location? @Ujjawal3 can you update the PR to fix the tests and post a comment mentioning the updates when it is ready for review? Would be good to fix this issue soon. > @Ujjawal3 can you update the PR to fix the tests and post a comment mentioning the updates when it is ready for review? Would be good to fix this issue soon. I was busy with my college exams since last week so could not do much contributions. But tomorrow they will finish so will work after that. @sahil839 I have updated the PR and addressed all your comments. Also now add subscriber section is disabled in stream creation form. Please have a look. @sahil839 I have updated the PR and addressed your comments. Please have a look.
2023-03-28T17:44:56
zulip/zulip
24,971
zulip__zulip-24971
[ "24676" ]
7ca08cb84bb9eee7005b62bc27a574d1de6db1e1
diff --git a/zerver/webhooks/github/view.py b/zerver/webhooks/github/view.py --- a/zerver/webhooks/github/view.py +++ b/zerver/webhooks/github/view.py @@ -490,6 +490,7 @@ def get_pull_request_review_body(helper: Helper) -> str: url=payload["review"]["html_url"].tame(check_string), type="PR review", title=title if include_title else None, + message=payload["review"]["body"].tame(check_string), )
diff --git a/zerver/webhooks/github/tests.py b/zerver/webhooks/github/tests.py --- a/zerver/webhooks/github/tests.py +++ b/zerver/webhooks/github/tests.py @@ -240,13 +240,13 @@ def test_status_with_target_url_msg(self) -> None: self.check_webhook("status__with_target_url", TOPIC_REPO, expected_message) def test_pull_request_review_msg(self) -> None: - expected_message = "baxterthehacker submitted [PR review](https://github.com/baxterthehacker/public-repo/pull/1#pullrequestreview-2626884)." + expected_message = "baxterthehacker submitted [PR review](https://github.com/baxterthehacker/public-repo/pull/1#pullrequestreview-2626884):\n\n~~~ quote\nLooks great!\n~~~" self.check_webhook("pull_request_review", TOPIC_PR, expected_message) def test_pull_request_review_msg_with_custom_topic_in_url(self) -> None: self.url = self.build_webhook_url(topic="notifications") expected_topic = "notifications" - expected_message = "baxterthehacker submitted [PR review for #1 Update the README with new information](https://github.com/baxterthehacker/public-repo/pull/1#pullrequestreview-2626884)." + expected_message = "baxterthehacker submitted [PR review for #1 Update the README with new information](https://github.com/baxterthehacker/public-repo/pull/1#pullrequestreview-2626884):\n\n~~~ quote\nLooks great!\n~~~" self.check_webhook("pull_request_review", expected_topic, expected_message) def test_pull_request_review_comment_msg(self) -> None:
Show PR review content in GitHub "submitted PR review" events Here's [an example message](https://chat.zulip.org/#narrow/stream/243-mobile-team/topic/zulip-flutter/near/1523925) from the GitHub bot: > gnprice submitted [PR review for #25 Add personal user_id & full_name data, updating latter via events & in UI](https://github.com/zulip/zulip-flutter/pull/25#pullrequestreview-1338016589). That's well and good as far as it goes. But that PR review had a body in it, with some text. That text is an important part of the review, so the GitHub bot should include it in its message.
Hello @zulip/server-integrations members, this issue was labeled with the "area: integrations" label, so you may want to check it out! <!-- areaLabelAddition --> @zulipbot claim Hello @Naman-sharma00100, it looks like you've currently claimed 1 issue in this repository. We encourage new contributors to focus their efforts on at most 1 issue at a time, so please complete your work on your other claimed issues before trying to claim this issue again. We look forward to your valuable contributions! @zulipbot claim @Naman-sharma00100 You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! hi @gnprice , i am still new to open source contribution so i have some doubts , here u are suggesting that when u do PR review , the github bot is only showing the message but leaving the content (body) right . if so, can you give me some advice about how to do this? thx in advance:) @zulipbot claim Welcome to Zulip, @sbansal1999! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)!
2023-04-03T17:07:52
zulip/zulip
24,986
zulip__zulip-24986
[ "24980" ]
0d4dcc858351405dd286e9bb156fd409121b968e
diff --git a/version.py b/version.py --- a/version.py +++ b/version.py @@ -33,7 +33,7 @@ # Changes should be accompanied by documentation explaining what the # new level means in api_docs/changelog.md, as well as "**Changes**" # entries in the endpoint's documentation in `zulip.yaml`. -API_FEATURE_LEVEL = 170 +API_FEATURE_LEVEL = 171 # Bump the minor PROVISION_VERSION to indicate that folks should provision # only when going from an old version of the code to a newer version. Bump diff --git a/zerver/views/auth.py b/zerver/views/auth.py --- a/zerver/views/auth.py +++ b/zerver/views/auth.py @@ -1000,7 +1000,10 @@ def api_fetch_api_key( api_key = process_api_key_fetch_authenticate_result(request, user_profile) - return json_success(request, data={"api_key": api_key, "email": user_profile.delivery_email}) + return json_success( + request, + data={"api_key": api_key, "email": user_profile.delivery_email, "user_id": user_profile.id}, + ) def get_auth_backends_data(request: HttpRequest) -> Dict[str, Any]: diff --git a/zerver/views/development/dev_login.py b/zerver/views/development/dev_login.py --- a/zerver/views/development/dev_login.py +++ b/zerver/views/development/dev_login.py @@ -135,7 +135,10 @@ def api_dev_fetch_api_key(request: HttpRequest, username: str = REQ()) -> HttpRe do_login(request, user_profile) api_key = get_api_key(user_profile) - return json_success(request, data={"api_key": api_key, "email": user_profile.delivery_email}) + return json_success( + request, + data={"api_key": api_key, "email": user_profile.delivery_email, "user_id": user_profile.id}, + ) @csrf_exempt
diff --git a/zerver/tests/test_auth_backends.py b/zerver/tests/test_auth_backends.py --- a/zerver/tests/test_auth_backends.py +++ b/zerver/tests/test_auth_backends.py @@ -4460,7 +4460,8 @@ def test_success(self) -> None: "/api/v1/fetch_api_key", dict(username=self.email, password=initial_password(self.email)), ) - self.assert_json_success(result) + json_response = self.assert_json_success(result) + self.assertEqual(json_response["user_id"], self.user_profile.id) def test_invalid_email(self) -> None: result = self.client_post( @@ -4500,7 +4501,8 @@ def test_ldap_auth_email_auth_disabled_success(self) -> None: "/api/v1/fetch_api_key", dict(username=self.example_email("hamlet"), password=self.ldap_password("hamlet")), ) - self.assert_json_success(result) + json_response = self.assert_json_success(result) + self.assertEqual(json_response["user_id"], self.user_profile.id) @override_settings( AUTHENTICATION_BACKENDS=("zproject.backends.ZulipLDAPAuthBackend",), @@ -4530,7 +4532,8 @@ def test_ldap_auth_email_auth_organization_restriction(self) -> None: "/api/v1/fetch_api_key", dict(username="hamlet", password=self.ldap_password("hamlet")), ) - self.assert_json_success(result) + json_response = self.assert_json_success(result) + self.assertEqual(json_response["user_id"], self.user_profile.id) @override_settings( AUTHENTICATION_BACKENDS=("zproject.backends.ZulipLDAPAuthBackend",), @@ -4663,6 +4666,7 @@ def test_success(self) -> None: result = self.client_post("/api/v1/dev_fetch_api_key", dict(username=self.email)) data = self.assert_json_success(result) self.assertEqual(data["email"], self.email) + self.assertEqual(data["user_id"], self.user_profile.id) user_api_keys = get_all_api_keys(self.user_profile) self.assertIn(data["api_key"], user_api_keys)
Include user ID in fetch-api-key response We should add one additional property to the response of the fetch-api-key endpoint (https://chat.zulip.org/api/fetch-api-key): the user's user ID. See [chat thread](https://chat.zulip.org/#narrow/stream/378-api-design/topic/user.20ID.20in.20fetch-api-key/near/1540592) for motivation and discussion.
Hello @zulip/server-api, @zulip/server-authentication members, this issue was labeled with the "area: authentication", "area: api" labels, so you may want to check it out! <!-- areaLabelAddition -->
2023-04-04T11:10:51
zulip/zulip
25,003
zulip__zulip-25003
[ "24806" ]
77ae3176cac2303966c34eb6b96e70bd55a42890
diff --git a/version.py b/version.py --- a/version.py +++ b/version.py @@ -33,7 +33,7 @@ # Changes should be accompanied by documentation explaining what the # new level means in api_docs/changelog.md, as well as "**Changes**" # entries in the endpoint's documentation in `zulip.yaml`. -API_FEATURE_LEVEL = 176 +API_FEATURE_LEVEL = 177 # Bump the minor PROVISION_VERSION to indicate that folks should provision # only when going from an old version of the code to a newer version. Bump diff --git a/zerver/lib/narrow.py b/zerver/lib/narrow.py --- a/zerver/lib/narrow.py +++ b/zerver/lib/narrow.py @@ -12,6 +12,7 @@ Mapping, Optional, Sequence, + Set, Tuple, TypeVar, Union, @@ -133,7 +134,7 @@ def is_web_public_narrow(narrow: Optional[Iterable[Dict[str, Any]]]) -> bool: def build_narrow_filter(narrow: Collection[Sequence[str]]) -> Callable[[Mapping[str, Any]], bool]: """Changes to this function should come with corresponding changes to - BuildNarrowFilterTest.""" + NarrowLibraryTest.""" check_supported_events_narrow_filter(narrow) def narrow_filter(event: Mapping[str, Any]) -> bool: @@ -156,7 +157,8 @@ def narrow_filter(event: Mapping[str, Any]) -> bool: elif operator == "sender": if operand.lower() != message["sender_email"].lower(): return False - elif operator == "is" and operand == "private": + elif operator == "is" and operand in ["dm", "private"]: + # "is:private" is a legacy alias for "is:dm" if message["type"] != "private": return False elif operator == "is" and operand in ["starred"]: @@ -267,14 +269,18 @@ def __init__( "near": self.by_near, "id": self.by_id, "search": self.by_search, - "pm-with": self.by_pm_with, + "dm": self.by_dm, + # "pm-with:" is a legacy alias for "dm:" + "pm-with": self.by_dm, + "dm-including": self.by_dm_including, + # "group-pm-with:" was deprecated by the addition of "dm-including:" "group-pm-with": self.by_group_pm_with, # TODO/compatibility: Prior to commit a9b3a9c, the server implementation # for documented search operators with dashes, also implicitly supported # clients sending those same operators with underscores. We can remove # support for the below operators when support for the associated dashed # operator is removed. - "pm_with": self.by_pm_with, + "pm_with": self.by_dm, "group_pm_with": self.by_group_pm_with, } @@ -336,7 +342,8 @@ def by_is(self, query: Select, operand: str, maybe_negate: ConditionTransform) - assert not self.is_web_public_query assert self.user_profile is not None - if operand == "private": + if operand in ["dm", "private"]: + # "is:private" is a legacy alias for "is:dm" cond = column("flags", Integer).op("&")(UserMessage.flags.is_private.mask) != 0 return query.where(maybe_negate(cond)) elif operand == "starred": @@ -506,7 +513,7 @@ def by_id( cond = self.msg_id_column == literal(operand) return query.where(maybe_negate(cond)) - def by_pm_with( + def by_dm( self, query: Select, operand: Union[str, Iterable[int]], maybe_negate: ConditionTransform ) -> Select: # This operator does not support is_web_public_query. @@ -540,22 +547,22 @@ def by_pm_with( except (JsonableError, ValidationError): raise BadNarrowOperatorError("unknown user in " + str(operand)) - # Group DM + # Group direct message if recipient.type == Recipient.HUDDLE: cond = column("recipient_id", Integer) == recipient.id return query.where(maybe_negate(cond)) - # 1:1 PM + # 1:1 direct message other_participant = None - # Find if another person is in PM + # Find if another person is in direct message for user in user_profiles: if user.id != self.user_profile.id: other_participant = user - # PM with another person + # Direct message with another person if other_participant: - # We need bidirectional messages PM with another person. + # We need bidirectional direct messages with another person. # But Recipient.PERSONAL objects only encode the person who # received the message, and not the other participant in # the thread (the sender), we need to do a somewhat @@ -574,13 +581,74 @@ def by_pm_with( ) return query.where(maybe_negate(cond)) - # PM with self + # Direct message with self cond = and_( column("sender_id", Integer) == self.user_profile.id, column("recipient_id", Integer) == recipient.id, ) return query.where(maybe_negate(cond)) + def _get_huddle_recipients(self, other_user: UserProfile) -> Set[int]: + self_recipient_ids = [ + recipient_tuple["recipient_id"] + for recipient_tuple in Subscription.objects.filter( + user_profile=self.user_profile, + recipient__type=Recipient.HUDDLE, + ).values("recipient_id") + ] + narrow_recipient_ids = [ + recipient_tuple["recipient_id"] + for recipient_tuple in Subscription.objects.filter( + user_profile=other_user, + recipient__type=Recipient.HUDDLE, + ).values("recipient_id") + ] + + return set(self_recipient_ids) & set(narrow_recipient_ids) + + def by_dm_including( + self, query: Select, operand: Union[str, int], maybe_negate: ConditionTransform + ) -> Select: + # This operator does not support is_web_public_query. + assert not self.is_web_public_query + assert self.user_profile is not None + + try: + if isinstance(operand, str): + narrow_user_profile = get_user_including_cross_realm(operand, self.realm) + else: + narrow_user_profile = get_user_by_id_in_realm_including_cross_realm( + operand, self.realm + ) + except UserProfile.DoesNotExist: + raise BadNarrowOperatorError("unknown user " + str(operand)) + + # "dm-including" when combined with the user's own ID/email as the operand + # should return all group and 1:1 direct messages (including direct messages + # with self), so the simplest query to get these messages is the same as "is:dm". + if narrow_user_profile.id == self.user_profile.id: + cond = column("flags", Integer).op("&")(UserMessage.flags.is_private.mask) != 0 + return query.where(maybe_negate(cond)) + + # all direct messages including another person (group and 1:1) + huddle_recipient_ids = self._get_huddle_recipients(narrow_user_profile) + + self_recipient_id = self.user_profile.recipient_id + # See note above in `by_dm` about needing bidirectional messages + # for direct messages with another person. + cond = or_( + and_( + column("sender_id", Integer) == narrow_user_profile.id, + column("recipient_id", Integer) == self_recipient_id, + ), + and_( + column("sender_id", Integer) == self.user_profile.id, + column("recipient_id", Integer) == narrow_user_profile.recipient_id, + ), + column("recipient_id", Integer).in_(huddle_recipient_ids), + ) + return query.where(maybe_negate(cond)) + def by_group_pm_with( self, query: Select, operand: Union[str, int], maybe_negate: ConditionTransform ) -> Select: @@ -596,22 +664,7 @@ def by_group_pm_with( except UserProfile.DoesNotExist: raise BadNarrowOperatorError("unknown user " + str(operand)) - self_recipient_ids = [ - recipient_tuple["recipient_id"] - for recipient_tuple in Subscription.objects.filter( - user_profile=self.user_profile, - recipient__type=Recipient.HUDDLE, - ).values("recipient_id") - ] - narrow_recipient_ids = [ - recipient_tuple["recipient_id"] - for recipient_tuple in Subscription.objects.filter( - user_profile=narrow_profile, - recipient__type=Recipient.HUDDLE, - ).values("recipient_id") - ] - - recipient_ids = set(self_recipient_ids) & set(narrow_recipient_ids) + recipient_ids = self._get_huddle_recipients(narrow_profile) cond = column("recipient_id", Integer).in_(recipient_ids) return query.where(maybe_negate(cond)) @@ -692,8 +745,8 @@ def convert_term(elem: Union[Dict[str, Any], List[str]]) -> Dict[str, Any]: # that supports user IDs. Relevant code is located in web/src/message_fetch.js # in handle_operators_supporting_id_based_api function where you will need to update # operators_supporting_id, or operators_supporting_ids array. - operators_supporting_id = ["sender", "group-pm-with", "stream"] - operators_supporting_ids = ["pm-with"] + operators_supporting_id = ["sender", "group-pm-with", "stream", "dm-including"] + operators_supporting_ids = ["pm-with", "dm"] operators_non_empty_operand = {"search"} operator = elem.get("operator", "") @@ -831,9 +884,9 @@ def exclude_muting_conditions( # muted messages exist where their absence might make conversation # difficult to understand. As a result, we do not need to consider # muted users in this server-side logic for returning messages to - # clients. (We could in theory exclude PMs from muted users, but - # they're likely to be sufficiently rare to not be worth extra - # logic/testing here). + # clients. (We could in theory exclude direct messages from muted + # users, but they're likely to be sufficiently rare to not be worth + # extra logic/testing here). return conditions diff --git a/zerver/lib/url_encoding.py b/zerver/lib/url_encoding.py --- a/zerver/lib/url_encoding.py +++ b/zerver/lib/url_encoding.py @@ -21,7 +21,7 @@ def encode_stream(stream_id: int, stream_name: str) -> str: def personal_narrow_url(realm: Realm, sender: UserProfile) -> str: - base_url = f"{realm.uri}/#narrow/pm-with/" + base_url = f"{realm.uri}/#narrow/dm/" encoded_user_name = re2.sub(r'[ "%\/<>`\p{C}]+', "-", sender.full_name) pm_slug = str(sender.id) + "-" + encoded_user_name return base_url + pm_slug @@ -29,7 +29,7 @@ def personal_narrow_url(realm: Realm, sender: UserProfile) -> str: def huddle_narrow_url(realm: Realm, other_user_ids: List[int]) -> str: pm_slug = ",".join(str(user_id) for user_id in sorted(other_user_ids)) + "-group" - base_url = f"{realm.uri}/#narrow/pm-with/" + base_url = f"{realm.uri}/#narrow/dm/" return base_url + pm_slug @@ -91,7 +91,7 @@ def near_pm_message_url(realm: Realm, message: Dict[str, Any]) -> str: parts = [ realm.uri, "#narrow", - "pm-with", + "dm", pm_str, "near", message_id,
diff --git a/web/e2e-tests/message-basics.test.ts b/web/e2e-tests/message-basics.test.ts --- a/web/e2e-tests/message-basics.test.ts +++ b/web/e2e-tests/message-basics.test.ts @@ -14,11 +14,14 @@ async function expect_home(page: Page): Promise<void> { ["Verona > test", ["verona test a", "verona test b"]], ["Verona > other topic", ["verona other topic c"]], ["Denmark > test", ["denmark message"]], - ["You and Cordelia, Lear's daughter, King Hamlet", ["group pm a", "group pm b"]], - ["You and Cordelia, Lear's daughter", ["pm c"]], + [ + "You and Cordelia, Lear's daughter, King Hamlet", + ["group direct message a", "group direct message b"], + ], + ["You and Cordelia, Lear's daughter", ["direct message c"]], ["Verona > test", ["verona test d"]], - ["You and Cordelia, Lear's daughter, King Hamlet", ["group pm d"]], - ["You and Cordelia, Lear's daughter", ["pm e"]], + ["You and Cordelia, Lear's daughter, King Hamlet", ["group direct message d"]], + ["You and Cordelia, Lear's daughter", ["direct message e"]], ]); } @@ -59,12 +62,12 @@ async function expect_test_topic(page: Page): Promise<void> { ]); } -async function expect_huddle(page: Page): Promise<void> { +async function expect_group_direct_messages(page: Page): Promise<void> { await page.waitForSelector("#zfilt", {visible: true}); await common.check_messages_sent(page, "zfilt", [ [ "You and Cordelia, Lear's daughter, King Hamlet", - ["group pm a", "group pm b", "group pm d"], + ["group direct message a", "group direct message b", "group direct message d"], ], ]); assert.strictEqual( @@ -73,10 +76,10 @@ async function expect_huddle(page: Page): Promise<void> { ); } -async function expect_cordelia_private_narrow(page: Page): Promise<void> { +async function expect_cordelia_direct_messages(page: Page): Promise<void> { await page.waitForSelector("#zfilt", {visible: true}); await common.check_messages_sent(page, "zfilt", [ - ["You and Cordelia, Lear's daughter", ["pm c", "pm e"]], + ["You and Cordelia, Lear's daughter", ["direct message c", "direct message e"]], ]); } @@ -120,7 +123,7 @@ async function test_navigations_from_home(page: Page): Promise<void> { await page.click( `#zhome [title="Narrow to your direct messages with Cordelia, Lear's daughter, King Hamlet"]`, ); - await expect_huddle(page); + await expect_group_direct_messages(page); await un_narrow(page); await expect_home(page); @@ -200,7 +203,7 @@ async function search_tests(page: Page): Promise<void> { page, "Cordelia", "Direct", - expect_cordelia_private_narrow, + expect_cordelia_direct_messages, "Cordelia, Lear's daughter - Zulip Dev - Zulip", ); @@ -242,7 +245,7 @@ async function search_tests(page: Page): Promise<void> { await search_and_check( page, - "pm-with:[email protected]", + "dm:[email protected]", "", expect_non_existing_user, "Invalid user - Zulip Dev - Zulip", @@ -250,20 +253,23 @@ async function search_tests(page: Page): Promise<void> { await search_and_check( page, - "pm-with:[email protected],[email protected]", + "dm:[email protected],[email protected]", "", expect_non_existing_users, "Invalid users - Zulip Dev - Zulip", ); } -async function expect_all_pm(page: Page): Promise<void> { +async function expect_all_direct_messages(page: Page): Promise<void> { await page.waitForSelector("#zfilt", {visible: true}); await common.check_messages_sent(page, "zfilt", [ - ["You and Cordelia, Lear's daughter, King Hamlet", ["group pm a", "group pm b"]], - ["You and Cordelia, Lear's daughter", ["pm c"]], - ["You and Cordelia, Lear's daughter, King Hamlet", ["group pm d"]], - ["You and Cordelia, Lear's daughter", ["pm e"]], + [ + "You and Cordelia, Lear's daughter, King Hamlet", + ["group direct message a", "group direct message b"], + ], + ["You and Cordelia, Lear's daughter", ["direct message c"]], + ["You and Cordelia, Lear's daughter, King Hamlet", ["group direct message d"]], + ["You and Cordelia, Lear's daughter", ["direct message e"]], ]); assert.strictEqual( await common.get_text_from_selector(page, "#left_bar_compose_stream_button_big"), @@ -284,7 +290,7 @@ async function test_narrow_by_clicking_the_left_sidebar(page: Page): Promise<voi const all_private_messages_icon = "#show_all_private_messages"; await page.waitForSelector(all_private_messages_icon, {visible: true}); await page.click(all_private_messages_icon); - await expect_all_pm(page); + await expect_all_direct_messages(page); await un_narrow(page); } @@ -442,10 +448,10 @@ async function test_users_search(page: Page): Promise<void> { await assert_not_selected(page, "aaron"); await assert_not_selected(page, "Desdemona"); - // arrow up and press Enter. We should be taken to pms with Cordelia, Lear's daughter + // arrow up and press Enter. We should be taken to direct messages with Cordelia, Lear's daughter await arrow(page, "Up"); await page.keyboard.press("Enter"); - await expect_cordelia_private_narrow(page); + await expect_cordelia_direct_messages(page); } async function test_narrow_public_streams(page: Page): Promise<void> { @@ -480,12 +486,12 @@ async function message_basic_tests(page: Page): Promise<void> { {stream: "Verona", topic: "test", content: "verona test b"}, {stream: "Verona", topic: "other topic", content: "verona other topic c"}, {stream: "Denmark", topic: "test", content: "denmark message"}, - {recipient: "[email protected], [email protected]", content: "group pm a"}, - {recipient: "[email protected], [email protected]", content: "group pm b"}, - {recipient: "[email protected]", content: "pm c"}, + {recipient: "[email protected], [email protected]", content: "group direct message a"}, + {recipient: "[email protected], [email protected]", content: "group direct message b"}, + {recipient: "[email protected]", content: "direct message c"}, {stream: "Verona", topic: "test", content: "verona test d"}, - {recipient: "[email protected], [email protected]", content: "group pm d"}, - {recipient: "[email protected]", content: "pm e"}, + {recipient: "[email protected], [email protected]", content: "group direct message d"}, + {recipient: "[email protected]", content: "direct message e"}, ]); await expect_home(page); diff --git a/web/tests/activity.test.js b/web/tests/activity.test.js --- a/web/tests/activity.test.js +++ b/web/tests/activity.test.js @@ -383,7 +383,7 @@ test("first/prev/next", ({override, mock_template}) => { rendered_alice = true; assert.deepEqual(data, { faded: true, - href: "#narrow/pm-with/1-Alice-Smith", + href: "#narrow/dm/1-Alice-Smith", is_current_user: false, name: "Alice Smith", num_unread: 0, @@ -401,7 +401,7 @@ test("first/prev/next", ({override, mock_template}) => { case fred.user_id: rendered_fred = true; assert.deepEqual(data, { - href: "#narrow/pm-with/2-Fred-Flintstone", + href: "#narrow/dm/2-Fred-Flintstone", name: "Fred Flintstone", user_id: fred.user_id, is_current_user: false, @@ -449,7 +449,7 @@ test("insert_one_user_into_empty_list", ({override, mock_template}) => { user_settings.user_list_style = 2; mock_template("presence_row.hbs", true, (data, html) => { assert.deepEqual(data, { - href: "#narrow/pm-with/1-Alice-Smith", + href: "#narrow/dm/1-Alice-Smith", name: "Alice Smith", user_id: 1, is_current_user: false, diff --git a/web/tests/browser_history.test.js b/web/tests/browser_history.test.js --- a/web/tests/browser_history.test.js +++ b/web/tests/browser_history.test.js @@ -21,7 +21,7 @@ function test(label, f) { test("basics", () => { const hash1 = "#settings/profile"; - const hash2 = "#narrow/is/private"; + const hash2 = "#narrow/is/dm"; browser_history.go_to_location(hash1); assert.equal(window.location.hash, hash1); @@ -69,7 +69,7 @@ test("update internal hash if required", ({override_rewire}) => { test("web-public view hash restore", () => { browser_history.update("#"); assert.equal(window.location.hash, ""); - const new_hash = "#narrow/is/private"; + const new_hash = "#narrow/is/dm"; browser_history.update(new_hash); assert.equal(window.location.hash, new_hash); browser_history.return_to_web_public_hash(); diff --git a/web/tests/buddy_data.test.js b/web/tests/buddy_data.test.js --- a/web/tests/buddy_data.test.js +++ b/web/tests/buddy_data.test.js @@ -510,7 +510,7 @@ test("get_items_for_users", () => { assert.deepEqual(buddy_data.get_items_for_users(user_ids), [ { faded: false, - href: "#narrow/pm-with/1001-Human-Myself", + href: "#narrow/dm/1001-Human-Myself", is_current_user: true, name: "Human Myself", num_unread: 0, @@ -522,7 +522,7 @@ test("get_items_for_users", () => { }, { faded: false, - href: "#narrow/pm-with/1002-Alice-Smith", + href: "#narrow/dm/1002-Alice-Smith", is_current_user: false, name: "Alice Smith", num_unread: 0, @@ -534,7 +534,7 @@ test("get_items_for_users", () => { }, { faded: false, - href: "#narrow/pm-with/1003-Fred-Flintstone", + href: "#narrow/dm/1003-Fred-Flintstone", is_current_user: false, name: "Fred Flintstone", num_unread: 0, diff --git a/web/tests/example8.test.js b/web/tests/example8.test.js --- a/web/tests/example8.test.js +++ b/web/tests/example8.test.js @@ -77,7 +77,7 @@ run_test("typing_events.render_notifications_for_narrow", ({override, mock_templ override(page_params, "user_id", anna.user_id); const group = [anna.user_id, vronsky.user_id, levin.user_id, kitty.user_id]; const group_emails = `${anna.email},${vronsky.email},${levin.email},${kitty.email}`; - narrow_state.set_current_filter(new Filter([{operator: "pm-with", operand: group_emails}])); + narrow_state.set_current_filter(new Filter([{operator: "dm", operand: group_emails}])); // Based on typing_events.MAX_USERS_TO_DISPLAY_NAME (which is currently 3), // we display either the list of all users typing (if they do not exceed diff --git a/web/tests/filter.test.js b/web/tests/filter.test.js --- a/web/tests/filter.test.js +++ b/web/tests/filter.test.js @@ -194,7 +194,7 @@ test("basics", () => { assert.ok(!filter.is_personal_filter()); assert.ok(!filter.is_conversation_view()); - operators = [{operator: "is", operand: "private"}]; + operators = [{operator: "is", operand: "dm"}]; filter = new Filter(operators); assert.ok(filter.contains_only_private_messages()); assert.ok(filter.can_mark_messages_read()); @@ -204,6 +204,12 @@ test("basics", () => { assert.ok(!filter.is_personal_filter()); assert.ok(!filter.is_conversation_view()); + // "is:private" was renamed to "is:dm" + operators = [{operator: "is", operand: "private"}]; + filter = new Filter(operators); + assert.ok(filter.has_operand("is", "dm")); + assert.ok(!filter.has_operand("is", "private")); + operators = [{operator: "is", operand: "mentioned"}]; filter = new Filter(operators); assert.ok(!filter.contains_only_private_messages()); @@ -224,7 +230,7 @@ test("basics", () => { assert.ok(filter.is_personal_filter()); assert.ok(!filter.is_conversation_view()); - operators = [{operator: "pm-with", operand: "[email protected]"}]; + operators = [{operator: "dm", operand: "[email protected]"}]; filter = new Filter(operators); assert.ok(filter.is_non_huddle_pm()); assert.ok(filter.contains_only_private_messages()); @@ -235,7 +241,7 @@ test("basics", () => { assert.ok(!filter.is_personal_filter()); assert.ok(filter.is_conversation_view()); - operators = [{operator: "pm-with", operand: "[email protected],[email protected]"}]; + operators = [{operator: "dm", operand: "[email protected],[email protected]"}]; filter = new Filter(operators); assert.ok(!filter.is_non_huddle_pm()); assert.ok(filter.contains_only_private_messages()); @@ -245,7 +251,13 @@ test("basics", () => { assert.ok(!filter.is_personal_filter()); assert.ok(filter.is_conversation_view()); - operators = [{operator: "group-pm-with", operand: "[email protected]"}]; + // "pm-with" was renamed to "dm" + operators = [{operator: "pm-with", operand: "[email protected]"}]; + filter = new Filter(operators); + assert.ok(filter.has_operator("dm")); + assert.ok(!filter.has_operator(" pm-with")); + + operators = [{operator: "dm-including", operand: "[email protected]"}]; filter = new Filter(operators); assert.ok(!filter.is_non_huddle_pm()); assert.ok(filter.contains_only_private_messages()); @@ -256,6 +268,12 @@ test("basics", () => { assert.ok(!filter.is_personal_filter()); assert.ok(!filter.is_conversation_view()); + // "group-pm-with" was replaced with "dm-including" + operators = [{operator: "group-pm-with", operand: "[email protected]"}]; + filter = new Filter(operators); + assert.ok(filter.has_operator("dm-including")); + assert.ok(!filter.has_operator("group-pm-with")); + operators = [{operator: "is", operand: "resolved"}]; filter = new Filter(operators); assert.ok(!filter.contains_only_private_messages()); @@ -270,7 +288,7 @@ test("basics", () => { // filter.supports_collapsing_recipients loop. operators = [ {operator: "is", operand: "resolved", negated: true}, - {operator: "is", operand: "private", negated: true}, + {operator: "is", operand: "dm", negated: true}, {operator: "stream", operand: "stream_name", negated: true}, {operator: "streams", operand: "web-public", negated: true}, {operator: "streams", operand: "public"}, @@ -426,30 +444,30 @@ test("can_mark_messages_read", () => { filter = new Filter(stream_negated_topic_operators); assert.ok(!filter.can_mark_messages_read()); - const pm_with = [{operator: "pm-with", operand: "[email protected],"}]; + const dm = [{operator: "dm", operand: "[email protected],"}]; - const pm_with_negated = [{operator: "pm-with", operand: "[email protected],", negated: true}]; + const dm_negated = [{operator: "dm", operand: "[email protected],", negated: true}]; - const group_pm = [{operator: "pm-with", operand: "[email protected],[email protected]"}]; - filter = new Filter(pm_with); + const dm_group = [{operator: "dm", operand: "[email protected],[email protected]"}]; + filter = new Filter(dm); assert.ok(filter.can_mark_messages_read()); - filter = new Filter(pm_with_negated); + filter = new Filter(dm_negated); assert.ok(!filter.can_mark_messages_read()); - filter = new Filter(group_pm); + filter = new Filter(dm_group); assert.ok(filter.can_mark_messages_read()); - assert_not_mark_read_with_is_operands(group_pm); - assert_not_mark_read_with_is_operands(pm_with); - assert_not_mark_read_with_has_operands(group_pm); - assert_not_mark_read_with_has_operands(pm_with); - assert_not_mark_read_when_searching(group_pm); - assert_not_mark_read_when_searching(pm_with); - - const is_private = [{operator: "is", operand: "private"}]; - filter = new Filter(is_private); + assert_not_mark_read_with_is_operands(dm_group); + assert_not_mark_read_with_is_operands(dm); + assert_not_mark_read_with_has_operands(dm_group); + assert_not_mark_read_with_has_operands(dm); + assert_not_mark_read_when_searching(dm_group); + assert_not_mark_read_when_searching(dm); + + const is_dm = [{operator: "is", operand: "dm"}]; + filter = new Filter(is_dm); assert.ok(filter.can_mark_messages_read()); - assert_not_mark_read_with_is_operands(is_private); - assert_not_mark_read_with_has_operands(is_private); - assert_not_mark_read_when_searching(is_private); + assert_not_mark_read_with_is_operands(is_dm); + assert_not_mark_read_with_has_operands(is_dm); + assert_not_mark_read_when_searching(is_dm); const in_all = [{operator: "in", operand: "all"}]; filter = new Filter(in_all); @@ -478,7 +496,7 @@ test("can_mark_messages_read", () => { // test caching of term types // init and stub - filter = new Filter(pm_with); + filter = new Filter(dm); filter.stub = filter.calc_can_mark_messages_read; filter.calc_can_mark_messages_read = function () { this.calc_can_mark_messages_read_called = true; @@ -592,18 +610,18 @@ test("redundancies", () => { let filter; terms = [ - {operator: "pm-with", operand: "[email protected],"}, - {operator: "is", operand: "private"}, + {operator: "dm", operand: "[email protected],"}, + {operator: "is", operand: "dm"}, ]; filter = new Filter(terms); - assert.ok(filter.can_bucket_by("pm-with")); + assert.ok(filter.can_bucket_by("dm")); terms = [ - {operator: "pm-with", operand: "[email protected],", negated: true}, - {operator: "is", operand: "private"}, + {operator: "dm", operand: "[email protected],", negated: true}, + {operator: "is", operand: "dm"}, ]; filter = new Filter(terms); - assert.ok(filter.can_bucket_by("is-private", "not-pm-with")); + assert.ok(filter.can_bucket_by("is-dm", "not-dm")); }); test("canonicalization", () => { @@ -621,10 +639,16 @@ test("canonicalization", () => { assert.equal(term.operator, "sender"); assert.equal(term.operand, "[email protected]"); + // "pm-with" was renamed to "dm" term = Filter.canonicalize_term({operator: "pm-with", operand: "me"}); - assert.equal(term.operator, "pm-with"); + assert.equal(term.operator, "dm"); assert.equal(term.operand, "[email protected]"); + // "group-pm-with" was replaced with "dm-including" + term = Filter.canonicalize_term({operator: "group-pm-with", operand: "[email protected]"}); + assert.equal(term.operator, "dm-including"); + assert.equal(term.operand, "[email protected]"); + term = Filter.canonicalize_term({operator: "search", operand: "foo"}); assert.equal(term.operator, "search"); assert.equal(term.operand, "foo"); @@ -690,7 +714,7 @@ test("predicate_basics", () => { predicate = get_predicate([["topic", "Bar"]]); assert.ok(!predicate({type: "private"})); - predicate = get_predicate([["is", "private"]]); + predicate = get_predicate([["is", "dm"]]); assert.ok(predicate({type: "private"})); assert.ok(!predicate({type: "stream"})); @@ -751,7 +775,7 @@ test("predicate_basics", () => { assert.ok(predicate({sender_id: joe.user_id})); assert.ok(!predicate({sender_email: steve.user_id})); - predicate = get_predicate([["pm-with", "[email protected]"]]); + predicate = get_predicate([["dm", "[email protected]"]]); assert.ok( predicate({ type: "private", @@ -772,7 +796,7 @@ test("predicate_basics", () => { ); assert.ok(!predicate({type: "stream"})); - predicate = get_predicate([["pm-with", "[email protected],[email protected]"]]); + predicate = get_predicate([["dm", "[email protected],[email protected]"]]); assert.ok( predicate({ type: "private", @@ -781,7 +805,7 @@ test("predicate_basics", () => { ); // Make sure your own email is ignored - predicate = get_predicate([["pm-with", "[email protected],[email protected],[email protected]"]]); + predicate = get_predicate([["dm", "[email protected],[email protected],[email protected]"]]); assert.ok( predicate({ type: "private", @@ -789,7 +813,7 @@ test("predicate_basics", () => { }), ); - predicate = get_predicate([["pm-with", "[email protected]"]]); + predicate = get_predicate([["dm", "[email protected]"]]); assert.ok( !predicate({ type: "private", @@ -797,15 +821,15 @@ test("predicate_basics", () => { }), ); - predicate = get_predicate([["group-pm-with", "[email protected]"]]); + predicate = get_predicate([["dm-including", "[email protected]"]]); assert.ok( !predicate({ type: "private", - display_recipient: [{id: joe.user_id}], + display_recipient: [{id: joe.user_id}, {id: me.user_id}], }), ); - predicate = get_predicate([["group-pm-with", "[email protected]"]]); + predicate = get_predicate([["dm-including", "[email protected]"]]); assert.ok( predicate({ type: "private", @@ -813,10 +837,9 @@ test("predicate_basics", () => { }), ); assert.ok( - !predicate({ - // you must be a part of the group pm + predicate({ type: "private", - display_recipient: [{id: joe.user_id}, {id: steve.user_id}], + display_recipient: [{id: joe.user_id}, {id: me.user_id}], }), ); assert.ok( @@ -994,8 +1017,8 @@ test("parse", () => { ]; _test(); - string = "pm-with:[email protected]"; - operators = [{operator: "pm-with", operand: "[email protected]"}]; + string = "dm:[email protected]"; + operators = [{operator: "dm", operand: "[email protected]"}]; _test(); string = "sender:[email protected]"; @@ -1167,7 +1190,7 @@ test("describe", () => { assert.equal(Filter.describe(narrow), string); narrow = [ - {operator: "is", operand: "private"}, + {operator: "is", operand: "dm"}, {operator: "search", operand: "lunch"}, ]; string = "direct messages, search for lunch"; @@ -1210,7 +1233,7 @@ test("describe", () => { assert.equal(Filter.describe(narrow), string); narrow = [ - {operator: "is", operand: "private"}, + {operator: "is", operand: "dm"}, {operator: "search", operand: "lunch", negated: true}, ]; string = "direct messages, exclude lunch"; @@ -1254,7 +1277,7 @@ test("can_bucket_by", () => { let filter = new Filter(terms); assert.equal(filter.can_bucket_by("stream"), true); assert.equal(filter.can_bucket_by("stream", "topic"), false); - assert.equal(filter.can_bucket_by("pm-with"), false); + assert.equal(filter.can_bucket_by("dm"), false); terms = [ // try a non-orthodox ordering @@ -1264,7 +1287,7 @@ test("can_bucket_by", () => { filter = new Filter(terms); assert.equal(filter.can_bucket_by("stream"), true); assert.equal(filter.can_bucket_by("stream", "topic"), true); - assert.equal(filter.can_bucket_by("pm-with"), false); + assert.equal(filter.can_bucket_by("dm"), false); terms = [ {operator: "stream", operand: "My stream", negated: true}, @@ -1273,31 +1296,31 @@ test("can_bucket_by", () => { filter = new Filter(terms); assert.equal(filter.can_bucket_by("stream"), false); assert.equal(filter.can_bucket_by("stream", "topic"), false); - assert.equal(filter.can_bucket_by("pm-with"), false); + assert.equal(filter.can_bucket_by("dm"), false); - terms = [{operator: "pm-with", operand: "[email protected]", negated: true}]; + terms = [{operator: "dm", operand: "[email protected]", negated: true}]; filter = new Filter(terms); assert.equal(filter.can_bucket_by("stream"), false); assert.equal(filter.can_bucket_by("stream", "topic"), false); - assert.equal(filter.can_bucket_by("pm-with"), false); + assert.equal(filter.can_bucket_by("dm"), false); - terms = [{operator: "pm-with", operand: "[email protected],[email protected]"}]; + terms = [{operator: "dm", operand: "[email protected],[email protected]"}]; filter = new Filter(terms); assert.equal(filter.can_bucket_by("stream"), false); assert.equal(filter.can_bucket_by("stream", "topic"), false); - assert.equal(filter.can_bucket_by("pm-with"), true); + assert.equal(filter.can_bucket_by("dm"), true); assert.equal(filter.can_bucket_by("is-mentioned"), false); - assert.equal(filter.can_bucket_by("is-private"), false); + assert.equal(filter.can_bucket_by("is-dm"), false); - terms = [{operator: "is", operand: "private"}]; + terms = [{operator: "is", operand: "dm"}]; filter = new Filter(terms); assert.equal(filter.can_bucket_by("is-mentioned"), false); - assert.equal(filter.can_bucket_by("is-private"), true); + assert.equal(filter.can_bucket_by("is-dm"), true); terms = [{operator: "is", operand: "mentioned"}]; filter = new Filter(terms); assert.equal(filter.can_bucket_by("is-mentioned"), true); - assert.equal(filter.can_bucket_by("is-private"), false); + assert.equal(filter.can_bucket_by("is-dm"), false); terms = [ {operator: "is", operand: "mentioned"}, @@ -1305,25 +1328,25 @@ test("can_bucket_by", () => { ]; filter = new Filter(terms); assert.equal(filter.can_bucket_by("is-mentioned"), true); - assert.equal(filter.can_bucket_by("is-private"), false); + assert.equal(filter.can_bucket_by("is-dm"), false); // The call below returns false for somewhat arbitrary - // reasons -- we say is-private has precedence over + // reasons -- we say is-dm has precedence over // is-starred. assert.equal(filter.can_bucket_by("is-starred"), false); terms = [{operator: "is", operand: "mentioned", negated: true}]; filter = new Filter(terms); assert.equal(filter.can_bucket_by("is-mentioned"), false); - assert.equal(filter.can_bucket_by("is-private"), false); + assert.equal(filter.can_bucket_by("is-dm"), false); terms = [{operator: "is", operand: "resolved"}]; filter = new Filter(terms); assert.equal(filter.can_bucket_by("stream", "topic"), false); assert.equal(filter.can_bucket_by("stream"), false); - assert.equal(filter.can_bucket_by("pm-with"), false); + assert.equal(filter.can_bucket_by("dm"), false); assert.equal(filter.can_bucket_by("is-mentioned"), false); - assert.equal(filter.can_bucket_by("is-private"), false); + assert.equal(filter.can_bucket_by("is-dm"), false); }); test("term_type", () => { @@ -1341,8 +1364,9 @@ test("term_type", () => { assert_term_type(term("streams", "public"), "streams-public"); assert_term_type(term("stream", "whatever"), "stream"); - assert_term_type(term("pm-with", "whomever"), "pm-with"); - assert_term_type(term("pm-with", "whomever", true), "not-pm-with"); + assert_term_type(term("dm", "whomever"), "dm"); + assert_term_type(term("dm", "whomever", true), "not-dm"); + assert_term_type(term("is", "dm"), "is-dm"); assert_term_type(term("is", "private"), "is-private"); assert_term_type(term("has", "link"), "has-link"); assert_term_type(term("has", "attachment", true), "not-has-attachment"); @@ -1355,8 +1379,8 @@ test("term_type", () => { assert_term_sort(["topic", "stream", "sender"], ["stream", "topic", "sender"]); assert_term_sort( - ["has-link", "near", "is-unread", "pm-with"], - ["pm-with", "near", "is-unread", "has-link"], + ["has-link", "near", "is-unread", "dm"], + ["dm", "near", "is-unread", "has-link"], ); assert_term_sort(["bogus", "stream", "topic"], ["stream", "topic", "bogus"]); @@ -1420,13 +1444,13 @@ test("first_valid_id_from", ({override}) => { test("update_email", () => { const terms = [ - {operator: "pm-with", operand: "[email protected]"}, + {operator: "dm", operand: "[email protected]"}, {operator: "sender", operand: "[email protected]"}, {operator: "stream", operand: "[email protected]"}, // try to be tricky ]; const filter = new Filter(terms); filter.update_email(steve.user_id, "[email protected]"); - assert.deepEqual(filter.operands("pm-with"), ["[email protected]"]); + assert.deepEqual(filter.operands("dm"), ["[email protected]"]); assert.deepEqual(filter.operands("sender"), ["[email protected]"]); assert.deepEqual(filter.operands("stream"), ["[email protected]"]); }); @@ -1493,7 +1517,7 @@ test("navbar_helpers", () => { const in_home = [{operator: "in", operand: "home"}]; const in_all = [{operator: "in", operand: "all"}]; const is_starred = [{operator: "is", operand: "starred"}]; - const is_private = [{operator: "is", operand: "private"}]; + const is_dm = [{operator: "is", operand: "dm"}]; const is_mentioned = [{operator: "is", operand: "mentioned"}]; const is_resolved = [{operator: "is", operand: "resolved"}]; const streams_public = [{operator: "streams", operand: "public"}]; @@ -1512,10 +1536,10 @@ test("navbar_helpers", () => { {operator: "stream", operand: "Elephant"}, {operator: "topic", operand: "pink"}, ]; - const pm_with = [{operator: "pm-with", operand: "[email protected]"}]; - const group_pm = [{operator: "pm-with", operand: "[email protected],[email protected]"}]; - const group_pm_including_missing_person = [ - {operator: "pm-with", operand: "[email protected],[email protected],[email protected]"}, + const dm = [{operator: "dm", operand: "[email protected]"}]; + const dm_group = [{operator: "dm", operand: "[email protected],[email protected]"}]; + const dm_group_including_missing_person = [ + {operator: "dm", operand: "[email protected],[email protected],[email protected]"}, ]; // not common narrows, but used for browser title updates const is_alerted = [{operator: "is", operand: "alerted"}]; @@ -1525,8 +1549,8 @@ test("navbar_helpers", () => { {operator: "topic", operand: "bar"}, {operator: "near", operand: "12"}, ]; - const pm_with_near = [ - {operator: "pm-with", operand: "[email protected]"}, + const dm_near = [ + {operator: "dm", operand: "[email protected]"}, {operator: "near", operand: "12"}, ]; @@ -1553,11 +1577,11 @@ test("navbar_helpers", () => { redirect_url_with_search: "#", }, { - operator: is_private, + operator: is_dm, is_common_narrow: true, icon: "envelope", title: "translated: Direct messages", - redirect_url_with_search: "/#narrow/is/private", + redirect_url_with_search: "/#narrow/is/dm", }, { operator: is_mentioned, @@ -1623,23 +1647,22 @@ test("navbar_helpers", () => { redirect_url_with_search: "/#narrow/stream/12-webPublicSub", }, { - operator: pm_with, + operator: dm, is_common_narrow: true, icon: "envelope", title: properly_separated_names([joe.full_name]), redirect_url_with_search: - "/#narrow/pm-with/" + joe.user_id + "-" + parseOneAddress(joe.email).local, + "/#narrow/dm/" + joe.user_id + "-" + parseOneAddress(joe.email).local, }, { - operator: group_pm, + operator: dm_group, is_common_narrow: true, icon: "envelope", title: properly_separated_names([joe.full_name, steve.full_name]), - redirect_url_with_search: - "/#narrow/pm-with/" + joe.user_id + "," + steve.user_id + "-group", + redirect_url_with_search: "/#narrow/dm/" + joe.user_id + "," + steve.user_id + "-group", }, { - operator: group_pm_including_missing_person, + operator: dm_group_including_missing_person, is_common_narrow: true, icon: "envelope", title: properly_separated_names([ @@ -1647,7 +1670,7 @@ test("navbar_helpers", () => { steve.full_name, "[email protected]", ]), - redirect_url_with_search: "/#narrow/pm-with/undefined", + redirect_url_with_search: "/#narrow/dm/undefined", }, { operator: is_alerted, @@ -1671,7 +1694,7 @@ test("navbar_helpers", () => { redirect_url_with_search: "#", }, { - operator: pm_with_near, + operator: dm_near, is_common_narrow: false, icon: "envelope", title: properly_separated_names([joe.full_name]), @@ -1750,7 +1773,7 @@ test("error_cases", () => { // This test just gives us 100% line coverage on defensive code that // should not be reached unless we break other code. - const predicate = get_predicate([["pm-with", "[email protected]"]]); + const predicate = get_predicate([["dm", "[email protected]"]]); blueslip.expect("error", "Empty recipient list in message"); assert.ok(!predicate({type: "private", display_recipient: []})); }); @@ -1769,11 +1792,9 @@ run_test("is_spectator_compatible", () => { ]), ); assert.ok(Filter.is_spectator_compatible([{operator: "sender", operand: "[email protected]"}])); + assert.ok(!Filter.is_spectator_compatible([{operator: "dm", operand: "[email protected]"}])); assert.ok( - !Filter.is_spectator_compatible([{operator: "pm-with", operand: "[email protected]"}]), - ); - assert.ok( - !Filter.is_spectator_compatible([{operator: "group-pm-with", operand: "[email protected]"}]), + !Filter.is_spectator_compatible([{operator: "dm-including", operand: "[email protected]"}]), ); assert.ok(Filter.is_spectator_compatible([{operator: "stream", operand: "Denmark"}])); assert.ok( @@ -1783,8 +1804,20 @@ run_test("is_spectator_compatible", () => { ]), ); assert.ok(!Filter.is_spectator_compatible([{operator: "is", operand: "starred"}])); - assert.ok(!Filter.is_spectator_compatible([{operator: "is", operand: "private"}])); + assert.ok(!Filter.is_spectator_compatible([{operator: "is", operand: "dm"}])); assert.ok(Filter.is_spectator_compatible([{operator: "streams", operand: "public"}])); + // Malformed input not allowed assert.ok(!Filter.is_spectator_compatible([{operator: "has"}])); + + // "is:private" was renamed to "is:dm" + assert.ok(!Filter.is_spectator_compatible([{operator: "is", operand: "private"}])); + // "pm-with" was renamed to "dm" + assert.ok( + !Filter.is_spectator_compatible([{operator: "pm-with", operand: "[email protected]"}]), + ); + // "group-pm-with:" was replaced with "dm-including:" + assert.ok( + !Filter.is_spectator_compatible([{operator: "group-pm-with", operand: "[email protected]"}]), + ); }); diff --git a/web/tests/hash_util.test.js b/web/tests/hash_util.test.js --- a/web/tests/hash_util.test.js +++ b/web/tests/hash_util.test.js @@ -162,7 +162,7 @@ run_test("test_by_conversation_and_time_url", () => { assert.equal( hash_util.by_conversation_and_time_url(message), - "http://zulip.zulipdev.com/#narrow/pm-with/15-pm/near/43", + "http://zulip.zulipdev.com/#narrow/dm/15-dm/near/43", ); }); diff --git a/web/tests/hashchange.test.js b/web/tests/hashchange.test.js --- a/web/tests/hashchange.test.js +++ b/web/tests/hashchange.test.js @@ -95,6 +95,7 @@ run_test("operators_trailing_slash", () => { run_test("people_slugs", () => { let operators; let hash; + let narrow; const alice = { email: "[email protected]", @@ -106,12 +107,22 @@ run_test("people_slugs", () => { operators = [{operator: "sender", operand: "[email protected]"}]; hash = hash_util.operators_to_hash(operators); assert.equal(hash, "#narrow/sender/42-Alice-Smith"); - const narrow = hash_util.parse_narrow(hash.split("/")); + narrow = hash_util.parse_narrow(hash.split("/")); assert.deepEqual(narrow, [{operator: "sender", operand: "[email protected]", negated: false}]); + operators = [{operator: "dm", operand: "[email protected]"}]; + hash = hash_util.operators_to_hash(operators); + assert.equal(hash, "#narrow/dm/42-Alice-Smith"); + narrow = hash_util.parse_narrow(hash.split("/")); + assert.deepEqual(narrow, [{operator: "dm", operand: "[email protected]", negated: false}]); + + // Even though we renamed "pm-with" to "dm", preexisting + // links/URLs with "pm-with" operator are handled correctly. operators = [{operator: "pm-with", operand: "[email protected]"}]; hash = hash_util.operators_to_hash(operators); assert.equal(hash, "#narrow/pm-with/42-Alice-Smith"); + narrow = hash_util.parse_narrow(hash.split("/")); + assert.deepEqual(narrow, [{operator: "pm-with", operand: "[email protected]", negated: false}]); }); function test_helper({override, change_tab}) { @@ -321,13 +332,13 @@ run_test("hash_interactions", ({override}) => { run_test("save_narrow", ({override}) => { const helper = test_helper({override}); - let operators = [{operator: "is", operand: "private"}]; + let operators = [{operator: "is", operand: "dm"}]; blueslip.expect("warn", "browser does not support pushState"); hashchange.save_narrow(operators); helper.assert_events([[message_viewport, "stop_auto_scrolling"]]); - assert.equal(window.location.hash, "#narrow/is/private"); + assert.equal(window.location.hash, "#narrow/is/dm"); let url_pushed; override(history, "pushState", (state, title, url) => { diff --git a/web/tests/message_fetch.test.js b/web/tests/message_fetch.test.js --- a/web/tests/message_fetch.test.js +++ b/web/tests/message_fetch.test.js @@ -293,7 +293,7 @@ run_test("initialize", () => { }); function simulate_narrow() { - const filter = new Filter([{operator: "pm-with", operand: alice.email}]); + const filter = new Filter([{operator: "dm", operand: alice.email}]); const msg_list = new message_list.MessageList({ table_name: "zfilt", @@ -364,7 +364,7 @@ run_test("loading_newer", () => { anchor: "444", num_before: 0, num_after: 100, - narrow: `[{"negated":false,"operator":"pm-with","operand":[${alice.user_id}]}]`, + narrow: `[{"negated":false,"operator":"dm","operand":[${alice.user_id}]}]`, client_gravatar: true, }, resp: { diff --git a/web/tests/message_list_data.test.js b/web/tests/message_list_data.test.js --- a/web/tests/message_list_data.test.js +++ b/web/tests/message_list_data.test.js @@ -126,7 +126,7 @@ run_test("basics", () => { run_test("muting", () => { let mld = new MessageListData({ excludes_muted_topics: false, - filter: new Filter([{operator: "pm-with", operand: "[email protected]"}]), + filter: new Filter([{operator: "dm", operand: "[email protected]"}]), }); const msgs = [ diff --git a/web/tests/narrow.test.js b/web/tests/narrow.test.js --- a/web/tests/narrow.test.js +++ b/web/tests/narrow.test.js @@ -175,15 +175,26 @@ run_test("urls", () => { people.initialize_current_user(me.user_id); let url = hash_util.pm_with_url(ray.email); - assert.equal(url, "#narrow/pm-with/22-Raymond"); + assert.equal(url, "#narrow/dm/22-Raymond"); url = hash_util.huddle_with_url("22,23"); - assert.equal(url, "#narrow/pm-with/22,23-group"); + assert.equal(url, "#narrow/dm/22,23-group"); url = hash_util.by_sender_url(ray.email); assert.equal(url, "#narrow/sender/22-Raymond"); - let emails = hash_util.decode_operand("pm-with", "22,23-group"); + let emails = hash_util.decode_operand("dm", "22,23-group"); + assert.equal(emails, "[email protected],[email protected]"); + + emails = hash_util.decode_operand("dm", "5,22,23-group"); + assert.equal(emails, "[email protected],[email protected]"); + + emails = hash_util.decode_operand("dm", "5-group"); + assert.equal(emails, "[email protected]"); + + // Even though we renamed "pm-with" to "dm", preexisting + // links/URLs with "pm-with" operator are decoded correctly. + emails = hash_util.decode_operand("pm-with", "22,23-group"); assert.equal(emails, "[email protected],[email protected]"); emails = hash_util.decode_operand("pm-with", "5,22,23-group"); @@ -286,10 +297,10 @@ run_test("show_empty_narrow_message", ({mock_template}) => { ), ); - // organization has disabled sending private messages + // organization has disabled sending direct messages page_params.realm_private_message_policy = settings_config.private_message_policy_values.disabled.code; - set_filter([["is", "private"]]); + set_filter([["is", "dm"]]); narrow_banner.show_empty_narrow_message(); assert.equal( $(".empty_feed_notice_main").html(), @@ -298,10 +309,10 @@ run_test("show_empty_narrow_message", ({mock_template}) => { ), ); - // sending private messages enabled + // sending direct messages enabled page_params.realm_private_message_policy = settings_config.private_message_policy_values.by_anyone.code; - set_filter([["is", "private"]]); + set_filter([["is", "dm"]]); narrow_banner.show_empty_narrow_message(); assert.equal( $(".empty_feed_notice_main").html(), @@ -325,12 +336,12 @@ run_test("show_empty_narrow_message", ({mock_template}) => { empty_narrow_html("translated: No topics are marked as resolved."), ); - // organization has disabled sending private messages + // organization has disabled sending direct messages page_params.realm_private_message_policy = settings_config.private_message_policy_values.disabled.code; // prioritize information about invalid user(s) in narrow/search - set_filter([["pm-with", ["Yo"]]]); + set_filter([["dm", ["Yo"]]]); narrow_banner.show_empty_narrow_message(); assert.equal( $(".empty_feed_notice_main").html(), @@ -338,14 +349,14 @@ run_test("show_empty_narrow_message", ({mock_template}) => { ); people.add_active_user(alice); - set_filter([["pm-with", ["[email protected]", "Yo"]]]); + set_filter([["dm", ["[email protected]", "Yo"]]]); narrow_banner.show_empty_narrow_message(); assert.equal( $(".empty_feed_notice_main").html(), empty_narrow_html("translated: One or more of these users do not exist!"), ); - set_filter([["pm-with", "[email protected]"]]); + set_filter([["dm", "[email protected]"]]); narrow_banner.show_empty_narrow_message(); assert.equal( $(".empty_feed_notice_main").html(), @@ -354,10 +365,10 @@ run_test("show_empty_narrow_message", ({mock_template}) => { ), ); - // private messages with a bot are possible even though - // the organization has disabled sending private messages + // direct messages with a bot are possible even though + // the organization has disabled sending direct messages people.add_active_user(bot); - set_filter([["pm-with", "[email protected]"]]); + set_filter([["dm", "[email protected]"]]); narrow_banner.show_empty_narrow_message(); assert.equal( $(".empty_feed_notice_main").html(), @@ -367,9 +378,9 @@ run_test("show_empty_narrow_message", ({mock_template}) => { ), ); - // group private messages with bots are not possible when - // sending private messages is disabled - set_filter([["pm-with", bot.email + "," + alice.email]]); + // group direct messages with bots are not possible when + // sending direct messages is disabled + set_filter([["dm", bot.email + "," + alice.email]]); narrow_banner.show_empty_narrow_message(); assert.equal( $(".empty_feed_notice_main").html(), @@ -378,10 +389,10 @@ run_test("show_empty_narrow_message", ({mock_template}) => { ), ); - // sending private messages enabled + // sending direct messages enabled page_params.realm_private_message_policy = settings_config.private_message_policy_values.by_anyone.code; - set_filter([["pm-with", "[email protected]"]]); + set_filter([["dm", "[email protected]"]]); narrow_banner.show_empty_narrow_message(); assert.equal( $(".empty_feed_notice_main").html(), @@ -393,7 +404,7 @@ run_test("show_empty_narrow_message", ({mock_template}) => { people.add_active_user(me); people.initialize_current_user(me.user_id); - set_filter([["pm-with", me.email]]); + set_filter([["dm", me.email]]); narrow_banner.show_empty_narrow_message(); assert.equal( $(".empty_feed_notice_main").html(), @@ -403,7 +414,7 @@ run_test("show_empty_narrow_message", ({mock_template}) => { ), ); - set_filter([["pm-with", me.email + "," + alice.email]]); + set_filter([["dm", me.email + "," + alice.email]]); narrow_banner.show_empty_narrow_message(); assert.equal( $(".empty_feed_notice_main").html(), @@ -413,51 +424,59 @@ run_test("show_empty_narrow_message", ({mock_template}) => { ), ); - // organization has disabled sending private messages + // organization has disabled sending direct messages page_params.realm_private_message_policy = settings_config.private_message_policy_values.disabled.code; // prioritize information about invalid user in narrow/search - set_filter([["group-pm-with", ["Yo"]]]); + set_filter([["dm-including", ["Yo"]]]); narrow_banner.show_empty_narrow_message(); assert.equal( $(".empty_feed_notice_main").html(), empty_narrow_html("translated: This user does not exist!"), ); - set_filter([["group-pm-with", "[email protected]"]]); + set_filter([["dm-including", "[email protected]"]]); narrow_banner.show_empty_narrow_message(); assert.equal( $(".empty_feed_notice_main").html(), empty_narrow_html( - "translated: You are not allowed to send group direct messages in this organization.", + "translated: You are not allowed to send direct messages in this organization.", ), ); - // group private messages with bots are not possible when - // sending private messages is disabled - set_filter([["group-pm-with", "[email protected]"]]); + // direct messages with a bot are possible even though + // the organization has disabled sending direct messages + set_filter([["dm-including", "[email protected]"]]); narrow_banner.show_empty_narrow_message(); assert.equal( $(".empty_feed_notice_main").html(), empty_narrow_html( - "translated: You are not allowed to send group direct messages in this organization.", + "translated: You have no direct messages including Example Bot yet.", + 'translated HTML: Why not <a href="#" class="empty_feed_compose_private">start the conversation</a>?', ), ); - // sending private messages enabled + // sending direct messages enabled page_params.realm_private_message_policy = settings_config.private_message_policy_values.by_anyone.code; - set_filter([["group-pm-with", "[email protected]"]]); + set_filter([["dm-including", "[email protected]"]]); narrow_banner.show_empty_narrow_message(); assert.equal( $(".empty_feed_notice_main").html(), empty_narrow_html( - "translated: You have no group direct messages with Alice Smith yet.", + "translated: You have no direct messages including Alice Smith yet.", 'translated HTML: Why not <a href="#" class="empty_feed_compose_private">start the conversation</a>?', ), ); + set_filter([["dm-including", me.email]]); + narrow_banner.show_empty_narrow_message(); + assert.equal( + $(".empty_feed_notice_main").html(), + empty_narrow_html("translated: You don't have any direct message conversations yet."), + ); + set_filter([["sender", "[email protected]"]]); narrow_banner.show_empty_narrow_message(); assert.equal( @@ -711,7 +730,7 @@ run_test("narrow_to_compose_target streams", ({override_rewire}) => { assert.deepEqual(args.operators, [{operator: "stream", operand: "ROME"}]); }); -run_test("narrow_to_compose_target PMs", ({override, override_rewire}) => { +run_test("narrow_to_compose_target direct messages", ({override, override_rewire}) => { const args = {called: false}; override_rewire(narrow, "activate", (operators, opts) => { args.operators = operators; @@ -732,7 +751,7 @@ run_test("narrow_to_compose_target PMs", ({override, override_rewire}) => { args.called = false; narrow.to_compose_target(); assert.equal(args.called, true); - assert.deepEqual(args.operators, [{operator: "pm-with", operand: "[email protected]"}]); + assert.deepEqual(args.operators, [{operator: "dm", operand: "[email protected]"}]); // Test with valid persons emails = "[email protected],[email protected]"; @@ -740,7 +759,7 @@ run_test("narrow_to_compose_target PMs", ({override, override_rewire}) => { narrow.to_compose_target(); assert.equal(args.called, true); assert.deepEqual(args.operators, [ - {operator: "pm-with", operand: "[email protected],[email protected]"}, + {operator: "dm", operand: "[email protected],[email protected]"}, ]); // Test with some invalid persons @@ -748,21 +767,21 @@ run_test("narrow_to_compose_target PMs", ({override, override_rewire}) => { args.called = false; narrow.to_compose_target(); assert.equal(args.called, true); - assert.deepEqual(args.operators, [{operator: "is", operand: "private"}]); + assert.deepEqual(args.operators, [{operator: "is", operand: "dm"}]); // Test with all invalid persons emails = "alice,random,ray"; args.called = false; narrow.to_compose_target(); assert.equal(args.called, true); - assert.deepEqual(args.operators, [{operator: "is", operand: "private"}]); + assert.deepEqual(args.operators, [{operator: "is", operand: "dm"}]); // Test with no persons emails = ""; args.called = false; narrow.to_compose_target(); assert.equal(args.called, true); - assert.deepEqual(args.operators, [{operator: "is", operand: "private"}]); + assert.deepEqual(args.operators, [{operator: "is", operand: "dm"}]); }); run_test("narrow_compute_title", ({override}) => { @@ -803,7 +822,7 @@ run_test("narrow_compute_title", ({override}) => { filter = new Filter([{operator: "stream", operand: "Elephant"}]); assert.equal(narrow.compute_narrow_title(filter), "translated: Unknown stream #Elephant"); - // Private messages with narrows + // Direct messages with narrows const joe = { email: "[email protected]", user_id: 31, @@ -811,14 +830,14 @@ run_test("narrow_compute_title", ({override}) => { }; people.add_active_user(joe); - filter = new Filter([{operator: "pm-with", operand: "[email protected]"}]); + filter = new Filter([{operator: "dm", operand: "[email protected]"}]); assert.equal(narrow.compute_narrow_title(filter), "joe"); - filter = new Filter([{operator: "pm-with", operand: "[email protected],[email protected]"}]); + filter = new Filter([{operator: "dm", operand: "[email protected],[email protected]"}]); blueslip.expect("warn", "Unknown emails: [email protected],[email protected]"); assert.equal(narrow.compute_narrow_title(filter), "translated: Invalid users"); - filter = new Filter([{operator: "pm-with", operand: "[email protected]"}]); + filter = new Filter([{operator: "dm", operand: "[email protected]"}]); blueslip.expect("warn", "Unknown emails: [email protected]"); assert.equal(narrow.compute_narrow_title(filter), "translated: Invalid user"); }); diff --git a/web/tests/narrow_local.test.js b/web/tests/narrow_local.test.js --- a/web/tests/narrow_local.test.js +++ b/web/tests/narrow_local.test.js @@ -195,9 +195,9 @@ run_test("is private with no target", () => { test_with(fixture); }); -run_test("pm-with with target outside of range", () => { +run_test("dm with target outside of range", () => { const fixture = { - filter_terms: [{operator: "pm-with", operand: "[email protected]"}], + filter_terms: [{operator: "dm", operand: "[email protected]"}], target_id: 5, unread_info: { flavor: "not_found", diff --git a/web/tests/narrow_state.test.js b/web/tests/narrow_state.test.js --- a/web/tests/narrow_state.test.js +++ b/web/tests/narrow_state.test.js @@ -79,7 +79,7 @@ test("narrowed", () => { assert.ok(narrow_state.narrowed_by_stream_reply()); assert.ok(!narrow_state.narrowed_to_starred()); - set_filter([["pm-with", "[email protected]"]]); + set_filter([["dm", "[email protected]"]]); assert.ok(narrow_state.narrowed_to_pms()); assert.ok(narrow_state.narrowed_by_reply()); assert.ok(narrow_state.narrowed_by_pm_reply()); @@ -178,9 +178,9 @@ test("set_compose_defaults", () => { assert.equal(stream_and_topic.stream, "Foo"); assert.equal(stream_and_topic.topic, "Bar"); - set_filter([["pm-with", "[email protected]"]]); - let pm_test = narrow_state.set_compose_defaults(); - assert.equal(pm_test.private_message_recipient, undefined); + set_filter([["dm", "[email protected]"]]); + let dm_test = narrow_state.set_compose_defaults(); + assert.equal(dm_test.private_message_recipient, undefined); const john = { email: "[email protected]", @@ -190,9 +190,15 @@ test("set_compose_defaults", () => { people.add_active_user(john); people.add_active_user(john); + set_filter([["dm", "[email protected]"]]); + dm_test = narrow_state.set_compose_defaults(); + assert.equal(dm_test.private_message_recipient, "[email protected]"); + + // Even though we renamed "pm-with" to "dm", + // compose defaults are set correctly. set_filter([["pm-with", "[email protected]"]]); - pm_test = narrow_state.set_compose_defaults(); - assert.equal(pm_test.private_message_recipient, "[email protected]"); + dm_test = narrow_state.set_compose_defaults(); + assert.equal(dm_test.private_message_recipient, "[email protected]"); set_filter([ ["topic", "duplicate"], @@ -216,13 +222,13 @@ test("update_email", () => { people.add_active_user(steve); set_filter([ - ["pm-with", "[email protected]"], + ["dm", "[email protected]"], ["sender", "[email protected]"], ["stream", "[email protected]"], // try to be tricky ]); narrow_state.update_email(steve.user_id, "[email protected]"); const filter = narrow_state.filter(); - assert.deepEqual(filter.operands("pm-with"), ["[email protected]"]); + assert.deepEqual(filter.operands("dm"), ["[email protected]"]); assert.deepEqual(filter.operands("sender"), ["[email protected]"]); assert.deepEqual(filter.operands("stream"), ["[email protected]"]); }); @@ -245,7 +251,7 @@ test("topic", () => { set_filter([ ["sender", "[email protected]"], - ["pm-with", "[email protected]"], + ["dm", "[email protected]"], ]); assert.equal(narrow_state.topic(), undefined); @@ -278,8 +284,8 @@ test("stream_sub", () => { test("pm_ids_string", () => { // This function will return undefined unless we're clearly - // narrowed to a specific PM (including huddles) with real - // users. + // narrowed to a specific direct message (including group + // direct messages) with real users. narrow_state.set_current_filter(undefined); assert.equal(narrow_state.pm_ids_string(), undefined); @@ -289,10 +295,10 @@ test("pm_ids_string", () => { ]); assert.equal(narrow_state.pm_ids_string(), undefined); - set_filter([["pm-with", ""]]); + set_filter([["dm", ""]]); assert.equal(narrow_state.pm_ids_string(), undefined); - set_filter([["pm-with", "[email protected]"]]); + set_filter([["dm", "[email protected]"]]); assert.equal(narrow_state.pm_ids_string(), undefined); const alice = { @@ -310,6 +316,6 @@ test("pm_ids_string", () => { people.add_active_user(alice); people.add_active_user(bob); - set_filter([["pm-with", "[email protected],[email protected]"]]); + set_filter([["dm", "[email protected],[email protected]"]]); assert.equal(narrow_state.pm_ids_string(), "444,555"); }); diff --git a/web/tests/narrow_unread.test.js b/web/tests/narrow_unread.test.js --- a/web/tests/narrow_unread.test.js +++ b/web/tests/narrow_unread.test.js @@ -143,7 +143,7 @@ run_test("get_unread_ids", () => { // this actually does filtering assert_unread_info({flavor: "not_found"}); - terms = [{operator: "pm-with", operand: "[email protected]"}]; + terms = [{operator: "dm", operand: "[email protected]"}]; set_filter(terms); unread_ids = candidate_ids(); assert.deepEqual(unread_ids, []); @@ -158,19 +158,25 @@ run_test("get_unread_ids", () => { msg_id: private_msg.id, }); + // "is:private" was renamed to "is:dm" terms = [{operator: "is", operand: "private"}]; set_filter(terms); unread_ids = candidate_ids(); assert.deepEqual(unread_ids, [private_msg.id]); + terms = [{operator: "is", operand: "dm"}]; + set_filter(terms); + unread_ids = candidate_ids(); + assert.deepEqual(unread_ids, [private_msg.id]); + // For a negated search, our candidate ids will be all // unread messages, even ones that don't pass the filter. - terms = [{operator: "is", operand: "private", negated: true}]; + terms = [{operator: "is", operand: "dm", negated: true}]; set_filter(terms); unread_ids = candidate_ids(); assert.deepEqual(unread_ids, [stream_msg.id, private_msg.id]); - terms = [{operator: "pm-with", operand: "[email protected]"}]; + terms = [{operator: "dm", operand: "[email protected]"}]; set_filter(terms); unread_ids = candidate_ids(); diff --git a/web/tests/people.test.js b/web/tests/people.test.js --- a/web/tests/people.test.js +++ b/web/tests/people.test.js @@ -771,8 +771,8 @@ test_people("message_methods", () => { display_recipient: [{id: maria.user_id}, {id: me.user_id}, {id: charles.user_id}], sender_id: charles.user_id, }; - assert.equal(people.pm_with_url(message), "#narrow/pm-with/301,302-group"); - assert.equal(people.pm_perma_link(message), "#narrow/pm-with/30,301,302-group"); + assert.equal(people.pm_with_url(message), "#narrow/dm/301,302-group"); + assert.equal(people.pm_perma_link(message), "#narrow/dm/30,301,302-group"); assert.equal(people.pm_reply_to(message), "[email protected],[email protected]"); assert.equal(people.small_avatar_url(message), "http://charles.com/foo.png?s=50"); @@ -781,8 +781,8 @@ test_people("message_methods", () => { display_recipient: [{id: maria.user_id}, {id: me.user_id}], avatar_url: "legacy.png", }; - assert.equal(people.pm_with_url(message), "#narrow/pm-with/302-Maria-Athens"); - assert.equal(people.pm_perma_link(message), "#narrow/pm-with/30,302-pm"); + assert.equal(people.pm_with_url(message), "#narrow/dm/302-Maria-Athens"); + assert.equal(people.pm_perma_link(message), "#narrow/dm/30,302-dm"); assert.equal(people.pm_reply_to(message), "[email protected]"); assert.equal(people.small_avatar_url(message), "http://zulip.zulipdev.com/legacy.png?s=50"); @@ -818,8 +818,8 @@ test_people("message_methods", () => { type: "private", display_recipient: [{id: me.user_id}], }; - assert.equal(people.pm_with_url(message), "#narrow/pm-with/30-Me-Myself"); - assert.equal(people.pm_perma_link(message), "#narrow/pm-with/30-pm"); + assert.equal(people.pm_with_url(message), "#narrow/dm/30-Me-Myself"); + assert.equal(people.pm_perma_link(message), "#narrow/dm/30-dm"); message = {type: "stream"}; assert.equal(people.pm_with_user_ids(message), undefined); diff --git a/web/tests/people_errors.test.js b/web/tests/people_errors.test.js --- a/web/tests/people_errors.test.js +++ b/web/tests/people_errors.test.js @@ -75,9 +75,8 @@ run_test("blueslip", () => { display_recipient: [], sender_id: me.user_id, }; - blueslip.expect("error", "Empty recipient list in message", 4); + blueslip.expect("error", "Empty recipient list in message", 3); people.pm_with_user_ids(message); - people.group_pm_with_user_ids(message); people.all_user_ids_in_pm(message); assert.equal(people.pm_perma_link(message), undefined); diff --git a/web/tests/pm_list_data.test.js b/web/tests/pm_list_data.test.js --- a/web/tests/pm_list_data.test.js +++ b/web/tests/pm_list_data.test.js @@ -68,7 +68,7 @@ function test(label, f) { } function set_pm_with_filter(emails) { - const active_filter = new Filter([{operator: "pm-with", operand: emails}]); + const active_filter = new Filter([{operator: "dm", operand: emails}]); narrow_state.set_current_filter(active_filter); } @@ -96,7 +96,7 @@ test("get_conversations", ({override}) => { is_zero: false, recipients: "Me Myself", unread: 1, - url: "#narrow/pm-with/103-Me-Myself", + url: "#narrow/dm/103-Me-Myself", user_circle_class: "user_circle_empty", user_ids_string: "103", status_emoji_info: { @@ -109,7 +109,7 @@ test("get_conversations", ({override}) => { unread: 1, is_zero: false, is_active: false, - url: "#narrow/pm-with/101,102-group", + url: "#narrow/dm/101,102-group", user_circle_class: undefined, is_group: true, status_emoji_info: undefined, @@ -147,7 +147,7 @@ test("get_conversations bot", ({override}) => { unread: 1, is_zero: false, is_active: false, - url: "#narrow/pm-with/314-Outgoing-webhook", + url: "#narrow/dm/314-Outgoing-webhook", status_emoji_info: undefined, user_circle_class: "user_circle_green", is_group: false, @@ -158,7 +158,7 @@ test("get_conversations bot", ({override}) => { unread: 1, is_zero: false, is_active: false, - url: "#narrow/pm-with/101,102-group", + url: "#narrow/dm/101,102-group", user_circle_class: undefined, status_emoji_info: undefined, is_group: true, diff --git a/web/tests/popovers.test.js b/web/tests/popovers.test.js --- a/web/tests/popovers.test.js +++ b/web/tests/popovers.test.js @@ -176,7 +176,7 @@ test_ui("sender_hover", ({override, mock_template}) => { user_type: $t({defaultMessage: "Member"}), user_circle_class: "user_circle_empty", user_last_seen_time_status: "translated: Active more than 2 weeks ago", - pm_with_url: "#narrow/pm-with/42-Alice-Smith", + pm_with_url: "#narrow/dm/42-Alice-Smith", sent_by_url: "#narrow/sender/42-Alice-Smith", private_message_class: "respond_personal_button", show_manage_menu: true, diff --git a/web/tests/search_future.test.js b/web/tests/search_future.test.js --- a/web/tests/search_future.test.js +++ b/web/tests/search_future.test.js @@ -151,11 +151,11 @@ test("initialize", ({mock_template}) => { const search_suggestions = { lookup_table: new Map([ [ - "group-pm-with:zo", + "dm-including:zo", { description_html: "group direct messages including", is_person: true, - search_string: "group-pm-with:[email protected]", + search_string: "dm-including:[email protected]", user_pill_context: { display_value: "<strong>Zo</strong>e", has_image: true, @@ -166,11 +166,11 @@ test("initialize", ({mock_template}) => { }, ], [ - "pm-with:zo", + "dm:zo", { description_html: "direct messages with", is_person: true, - search_string: "pm-with:[email protected]", + search_string: "dm:[email protected]", user_pill_context: { display_value: "<strong>Zo</strong>e", has_image: true, @@ -203,7 +203,7 @@ test("initialize", ({mock_template}) => { }, ], ]), - strings: ["zo", "sender:zo", "pm-with:zo", "group-pm-with:zo"], + strings: ["zo", "sender:zo", "dm:zo", "dm-including:zo"], }; /* Test source */ diff --git a/web/tests/search_now.test.js b/web/tests/search_now.test.js --- a/web/tests/search_now.test.js +++ b/web/tests/search_now.test.js @@ -133,11 +133,11 @@ run_test("initialize", ({mock_template}) => { const search_suggestions = { lookup_table: new Map([ [ - "group-pm-with:zo", + "dm-including:zo", { description_html: "group direct messages including", is_person: true, - search_string: "group-pm-with:[email protected]", + search_string: "dm-including:[email protected]", user_pill_context: { display_value: "<strong>Zo</strong>e", has_image: true, @@ -148,11 +148,11 @@ run_test("initialize", ({mock_template}) => { }, ], [ - "pm-with:zo", + "dm:zo", { description_html: "direct messages with", is_person: true, - search_string: "pm-with:[email protected]", + search_string: "dm:[email protected]", user_pill_context: { display_value: "<strong>Zo</strong>e", has_image: true, @@ -185,7 +185,7 @@ run_test("initialize", ({mock_template}) => { }, ], ]), - strings: ["zo", "sender:zo", "pm-with:zo", "group-pm-with:zo"], + strings: ["zo", "sender:zo", "dm:zo", "dm-including:zo"], }; /* Test source */ diff --git a/web/tests/search_suggestion_future.test.js b/web/tests/search_suggestion_future.test.js --- a/web/tests/search_suggestion_future.test.js +++ b/web/tests/search_suggestion_future.test.js @@ -112,44 +112,57 @@ test("subset_suggestions", () => { assert.deepEqual(suggestions.strings, expected); }); -test("private_suggestions", () => { - let query = "is:private"; +test("dm_suggestions", ({override}) => { + let query = "is:dm"; let suggestions = get_suggestions("", query); let expected = [ - "is:private", - "pm-with:[email protected]", - "pm-with:[email protected]", - "pm-with:[email protected]", - "pm-with:[email protected]", - "pm-with:[email protected]", + "is:dm", + "dm:[email protected]", + "dm:[email protected]", + "dm:[email protected]", + "dm:[email protected]", + "dm:[email protected]", ]; assert.deepEqual(suggestions.strings, expected); query = "al"; - let base_query = "is:private"; + let base_query = "is:dm"; suggestions = get_suggestions(base_query, query); expected = [ "al", "is:alerted", "sender:[email protected]", - "pm-with:[email protected]", - "group-pm-with:[email protected]", + "dm:[email protected]", + "dm-including:[email protected]", ]; assert.deepEqual(suggestions.strings, expected); - query = "pm-with:t"; + // "is:private" was renamed to "is:dm", so + // we suggest "is:dm" to anyone with "is:private" + // in their muscle memory. + query = "is:pr"; + suggestions = get_suggestions("", query); + expected = ["is:dm"]; + assert.deepEqual(suggestions.strings, expected); + + query = "is:private"; suggestions = get_suggestions("", query); - expected = ["pm-with:t", "pm-with:[email protected]"]; + expected = ["is:dm"]; assert.deepEqual(suggestions.strings, expected); - query = "-pm-with:t"; + query = "dm:t"; suggestions = get_suggestions("", query); - expected = ["-pm-with:t", "is:private -pm-with:[email protected]"]; + expected = ["dm:t", "dm:[email protected]"]; assert.deepEqual(suggestions.strings, expected); - query = "pm-with:[email protected]"; + query = "-dm:t"; suggestions = get_suggestions("", query); - expected = ["pm-with:[email protected]"]; + expected = ["-dm:t", "is:dm -dm:[email protected]"]; + assert.deepEqual(suggestions.strings, expected); + + query = "dm:[email protected]"; + suggestions = get_suggestions("", query); + expected = ["dm:[email protected]"]; assert.deepEqual(suggestions.strings, expected); query = "sender:ted"; @@ -181,13 +194,13 @@ test("private_suggestions", () => { // Users can enter bizarre queries, and if they do, we want to // be conservative with suggestions. query = "near:3"; - base_query = "is:private"; + base_query = "is:dm"; suggestions = get_suggestions(base_query, query); expected = ["near:3"]; assert.deepEqual(suggestions.strings, expected); query = "near:3"; - base_query = "pm-with:[email protected]"; + base_query = "dm:[email protected]"; suggestions = get_suggestions(base_query, query); expected = ["near:3"]; assert.deepEqual(suggestions.strings, expected); @@ -200,22 +213,22 @@ test("private_suggestions", () => { assert.deepEqual(suggestions.strings, expected); query = "al"; - base_query = "is:starred has:link is:private"; + base_query = "is:starred has:link is:dm"; suggestions = get_suggestions(base_query, query); expected = [ "al", "is:alerted", "sender:[email protected]", - "pm-with:[email protected]", - "group-pm-with:[email protected]", + "dm:[email protected]", + "dm-including:[email protected]", ]; assert.deepEqual(suggestions.strings, expected); // Make sure it handles past context correctly - query = "pm-with:"; + query = "dm:"; base_query = "stream:Denmark"; suggestions = get_suggestions(base_query, query); - expected = ["pm-with:"]; + expected = ["dm:"]; assert.deepEqual(suggestions.strings, expected); query = "sender:"; @@ -223,85 +236,111 @@ test("private_suggestions", () => { suggestions = get_suggestions(base_query, query); expected = ["sender:"]; assert.deepEqual(suggestions.strings, expected); + + // "pm-with" operator returns search result + // and "dm" operator as a suggestions + override(narrow_state, "stream", () => undefined); + query = "pm-with"; + suggestions = get_suggestions("", query); + expected = ["pm-with", "dm:"]; + assert.deepEqual(suggestions.strings, expected); + + query = "pm-with:t"; + suggestions = get_suggestions("", query); + expected = ["pm-with:t", "dm:[email protected]"]; + assert.deepEqual(suggestions.strings, expected); }); test("group_suggestions", () => { - // Entering a comma in a pm-with query should immediately generate + // Entering a comma in a dm query should immediately generate // suggestions for the next person. - let query = "pm-with:[email protected],"; + let query = "dm:[email protected],"; let suggestions = get_suggestions("", query); let expected = [ - "pm-with:[email protected],", - "pm-with:[email protected],[email protected]", - "pm-with:[email protected],[email protected]", - "pm-with:[email protected],[email protected]", + "dm:[email protected],", + "dm:[email protected],[email protected]", + "dm:[email protected],[email protected]", + "dm:[email protected],[email protected]", ]; assert.deepEqual(suggestions.strings, expected); - // Only the last part of a comma-separated pm-with query should be used to + // Only the last part of a comma-separated dm query should be used to // generate suggestions. - query = "pm-with:[email protected],t"; + query = "dm:[email protected],t"; suggestions = get_suggestions("", query); - expected = ["pm-with:[email protected],t", "pm-with:[email protected],[email protected]"]; + expected = ["dm:[email protected],t", "dm:[email protected],[email protected]"]; assert.deepEqual(suggestions.strings, expected); // Smit should also generate [email protected] (Ted Smith) as a suggestion. - query = "pm-with:[email protected],Smit"; + query = "dm:[email protected],Smit"; suggestions = get_suggestions("", query); - expected = ["pm-with:[email protected],Smit", "pm-with:[email protected],[email protected]"]; + expected = ["dm:[email protected],Smit", "dm:[email protected],[email protected]"]; assert.deepEqual(suggestions.strings, expected); // Do not suggest "[email protected]" (the name of the current user) - query = "pm-with:[email protected],mys"; + query = "dm:[email protected],mys"; suggestions = get_suggestions("", query); - expected = ["pm-with:[email protected],mys"]; + expected = ["dm:[email protected],mys"]; assert.deepEqual(suggestions.strings, expected); // No superfluous suggestions should be generated. - query = "pm-with:[email protected],red"; + query = "dm:[email protected],red"; suggestions = get_suggestions("", query); - expected = ["pm-with:[email protected],red"]; + expected = ["dm:[email protected],red"]; assert.deepEqual(suggestions.strings, expected); - // is:private should be properly prepended to each suggestion if the pm-with - // operator is negated. + // "is:dm" should be properly prepended to each suggestion + // if the "dm" operator is negated. - query = "-pm-with:[email protected],"; + query = "-dm:[email protected],"; suggestions = get_suggestions("", query); expected = [ - "-pm-with:[email protected],", - "is:private -pm-with:[email protected],[email protected]", - "is:private -pm-with:[email protected],[email protected]", - "is:private -pm-with:[email protected],[email protected]", + "-dm:[email protected],", + "is:dm -dm:[email protected],[email protected]", + "is:dm -dm:[email protected],[email protected]", + "is:dm -dm:[email protected],[email protected]", ]; assert.deepEqual(suggestions.strings, expected); - query = "-pm-with:[email protected],t"; + query = "-dm:[email protected],t"; suggestions = get_suggestions("", query); - expected = ["-pm-with:[email protected],t", "is:private -pm-with:[email protected],[email protected]"]; + expected = ["-dm:[email protected],t", "is:dm -dm:[email protected],[email protected]"]; assert.deepEqual(suggestions.strings, expected); - query = "-pm-with:[email protected],Smit"; + query = "-dm:[email protected],Smit"; suggestions = get_suggestions("", query); - expected = ["-pm-with:[email protected],Smit", "is:private -pm-with:[email protected],[email protected]"]; + expected = ["-dm:[email protected],Smit", "is:dm -dm:[email protected],[email protected]"]; assert.deepEqual(suggestions.strings, expected); - query = "-pm-with:[email protected],red"; + query = "-dm:[email protected],red"; suggestions = get_suggestions("", query); - expected = ["-pm-with:[email protected],red"]; + expected = ["-dm:[email protected],red"]; + assert.deepEqual(suggestions.strings, expected); + + // If user types "pm-with" operator, an email and a comma, + // show suggestions for group direct messages with the "dm" + // operator. + query = "pm-with:[email protected],"; + suggestions = get_suggestions("", query); + expected = [ + "pm-with:[email protected],", + "dm:[email protected],[email protected]", + "dm:[email protected],[email protected]", + "dm:[email protected],[email protected]", + ]; assert.deepEqual(suggestions.strings, expected); // Test multiple operators - query = "pm-with:[email protected],Smit"; + query = "dm:[email protected],Smit"; let base_query = "is:starred has:link"; suggestions = get_suggestions(base_query, query); - expected = ["pm-with:[email protected],Smit", "pm-with:[email protected],[email protected]"]; + expected = ["dm:[email protected],Smit", "dm:[email protected],[email protected]"]; assert.deepEqual(suggestions.strings, expected); - query = "pm-with:[email protected],Smit"; + query = "dm:[email protected],Smit"; base_query = "stream:Denmark has:link"; suggestions = get_suggestions(base_query, query); - expected = ["pm-with:[email protected],Smit"]; + expected = ["dm:[email protected],Smit"]; assert.deepEqual(suggestions.strings, expected); function message(user_ids, timestamp) { @@ -319,42 +358,45 @@ test("group_suggestions", () => { message([bob.user_id, ted.user_id, jeff.user_id], 98), ]); - // Simulate a past huddle which should now prioritize ted over alice - query = "pm-with:[email protected],"; + // Simulate a past group direct message which should now + // prioritize ted over alice + query = "dm:[email protected],"; suggestions = get_suggestions("", query); expected = [ - "pm-with:[email protected],", - "pm-with:[email protected],[email protected]", - "pm-with:[email protected],[email protected]", - "pm-with:[email protected],[email protected]", + "dm:[email protected],", + "dm:[email protected],[email protected]", + "dm:[email protected],[email protected]", + "dm:[email protected],[email protected]", ]; assert.deepEqual(suggestions.strings, expected); - // bob,ted,jeff is already an existing huddle, so prioritize this one - query = "pm-with:[email protected],[email protected],"; + // bob, ted, and jeff are already an existing group direct message, + // so prioritize this one + query = "dm:[email protected],[email protected],"; suggestions = get_suggestions("", query); expected = [ - "pm-with:[email protected],[email protected],", - "pm-with:[email protected],[email protected],[email protected]", - "pm-with:[email protected],[email protected],[email protected]", + "dm:[email protected],[email protected],", + "dm:[email protected],[email protected],[email protected]", + "dm:[email protected],[email protected],[email protected]", ]; assert.deepEqual(suggestions.strings, expected); - // bob,ted,jeff is already an existing huddle, but if we start with just jeff, - // then don't prioritize ted over alice because it doesn't complete the full huddle. - query = "pm-with:[email protected],"; + // bob, ted, and jeff are already an existing group direct message, + // but if we start with just jeff, then don't prioritize ted over + // alice because it doesn't complete the full group direct message. + query = "dm:[email protected],"; suggestions = get_suggestions("", query); expected = [ - "pm-with:[email protected],", - "pm-with:[email protected],[email protected]", - "pm-with:[email protected],[email protected]", - "pm-with:[email protected],[email protected]", + "dm:[email protected],", + "dm:[email protected],[email protected]", + "dm:[email protected],[email protected]", + "dm:[email protected],[email protected]", ]; assert.deepEqual(suggestions.strings, expected); - query = "pm-with:[email protected],[email protected] hi"; + query = "dm:[email protected],[email protected] hi"; suggestions = get_suggestions("", query); - expected = ["pm-with:[email protected],[email protected] hi"]; + expected = ["dm:[email protected],[email protected] hi"]; assert.deepEqual(suggestions.strings, expected); }); @@ -369,7 +411,7 @@ test("empty_query_suggestions", () => { const expected = [ "", "streams:public", - "is:private", + "is:dm", "is:starred", "is:mentioned", "is:alerted", @@ -388,7 +430,7 @@ test("empty_query_suggestions", () => { function describe(q) { return suggestions.lookup_table.get(q).description_html; } - assert.equal(describe("is:private"), "Direct messages"); + assert.equal(describe("is:dm"), "Direct messages"); assert.equal(describe("is:starred"), "Starred messages"); assert.equal(describe("is:mentioned"), "@-mentions"); assert.equal(describe("is:alerted"), "Alerted messages"); @@ -466,15 +508,15 @@ test("check_is_suggestions", ({override}) => { let suggestions = get_suggestions("", query); let expected = [ "i", - "is:private", + "is:dm", "is:starred", "is:mentioned", "is:alerted", "is:unread", "is:resolved", "sender:[email protected]", - "pm-with:[email protected]", - "group-pm-with:[email protected]", + "dm:[email protected]", + "dm-including:[email protected]", "has:image", ]; assert.deepEqual(suggestions.strings, expected); @@ -483,7 +525,7 @@ test("check_is_suggestions", ({override}) => { return suggestions.lookup_table.get(q).description_html; } - assert.equal(describe("is:private"), "Direct messages"); + assert.equal(describe("is:dm"), "Direct messages"); assert.equal(describe("is:starred"), "Starred messages"); assert.equal(describe("is:mentioned"), "@-mentions"); assert.equal(describe("is:alerted"), "Alerted messages"); @@ -494,7 +536,7 @@ test("check_is_suggestions", ({override}) => { suggestions = get_suggestions("", query); expected = [ "-i", - "-is:private", + "-is:dm", "-is:starred", "-is:mentioned", "-is:alerted", @@ -503,7 +545,7 @@ test("check_is_suggestions", ({override}) => { ]; assert.deepEqual(suggestions.strings, expected); - assert.equal(describe("-is:private"), "Exclude direct messages"); + assert.equal(describe("-is:dm"), "Exclude direct messages"); assert.equal(describe("-is:starred"), "Exclude starred messages"); assert.equal(describe("-is:mentioned"), "Exclude @-mentions"); assert.equal(describe("-is:alerted"), "Exclude alerted messages"); @@ -515,7 +557,7 @@ test("check_is_suggestions", ({override}) => { expected = [ "", "streams:public", - "is:private", + "is:dm", "is:starred", "is:mentioned", "is:alerted", @@ -531,7 +573,7 @@ test("check_is_suggestions", ({override}) => { assert.deepEqual(suggestions.strings, expected); query = ""; - let base_query = "is:private"; + let base_query = "is:dm"; suggestions = get_suggestions(base_query, query); expected = [ "is:starred", @@ -549,14 +591,7 @@ test("check_is_suggestions", ({override}) => { query = "is:"; suggestions = get_suggestions("", query); - expected = [ - "is:private", - "is:starred", - "is:mentioned", - "is:alerted", - "is:unread", - "is:resolved", - ]; + expected = ["is:dm", "is:starred", "is:mentioned", "is:alerted", "is:unread", "is:resolved"]; assert.deepEqual(suggestions.strings, expected); query = "is:st"; @@ -672,12 +707,7 @@ test("topic_suggestions", ({override}) => { stream_data.add_sub({stream_id: office_id, name: "office", subscribed: true}); suggestions = get_suggestions("", "te"); - expected = [ - "te", - "sender:[email protected]", - "pm-with:[email protected]", - "group-pm-with:[email protected]", - ]; + expected = ["te", "sender:[email protected]", "dm:[email protected]", "dm-including:[email protected]"]; assert.deepEqual(suggestions.strings, expected); stream_topic_history.add_message({ @@ -696,8 +726,8 @@ test("topic_suggestions", ({override}) => { expected = [ "te", "sender:[email protected]", - "pm-with:[email protected]", - "group-pm-with:[email protected]", + "dm:[email protected]", + "dm-including:[email protected]", "stream:office topic:team", "stream:office topic:test", ]; @@ -729,7 +759,7 @@ test("topic_suggestions", ({override}) => { expected = ["topic:", "topic:REXX"]; assert.deepEqual(suggestions.strings, expected); - suggestions = get_suggestions("is:private stream:devel", "topic:"); + suggestions = get_suggestions("is:dm stream:devel", "topic:"); expected = ["topic:"]; assert.deepEqual(suggestions.strings, expected); @@ -850,51 +880,46 @@ test("people_suggestions", ({override}) => { "te", "sender:[email protected]", "sender:[email protected]", - "pm-with:[email protected]", // bob térry - "pm-with:[email protected]", - "group-pm-with:[email protected]", - "group-pm-with:[email protected]", + "dm:[email protected]", // bob térry + "dm:[email protected]", + "dm-including:[email protected]", + "dm-including:[email protected]", ]; assert.deepEqual(suggestions.strings, expected); const is_person = (q) => suggestions.lookup_table.get(q).is_person; - assert.equal(is_person("pm-with:[email protected]"), true); + assert.equal(is_person("dm:[email protected]"), true); assert.equal(is_person("sender:[email protected]"), true); - assert.equal(is_person("group-pm-with:[email protected]"), true); + assert.equal(is_person("dm-including:[email protected]"), true); const has_image = (q) => suggestions.lookup_table.get(q).user_pill_context.has_image; - assert.equal(has_image("pm-with:[email protected]"), true); + assert.equal(has_image("dm:[email protected]"), true); assert.equal(has_image("sender:[email protected]"), true); - assert.equal(has_image("group-pm-with:[email protected]"), true); + assert.equal(has_image("dm-including:[email protected]"), true); const describe = (q) => suggestions.lookup_table.get(q).description_html; - assert.equal(describe("pm-with:[email protected]"), "Direct messages with"); + assert.equal(describe("dm:[email protected]"), "Direct messages with"); assert.equal(describe("sender:[email protected]"), "Sent by"); - assert.equal(describe("group-pm-with:[email protected]"), "Group direct messages including"); + assert.equal(describe("dm-including:[email protected]"), "Direct messages including"); let expectedString = "<strong>Te</strong>d Smith"; const get_full_name = (q) => suggestions.lookup_table.get(q).user_pill_context.display_value.string; assert.equal(get_full_name("sender:[email protected]"), expectedString); - assert.equal(get_full_name("pm-with:[email protected]"), expectedString); - assert.equal(get_full_name("group-pm-with:[email protected]"), expectedString); + assert.equal(get_full_name("dm:[email protected]"), expectedString); + assert.equal(get_full_name("dm-including:[email protected]"), expectedString); expectedString = `${example_avatar_url}?s=50`; const get_avatar_url = (q) => suggestions.lookup_table.get(q).user_pill_context.img_src; - assert.equal(get_avatar_url("pm-with:[email protected]"), expectedString); + assert.equal(get_avatar_url("dm:[email protected]"), expectedString); assert.equal(get_avatar_url("sender:[email protected]"), expectedString); - assert.equal(get_avatar_url("group-pm-with:[email protected]"), expectedString); + assert.equal(get_avatar_url("dm-including:[email protected]"), expectedString); suggestions = get_suggestions("", "Ted "); // note space - expected = [ - "Ted", - "sender:[email protected]", - "pm-with:[email protected]", - "group-pm-with:[email protected]", - ]; + expected = ["Ted", "sender:[email protected]", "dm:[email protected]", "dm-including:[email protected]"]; assert.deepEqual(suggestions.strings, expected); @@ -937,11 +962,6 @@ test("operator_suggestions", ({override}) => { expected = ["st", "streams:public", "is:starred", "stream:"]; assert.deepEqual(suggestions.strings, expected); - query = "group-"; - suggestions = get_suggestions("", query); - expected = ["group-", "group-pm-with:"]; - assert.deepEqual(suggestions.strings, expected); - query = "-s"; suggestions = get_suggestions("", query); expected = ["-s", "-streams:public", "-sender:[email protected]", "-stream:", "-sender:"]; @@ -980,15 +1000,15 @@ test("queries_with_spaces", () => { // When input search query contains multiple operators // and a pill hasn't been formed from those operators. test("multiple_operators_without_pills", () => { - let query = "is:private al"; + let query = "is:dm al"; let base_query = ""; let suggestions = get_suggestions(base_query, query); let expected = [ - "is:private al", - "is:private is:alerted", - "is:private sender:[email protected]", - "is:private pm-with:[email protected]", - "is:private group-pm-with:[email protected]", + "is:dm al", + "is:dm is:alerted", + "is:dm sender:[email protected]", + "is:dm dm:[email protected]", + "is:dm dm-including:[email protected]", ]; assert.deepEqual(suggestions.strings, expected); diff --git a/web/tests/search_suggestion_now.test.js b/web/tests/search_suggestion_now.test.js --- a/web/tests/search_suggestion_now.test.js +++ b/web/tests/search_suggestion_now.test.js @@ -114,44 +114,57 @@ test("subset_suggestions", () => { assert.deepEqual(suggestions.strings, expected); }); -test("private_suggestions", () => { - let query = "is:private"; +test("dm_suggestions", ({override}) => { + let query = "is:dm"; let suggestions = get_suggestions("", query); let expected = [ - "is:private", - "pm-with:[email protected]", - "pm-with:[email protected]", - "pm-with:[email protected]", - "pm-with:[email protected]", - "pm-with:[email protected]", + "is:dm", + "dm:[email protected]", + "dm:[email protected]", + "dm:[email protected]", + "dm:[email protected]", + "dm:[email protected]", ]; assert.deepEqual(suggestions.strings, expected); - query = "is:private al"; + query = "is:dm al"; suggestions = get_suggestions("", query); expected = [ - "is:private al", - "is:private is:alerted", - "is:private sender:[email protected]", - "is:private pm-with:[email protected]", - "is:private group-pm-with:[email protected]", - "is:private", + "is:dm al", + "is:dm is:alerted", + "is:dm sender:[email protected]", + "is:dm dm:[email protected]", + "is:dm dm-including:[email protected]", + "is:dm", ]; assert.deepEqual(suggestions.strings, expected); - query = "pm-with:t"; + // "is:private" was renamed to "is:dm", so + // we suggest "is:dm" to anyone with "is:private" + // in their muscle memory. + query = "is:pr"; + suggestions = get_suggestions("", query); + expected = ["is:dm"]; + assert.deepEqual(suggestions.strings, expected); + + query = "is:private"; suggestions = get_suggestions("", query); - expected = ["pm-with:t", "pm-with:[email protected]"]; + expected = ["is:dm"]; assert.deepEqual(suggestions.strings, expected); - query = "-pm-with:t"; + query = "dm:t"; suggestions = get_suggestions("", query); - expected = ["-pm-with:t", "is:private -pm-with:[email protected]"]; + expected = ["dm:t", "dm:[email protected]"]; assert.deepEqual(suggestions.strings, expected); - query = "pm-with:[email protected]"; + query = "-dm:t"; suggestions = get_suggestions("", query); - expected = ["pm-with:[email protected]"]; + expected = ["-dm:t", "is:dm -dm:[email protected]"]; + assert.deepEqual(suggestions.strings, expected); + + query = "dm:[email protected]"; + suggestions = get_suggestions("", query); + expected = ["dm:[email protected]"]; assert.deepEqual(suggestions.strings, expected); query = "sender:ted"; @@ -181,14 +194,14 @@ test("private_suggestions", () => { // Users can enter bizarre queries, and if they do, we want to // be conservative with suggestions. - query = "is:private near:3"; + query = "is:dm near:3"; suggestions = get_suggestions("", query); - expected = ["is:private near:3", "is:private"]; + expected = ["is:dm near:3", "is:dm"]; assert.deepEqual(suggestions.strings, expected); - query = "pm-with:[email protected] near:3"; + query = "dm:[email protected] near:3"; suggestions = get_suggestions("", query); - expected = ["pm-with:[email protected] near:3", "pm-with:[email protected]"]; + expected = ["dm:[email protected] near:3", "dm:[email protected]"]; assert.deepEqual(suggestions.strings, expected); // Make sure suggestions still work if preceding tokens @@ -197,113 +210,139 @@ test("private_suggestions", () => { expected = ["is:alerted sender:[email protected]", "is:alerted"]; assert.deepEqual(suggestions.strings, expected); - query = "is:starred has:link is:private al"; + query = "is:starred has:link is:dm al"; suggestions = get_suggestions("", query); expected = [ - "is:starred has:link is:private al", - "is:starred has:link is:private is:alerted", - "is:starred has:link is:private sender:[email protected]", - "is:starred has:link is:private pm-with:[email protected]", - "is:starred has:link is:private group-pm-with:[email protected]", - "is:starred has:link is:private", + "is:starred has:link is:dm al", + "is:starred has:link is:dm is:alerted", + "is:starred has:link is:dm sender:[email protected]", + "is:starred has:link is:dm dm:[email protected]", + "is:starred has:link is:dm dm-including:[email protected]", + "is:starred has:link is:dm", "is:starred has:link", "is:starred", ]; assert.deepEqual(suggestions.strings, expected); // Make sure it handles past context correctly - query = "stream:Denmark pm-with:"; + query = "stream:Denmark dm:"; suggestions = get_suggestions("", query); - expected = ["stream:Denmark pm-with:", "stream:Denmark"]; + expected = ["stream:Denmark dm:", "stream:Denmark"]; assert.deepEqual(suggestions.strings, expected); query = "sender:[email protected] sender:"; suggestions = get_suggestions("", query); expected = ["sender:[email protected] sender:", "sender:[email protected]"]; assert.deepEqual(suggestions.strings, expected); + + // "pm-with" operator returns search result + // and "dm" operator as a suggestions + override(narrow_state, "stream", () => undefined); + query = "pm-with"; + suggestions = get_suggestions("", query); + expected = ["pm-with", "dm:"]; + assert.deepEqual(suggestions.strings, expected); + + query = "pm-with:t"; + suggestions = get_suggestions("", query); + expected = ["pm-with:t", "dm:[email protected]"]; + assert.deepEqual(suggestions.strings, expected); }); test("group_suggestions", () => { - // Entering a comma in a pm-with query should immediately generate - // suggestions for the next person. - let query = "pm-with:[email protected],"; + // Entering a comma in a "dm:" query should immediately + // generate suggestions for the next person. + let query = "dm:[email protected],"; let suggestions = get_suggestions("", query); let expected = [ - "pm-with:[email protected],", - "pm-with:[email protected],[email protected]", - "pm-with:[email protected],[email protected]", - "pm-with:[email protected],[email protected]", + "dm:[email protected],", + "dm:[email protected],[email protected]", + "dm:[email protected],[email protected]", + "dm:[email protected],[email protected]", ]; assert.deepEqual(suggestions.strings, expected); - // Only the last part of a comma-separated pm-with query should be used to - // generate suggestions. - query = "pm-with:[email protected],t"; + // Only the last part of a comma-separated "dm" query + // should be used to generate suggestions. + query = "dm:[email protected],t"; suggestions = get_suggestions("", query); - expected = ["pm-with:[email protected],t", "pm-with:[email protected],[email protected]"]; + expected = ["dm:[email protected],t", "dm:[email protected],[email protected]"]; assert.deepEqual(suggestions.strings, expected); // Smit should also generate [email protected] (Ted Smith) as a suggestion. - query = "pm-with:[email protected],Smit"; + query = "dm:[email protected],Smit"; suggestions = get_suggestions("", query); - expected = ["pm-with:[email protected],Smit", "pm-with:[email protected],[email protected]"]; + expected = ["dm:[email protected],Smit", "dm:[email protected],[email protected]"]; assert.deepEqual(suggestions.strings, expected); // Do not suggest "[email protected]" (the name of the current user) - query = "pm-with:[email protected],my"; + query = "dm:[email protected],my"; suggestions = get_suggestions("", query); - expected = ["pm-with:[email protected],my"]; + expected = ["dm:[email protected],my"]; assert.deepEqual(suggestions.strings, expected); // No superfluous suggestions should be generated. - query = "pm-with:[email protected],red"; + query = "dm:[email protected],red"; suggestions = get_suggestions("", query); - expected = ["pm-with:[email protected],red"]; + expected = ["dm:[email protected],red"]; assert.deepEqual(suggestions.strings, expected); - // is:private should be properly prepended to each suggestion if the pm-with - // operator is negated. + // "is:dm" should be properly prepended to each suggestion + // if the "dm" operator is negated. - query = "-pm-with:[email protected],"; + query = "-dm:[email protected],"; suggestions = get_suggestions("", query); expected = [ - "-pm-with:[email protected],", - "is:private -pm-with:[email protected],[email protected]", - "is:private -pm-with:[email protected],[email protected]", - "is:private -pm-with:[email protected],[email protected]", + "-dm:[email protected],", + "is:dm -dm:[email protected],[email protected]", + "is:dm -dm:[email protected],[email protected]", + "is:dm -dm:[email protected],[email protected]", ]; assert.deepEqual(suggestions.strings, expected); - query = "-pm-with:[email protected],t"; + query = "-dm:[email protected],t"; suggestions = get_suggestions("", query); - expected = ["-pm-with:[email protected],t", "is:private -pm-with:[email protected],[email protected]"]; + expected = ["-dm:[email protected],t", "is:dm -dm:[email protected],[email protected]"]; assert.deepEqual(suggestions.strings, expected); - query = "-pm-with:[email protected],Smit"; + query = "-dm:[email protected],Smit"; suggestions = get_suggestions("", query); - expected = ["-pm-with:[email protected],Smit", "is:private -pm-with:[email protected],[email protected]"]; + expected = ["-dm:[email protected],Smit", "is:dm -dm:[email protected],[email protected]"]; assert.deepEqual(suggestions.strings, expected); - query = "-pm-with:[email protected],red"; + query = "-dm:[email protected],red"; suggestions = get_suggestions("", query); - expected = ["-pm-with:[email protected],red"]; + expected = ["-dm:[email protected],red"]; + assert.deepEqual(suggestions.strings, expected); + + // If user types "pm-with" operator, an email and a comma, + // show suggestions for group direct messages with the "dm" + // operator. + query = "pm-with:[email protected],"; + suggestions = get_suggestions("", query); + expected = [ + "pm-with:[email protected],", + "dm:[email protected],[email protected]", + "dm:[email protected],[email protected]", + "dm:[email protected],[email protected]", + ]; assert.deepEqual(suggestions.strings, expected); // Test multiple operators - query = "is:starred has:link pm-with:[email protected],Smit"; + query = "is:starred has:link dm:[email protected],Smit"; suggestions = get_suggestions("", query); expected = [ - "is:starred has:link pm-with:[email protected],Smit", - "is:starred has:link pm-with:[email protected],[email protected]", + "is:starred has:link dm:[email protected],Smit", + "is:starred has:link dm:[email protected],[email protected]", "is:starred has:link", "is:starred", ]; assert.deepEqual(suggestions.strings, expected); - query = "stream:Denmark has:link pm-with:[email protected],Smit"; + query = "stream:Denmark has:link dm:[email protected],Smit"; suggestions = get_suggestions("", query); expected = [ - "stream:Denmark has:link pm-with:[email protected],Smit", + "stream:Denmark has:link dm:[email protected],Smit", "stream:Denmark has:link", "stream:Denmark", ]; @@ -324,42 +363,45 @@ test("group_suggestions", () => { message([bob.user_id, ted.user_id, jeff.user_id], 98), ]); - // Simulate a past huddle which should now prioritize ted over alice - query = "pm-with:[email protected],"; + // Simulate a past group direct message which should now + // prioritize ted over alice + query = "dm:[email protected],"; suggestions = get_suggestions("", query); expected = [ - "pm-with:[email protected],", - "pm-with:[email protected],[email protected]", - "pm-with:[email protected],[email protected]", - "pm-with:[email protected],[email protected]", + "dm:[email protected],", + "dm:[email protected],[email protected]", + "dm:[email protected],[email protected]", + "dm:[email protected],[email protected]", ]; assert.deepEqual(suggestions.strings, expected); - // bob,ted,jeff is already an existing huddle, so prioritize this one - query = "pm-with:[email protected],[email protected],"; + // bob, ted, and jeff are already an existing group direct message, + // so prioritize this one + query = "dm:[email protected],[email protected],"; suggestions = get_suggestions("", query); expected = [ - "pm-with:[email protected],[email protected],", - "pm-with:[email protected],[email protected],[email protected]", - "pm-with:[email protected],[email protected],[email protected]", + "dm:[email protected],[email protected],", + "dm:[email protected],[email protected],[email protected]", + "dm:[email protected],[email protected],[email protected]", ]; assert.deepEqual(suggestions.strings, expected); - // bob,ted,jeff is already an existing huddle, but if we start with just jeff, - // then don't prioritize ted over alice because it doesn't complete the full huddle. - query = "pm-with:[email protected],"; + // bob, ted, and jeff are already an existing group direct message, + // but if we start with just jeff, then don't prioritize ted over + // alice because it doesn't complete the full group direct message. + query = "dm:[email protected],"; suggestions = get_suggestions("", query); expected = [ - "pm-with:[email protected],", - "pm-with:[email protected],[email protected]", - "pm-with:[email protected],[email protected]", - "pm-with:[email protected],[email protected]", + "dm:[email protected],", + "dm:[email protected],[email protected]", + "dm:[email protected],[email protected]", + "dm:[email protected],[email protected]", ]; assert.deepEqual(suggestions.strings, expected); - query = "pm-with:[email protected],[email protected] hi"; + query = "dm:[email protected],[email protected] hi"; suggestions = get_suggestions("", query); - expected = ["pm-with:[email protected],[email protected] hi", "pm-with:[email protected],[email protected]"]; + expected = ["dm:[email protected],[email protected] hi", "dm:[email protected],[email protected]"]; assert.deepEqual(suggestions.strings, expected); }); @@ -374,7 +416,7 @@ test("empty_query_suggestions", () => { const expected = [ "", "streams:public", - "is:private", + "is:dm", "is:starred", "is:mentioned", "is:alerted", @@ -393,7 +435,7 @@ test("empty_query_suggestions", () => { function describe(q) { return suggestions.lookup_table.get(q).description_html; } - assert.equal(describe("is:private"), "Direct messages"); + assert.equal(describe("is:dm"), "Direct messages"); assert.equal(describe("is:starred"), "Starred messages"); assert.equal(describe("is:mentioned"), "@-mentions"); assert.equal(describe("is:alerted"), "Alerted messages"); @@ -474,15 +516,15 @@ test("check_is_suggestions", ({override}) => { let suggestions = get_suggestions("", query); let expected = [ "i", - "is:private", + "is:dm", "is:starred", "is:mentioned", "is:alerted", "is:unread", "is:resolved", "sender:[email protected]", - "pm-with:[email protected]", - "group-pm-with:[email protected]", + "dm:[email protected]", + "dm-including:[email protected]", "has:image", ]; assert.deepEqual(suggestions.strings, expected); @@ -491,7 +533,7 @@ test("check_is_suggestions", ({override}) => { return suggestions.lookup_table.get(q).description_html; } - assert.equal(describe("is:private"), "Direct messages"); + assert.equal(describe("is:dm"), "Direct messages"); assert.equal(describe("is:starred"), "Starred messages"); assert.equal(describe("is:mentioned"), "@-mentions"); assert.equal(describe("is:alerted"), "Alerted messages"); @@ -502,7 +544,7 @@ test("check_is_suggestions", ({override}) => { suggestions = get_suggestions("", query); expected = [ "-i", - "-is:private", + "-is:dm", "-is:starred", "-is:mentioned", "-is:alerted", @@ -511,7 +553,7 @@ test("check_is_suggestions", ({override}) => { ]; assert.deepEqual(suggestions.strings, expected); - assert.equal(describe("-is:private"), "Exclude direct messages"); + assert.equal(describe("-is:dm"), "Exclude direct messages"); assert.equal(describe("-is:starred"), "Exclude starred messages"); assert.equal(describe("-is:mentioned"), "Exclude @-mentions"); assert.equal(describe("-is:alerted"), "Exclude alerted messages"); @@ -522,14 +564,7 @@ test("check_is_suggestions", ({override}) => { query = "is:"; suggestions = get_suggestions("", query); - expected = [ - "is:private", - "is:starred", - "is:mentioned", - "is:alerted", - "is:unread", - "is:resolved", - ]; + expected = ["is:dm", "is:starred", "is:mentioned", "is:alerted", "is:unread", "is:resolved"]; assert.deepEqual(suggestions.strings, expected); query = "is:st"; @@ -639,12 +674,7 @@ test("topic_suggestions", ({override}) => { stream_data.add_sub({stream_id: office_id, name: "office", subscribed: true}); suggestions = get_suggestions("", "te"); - expected = [ - "te", - "sender:[email protected]", - "pm-with:[email protected]", - "group-pm-with:[email protected]", - ]; + expected = ["te", "sender:[email protected]", "dm:[email protected]", "dm-including:[email protected]"]; assert.deepEqual(suggestions.strings, expected); stream_topic_history.add_message({ @@ -663,8 +693,8 @@ test("topic_suggestions", ({override}) => { expected = [ "te", "sender:[email protected]", - "pm-with:[email protected]", - "group-pm-with:[email protected]", + "dm:[email protected]", + "dm-including:[email protected]", "stream:office topic:team", "stream:office topic:test", ]; @@ -702,8 +732,8 @@ test("topic_suggestions", ({override}) => { ]; assert.deepEqual(suggestions.strings, expected); - suggestions = get_suggestions("", "is:private stream:devel topic:"); - expected = ["is:private stream:devel topic:", "is:private stream:devel", "is:private"]; + suggestions = get_suggestions("", "is:dm stream:devel topic:"); + expected = ["is:dm stream:devel topic:", "is:dm stream:devel", "is:dm"]; assert.deepEqual(suggestions.strings, expected); suggestions = get_suggestions("", "topic:REXX stream:devel topic:"); @@ -822,10 +852,10 @@ test("people_suggestions", ({override}) => { "te", "sender:[email protected]", "sender:[email protected]", - "pm-with:[email protected]", // bob térry - "pm-with:[email protected]", - "group-pm-with:[email protected]", - "group-pm-with:[email protected]", + "dm:[email protected]", // bob térry + "dm:[email protected]", + "dm-including:[email protected]", + "dm-including:[email protected]", ]; assert.deepEqual(suggestions.strings, expected); @@ -833,23 +863,23 @@ test("people_suggestions", ({override}) => { function is_person(q) { return suggestions.lookup_table.get(q).is_person; } - assert.equal(is_person("pm-with:[email protected]"), true); + assert.equal(is_person("dm:[email protected]"), true); assert.equal(is_person("sender:[email protected]"), true); - assert.equal(is_person("group-pm-with:[email protected]"), true); + assert.equal(is_person("dm-including:[email protected]"), true); function has_image(q) { return suggestions.lookup_table.get(q).user_pill_context.has_image; } - assert.equal(has_image("pm-with:[email protected]"), true); + assert.equal(has_image("dm:[email protected]"), true); assert.equal(has_image("sender:[email protected]"), true); - assert.equal(has_image("group-pm-with:[email protected]"), true); + assert.equal(has_image("dm-including:[email protected]"), true); function describe(q) { return suggestions.lookup_table.get(q).description_html; } - assert.equal(describe("pm-with:[email protected]"), "Direct messages with"); + assert.equal(describe("dm:[email protected]"), "Direct messages with"); assert.equal(describe("sender:[email protected]"), "Sent by"); - assert.equal(describe("group-pm-with:[email protected]"), "Group direct messages including"); + assert.equal(describe("dm-including:[email protected]"), "Direct messages including"); let expectedString = "<strong>Te</strong>d Smith"; @@ -857,26 +887,21 @@ test("people_suggestions", ({override}) => { return suggestions.lookup_table.get(q).user_pill_context.display_value.string; } assert.equal(get_full_name("sender:[email protected]"), expectedString); - assert.equal(get_full_name("pm-with:[email protected]"), expectedString); - assert.equal(get_full_name("group-pm-with:[email protected]"), expectedString); + assert.equal(get_full_name("dm:[email protected]"), expectedString); + assert.equal(get_full_name("dm-including:[email protected]"), expectedString); expectedString = example_avatar_url + "?s=50"; function get_avatar_url(q) { return suggestions.lookup_table.get(q).user_pill_context.img_src; } - assert.equal(get_avatar_url("pm-with:[email protected]"), expectedString); + assert.equal(get_avatar_url("dm:[email protected]"), expectedString); assert.equal(get_avatar_url("sender:[email protected]"), expectedString); - assert.equal(get_avatar_url("group-pm-with:[email protected]"), expectedString); + assert.equal(get_avatar_url("dm-including:[email protected]"), expectedString); suggestions = get_suggestions("", "Ted "); // note space - expected = [ - "Ted", - "sender:[email protected]", - "pm-with:[email protected]", - "group-pm-with:[email protected]", - ]; + expected = ["Ted", "sender:[email protected]", "dm:[email protected]", "dm-including:[email protected]"]; assert.deepEqual(suggestions.strings, expected); @@ -910,11 +935,6 @@ test("operator_suggestions", ({override}) => { expected = ["st", "streams:public", "is:starred", "stream:"]; assert.deepEqual(suggestions.strings, expected); - query = "group-"; - suggestions = get_suggestions("", query); - expected = ["group-", "group-pm-with:"]; - assert.deepEqual(suggestions.strings, expected); - query = "-s"; suggestions = get_suggestions("", query); expected = ["-s", "-streams:public", "-sender:[email protected]", "-stream:", "-sender:"]; diff --git a/web/tests/typing_events.test.js b/web/tests/typing_events.test.js --- a/web/tests/typing_events.test.js +++ b/web/tests/typing_events.test.js @@ -46,7 +46,7 @@ run_test("render_notifications_for_narrow", ({override, mock_template}) => { override(page_params, "user_id", anna.user_id); const group = [anna.user_id, vronsky.user_id, levin.user_id, kitty.user_id]; const group_emails = `${anna.email},${vronsky.email},${levin.email},${kitty.email}`; - narrow_state.set_current_filter(new Filter([{operator: "pm-with", operand: group_emails}])); + narrow_state.set_current_filter(new Filter([{operator: "dm", operand: group_emails}])); const $typing_notifications = $("#typing_notifications"); diff --git a/zerver/tests/fixtures/narrow.json b/zerver/tests/fixtures/narrow.json --- a/zerver/tests/fixtures/narrow.json +++ b/zerver/tests/fixtures/narrow.json @@ -146,6 +146,30 @@ ] ] }, + { + "accept_events":[ + { + "message":{ + "type":"private" + }, + "flags":null + } + ], + "reject_events":[ + { + "message":{ + "type":"stream" + }, + "flags":null + } + ], + "narrow":[ + [ + "is", + "dm" + ] + ] + }, { "accept_events":[ { diff --git a/zerver/tests/test_email_notifications.py b/zerver/tests/test_email_notifications.py --- a/zerver/tests/test_email_notifications.py +++ b/zerver/tests/test_email_notifications.py @@ -1449,7 +1449,7 @@ def test_pm_link_in_missed_message_header(self) -> None: encoded_name = "Cordelia,-Lear's-daughter" verify_body_include = [ - f"view it in Zulip Dev Zulip: http://zulip.testserver/#narrow/pm-with/{cordelia.id}-{encoded_name}" + f"view it in Zulip Dev Zulip: http://zulip.testserver/#narrow/dm/{cordelia.id}-{encoded_name}" ] email_subject = "DMs with Cordelia, Lear's daughter" self._test_cases(msg_id, verify_body_include, email_subject, send_as_user=False) diff --git a/zerver/tests/test_message_fetch.py b/zerver/tests/test_message_fetch.py --- a/zerver/tests/test_message_fetch.py +++ b/zerver/tests/test_message_fetch.py @@ -127,10 +127,6 @@ def test_add_term_using_stream_operator_and_non_existing_operand_should_raise_er term = dict(operator="stream", operand="NonExistingStream") self.assertRaises(BadNarrowOperatorError, self._build_query, term) - def test_add_term_using_is_operator_and_private_operand(self) -> None: - term = dict(operator="is", operand="private") - self._do_add_term_test(term, "WHERE (flags & %(flags_1)s) != %(param_1)s") - def test_add_term_using_streams_operator_and_invalid_operand_should_raise_error( self, ) -> None: # NEGATED @@ -209,11 +205,15 @@ def test_add_term_using_streams_operator_and_public_stream_operand_negated(self) "WHERE (recipient_id NOT IN (__[POSTCOMPILE_recipient_id_1]))", ) - def test_add_term_using_is_operator_private_operand_and_negated(self) -> None: # NEGATED - term = dict(operator="is", operand="private", negated=True) + def test_add_term_using_is_operator_and_dm_operand(self) -> None: + term = dict(operator="is", operand="dm") + self._do_add_term_test(term, "WHERE (flags & %(flags_1)s) != %(param_1)s") + + def test_add_term_using_is_operator_dm_operand_and_negated(self) -> None: # NEGATED + term = dict(operator="is", operand="dm", negated=True) self._do_add_term_test(term, "WHERE (flags & %(flags_1)s) = %(param_1)s") - def test_add_term_using_is_operator_and_non_private_operand(self) -> None: + def test_add_term_using_is_operator_and_non_dm_operand(self) -> None: for operand in ["starred", "mentioned", "alerted"]: term = dict(operator="is", operand=operand) self._do_add_term_test(term, "WHERE (flags & %(flags_1)s) != %(param_1)s") @@ -226,7 +226,7 @@ def test_add_term_using_is_operator_and_unread_operand_and_negated(self) -> None term = dict(operator="is", operand="unread", negated=True) self._do_add_term_test(term, "WHERE (flags & %(flags_1)s) != %(param_1)s") - def test_add_term_using_is_operator_non_private_operand_and_negated(self) -> None: # NEGATED + def test_add_term_using_is_operator_non_dm_operand_and_negated(self) -> None: # NEGATED term = dict(operator="is", operand="starred", negated=True) where_clause = "WHERE (flags & %(flags_1)s) = %(param_1)s" params = dict( @@ -295,60 +295,60 @@ def test_add_term_using_sender_operator_with_non_existing_user_as_operand( term = dict(operator="sender", operand="[email protected]") self.assertRaises(BadNarrowOperatorError, self._build_query, term) - def test_add_term_using_pm_with_operator_and_not_the_same_user_as_operand(self) -> None: - term = dict(operator="pm-with", operand=self.othello_email) + def test_add_term_using_dm_operator_and_not_the_same_user_as_operand(self) -> None: + term = dict(operator="dm", operand=self.othello_email) self._do_add_term_test( term, "WHERE sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s", ) - def test_add_term_using_pm_with_operator_not_the_same_user_as_operand_and_negated( + def test_add_term_using_dm_operator_not_the_same_user_as_operand_and_negated( self, ) -> None: # NEGATED - term = dict(operator="pm-with", operand=self.othello_email, negated=True) + term = dict(operator="dm", operand=self.othello_email, negated=True) self._do_add_term_test( term, "WHERE NOT (sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s)", ) - def test_add_term_using_pm_with_operator_the_same_user_as_operand(self) -> None: - term = dict(operator="pm-with", operand=self.hamlet_email) + def test_add_term_using_dm_operator_the_same_user_as_operand(self) -> None: + term = dict(operator="dm", operand=self.hamlet_email) self._do_add_term_test( term, "WHERE sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s" ) - def test_add_term_using_pm_with_operator_the_same_user_as_operand_and_negated( + def test_add_term_using_dm_operator_the_same_user_as_operand_and_negated( self, ) -> None: # NEGATED - term = dict(operator="pm-with", operand=self.hamlet_email, negated=True) + term = dict(operator="dm", operand=self.hamlet_email, negated=True) self._do_add_term_test( term, "WHERE NOT (sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s)" ) - def test_add_term_using_pm_with_operator_and_self_and_user_as_operand(self) -> None: + def test_add_term_using_dm_operator_and_self_and_user_as_operand(self) -> None: myself_and_other = ",".join( [ self.example_user("hamlet").email, self.example_user("othello").email, ] ) - term = dict(operator="pm-with", operand=myself_and_other) + term = dict(operator="dm", operand=myself_and_other) self._do_add_term_test( term, "WHERE sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s", ) - def test_add_term_using_pm_with_operator_more_than_one_user_as_operand(self) -> None: + def test_add_term_using_dm_operator_more_than_one_user_as_operand(self) -> None: two_others = ",".join( [ self.example_user("cordelia").email, self.example_user("othello").email, ] ) - term = dict(operator="pm-with", operand=two_others) + term = dict(operator="dm", operand=two_others) self._do_add_term_test(term, "WHERE recipient_id = %(recipient_id_1)s") - def test_add_term_using_pm_with_operator_self_and_user_as_operand_and_negated( + def test_add_term_using_dm_operator_self_and_user_as_operand_and_negated( self, ) -> None: # NEGATED myself_and_other = ",".join( @@ -357,34 +357,66 @@ def test_add_term_using_pm_with_operator_self_and_user_as_operand_and_negated( self.example_user("othello").email, ] ) - term = dict(operator="pm-with", operand=myself_and_other, negated=True) + term = dict(operator="dm", operand=myself_and_other, negated=True) self._do_add_term_test( term, "WHERE NOT (sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s)", ) - def test_add_term_using_pm_with_operator_more_than_one_user_as_operand_and_negated( + def test_add_term_using_dm_operator_more_than_one_user_as_operand_and_negated( self, - ) -> None: + ) -> None: # NEGATED two_others = ",".join( [ self.example_user("cordelia").email, self.example_user("othello").email, ] ) - term = dict(operator="pm-with", operand=two_others, negated=True) + term = dict(operator="dm", operand=two_others, negated=True) self._do_add_term_test(term, "WHERE recipient_id != %(recipient_id_1)s") - def test_add_term_using_pm_with_operator_with_comma_noise(self) -> None: - term = dict(operator="pm-with", operand=" ,,, ,,, ,") + def test_add_term_using_dm_operator_with_comma_noise(self) -> None: + term = dict(operator="dm", operand=" ,,, ,,, ,") self.assertRaises(BadNarrowOperatorError, self._build_query, term) - def test_add_term_using_pm_with_operator_with_existing_and_non_existing_user_as_operand( + def test_add_term_using_dm_operator_with_existing_and_non_existing_user_as_operand( self, ) -> None: - term = dict(operator="pm-with", operand=self.othello_email + ",[email protected]") + term = dict(operator="dm", operand=self.othello_email + ",[email protected]") self.assertRaises(BadNarrowOperatorError, self._build_query, term) + def test_add_term_using_dm_including_operator_with_logged_in_user_email(self) -> None: + term = dict(operator="dm-including", operand=self.hamlet_email) + self._do_add_term_test(term, "WHERE (flags & %(flags_1)s) != %(param_1)s") + + def test_add_term_using_dm_including_operator_with_different_user_email(self) -> None: + # Test without any such group direct messages existing + term = dict(operator="dm-including", operand=self.othello_email) + self._do_add_term_test( + term, + "WHERE sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s OR recipient_id IN (__[POSTCOMPILE_recipient_id_3])", + ) + + # Test with at least one such group direct messages existing + self.send_huddle_message( + self.user_profile, [self.example_user("othello"), self.example_user("cordelia")] + ) + + term = dict(operator="dm-including", operand=self.othello_email) + self._do_add_term_test( + term, + "WHERE sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s OR recipient_id IN (__[POSTCOMPILE_recipient_id_3])", + ) + + def test_add_term_using_dm_including_operator_with_different_user_email_and_negated( + self, + ) -> None: # NEGATED + term = dict(operator="dm-including", operand=self.othello_email, negated=True) + self._do_add_term_test( + term, + "WHERE NOT (sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s OR sender_id = %(sender_id_2)s AND recipient_id = %(recipient_id_2)s OR recipient_id IN (__[POSTCOMPILE_recipient_id_3]))", + ) + def test_add_term_using_id_operator(self) -> None: term = dict(operator="id", operand=555) self._do_add_term_test(term, "WHERE id = %(param_1)s") @@ -400,29 +432,6 @@ def test_add_term_using_id_operator_and_negated(self) -> None: # NEGATED term = dict(operator="id", operand=555, negated=True) self._do_add_term_test(term, "WHERE id != %(param_1)s") - def test_add_term_using_group_pm_operator_and_not_the_same_user_as_operand(self) -> None: - # Test without any such group PM threads existing - term = dict(operator="group-pm-with", operand=self.othello_email) - self._do_add_term_test(term, "WHERE recipient_id IN (__[POSTCOMPILE_recipient_id_1])") - - # Test with at least one such group PM thread existing - self.send_huddle_message( - self.user_profile, [self.example_user("othello"), self.example_user("cordelia")] - ) - - term = dict(operator="group-pm-with", operand=self.othello_email) - self._do_add_term_test(term, "WHERE recipient_id IN (__[POSTCOMPILE_recipient_id_1])") - - def test_add_term_using_group_pm_operator_not_the_same_user_as_operand_and_negated( - self, - ) -> None: # NEGATED - term = dict(operator="group-pm-with", operand=self.othello_email, negated=True) - self._do_add_term_test(term, "WHERE (recipient_id NOT IN (__[POSTCOMPILE_recipient_id_1]))") - - def test_add_term_using_group_pm_operator_with_non_existing_user_as_operand(self) -> None: - term = dict(operator="group-pm-with", operand="[email protected]") - self.assertRaises(BadNarrowOperatorError, self._build_query, term) - @override_settings(USING_PGROONGA=False) def test_add_term_using_search_operator(self) -> None: term = dict(operator="search", operand='"french fries"') @@ -522,6 +531,22 @@ def _build_query(term: Dict[str, Any]) -> Select: self.assertRaises(BadNarrowOperatorError, _build_query, term) + # Test "is:private" (legacy alias for "is:dm") + def test_add_term_using_is_operator_and_private_operand(self) -> None: + term = dict(operator="is", operand="private") + self._do_add_term_test(term, "WHERE (flags & %(flags_1)s) != %(param_1)s") + + def test_add_term_using_is_operator_private_operand_and_negated(self) -> None: # NEGATED + term = dict(operator="is", operand="private", negated=True) + self._do_add_term_test(term, "WHERE (flags & %(flags_1)s) = %(param_1)s") + + # Test that "pm-with" (legacy alias for "dm") works. + def test_add_term_using_pm_with_operator(self) -> None: + term = dict(operator="pm-with", operand=self.hamlet_email) + self._do_add_term_test( + term, "WHERE sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s" + ) + # Test that the underscore version of "pm-with" works. def test_add_term_using_underscore_version_of_pm_with_operator(self) -> None: term = dict(operator="pm_with", operand=self.hamlet_email) @@ -529,6 +554,25 @@ def test_add_term_using_underscore_version_of_pm_with_operator(self) -> None: term, "WHERE sender_id = %(sender_id_1)s AND recipient_id = %(recipient_id_1)s" ) + # Test that deprecated "group-pm-with" (replaced by "dm-including" ) works. + def test_add_term_using_dm_including_operator_with_non_existing_user(self) -> None: + term = dict(operator="dm-including", operand="[email protected]") + self.assertRaises(BadNarrowOperatorError, self._build_query, term) + + def test_add_term_using_group_pm_operator_and_not_the_same_user_as_operand(self) -> None: + term = dict(operator="group-pm-with", operand=self.othello_email) + self._do_add_term_test(term, "WHERE recipient_id IN (__[POSTCOMPILE_recipient_id_1])") + + def test_add_term_using_group_pm_operator_not_the_same_user_as_operand_and_negated( + self, + ) -> None: # NEGATED + term = dict(operator="group-pm-with", operand=self.othello_email, negated=True) + self._do_add_term_test(term, "WHERE (recipient_id NOT IN (__[POSTCOMPILE_recipient_id_1]))") + + def test_add_term_using_group_pm_operator_with_non_existing_user_as_operand(self) -> None: + term = dict(operator="group-pm-with", operand="[email protected]") + self.assertRaises(BadNarrowOperatorError, self._build_query, term) + # Test that the underscore version of "group-pm-with" works. def test_add_term_using_underscore_version_of_group_pm_with_operator(self) -> None: term = dict(operator="group_pm_with", operand=self.othello_email) @@ -552,7 +596,7 @@ def test_build_narrow_filter(self) -> None: fixtures_path = os.path.join(os.path.dirname(__file__), "fixtures/narrow.json") with open(fixtures_path, "rb") as f: scenarios = orjson.loads(f.read()) - self.assert_length(scenarios, 10) + self.assert_length(scenarios, 11) for scenario in scenarios: narrow = scenario["narrow"] accept_events = scenario["accept_events"] @@ -582,10 +626,10 @@ def test_is_spectator_compatible(self) -> None: is_spectator_compatible([{"operator": "sender", "operand": "[email protected]"}]) ) self.assertFalse( - is_spectator_compatible([{"operator": "pm-with", "operand": "[email protected]"}]) + is_spectator_compatible([{"operator": "dm", "operand": "[email protected]"}]) ) self.assertFalse( - is_spectator_compatible([{"operator": "group-pm-with", "operand": "[email protected]"}]) + is_spectator_compatible([{"operator": "dm-including", "operand": "[email protected]"}]) ) self.assertTrue(is_spectator_compatible([{"operator": "stream", "operand": "Denmark"}])) self.assertTrue( @@ -597,11 +641,23 @@ def test_is_spectator_compatible(self) -> None: ) ) self.assertFalse(is_spectator_compatible([{"operator": "is", "operand": "starred"}])) - self.assertFalse(is_spectator_compatible([{"operator": "is", "operand": "private"}])) + self.assertFalse(is_spectator_compatible([{"operator": "is", "operand": "dm"}])) self.assertTrue(is_spectator_compatible([{"operator": "streams", "operand": "public"}])) + # Malformed input not allowed self.assertFalse(is_spectator_compatible([{"operator": "has"}])) + # "is:private" is a legacy alias for "is:dm". + self.assertFalse(is_spectator_compatible([{"operator": "is", "operand": "private"}])) + # "pm-with:"" is a legacy alias for "dm:" + self.assertFalse( + is_spectator_compatible([{"operator": "pm-with", "operand": "[email protected]"}]) + ) + # "group-pm-with:" was deprecated by the addition of "dm-including:" + self.assertFalse( + is_spectator_compatible([{"operator": "group-pm-with", "operand": "[email protected]"}]) + ) + class IncludeHistoryTest(ZulipTestCase): def test_ok_to_include_history(self) -> None: @@ -651,7 +707,12 @@ def test_ok_to_include_history(self) -> None: self.assertFalse(ok_to_include_history(narrow, user_profile, False)) self.assertTrue(ok_to_include_history(narrow, subscribed_user_profile, False)) - # History doesn't apply to PMs. + # History doesn't apply to direct messages. + narrow = [ + dict(operator="is", operand="dm"), + ] + self.assertFalse(ok_to_include_history(narrow, user_profile, False)) + # "is:private" is a legacy alias for "is:dm". narrow = [ dict(operator="is", operand="private"), ] @@ -1497,7 +1558,7 @@ def test_successful_get_messages(self) -> None: self.get_and_check_messages( dict( narrow=orjson.dumps( - [["pm-with", othello_email]], + [["dm", othello_email]], ).decode(), ), ) @@ -1505,7 +1566,7 @@ def test_successful_get_messages(self) -> None: self.get_and_check_messages( dict( narrow=orjson.dumps( - [dict(operator="pm-with", operand=othello_email)], + [dict(operator="dm", operand=othello_email)], ).decode(), ), ) @@ -1539,7 +1600,14 @@ def test_unauthenticated_get_messages(self) -> None: result = self.client_get("/json/messages", dict(web_public_stream_get_params)) self.assert_json_error(result, "Invalid subdomain", status_code=404) - # Cannot access private messages without login. + # Cannot access direct messages without login. + direct_messages_get_params: Dict[str, Union[int, str, bool]] = { + **get_params, + "narrow": orjson.dumps([dict(operator="is", operand="dm")]).decode(), + } + result = self.client_get("/json/messages", dict(direct_messages_get_params)) + self.check_unauthenticated_response(result) + # "is:private" is a legacy alias for "is:dm". private_message_get_params: Dict[str, Union[int, str, bool]] = { **get_params, "narrow": orjson.dumps([dict(operator="is", operand="private")]).decode(), @@ -1550,11 +1618,11 @@ def test_unauthenticated_get_messages(self) -> None: # narrow should pass conditions in `is_spectator_compatible`. non_spectator_compatible_narrow_get_params: Dict[str, Union[int, str, bool]] = { **get_params, - # "is:private" is not a is_spectator_compatible narrow. + # "is:dm" is not a is_spectator_compatible narrow. "narrow": orjson.dumps( [ dict(operator="streams", operand="web-public"), - dict(operator="is", operand="private"), + dict(operator="is", operand="dm"), ] ).decode(), } @@ -1613,7 +1681,7 @@ def test_unauthenticated_get_messages(self) -> None: def setup_web_public_test(self, num_web_public_message: int = 1) -> None: """ Send N+2 messages, N in a web-public stream, then one in a non-web-public stream - and then a private message. + and then a direct message. """ user_profile = self.example_user("iago") do_set_realm_property( @@ -1633,7 +1701,7 @@ def setup_web_public_test(self, num_web_public_message: int = 1) -> None: user_profile, non_web_public_stream.name, content="non-web-public message" ) self.send_personal_message( - user_profile, self.example_user("hamlet"), content="private message" + user_profile, self.example_user("hamlet"), content="direct message" ) self.logout() @@ -1729,9 +1797,9 @@ def test_client_avatar(self) -> None: message = result["messages"][0] self.assertIn("gravatar.com", message["avatar_url"]) - def test_get_messages_with_narrow_pm_with(self) -> None: + def test_get_messages_with_narrow_dm(self) -> None: """ - A request for old messages with a narrow by pm-with only returns + A request for old messages with a narrow by direct message only returns conversations with that user. """ me = self.example_user("hamlet") @@ -1751,8 +1819,8 @@ def dr_ids(dr: DisplayRecipientT) -> List[int]: [self.example_user("iago"), self.example_user("cordelia")], ) - # Send a 1:1 and group PM containing Aaron. - # Then deactivate aaron to test pm-with narrow includes messages + # Send a 1:1 and group direct message containing Aaron. + # Then deactivate Aaron to test "dm" narrow includes messages # from deactivated users also. self.send_personal_message(me, self.example_user("aaron")) self.send_huddle_message( @@ -1769,21 +1837,21 @@ def dr_ids(dr: DisplayRecipientT) -> List[int]: for personal in personals: emails = dr_emails(get_display_recipient(personal.recipient)) self.login_user(me) - narrow: List[Dict[str, Any]] = [dict(operator="pm-with", operand=emails)] + narrow: List[Dict[str, Any]] = [dict(operator="dm", operand=emails)] result = self.get_and_check_messages(dict(narrow=orjson.dumps(narrow).decode())) for message in result["messages"]: self.assertEqual(dr_emails(message["display_recipient"]), emails) - # check passing id is consistent with passing emails as operand + # check passing user IDs is consistent with passing user emails as operand ids = dr_ids(get_display_recipient(personal.recipient)) - narrow = [dict(operator="pm-with", operand=ids)] + narrow = [dict(operator="dm", operand=ids)] result = self.get_and_check_messages(dict(narrow=orjson.dumps(narrow).decode())) for message in result["messages"]: self.assertEqual(dr_emails(message["display_recipient"]), emails) - def test_get_visible_messages_with_narrow_pm_with(self) -> None: + def test_get_visible_messages_with_narrow_dm(self) -> None: me = self.example_user("hamlet") self.login_user(me) self.subscribe(self.example_user("hamlet"), "Scotland") @@ -1792,13 +1860,125 @@ def test_get_visible_messages_with_narrow_pm_with(self) -> None: for i in range(5): message_ids.append(self.send_personal_message(me, self.example_user("iago"))) - narrow = [dict(operator="pm-with", operand=self.example_user("iago").email)] + narrow = [dict(operator="dm", operand=self.example_user("iago").email)] + self.message_visibility_test(narrow, message_ids, 2) + + def test_get_messages_with_narrow_dm_including(self) -> None: + """ + A request for old messages with a narrow by "dm-including" only + returns direct messages (both group and 1:1) with that user. + """ + me = self.example_user("hamlet") + + iago = self.example_user("iago") + cordelia = self.example_user("cordelia") + othello = self.example_user("othello") + + matching_message_ids = [] + # group direct message, sent by current user + matching_message_ids.append( + self.send_huddle_message( + me, + [iago, cordelia, othello], + ), + ) + # group direct message, sent by searched user + matching_message_ids.append( + self.send_huddle_message( + cordelia, + [me, othello], + ), + ) + # group direct message, sent by another user + matching_message_ids.append( + self.send_huddle_message( + othello, + [me, cordelia], + ), + ) + # direct 1:1 message, sent by current user to searched user + matching_message_ids.append( + self.send_personal_message(me, cordelia), + ) + # direct 1:1 message, sent by searched user to current user + matching_message_ids.append( + self.send_personal_message(cordelia, me), + ) + + non_matching_message_ids = [] + # direct 1:1 message, does not include current user + non_matching_message_ids.append( + self.send_personal_message(iago, cordelia), + ) + # direct 1:1 message, does not include searched user + non_matching_message_ids.append( + self.send_personal_message(iago, me), + ) + # direct 1:1 message, current user to self + non_matching_message_ids.append( + self.send_personal_message(me, me), + ) + # group direct message, sent by current user + non_matching_message_ids.append( + self.send_huddle_message( + me, + [iago, othello], + ), + ) + # group direct message, sent by searched user + non_matching_message_ids.append( + self.send_huddle_message( + cordelia, + [iago, othello], + ), + ) + + self.login_user(me) + test_operands = [cordelia.email, cordelia.id] + for operand in test_operands: + narrow = [dict(operator="dm-including", operand=operand)] + result = self.get_and_check_messages(dict(narrow=orjson.dumps(narrow).decode())) + for message in result["messages"]: + self.assertIn(message["id"], matching_message_ids) + self.assertNotIn(message["id"], non_matching_message_ids) + + def test_get_visible_messages_with_narrow_dm_including(self) -> None: + me = self.example_user("hamlet") + self.login_user(me) + + iago = self.example_user("iago") + cordelia = self.example_user("cordelia") + othello = self.example_user("othello") + + message_ids = [] + message_ids.append( + self.send_huddle_message( + me, + [iago, cordelia, othello], + ), + ) + message_ids.append(self.send_personal_message(me, cordelia)) + message_ids.append( + self.send_huddle_message( + cordelia, + [me, othello], + ), + ) + message_ids.append(self.send_personal_message(cordelia, me)) + message_ids.append( + self.send_huddle_message( + iago, + [cordelia, me], + ), + ) + + narrow = [dict(operator="dm-including", operand=cordelia.email)] self.message_visibility_test(narrow, message_ids, 2) def test_get_messages_with_narrow_group_pm_with(self) -> None: """ - A request for old messages with a narrow by group-pm-with only returns - group-private conversations with that user. + A request for old messages with a narrow by deprecated "group-pm-with" + only returns direct message group conversations with that user. """ me = self.example_user("hamlet") @@ -3001,20 +3181,22 @@ def test_bad_narrow_operator(self) -> None: def test_invalid_narrow_operand_in_dict(self) -> None: self.login("hamlet") - # str or int is required for sender, group-pm-with, stream + # str or int is required for "sender", "stream", "dm-including" and "group-pm-with" operators invalid_operands = [["1"], [2], None] error_msg = 'elem["operand"] is not a string or integer' - for operand in ["sender", "group-pm-with", "stream"]: + for operand in ["sender", "group-pm-with", "stream", "dm-including"]: self.exercise_bad_narrow_operand_using_dict_api(operand, invalid_operands, error_msg) - # str or int list is required for pm-with operator + # str or int list is required for "dm" and "pm-with" operator invalid_operands = [None] error_msg = 'elem["operand"] is not a string or an integer list' - self.exercise_bad_narrow_operand_using_dict_api("pm-with", invalid_operands, error_msg) + for operand in ["dm", "pm-with"]: + self.exercise_bad_narrow_operand_using_dict_api(operand, invalid_operands, error_msg) invalid_operands = [["2"]] error_msg = 'elem["operand"][0] is not an integer' - self.exercise_bad_narrow_operand_using_dict_api("pm-with", invalid_operands, error_msg) + for operand in ["dm", "pm-with"]: + self.exercise_bad_narrow_operand_using_dict_api(operand, invalid_operands, error_msg) # For others only str is acceptable invalid_operands = [2, None, [1]] @@ -3057,12 +3239,12 @@ def test_bad_narrow_stream_content(self) -> None: def test_bad_narrow_one_on_one_email_content(self) -> None: """ - If an invalid 'pm-with' is requested in get_messages, an - error is returned. + If an invalid "dm" narrow is requested in get_messages, + an error is returned. """ self.login("hamlet") bad_stream_content: Tuple[int, List[None], List[str]] = (0, [], ["x", "y"]) - self.exercise_bad_narrow_operand("pm-with", bad_stream_content, "Bad value for 'narrow'") + self.exercise_bad_narrow_operand("dm", bad_stream_content, "Bad value for 'narrow'") def test_bad_narrow_nonexistent_stream(self) -> None: self.login("hamlet") @@ -3078,14 +3260,12 @@ def test_bad_narrow_nonexistent_stream(self) -> None: def test_bad_narrow_nonexistent_email(self) -> None: self.login("hamlet") self.exercise_bad_narrow_operand( - "pm-with", ["[email protected]"], "Invalid narrow operator: unknown user" + "dm", ["[email protected]"], "Invalid narrow operator: unknown user" ) - def test_bad_narrow_pm_with_id_list(self) -> None: + def test_bad_narrow_dm_id_list(self) -> None: self.login("hamlet") - self.exercise_bad_narrow_operand( - "pm-with", [-24], "Bad value for 'narrow': [[\"pm-with\",-24]]" - ) + self.exercise_bad_narrow_operand("dm", [-24], "Bad value for 'narrow': [[\"dm\",-24]]") def test_message_without_rendered_content(self) -> None: """Older messages may not have rendered_content in the database""" @@ -3564,7 +3744,7 @@ def test_get_messages_with_narrow_queries(self) -> None: "anchor": 0, "num_before": 0, "num_after": 0, - "narrow": f'[["pm-with", "{othello_email}"]]', + "narrow": f'[["dm", "{othello_email}"]]', }, sql, ) @@ -3576,7 +3756,7 @@ def test_get_messages_with_narrow_queries(self) -> None: "anchor": 0, "num_before": 1, "num_after": 0, - "narrow": f'[["pm-with", "{othello_email}"]]', + "narrow": f'[["dm", "{othello_email}"]]', }, sql, ) @@ -3588,7 +3768,7 @@ def test_get_messages_with_narrow_queries(self) -> None: "anchor": 0, "num_before": 0, "num_after": 9, - "narrow": f'[["pm-with", "{othello_email}"]]', + "narrow": f'[["dm", "{othello_email}"]]', }, sql, ) @@ -3654,7 +3834,7 @@ def test_get_messages_with_narrow_queries(self) -> None: sql, ) - # Narrow to pms with yourself + # Narrow to direct messages with yourself sql_template = "SELECT anon_1.message_id, anon_1.flags \nFROM (SELECT message_id, flags \nFROM zerver_usermessage JOIN zerver_message ON zerver_usermessage.message_id = zerver_message.id \nWHERE user_profile_id = {hamlet_id} AND sender_id = {hamlet_id} AND recipient_id = {hamlet_recipient} ORDER BY message_id ASC \n LIMIT 10) AS anon_1 ORDER BY message_id ASC" sql = sql_template.format(**query_ids) self.common_check_get_messages_query( @@ -3662,7 +3842,7 @@ def test_get_messages_with_narrow_queries(self) -> None: "anchor": 0, "num_before": 0, "num_after": 9, - "narrow": f'[["pm-with", "{hamlet_email}"]]', + "narrow": f'[["dm", "{hamlet_email}"]]', }, sql, ) @@ -4090,4 +4270,4 @@ def test_near_pm_message_url(self) -> None: realm=realm, message=message, ) - self.assertEqual(url, "http://zulip.testserver/#narrow/pm-with/77,80-pm/near/555") + self.assertEqual(url, "http://zulip.testserver/#narrow/dm/77,80-pm/near/555")
Update and improve direct message search filters As [discussed on CZO](https://chat.zulip.org/#narrow/stream/101-design/topic/.22Private.22.20vs.20.22Direct.22/near/1516241), following up on #24224, we should make the following changes to the search filters related to direct messages. Note that links should be rewritten with the new URLs. ## is:private - [ ] Rename `is:private` to `is:dm`. - [ ] Typing `is:private` into the search box should be automatically substituted with `is:dm`. - [ ] Change the URL `/is/private` -> `/is/dm`. ## pm-with - [ ] Rename to `dm:`. - [ ] Ideally, typing `pm-with:` into the search box should be automatically substituted with `dm:`. - [ ] Change the URL `/pm-with/` -> `/dm/` ## group-pm-with - [ ] Drop support for `group-pm-with`. - [ ] Instead, add a `dm-including` filter to search for all DM conversations including a user (including 1:1 and group DMs). - [ ] Rename this option "Group direct messages including" -> "Direct messages including" in the typeahead. - [ ] The new URL will be `/dm-including`. The old filter can be remapped to a combination of two filters: `/dm-including/user/-dm/user`. The documentation on https://zulip.com/help/search-for-messages should be updated to reflect these changes. ---- Update: The URL changes are blocked for now, but we can proceed on the other parts of this issue. Blocker: - [ ] https://github.com/zulip/zulip-mobile/issues/5692
The URLs are something mobile (and perhaps terminal?) interprets in order to be able to follow links. So before we start generating different URLs (and causing people to put them in messages), we should update mobile to understand the new URLs, and get a release out with that update. I think it'd be OK to go ahead with the other changes, while holding off on the URL changes. It means the terms in the search bar will temporarily not match the URL as closely as they usually do; but probably most users don't notice the URL that much anyway. > I think it'd be OK to go ahead with the other changes, while holding off on the URL changes. Got it, that plan sounds good to me. Should I file a corresponding mobile issue? Also @neiljp for whether we need to do some work on the ZT side as well. Please do, thanks! @zulipbot claim @UjjwalAggarwal-1 This issue cannot be claimed, as someone else is already working on it. Please see our [contributor guide](https://zulip.readthedocs.io/en/latest/overview/contributing.html#your-first-codebase-contribution) for advice on finding an issue to work on. Thanks!
2023-04-05T17:02:41
zulip/zulip
25,031
zulip__zulip-25031
[ "24982" ]
a06f3d26d048bfeb32b8c4be5f6e9c18080f6bbb
diff --git a/zproject/urls.py b/zproject/urls.py --- a/zproject/urls.py +++ b/zproject/urls.py @@ -725,6 +725,9 @@ # API key - as we consider access to the API key sensitive # and just having a logged-in session should be insufficient. rest_path("users/me/api_key/regenerate", POST=regenerate_api_key), + # This view accepts a JWT containing an email and returns an API key + # and the details for a single user. + path("jwt/fetch_api_key", jwt_fetch_api_key), ] # View for uploading messages from email mirror @@ -755,11 +758,6 @@ urls += [path("", include("social_django.urls", namespace="social"))] urls += [path("saml/metadata.xml", saml_sp_metadata)] -# This view accepts a JWT containing an email and returns an API key -# and the details for a single user. -urls += [ - path("api/v1/jwt/fetch_api_key", jwt_fetch_api_key), -] # SCIM2
diff --git a/zerver/tests/test_openapi.py b/zerver/tests/test_openapi.py --- a/zerver/tests/test_openapi.py +++ b/zerver/tests/test_openapi.py @@ -275,6 +275,7 @@ class OpenAPIArgumentsTest(ZulipTestCase): "/rest-error-handling", # Zulip outgoing webhook payload "/zulip-outgoing-webhook", + "/jwt/fetch_api_key", } # Endpoints where the documentation is currently failing our
OpenAPI testsuite reporting endpoint as not in urls.py While working on the issue #24278, I noticed that adding the openAPI documentation for the endpoint /jwt/fetch_api_key returns an error that the endpoint is not in urls.py while running the backend testsuite. On closer inspection it seems that the testsuite detects urls in v1_api_mobile_patterns and v1_api_and_json_patterns and the above endpoint is not added to either despite having the /api/v1 prefix format. I think it makes sense to add the endpoint to the v1_api_and_json_patterns array ![Screenshot from 2023-04-04 09-59-16](https://user-images.githubusercontent.com/72982935/229688107-d3cce4be-2069-45ad-bbb3-3cccb715b5b0.png) ![Screenshot from 2023-04-04 01-07-00](https://user-images.githubusercontent.com/72982935/229687961-8db4c78b-3ec9-4f4b-b6f3-d34df35d4d17.png)
@zulipbot add "bug" @zulipbot add "good first issue" "help wanted" @zulipbot claim Welcome to Zulip, @Riv3tz! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @tanmaymunjal I've added the endpoint to the v1_api_and_json_patterns array. However, the build is failing since I've not added the docs. Not sure what the correct way to move forward is since you're working on the documentation for the same... Hey @Riv3tz , I was looking into it and it seems to be the case that they is another testsuite issue which is not able to detect the token parameter, creating issues for me to OpenAPI document the endpoint, will look further into this to make sure it is not a mistake from my side else will need to start an issue on it as well ig
2023-04-07T19:06:55
zulip/zulip
25,053
zulip__zulip-25053
[ "24969" ]
4e2931cefdfe58a0ae0e202e3f2cc5547a1a57e6
diff --git a/zerver/lib/push_notifications.py b/zerver/lib/push_notifications.py --- a/zerver/lib/push_notifications.py +++ b/zerver/lib/push_notifications.py @@ -547,6 +547,9 @@ def add_push_device_token( post_data = { "server_uuid": settings.ZULIP_ORG_ID, "user_uuid": str(user_profile.uuid), + # user_id is sent so that the bouncer can delete any pre-existing registrations + # for this user+device to avoid duplication upon adding the uuid registration. + "user_id": str(user_profile.id), "token": token_str, "token_kind": kind, } diff --git a/zilencer/views.py b/zilencer/views.py --- a/zilencer/views.py +++ b/zilencer/views.py @@ -1,5 +1,6 @@ import datetime import logging +from collections import Counter from typing import Any, Dict, List, Optional, Type, TypeVar from uuid import UUID @@ -157,23 +158,26 @@ def register_remote_push_device( if user_id is None and user_uuid is None: raise JsonableError(_("Missing user_id or user_uuid")) if user_id is not None and user_uuid is not None: - # We don't want "hybrid" registrations with both. - # Our RemotePushDeviceToken should be either in the new uuid format - # or the legacy id one. - raise JsonableError(_("Specify only one of user_id or user_uuid")) - + kwargs: Dict[str, object] = {"user_uuid": user_uuid, "user_id": None} + # Delete pre-existing user_id registration for this user+device to avoid + # duplication. Further down, uuid registration will be created. + RemotePushDeviceToken.objects.filter( + server=server, token=token, kind=token_kind, user_id=user_id + ).delete() + else: + # One of these is None, so these kwargs will lead to a proper registration + # of either user_id or user_uuid type + kwargs = {"user_id": user_id, "user_uuid": user_uuid} try: with transaction.atomic(): RemotePushDeviceToken.objects.create( - # Exactly one of these two user identity fields will be None. - user_id=user_id, - user_uuid=user_uuid, server=server, kind=token_kind, token=token, ios_app_id=ios_app_id, # last_updated is to be renamed to date_created. last_updated=timezone.now(), + **kwargs, ) except IntegrityError: pass @@ -216,13 +220,73 @@ def unregister_all_remote_push_devices( return json_success(request) +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 - 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 push notification request + to us, it sends both user_id and user_uuid of the user. + See https://github.com/zulip/zulip/issues/24969 for reference. + + This function, knowing the user_id and user_uuid of the user, can detect duplicates + and delete the legacy user_id registration if appropriate. + + Return the list of registrations with the user_id-based duplicates removed. + """ + + # All registrations passed here should be of the same kind (apple vs android). + assert len({registration.kind for registration in registrations}) == 1 + kind = registrations[0].kind + + tokens_counter = Counter(device.token for device in registrations) + + tokens_to_deduplicate = [] + for key in tokens_counter: + if tokens_counter[key] <= 1: + continue + if tokens_counter[key] > 2: + raise AssertionError( + f"More than two registrations for token {key} for user id:{user_id} uuid:{user_uuid}, shouldn't be possible" + ) + assert tokens_counter[key] == 2 + tokens_to_deduplicate.append(key) + + if not tokens_to_deduplicate: + return registrations + + logger.info( + "Deduplicating push registrations for server id:%s user id:%s uuid:%s and tokens:%s", + server_id, + user_id, + user_uuid, + sorted(tokens_to_deduplicate), + ) + RemotePushDeviceToken.objects.filter( + token__in=tokens_to_deduplicate, kind=kind, server_id=server_id, user_id=user_id + ).delete() + + deduplicated_registrations_to_return = [] + for registration in registrations: + if registration.token in tokens_to_deduplicate and registration.user_id is not None: + # user_id registrations are the ones we deleted + continue + deduplicated_registrations_to_return.append(registration) + + return deduplicated_registrations_to_return + + @has_request_variables def remote_server_notify_push( request: HttpRequest, server: RemoteZulipServer, payload: Dict[str, Any] = REQ(argument_type="body"), ) -> HttpResponse: - user_identity = UserPushIdentityCompat(payload.get("user_id"), payload.get("user_uuid")) + user_id = payload.get("user_id") + user_uuid = payload.get("user_uuid") + user_identity = UserPushIdentityCompat(user_id, user_uuid) gcm_payload = payload["gcm_payload"] apns_payload = payload["apns_payload"] @@ -235,6 +299,10 @@ def remote_server_notify_push( server=server, ) ) + if android_devices and user_id is not None and user_uuid is not None: + android_devices = delete_duplicate_registrations( + android_devices, server.id, user_id, user_uuid + ) apple_devices = list( RemotePushDeviceToken.objects.filter( @@ -243,6 +311,8 @@ def remote_server_notify_push( server=server, ) ) + if apple_devices and user_id is not None and user_uuid is not None: + apple_devices = delete_duplicate_registrations(apple_devices, server.id, user_id, user_uuid) logger.info( "Sending mobile push notifications for remote user %s:%s: %s via FCM devices, %s via APNs devices",
diff --git a/zerver/tests/test_push_notifications.py b/zerver/tests/test_push_notifications.py --- a/zerver/tests/test_push_notifications.py +++ b/zerver/tests/test_push_notifications.py @@ -192,12 +192,6 @@ def test_register_remote_push_user_params(self) -> None: self.server_uuid, endpoint, {"token": token, "token_kind": token_kind} ) self.assert_json_error(result, "Missing user_id or user_uuid") - result = self.uuid_post( - self.server_uuid, - endpoint, - {"user_id": user_id, "user_uuid": "xxx", "token": token, "token_kind": token_kind}, - ) - self.assert_json_error(result, "Specify only one of user_id or user_uuid") result = self.uuid_post( self.server_uuid, endpoint, {"user_id": user_id, "token": token, "token_kind": 17} ) @@ -280,6 +274,40 @@ def test_register_remote_push_user_params(self) -> None: 401, ) + def test_register_device_deduplication(self) -> None: + hamlet = self.example_user("hamlet") + token = "111222" + user_id = hamlet.id + user_uuid = str(hamlet.uuid) + token_kind = PushDeviceToken.GCM + + endpoint = "/api/v1/remotes/push/register" + + # First we create a legacy user_id registration. + result = self.uuid_post( + self.server_uuid, + endpoint, + {"user_id": user_id, "token_kind": token_kind, "token": token}, + ) + self.assert_json_success(result) + + registrations = list(RemotePushDeviceToken.objects.filter(token=token)) + self.assert_length(registrations, 1) + self.assertEqual(registrations[0].user_id, user_id) + self.assertEqual(registrations[0].user_uuid, None) + + # Register same user+device with uuid now. The old registration should be deleted + # to avoid duplication. + result = self.uuid_post( + self.server_uuid, + endpoint, + {"user_id": user_id, "user_uuid": user_uuid, "token_kind": token_kind, "token": token}, + ) + registrations = list(RemotePushDeviceToken.objects.filter(token=token)) + self.assert_length(registrations, 1) + self.assertEqual(registrations[0].user_id, None) + self.assertEqual(str(registrations[0].user_uuid), user_uuid) + def test_remote_push_user_endpoints(self) -> None: endpoints = [ ("/api/v1/remotes/push/register", "register"), @@ -308,6 +336,7 @@ def test_send_notification_endpoint(self) -> None: server = RemoteZulipServer.objects.get(uuid=self.server_uuid) token = "aaaa" android_tokens = [] + uuid_android_tokens = [] for i in ["aa", "bb"]: android_tokens.append( RemotePushDeviceToken.objects.create( @@ -317,6 +346,19 @@ def test_send_notification_endpoint(self) -> None: server=server, ) ) + + # Create a duplicate, newer uuid-based registration for the same user to verify + # the bouncer will handle that correctly, without triggering a duplicate notification, + # and will delete the old, legacy registration. + uuid_android_tokens.append( + RemotePushDeviceToken.objects.create( + kind=RemotePushDeviceToken.GCM, + token=hex_to_b64(token + i), + user_uuid=str(hamlet.uuid), + server=server, + ) + ) + apple_token = RemotePushDeviceToken.objects.create( kind=RemotePushDeviceToken.APNS, token=hex_to_b64(token), @@ -326,6 +368,7 @@ def test_send_notification_endpoint(self) -> None: many_ids = ",".join(str(i) for i in range(1, 250)) payload = { "user_id": hamlet.id, + "user_uuid": str(hamlet.uuid), "gcm_payload": {"event": "remove", "zulip_message_ids": many_ids}, "apns_payload": { "badge": 0, @@ -355,12 +398,14 @@ def test_send_notification_endpoint(self) -> None: logger.output, [ "INFO:zilencer.views:" - f"Sending mobile push notifications for remote user 6cde5f7a-1f7e-4978-9716-49f69ebfc9fe:<id:{hamlet.id}>: " - "2 via FCM devices, 1 via APNs devices" + f"Deduplicating push registrations for server id:{server.id} user id:{hamlet.id} uuid:{str(hamlet.uuid)} and tokens:{sorted([t.token for t in android_tokens[:]])}", + "INFO:zilencer.views:" + f"Sending mobile push notifications for remote user 6cde5f7a-1f7e-4978-9716-49f69ebfc9fe:<id:{hamlet.id}><uuid:{str(hamlet.uuid)}>: " + "2 via FCM devices, 1 via APNs devices", ], ) - user_identity = UserPushIdentityCompat(user_id=hamlet.id) + user_identity = UserPushIdentityCompat(user_id=hamlet.id, user_uuid=str(hamlet.uuid)) apple_push.assert_called_once_with( user_identity, [apple_token], @@ -377,7 +422,7 @@ def test_send_notification_endpoint(self) -> None: ) android_push.assert_called_once_with( user_identity, - list(reversed(android_tokens)), + list(reversed(uuid_android_tokens)), {"event": "remove", "zulip_message_ids": ",".join(str(i) for i in range(50, 250))}, {}, remote=server,
Push bouncer: Deduplicate device registrations In the migration to using uuid instead of simple id as the user identifier in the push bouncer (d800ac33a0322b0d3ef327bcebf318a27448bbee) we preserved legacy `id`-based registrations to avoid breaking notifications for all the devices already registered. However this means the possibility of duplicate registrations for one device - if a device was registered with `id` originally and then re-registered at some point after this migration, creating a new, `uuid`-based registration. The bouncer will send duplicate notifications to such a device. The `RemotePushDeviceToken` data model doesn't have a way of linking `id`s to `uuid`s of a user, so we can't just write a database migration to detect and delete duplicates. The proposed solution is the following: 1. Currently, when a Zulip server sends a notification to the bouncer (https://github.com/zulip/zulip/blob/3f199d570d5b238e28ee6b0e7c7a0ca72156a790/zerver/lib/push_notifications.py#L487) it sends both the `user_id` and `user_uuid` to the bouncer. Thus we can tweak the bouncer to detect in that moment if both registrations exist for the same `token` - and if so, delete the old `user_id` registration. This will over time clean up existing duplicates. 2. When the bouncer receives a new `uuid` registration request to `remotes/push/register` it should check if there isn't already an existing `id` registration for the `token` and if there is, delete it. This will prevent future duplications. https://chat.zulip.org/#narrow/stream/48-mobile/topic/iOS.20duplicate.20notifications for more background
Hello @zulip/server-production members, this issue was labeled with the "area: production" label, so you may want to check it out! <!-- areaLabelAddition -->
2023-04-09T23:02:02
zulip/zulip
25,155
zulip__zulip-25155
[ "24554" ]
dee3d7a172bea731b69fd3891bbf46636588b883
diff --git a/zerver/webhooks/github/view.py b/zerver/webhooks/github/view.py --- a/zerver/webhooks/github/view.py +++ b/zerver/webhooks/github/view.py @@ -159,17 +159,27 @@ def get_issue_body(helper: Helper) -> str: include_title = helper.include_title action = payload["action"].tame(check_string) issue = payload["issue"] - assignee = issue["assignee"] - return get_issue_event_message( + has_assignee = "assignee" in payload + base_message = get_issue_event_message( user_name=get_sender_name(payload), action=action, url=issue["html_url"].tame(check_string), number=issue["number"].tame(check_int), - message=issue["body"].tame(check_none_or(check_string)), - assignee=assignee["login"].tame(check_string) if assignee else None, + message=None + if action in ("assigned", "unassigned") + else issue["body"].tame(check_none_or(check_string)), title=issue["title"].tame(check_string) if include_title else None, ) + if has_assignee: + stringified_assignee = payload["assignee"]["login"].tame(check_string) + if action == "assigned": + return f"{base_message[:-1]} to {stringified_assignee}." + elif action == "unassigned": + return base_message.replace("unassigned", f"unassigned {stringified_assignee} from") + + return base_message + def get_issue_comment_body(helper: Helper) -> str: payload = helper.payload
diff --git a/zerver/webhooks/github/tests.py b/zerver/webhooks/github/tests.py --- a/zerver/webhooks/github/tests.py +++ b/zerver/webhooks/github/tests.py @@ -142,6 +142,28 @@ def test_issue_msg_with_custom_topic_in_url(self) -> None: expected_message = "baxterthehacker opened [issue #2 Spelling error in the README file](https://github.com/baxterthehacker/public-repo/issues/2):\n\n~~~ quote\nIt looks like you accidentally spelled 'commit' with two 't's.\n~~~" self.check_webhook("issues", expected_topic, expected_message) + def test_issue_assigned(self) -> None: + expected_message = "sbansal1999 assigned [issue #7](https://github.com/sbansal1999/testing-gh/issues/7) to sbansal1999." + expected_topic = "testing-gh / issue #7 Sample Issue testing something" + self.check_webhook("issues__assigned", expected_topic, expected_message) + + def test_issue_assigned_with_custom_topic_in_url(self) -> None: + self.url = self.build_webhook_url(topic="notifications") + expected_topic = "notifications" + expected_message = "sbansal1999 assigned [issue #7 Sample Issue testing something](https://github.com/sbansal1999/testing-gh/issues/7) to sbansal1999." + self.check_webhook("issues__assigned", expected_topic, expected_message) + + def test_issue_unassigned(self) -> None: + expected_message = "sbansal1999 unassigned sbansal1999 from [issue #9](https://github.com/sbansal1999/testing-gh/issues/9)." + expected_topic = "testing-gh / issue #9 idk man" + self.check_webhook("issues__unassigned", expected_topic, expected_message) + + def test_issue_unassigned_with_custom_topic_in_url(self) -> None: + self.url = self.build_webhook_url(topic="notifications") + expected_topic = "notifications" + expected_message = "sbansal1999 unassigned sbansal1999 from [issue #9 idk man](https://github.com/sbansal1999/testing-gh/issues/9)." + self.check_webhook("issues__unassigned", expected_topic, expected_message) + def test_membership_msg(self) -> None: expected_message = ( "baxterthehacker added [kdaigle](https://github.com/kdaigle) to the Contractors team."
GitHub bot should leave out issue description text on "issue assigned" events Here's an [example message](https://chat.zulip.org/#narrow/stream/243-mobile-team/topic/zulip-flutter/near/1517324) from the GitHub bot: > gnprice assigned [issue #21 Push PerAccountRoot under MaterialApp, into each individual page widget](https://github.com/zulip/zulip-flutter/issues/21) (assigned to gnprice): > > > This will let us have a single MaterialApp that can navigate between pages that are for different accounts, as well as pages like the login flow and account-switch UI that are for no particular account at all. That makes it a necessity for doing #11 in a reasonable way. > > > > One part of this will be to let the PerAccountRoots for a given account all point to a single PerAccountStore. That's this TODO from #20 which I just sent: > > ```dart > > // TODO add a registry of [PerAccountStore]s, like the latter's of [MessageListView] > > // That will allow us to have many [PerAccountRoot] widgets for a given > > // account, e.g. at the top of each page; and to access server data from > > // outside any [PerAccountRoot], e.g. for handling a notification. > > ``` > > > > The other part to take care of will be arranging that the API we provide for ourselves to use when we're adding new routes, and navigating to routes, isn't too annoying or error-prone. I have some thoughts and we'll see how it looks after I experiment. That would be about right for the "issue created" event. But this isn't that — it's the "issue assigned" event. The description — those multiple paragraphs of prose plus code — isn't something that is new or changed, or ever will be on this type of event. So it should be omitted. In particular this event will commonly come immediately after the "issue created" event, which means the description gets posted twice in a row. I don't know what the bot currently does on "PR assigned" events, but the same thing applies there: it should not include the PR description text.
Hello @zulip/server-integrations members, this issue was labeled with the "area: integrations" label, so you may want to check it out! <!-- areaLabelAddition --> @zulipbot claim Welcome to Zulip, @AbhishekCS3459! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @gnprice can you please describe the steps to reproduce this and also what you are expecting from it? > Here's an [example message](https://chat.zulip.org/#narrow/stream/243-mobile-team/topic/zulip-flutter/near/1517324) from the GitHub bot: > > > gnprice assigned [issue #21 Push PerAccountRoot under MaterialApp, into each individual page widget](https://github.com/zulip/zulip-flutter/issues/21) (assigned to gnprice): > > > This will let us have a single MaterialApp that can navigate between pages that are for different accounts, as well as pages like the login flow and account-switch UI that are for no particular account at all. That makes it a necessity for doing #11 in a reasonable way. > > > One part of this will be to let the PerAccountRoots for a given account all point to a single PerAccountStore. That's this TODO from #20 which I just sent: > > > ```dart > > > // TODO add a registry of [PerAccountStore]s, like the latter's of [MessageListView] > > > // That will allow us to have many [PerAccountRoot] widgets for a given > > > // account, e.g. at the top of each page; and to access server data from > > > // outside any [PerAccountRoot], e.g. for handling a notification. > > > ``` > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > The other part to take care of will be arranging that the API we provide for ourselves to use when we're adding new routes, and navigating to routes, isn't too annoying or error-prone. I have some thoughts and we'll see how it looks after I experiment. > > That would be about right for the "issue created" event. But this isn't that — it's the "issue assigned" event. The description — those multiple paragraphs of prose plus code — isn't something that is new or changed, or ever will be on this type of event. So it should be omitted. > > In particular this event will commonly come immediately after the "issue created" event, which means the description gets posted twice in a row. > > I don't know what the bot currently does on "PR assigned" events, but the same thing applies there: it should not include the PR description text. @gnprice Could You Please let me know what you expect from it , so that I can work upon it. @zulipbot help wanted The issue describes the desired behavior: > The description — those multiple paragraphs of prose plus code — […] should be omitted. For how to reproduce the issue, the `#development help` or `#integrations` streams would be good places to ask. @AbhishekCS3459 You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! Yes it will be over tomorrow
2023-04-17T18:29:38
zulip/zulip
25,294
zulip__zulip-25294
[ "25249" ]
033f561d943a0a2096d5a1778b37ded06731d74a
diff --git a/zerver/models.py b/zerver/models.py --- a/zerver/models.py +++ b/zerver/models.py @@ -623,6 +623,8 @@ class Realm(models.Model): # type: ignore[django-manager-missing] # django-stub }, } + ORG_TYPE_IDS: List[int] = [t["id"] for t in ORG_TYPES.values()] + org_type = models.PositiveSmallIntegerField( default=ORG_TYPES["unspecified"]["id"], choices=[(t["id"], t["name"]) for t in ORG_TYPES.values()], diff --git a/zerver/views/realm.py b/zerver/views/realm.py --- a/zerver/views/realm.py +++ b/zerver/views/realm.py @@ -1,4 +1,4 @@ -from typing import Any, Dict, List, Optional, Union +from typing import Any, Dict, Optional, Union from django.core.exceptions import ValidationError from django.http import HttpRequest, HttpResponse @@ -40,8 +40,6 @@ from zerver.models import Realm, RealmReactivationStatus, RealmUserDefault, UserProfile from zerver.views.user_settings import check_settings_values -ORG_TYPE_IDS: List[int] = [t["id"] for t in Realm.ORG_TYPES.values()] - @require_realm_admin @has_request_variables @@ -137,7 +135,7 @@ def update_realm( str_validator=check_capped_string(Realm.MAX_REALM_SUBDOMAIN_LENGTH), default=None, ), - org_type: Optional[int] = REQ(json_validator=check_int_in(ORG_TYPE_IDS), default=None), + org_type: Optional[int] = REQ(json_validator=check_int_in(Realm.ORG_TYPE_IDS), default=None), enable_spectator_access: Optional[bool] = REQ(json_validator=check_bool, default=None), want_advertise_in_communities_directory: Optional[bool] = REQ( json_validator=check_bool, default=None diff --git a/zerver/views/registration.py b/zerver/views/registration.py --- a/zerver/views/registration.py +++ b/zerver/views/registration.py @@ -58,7 +58,13 @@ from zerver.lib.subdomains import get_subdomain from zerver.lib.url_encoding import append_url_query_string from zerver.lib.users import get_accounts_for_email -from zerver.lib.validator import to_converted_or_fallback, to_non_negative_int, to_timezone_or_empty +from zerver.lib.validator import ( + check_capped_string, + check_int_in, + to_converted_or_fallback, + to_non_negative_int, + to_timezone_or_empty, +) from zerver.lib.zephyr import compute_mit_user_fullname from zerver.models import ( DisposableEmailError, @@ -756,7 +762,14 @@ def create_realm(request: HttpRequest, creation_key: Optional[str] = None) -> Ht if key_record is not None: key_record.delete() new_realm_send_confirm_url = reverse("new_realm_send_confirm") - query = urlencode({"email": email}) + query = urlencode( + { + "email": email, + "realm_name": realm_name, + "realm_type": realm_type, + "realm_subdomain": realm_subdomain, + } + ) url = append_url_query_string(new_realm_send_confirm_url, query) return HttpResponseRedirect(url) else: @@ -787,11 +800,26 @@ def signup_send_confirm(request: HttpRequest, email: str = REQ("email")) -> Http @add_google_analytics @has_request_variables -def new_realm_send_confirm(request: HttpRequest, email: str = REQ("email")) -> HttpResponse: +def new_realm_send_confirm( + request: HttpRequest, + email: str = REQ("email"), + realm_name: str = REQ(str_validator=check_capped_string(Realm.MAX_REALM_NAME_LENGTH)), + realm_type: int = REQ(json_validator=check_int_in(Realm.ORG_TYPE_IDS)), + realm_subdomain: str = REQ(str_validator=check_capped_string(Realm.MAX_REALM_SUBDOMAIN_LENGTH)), +) -> HttpResponse: return TemplateResponse( request, "zerver/accounts_send_confirm.html", - context={"email": email, "realm_creation": True}, + context={ + "email": email, + # Using "new_realm_name" key here since "realm_name" key is already present in + # the context provided by zulip_default_context and it is "None" during realm + # creation. + "new_realm_name": realm_name, + "realm_type": realm_type, + "realm_subdomain": realm_subdomain, + "realm_creation": True, + }, )
diff --git a/zerver/tests/test_management_commands.py b/zerver/tests/test_management_commands.py --- a/zerver/tests/test_management_commands.py +++ b/zerver/tests/test_management_commands.py @@ -323,20 +323,23 @@ def test_generate_link_and_create_realm(self) -> None: @override_settings(OPEN_REALM_CREATION=False) def test_generate_link_confirm_email(self) -> None: email = "[email protected]" + realm_name = "Zulip test" + string_id = "zuliptest" generated_link = generate_realm_creation_url(by_admin=False) result = self.client_post( generated_link, { "email": email, - "realm_name": "Zulip test", + "realm_name": realm_name, "realm_type": Realm.ORG_TYPES["business"]["id"], - "realm_subdomain": "zuliptest", + "realm_subdomain": string_id, }, ) self.assertEqual(result.status_code, 302) self.assertEqual( - f"/accounts/new/send_confirm/?email={urllib.parse.quote(email)}", result["Location"] + f"/accounts/new/send_confirm/?email={urllib.parse.quote(email)}&realm_name={urllib.parse.quote_plus(realm_name)}&realm_type=10&realm_subdomain={string_id}", + result["Location"], ) result = self.client_get(result["Location"]) self.assert_in_response("Check your email", result) diff --git a/zerver/tests/test_signup.py b/zerver/tests/test_signup.py --- a/zerver/tests/test_signup.py +++ b/zerver/tests/test_signup.py @@ -758,7 +758,9 @@ def test_redirect_endpoints(self) -> None: result = self.client_get("/accounts/send_confirm/[email protected]") self.assert_in_success_response(["/accounts/home/"], result) - result = self.client_get("/accounts/new/send_confirm/[email protected]") + result = self.client_get( + "/accounts/new/send_confirm/[email protected]&realm_name=Zulip+test&realm_type=10&realm_subdomain=zuliptest" + ) self.assert_in_success_response(["/new/"], result) def test_password_reset_for_soft_deactivated_user(self) -> None: @@ -1266,7 +1268,7 @@ def check_able_to_create_realm(self, email: str, password: str = "test") -> None self.assertEqual(result.status_code, 302) self.assertTrue( result["Location"].endswith( - f"/accounts/new/send_confirm/?email={urllib.parse.quote(email)}" + f"/accounts/new/send_confirm/?email={urllib.parse.quote(email)}&realm_name={urllib.parse.quote_plus(org_name)}&realm_type=10&realm_subdomain={string_id}" ) ) result = self.client_get(result["Location"]) @@ -1401,7 +1403,7 @@ def test_create_realm_with_subdomain(self) -> None: self.assertEqual(result.status_code, 302) self.assertTrue( result["Location"].endswith( - f"/accounts/new/send_confirm/?email={urllib.parse.quote(email)}" + f"/accounts/new/send_confirm/?email={urllib.parse.quote(email)}&realm_name={urllib.parse.quote_plus(realm_name)}&realm_type=10&realm_subdomain={string_id}" ) ) result = self.client_get(result["Location"]) @@ -1447,7 +1449,7 @@ def test_create_realm_with_marketing_emails_enabled(self) -> None: self.assertEqual(result.status_code, 302) self.assertTrue( result["Location"].endswith( - f"/accounts/new/send_confirm/?email={urllib.parse.quote(email)}" + f"/accounts/new/send_confirm/?email={urllib.parse.quote(email)}&realm_name={urllib.parse.quote_plus(realm_name)}&realm_type=10&realm_subdomain={string_id}" ) ) result = self.client_get(result["Location"]) @@ -1496,7 +1498,7 @@ def test_create_realm_without_prompting_for_marketing_emails(self) -> None: self.assertEqual(result.status_code, 302) self.assertTrue( result["Location"].endswith( - f"/accounts/new/send_confirm/?email={urllib.parse.quote(email)}" + f"/accounts/new/send_confirm/?email={urllib.parse.quote(email)}&realm_name={urllib.parse.quote_plus(realm_name)}&realm_type=10&realm_subdomain={string_id}" ) ) result = self.client_get(result["Location"]) @@ -1543,7 +1545,7 @@ def test_create_realm_with_marketing_emails_disabled(self) -> None: password = "test" string_id = "zuliptest" email = "[email protected]" - realm_name = "Test" + realm_name = "Zulip test" # Make sure the realm does not exist with self.assertRaises(Realm.DoesNotExist): @@ -1551,12 +1553,12 @@ def test_create_realm_with_marketing_emails_disabled(self) -> None: # Create new realm with the email result = self.submit_realm_creation_form( - email, realm_subdomain=string_id, realm_name="Zulip test" + email, realm_subdomain=string_id, realm_name=realm_name ) self.assertEqual(result.status_code, 302) self.assertTrue( result["Location"].endswith( - f"/accounts/new/send_confirm/?email={urllib.parse.quote(email)}" + f"/accounts/new/send_confirm/?email={urllib.parse.quote(email)}&realm_name={urllib.parse.quote_plus(realm_name)}&realm_type=10&realm_subdomain={string_id}" ) ) result = self.client_get(result["Location"]) @@ -1601,7 +1603,7 @@ def test_create_regular_realm_welcome_bot_pm(self) -> None: self.assertEqual(result.status_code, 302) self.assertTrue( result["Location"].endswith( - f"/accounts/new/send_confirm/?email={urllib.parse.quote(email)}" + f"/accounts/new/send_confirm/?email={urllib.parse.quote(email)}&realm_name={urllib.parse.quote_plus(realm_name)}&realm_type=10&realm_subdomain={string_id}" ) ) result = self.client_get(result["Location"]) @@ -1642,7 +1644,7 @@ def test_create_demo_realm_welcome_bot_pm(self) -> None: self.assertEqual(result.status_code, 302) self.assertTrue( result["Location"].endswith( - f"/accounts/new/send_confirm/?email={urllib.parse.quote(email)}" + f"/accounts/new/send_confirm/?email={urllib.parse.quote(email)}&realm_name={urllib.parse.quote_plus(realm_name)}&realm_type=10&realm_subdomain={string_id}" ) ) result = self.client_get(result["Location"]) @@ -1687,7 +1689,7 @@ def test_create_realm_during_free_trial(self) -> None: self.assertEqual(result.status_code, 302) self.assertTrue( result["Location"].endswith( - f"/accounts/new/send_confirm/?email={urllib.parse.quote(email)}" + f"/accounts/new/send_confirm/?email={urllib.parse.quote(email)}&realm_name={urllib.parse.quote_plus(realm_name)}&realm_type=10&realm_subdomain={string_id}" ) ) result = self.client_get(result["Location"]) @@ -1741,7 +1743,7 @@ def test_create_two_realms(self) -> None: self.assertEqual(result.status_code, 302) self.assertTrue( result["Location"].endswith( - f"/accounts/new/send_confirm/?email={urllib.parse.quote(email)}" + f"/accounts/new/send_confirm/?email={urllib.parse.quote(email)}&realm_name={urllib.parse.quote_plus(first_realm_name)}&realm_type=10&realm_subdomain={first_string_id}" ) ) result = self.client_get(result["Location"]) @@ -1755,7 +1757,7 @@ def test_create_two_realms(self) -> None: self.assertEqual(result.status_code, 302) self.assertTrue( result["Location"].endswith( - f"/accounts/new/send_confirm/?email={urllib.parse.quote(email)}" + f"/accounts/new/send_confirm/?email={urllib.parse.quote(email)}&realm_name={urllib.parse.quote_plus(second_realm_name)}&realm_type=10&realm_subdomain={second_string_id}" ) ) result = self.client_get(result["Location"])
Bug: Resend button during organization verification redirects to create page When verifying a new organization, clicking on the "resend" button to receive the verification link again redirects the user to the "create organization" page, rather than resending the email. This can lead to confusion and frustration for users who expect the verification link to be resent. Expected behavior: Clicking on the "resend" button should resend the verification link to the specified email address. Actual behavior: Clicking on the "resend" button redirects the user to the "create organization" page.
@sahil839 Is this potentially related to #24689? Got it. It is related to that only. Will open a PR.
2023-04-26T14:41:48
zulip/zulip
25,345
zulip__zulip-25345
[ "25130" ]
a97c4708e804db7a08a74c249a16c168a87dff23
diff --git a/zerver/lib/export.py b/zerver/lib/export.py --- a/zerver/lib/export.py +++ b/zerver/lib/export.py @@ -54,6 +54,7 @@ RealmPlayground, RealmUserDefault, Recipient, + ScheduledMessage, Service, Stream, Subscription, @@ -205,7 +206,6 @@ class MessagePartial(TypedDict): # sense to export, but is relatively low value. "zerver_scheduledemail", "zerver_scheduledemail_users", - "zerver_scheduledmessage", # These tables are related to a user's 2FA authentication # configuration, which will need to be set up again on the new # server. @@ -223,8 +223,6 @@ class MessagePartial(TypedDict): "zerver_archivedreaction", "zerver_archivedsubmessage", "zerver_archivetransaction", - # We don't export this until export of ScheduledMessage in general is implemented. - "zerver_attachment_scheduled_messages", # Social auth tables are not needed post-export, since we don't # use any of this state outside of a direct authentication flow. "social_auth_association", @@ -252,6 +250,7 @@ class MessagePartial(TypedDict): # ManyToMany relationships are exported implicitly when importing # the parent table. "zerver_attachment_messages", + "zerver_attachment_scheduled_messages", } ATTACHMENT_TABLES = { @@ -292,6 +291,7 @@ class MessagePartial(TypedDict): "zerver_muteduser": ["date_muted"], "zerver_realmauditlog": ["event_time"], "zerver_realm": ["date_created"], + "zerver_scheduledmessage": ["scheduled_timestamp"], "zerver_stream": ["date_created"], "zerver_useractivityinterval": ["start", "end"], "zerver_useractivity": ["last_visit"], @@ -691,6 +691,12 @@ def get_realm_config() -> Config: include_rows="realm_id__in", ) + Config( + custom_tables=["zerver_scheduledmessage"], + virtual_parent=realm_config, + custom_fetch=custom_fetch_scheduled_messages, + ) + Config( table="zerver_defaultstream", model=DefaultStream, @@ -1047,10 +1053,13 @@ def custom_fetch_user_profile_cross_realm(response: TableData, context: Context) def fetch_attachment_data( - response: TableData, realm_id: int, message_ids: Set[int] + response: TableData, realm_id: int, message_ids: Set[int], scheduled_message_ids: Set[int] ) -> List[Attachment]: attachments = list( - Attachment.objects.filter(realm_id=realm_id, messages__in=message_ids).distinct() + Attachment.objects.filter( + Q(messages__in=message_ids) | Q(scheduled_messages__in=scheduled_message_ids), + realm_id=realm_id, + ).distinct() ) response["zerver_attachment"] = make_raw(attachments) floatify_datetime_fields(response, "zerver_attachment") @@ -1060,10 +1069,17 @@ def fetch_attachment_data( quite ALL messages for the realm. So, we need to clean up our attachment data to have correct values for response['zerver_attachment'][<n>]['messages']. + + Same reasoning applies to scheduled_messages. """ for row in response["zerver_attachment"]: - filterer_message_ids = set(row["messages"]).intersection(message_ids) - row["messages"] = sorted(filterer_message_ids) + filtered_message_ids = set(row["messages"]).intersection(message_ids) + row["messages"] = sorted(filtered_message_ids) + + filtered_scheduled_message_ids = set(row["scheduled_messages"]).intersection( + scheduled_message_ids + ) + row["scheduled_messages"] = sorted(filtered_scheduled_message_ids) return attachments @@ -1123,6 +1139,19 @@ def custom_fetch_huddle_objects(response: TableData, context: Context) -> None: response["zerver_huddle"] = make_raw(Huddle.objects.filter(id__in=huddle_ids)) +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"] + + query = ScheduledMessage.objects.filter(realm=realm, id__in=exportable_scheduled_message_ids) + rows = make_raw(list(query)) + + response["zerver_scheduledmessage"] = rows + + def fetch_usermessages( realm: Realm, message_ids: Set[int], @@ -1827,6 +1856,28 @@ def do_write_stats_file_for_realm_export(output_dir: Path) -> None: f.write("\n") +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 set() + + if consent_message_id: + sender_ids = get_consented_user_ids(consent_message_id) + return set( + ScheduledMessage.objects.filter(sender_id__in=sender_ids, realm=realm).values_list( + "id", flat=True + ) + ) + + return set(ScheduledMessage.objects.filter(realm=realm).values_list("id", flat=True)) + + def do_export_realm( realm: Realm, output_dir: Path, @@ -1848,12 +1899,20 @@ def do_export_realm( create_soft_link(source=output_dir, in_progress=True) + exportable_scheduled_message_ids = get_exportable_scheduled_message_ids( + realm, public_only, consent_message_id + ) + logging.info("Exporting data from get_realm_config()...") export_from_config( response=response, config=realm_config, seed_object=realm, - context=dict(realm=realm, exportable_user_ids=exportable_user_ids), + context=dict( + realm=realm, + exportable_user_ids=exportable_user_ids, + exportable_scheduled_message_ids=exportable_scheduled_message_ids, + ), ) logging.info("...DONE with get_realm_config() data") @@ -1892,7 +1951,10 @@ def do_export_realm( # zerver_attachment attachments = export_attachment_table( - realm=realm, output_dir=output_dir, message_ids=message_ids + realm=realm, + output_dir=output_dir, + message_ids=message_ids, + scheduled_message_ids=exportable_scheduled_message_ids, ) logging.info("Exporting uploaded files and avatars") @@ -1921,11 +1983,14 @@ def do_export_realm( def export_attachment_table( - realm: Realm, output_dir: Path, message_ids: Set[int] + realm: Realm, output_dir: Path, message_ids: Set[int], scheduled_message_ids: Set[int] ) -> List[Attachment]: response: TableData = {} attachments = fetch_attachment_data( - response=response, realm_id=realm.id, message_ids=message_ids + response=response, + realm_id=realm.id, + message_ids=message_ids, + scheduled_message_ids=scheduled_message_ids, ) output_file = os.path.join(output_dir, "attachment.json") write_table_data(output_file=output_file, data=response) diff --git a/zerver/lib/import_realm.py b/zerver/lib/import_realm.py --- a/zerver/lib/import_realm.py +++ b/zerver/lib/import_realm.py @@ -58,6 +58,7 @@ RealmPlayground, RealmUserDefault, Recipient, + ScheduledMessage, Service, Stream, Subscription, @@ -136,6 +137,7 @@ "analytics_streamcount": {}, "analytics_usercount": {}, "realmuserdefault": {}, + "scheduledmessage": {}, } id_map_to_list: Dict[str, Dict[int, List[int]]] = { @@ -371,7 +373,10 @@ def fix_message_rendered_content( ).rendered_content message["rendered_content"] = rendered_content - message["rendered_content_version"] = markdown_version + if "scheduled_timestamp" not in message: + # This logic runs also for ScheduledMessage, which doesn't use + # the rendered_content_version field. + message["rendered_content_version"] = markdown_version except Exception: # This generally happens with two possible causes: # * rendering Markdown throwing an uncaught exception @@ -897,13 +902,18 @@ def import_uploads( # Importing data suffers from a difficult ordering problem because of # models that reference each other circularly. Here is a correct order. # +# (Note that this list is not exhaustive and only talks about the main, +# most important models. There's a bunch of minor models that are handled +# separately and not mentioned here - but following the principle that we +# have to import the dependencies first.) +# # * Client [no deps] # * Realm [-notifications_stream] # * UserGroup # * Stream [only depends on realm] # * Realm's notifications_stream -# * Now can do all realm_tables # * UserProfile, in order by ID to avoid bot loop issues +# * Now can do all realm_tables # * Huddle # * Recipient # * Subscription @@ -1312,6 +1322,27 @@ def do_import_realm(import_dir: Path, subdomain: str, processes: int = 1) -> Rea sender_map = {user["id"]: user for user in data["zerver_userprofile"]} + if "zerver_scheduledmessage" in data: + fix_datetime_fields(data, "zerver_scheduledmessage") + re_map_foreign_keys(data, "zerver_scheduledmessage", "sender", related_table="user_profile") + re_map_foreign_keys(data, "zerver_scheduledmessage", "recipient", related_table="recipient") + re_map_foreign_keys( + data, "zerver_scheduledmessage", "sending_client", related_table="client" + ) + re_map_foreign_keys(data, "zerver_scheduledmessage", "stream", related_table="stream") + re_map_foreign_keys(data, "zerver_scheduledmessage", "realm", related_table="realm") + + fix_upload_links(data, "zerver_scheduledmessage") + + fix_message_rendered_content( + realm=realm, + sender_map=sender_map, + messages=data["zerver_scheduledmessage"], + ) + + update_model_ids(ScheduledMessage, data, "scheduledmessage") + bulk_import_model(data, ScheduledMessage) + # Import zerver_message and zerver_usermessage import_message_data(realm=realm, sender_map=sender_map, import_dir=import_dir) @@ -1524,11 +1555,7 @@ def import_attachments(data: TableData) -> None: parent_model = Attachment parent_db_table_name = "zerver_attachment" parent_singular = "attachment" - child_singular = "message" - child_plural = "messages" - m2m_table_name = "zerver_attachment_messages" parent_id = "attachment_id" - child_id = "message_id" update_model_ids(parent_model, data, "attachment") # We don't bulk_import_model yet, because we need to first compute @@ -1538,27 +1565,41 @@ def import_attachments(data: TableData) -> None: # We do this in a slightly convoluted way to anticipate # a future where we may need to call re_map_foreign_keys. - m2m_rows: List[Record] = [] - for parent_row in data[parent_db_table_name]: - for fk_id in parent_row[child_plural]: - m2m_row: Record = {} - m2m_row[parent_singular] = parent_row["id"] - m2m_row[child_singular] = ID_MAP["message"][fk_id] - m2m_rows.append(m2m_row) - - # TODO: Import of scheduled messages is not implemented yet. - if "scheduled_messages" in parent_row: - del parent_row["scheduled_messages"] - - # Create our table data for insert. - m2m_data: TableData = {m2m_table_name: m2m_rows} - convert_to_id_fields(m2m_data, m2m_table_name, parent_singular) - convert_to_id_fields(m2m_data, m2m_table_name, child_singular) - m2m_rows = m2m_data[m2m_table_name] - - # Next, delete out our child data from the parent rows. - for parent_row in data[parent_db_table_name]: - del parent_row[child_plural] + def format_m2m_data( + child_singular: str, child_plural: str, m2m_table_name: str, child_id: str + ) -> Tuple[str, List[Record], str]: + m2m_rows: List[Record] = [] + for parent_row in data[parent_db_table_name]: + for fk_id in parent_row[child_plural]: + m2m_row: Record = {} + m2m_row[parent_singular] = parent_row["id"] + # child_singular will generally match the model name (e.g. Message, ScheduledMessage) + # after lowercasing, and that's what we enter as ID_MAP keys, so this should be + # a reasonable assumption to make. + m2m_row[child_singular] = ID_MAP[child_singular][fk_id] + m2m_rows.append(m2m_row) + + # Create our table data for insert. + m2m_data: TableData = {m2m_table_name: m2m_rows} + convert_to_id_fields(m2m_data, m2m_table_name, parent_singular) + convert_to_id_fields(m2m_data, m2m_table_name, child_singular) + m2m_rows = m2m_data[m2m_table_name] + + # Next, delete out our child data from the parent rows. + for parent_row in data[parent_db_table_name]: + del parent_row[child_plural] + + return m2m_table_name, m2m_rows, child_id + + messages_m2m_tuple = format_m2m_data( + "message", "messages", "zerver_attachment_messages", "message_id" + ) + scheduled_messages_m2m_tuple = format_m2m_data( + "scheduledmessage", + "scheduled_messages", + "zerver_attachment_scheduled_messages", + "scheduledmessage_id", + ) # Update 'path_id' for the attachments for attachment in data[parent_db_table_name]: @@ -1571,19 +1612,23 @@ def import_attachments(data: TableData) -> None: # TODO: Do this the kosher Django way. We may find a # better way to do this in Django 1.9 particularly. with connection.cursor() as cursor: - sql_template = SQL( + for m2m_table_name, m2m_rows, child_id in [ + messages_m2m_tuple, + scheduled_messages_m2m_tuple, + ]: + sql_template = SQL( + """ + INSERT INTO {m2m_table_name} ({parent_id}, {child_id}) VALUES %s """ - INSERT INTO {m2m_table_name} ({parent_id}, {child_id}) VALUES %s - """ - ).format( - m2m_table_name=Identifier(m2m_table_name), - parent_id=Identifier(parent_id), - child_id=Identifier(child_id), - ) - tups = [(row[parent_id], row[child_id]) for row in m2m_rows] - execute_values(cursor.cursor, sql_template, tups) + ).format( + m2m_table_name=Identifier(m2m_table_name), + parent_id=Identifier(parent_id), + child_id=Identifier(child_id), + ) + tups = [(row[parent_id], row[child_id]) for row in m2m_rows] + execute_values(cursor.cursor, sql_template, tups) - logging.info("Successfully imported M2M table %s", m2m_table_name) + logging.info("Successfully imported M2M table %s", m2m_table_name) def import_analytics_data(realm: Realm, import_dir: Path) -> None:
diff --git a/zerver/tests/test_import_export.py b/zerver/tests/test_import_export.py --- a/zerver/tests/test_import_export.py +++ b/zerver/tests/test_import_export.py @@ -27,6 +27,7 @@ do_change_realm_plan_type, do_set_realm_authentication_methods, ) +from zerver.actions.scheduled_messages import check_schedule_message from zerver.actions.user_activity import do_update_user_activity, do_update_user_activity_interval from zerver.actions.user_status import do_update_user_status from zerver.actions.user_topics import do_set_user_topic_visibility_policy @@ -66,6 +67,7 @@ RealmEmoji, RealmUserDefault, Recipient, + ScheduledMessage, Stream, Subscription, UserGroup, @@ -790,6 +792,22 @@ def test_import_realm(self) -> None: sample_user, client, timezone_now(), UserPresence.LEGACY_STATUS_ACTIVE_INT ) + # Set up scheduled messages. + ScheduledMessage.objects.filter(realm=original_realm).delete() + check_schedule_message( + sender=hamlet, + client=get_client("website"), + recipient_type_name="stream", + message_to=[Stream.objects.get(name="Denmark", realm=original_realm).id], + topic_name="test-import", + message_content="test message", + scheduled_message_id=None, + deliver_at=timezone_now() + datetime.timedelta(days=365), + realm=original_realm, + ) + original_scheduled_message = ScheduledMessage.objects.filter(realm=original_realm).last() + assert original_scheduled_message is not None + # send Cordelia to the islands do_update_user_status( user_profile=cordelia, @@ -940,6 +958,15 @@ def assert_realm_values(f: Callable[[Realm], object]) -> None: Recipient.objects.get(type=Recipient.HUDDLE, type_id=huddle_object.id).id, ) + self.assertEqual(ScheduledMessage.objects.filter(realm=imported_realm).count(), 1) + imported_scheduled_message = ScheduledMessage.objects.first() + assert imported_scheduled_message is not None + self.assertEqual(imported_scheduled_message.content, original_scheduled_message.content) + self.assertEqual( + imported_scheduled_message.scheduled_timestamp, + original_scheduled_message.scheduled_timestamp, + ) + for user_profile in UserProfile.objects.filter(realm=imported_realm): # Check that all Subscriptions have the correct is_user_active set. self.assertEqual(
Backend follow-up changes for scheduled messages API (#23670) I've extracting a TODO list of backend follow-ups for #23670, roughly in an order that I think would make a good commit series: - [x] We should extract the tests from the giant `test_message_send.py` to a `test_scheduled_messages` - [x] We should move the core logic that does the database changes and sends events from `zerver/views/scheduled_messages` and `zerver/actions/message_send.py` to a `zerver/actions/scheduled_messages.py` -- this would match the pattern we use for other modules and also shrink the giant `message_send.py`. - [x] We should split sending and editing scheduled messages into a separate endpoint from sending messages -- `POST /scheduled_messages`. See https://chat.zulip.org/#narrow/stream/378-api-design/topic/scheduled.20messages for discussion -- one point to bring up there is whether we want editing to use the same endpoint as scheduling; my theory is yes given the way the system works (basically that we validate the new scheduled message request, and then replace all the data if we're allowed to send the new one). We can probably just disable/remove the "reminder" support when doing so, since our plan is to add a separate endpoint for that feature in the future with a different structure, and it'll be nice to have the "send a message" endpoint be freed of this clutter. - [ ] We should make sure the data import/export tools handle ScheduledMessage correctly -- they're currently excluded from exports/imports. Could make sense for @mateuszmandera to do this point, since it's orthogonal to the rest and requires some specialized knowledge. - [x] We should setup events to send live updates of scheduled messages to the client. - [x] We should probably optionally include scheduled messages in the `POST /register` response, so that clients can more readily display a count of your scheduled messages in the left sidebar alongside drafts, or surface that you have some when viewing a message feed where you have something scheduled to be sent.
Hello @zulip/server-misc members, this issue was labeled with the "area: misc" label, so you may want to check it out! <!-- areaLabelAddition -->
2023-04-29T18:49:19
zulip/zulip
25,347
zulip__zulip-25347
[ "21969" ]
715fa3aff6b43ab436a8410a0edb631f6c409ee3
diff --git a/zerver/lib/webhooks/git.py b/zerver/lib/webhooks/git.py --- a/zerver/lib/webhooks/git.py +++ b/zerver/lib/webhooks/git.py @@ -13,8 +13,8 @@ COMMITS_MORE_THAN_LIMIT_TEMPLATE = "[and {commits_number} more commit(s)]" COMMIT_OR_COMMITS = "commit{}" -PUSH_PUSHED_TEXT_WITH_URL = "[pushed]({compare_url}) {number_of_commits} {commit_or_commits}" -PUSH_PUSHED_TEXT_WITHOUT_URL = "pushed {number_of_commits} {commit_or_commits}" +PUSH_PUSHED_TEXT_WITH_URL = "[{push_type}]({compare_url}) {number_of_commits} {commit_or_commits}" +PUSH_PUSHED_TEXT_WITHOUT_URL = "{push_type} {number_of_commits} {commit_or_commits}" PUSH_COMMITS_BASE = "{user_name} {pushed_text} to branch {branch_name}." PUSH_COMMITS_MESSAGE_TEMPLATE_WITH_COMMITTERS = ( @@ -35,10 +35,10 @@ "{user_name} [deleted]({compare_url}) the branch {branch_name}." ) PUSH_LOCAL_BRANCH_WITHOUT_COMMITS_MESSAGE_TEMPLATE = ( - "{user_name} [pushed]({compare_url}) the branch {branch_name}." + "{user_name} [{push_type}]({compare_url}) the branch {branch_name}." ) PUSH_LOCAL_BRANCH_WITHOUT_COMMITS_MESSAGE_WITHOUT_URL_TEMPLATE = ( - "{user_name} pushed the branch {branch_name}." + "{user_name} {push_type} the branch {branch_name}." ) PUSH_COMMITS_MESSAGE_EXTENSION = "Commits by {}" PUSH_COMMITTERS_LIMIT_INFO = 3 @@ -89,6 +89,7 @@ def get_push_commits_event_message( commits_data: List[Dict[str, Any]], is_truncated: bool = False, deleted: bool = False, + force_push: Optional[bool] = False, ) -> str: if not commits_data and deleted: return PUSH_DELETE_BRANCH_MESSAGE_TEMPLATE.format( @@ -97,14 +98,17 @@ def get_push_commits_event_message( branch_name=branch_name, ) + push_type = "force pushed" if force_push else "pushed" if not commits_data and not deleted: if compare_url: return PUSH_LOCAL_BRANCH_WITHOUT_COMMITS_MESSAGE_TEMPLATE.format( + push_type=push_type, user_name=user_name, compare_url=compare_url, branch_name=branch_name, ) return PUSH_LOCAL_BRANCH_WITHOUT_COMMITS_MESSAGE_WITHOUT_URL_TEMPLATE.format( + push_type=push_type, user_name=user_name, branch_name=branch_name, ) @@ -114,6 +118,7 @@ def get_push_commits_event_message( ) pushed_text_message = pushed_message_template.format( + push_type=push_type, compare_url=compare_url, number_of_commits=len(commits_data), commit_or_commits=COMMIT_OR_COMMITS.format("s" if len(commits_data) > 1 else ""), diff --git a/zerver/webhooks/github/view.py b/zerver/webhooks/github/view.py --- a/zerver/webhooks/github/view.py +++ b/zerver/webhooks/github/view.py @@ -283,6 +283,7 @@ def get_push_commits_body(helper: Helper) -> str: get_branch_name_from_ref(payload["ref"].tame(check_string)), commits_data, deleted=payload["deleted"].tame(check_bool), + force_push=payload["forced"].tame(check_bool), )
diff --git a/zerver/webhooks/github/tests.py b/zerver/webhooks/github/tests.py --- a/zerver/webhooks/github/tests.py +++ b/zerver/webhooks/github/tests.py @@ -37,6 +37,14 @@ def test_push_delete_branch(self) -> None: expected_message = "eeshangarg [deleted](https://github.com/eeshangarg/public-repo/compare/2e8cf535fb38...000000000000) the branch feature." self.check_webhook("push__delete_branch", "public-repo / feature", expected_message) + def test_push_force_1_commit(self) -> None: + expected_message = "sbansal1999 [force pushed](https://github.com/sbansal1999/zulip/compare/b6de8891fc10...971d76ca3094) 1 commit to branch temp.\n\n* log: Add important.txt which is useful for logging errors. ([971d76ca309](https://github.com/sbansal1999/zulip/commit/971d76ca309446a9c20381f6271cea8a59b4e40a))" + self.check_webhook("push__force_1_commit", "zulip / temp", expected_message) + + def test_push__force_remove_commits(self) -> None: + expected_message = "sbansal1999 [force pushed](https://github.com/sbansal1999/zulip/compare/2084a91af9ca...9a8749ea8fe7) the branch temp." + self.check_webhook("push__force_remove_commits", "zulip / temp", expected_message) + def test_push_local_branch_without_commits(self) -> None: expected_message = "eeshangarg [pushed](https://github.com/eeshangarg/public-repo/compare/feature) the branch feature." self.check_webhook(
github integration: show if push was forced The github integration bot is really useful :heart:, I'd like to help make it even better. The github integration currently does not inform the user if a push was forced or not, the message is the same for both cases. We consider a force push to be an important security event and would like to be notified when one happens. The current format in case of a force push is: ``` <username> [pushed](https://github.com/repo/...) <commits> to branch <branch_name>. <changelist> ``` My proposed format is: ``` <username> :boom: [force pushed](https://github.com/repo/...) :boom: <commits> to branch <branch_name>. <changelist> ``` I'm willing to do the implementation myself, let me know what you think :) .
I think probably the :boom: is unnecessary, but we'd be happy to merge a patch that did this! https://zulip.com/api/incoming-webhooks-overview should help you find the code. Hello @zulip/server-integrations members, this issue was labeled with the "area: integrations" label, so you may want to check it out! <!-- areaLabelAddition --> Thanks for responding @timabbott :) Without the :boom: I believe it is easy to miss that the push was forced, especially when there are many push messages. When a "bad" force push happens I think it is vital that all developers are aware of this as fast as possible and that actions to fix this are started as fast as possible. For these reasons, it is necessary for the message to stand out. We can play with it -- I wouldn't put 2 copies of :boom:, at least. It's possible a single copy at the start of the line would be appropriate. In any case, it'll be easier to play with when we have screenshots, which the development environment makes easy to generate. It seems possible that just the longer link text of "force pushed" might already stand out, which had been what I was thinking.
2023-04-29T19:34:50
zulip/zulip
25,362
zulip__zulip-25362
[ "21694" ]
663170f0d3920299c8b4504328f898cafc7f0365
diff --git a/zerver/actions/create_user.py b/zerver/actions/create_user.py --- a/zerver/actions/create_user.py +++ b/zerver/actions/create_user.py @@ -252,9 +252,9 @@ def process_new_human_user( # We have an import loop here; it's intentional, because we want # to keep all the onboarding code in zerver/lib/onboarding.py. - from zerver.lib.onboarding import send_initial_pms + from zerver.lib.onboarding import send_initial_direct_message - send_initial_pms(user_profile) + send_initial_direct_message(user_profile) def notify_created_user(user_profile: UserProfile) -> None: diff --git a/zerver/lib/onboarding.py b/zerver/lib/onboarding.py --- a/zerver/lib/onboarding.py +++ b/zerver/lib/onboarding.py @@ -39,40 +39,75 @@ def create_if_missing_realm_internal_bots() -> None: setup_realm_internal_bots(realm) -def send_initial_pms(user: UserProfile) -> None: - organization_setup_text = "" +def send_initial_direct_message(user: UserProfile) -> None: + # We adjust the initial Welcome Bot direct message for education organizations. + education_organization = False + if ( + user.realm.org_type == Realm.ORG_TYPES["education_nonprofit"]["id"] + or user.realm.org_type == Realm.ORG_TYPES["education"]["id"] + ): + education_organization = True # We need to override the language in this code path, because it's # called from account registration, which is a pre-account API # request and thus may not have the user's language context yet. with override_language(user.default_language): + if education_organization: + getting_started_help = user.realm.uri + "/help/using-zulip-for-a-class" + getting_started_string = ( + _( + "If you are new to Zulip, check out our [Using Zulip for a class guide]({getting_started_url})!" + ) + ).format(getting_started_url=getting_started_help) + else: + getting_started_help = user.realm.uri + "/help/getting-started-with-zulip" + getting_started_string = ( + _( + "If you are new to Zulip, check out our [Getting started guide]({getting_started_url})!" + ) + ).format(getting_started_url=getting_started_help) + + organization_setup_string = "" + # Add extra content on setting up a new organization for administrators. if user.is_realm_admin: - help_url = user.realm.uri + "/help/getting-your-organization-started-with-zulip" - organization_setup_text = ( - " " + _("We also have a guide for [Setting up your organization]({help_url}).") - ).format(help_url=help_url) + if education_organization: + organization_setup_help = user.realm.uri + "/help/setting-up-zulip-for-a-class" + organization_setup_string = ( + " " + + _( + "We also have a guide for [Setting up Zulip for a class]({organization_setup_url})." + ) + ).format(organization_setup_url=organization_setup_help) + else: + organization_setup_help = ( + user.realm.uri + "/help/getting-your-organization-started-with-zulip" + ) + organization_setup_string = ( + " " + + _( + "We also have a guide for [Setting up your organization]({organization_setup_url})." + ) + ).format(organization_setup_url=organization_setup_help) - welcome_msg = _("Hello, and welcome to Zulip!") + "👋" - demo_org_warning = "" - if user.realm.demo_organization_scheduled_deletion_date is not None: - demo_org_help_url = user.realm.uri + "/help/demo-organizations" - demo_org_warning = ( + demo_organization_warning_string = "" + # Add extra content about automatic deletion for demo organization owners. + if user.is_realm_owner and user.realm.demo_organization_scheduled_deletion_date is not None: + demo_organization_help = user.realm.uri + "/help/demo-organizations" + demo_organization_warning_string = ( _( - "Note that this is a [demo organization]({demo_org_help_url}) and will be " + "Note that this is a [demo organization]({demo_organization_help_url}) and will be " "**automatically deleted** in 30 days." ) + "\n\n" - ).format(demo_org_help_url=demo_org_help_url) + ).format(demo_organization_help_url=demo_organization_help) content = "".join( [ - welcome_msg + " ", + _("Hello, and welcome to Zulip!") + "👋" + " ", _("This is a direct message from me, Welcome Bot.") + "\n\n", - _( - "If you are new to Zulip, check out our [Getting started guide]({getting_started_url})!" - ), + "{getting_started_text}", "{organization_setup_text}\n\n", - "{demo_org_warning}", + "{demo_organization_text}", _( "I can also help you get set up! Just click anywhere on this message or press `r` to reply." ) @@ -83,9 +118,9 @@ def send_initial_pms(user: UserProfile) -> None: ) content = content.format( - organization_setup_text=organization_setup_text, - demo_org_warning=demo_org_warning, - getting_started_url="/help/getting-started-with-zulip", + getting_started_text=getting_started_string, + organization_setup_text=organization_setup_string, + demo_organization_text=demo_organization_warning_string, ) internal_send_private_message( diff --git a/zerver/management/commands/send_welcome_bot_message.py b/zerver/management/commands/send_welcome_bot_message.py --- a/zerver/management/commands/send_welcome_bot_message.py +++ b/zerver/management/commands/send_welcome_bot_message.py @@ -2,7 +2,7 @@ from typing import Any from zerver.lib.management import ZulipBaseCommand -from zerver.lib.onboarding import send_initial_pms +from zerver.lib.onboarding import send_initial_direct_message class Command(ZulipBaseCommand): @@ -18,4 +18,4 @@ def add_arguments(self, parser: ArgumentParser) -> None: def handle(self, *args: Any, **options: str) -> None: for user_profile in self.get_users(options, self.get_realm(options), is_bot=False): - send_initial_pms(user_profile) + send_initial_direct_message(user_profile)
diff --git a/zerver/tests/test_signup.py b/zerver/tests/test_signup.py --- a/zerver/tests/test_signup.py +++ b/zerver/tests/test_signup.py @@ -1590,13 +1590,13 @@ def test_create_realm_with_marketing_emails_disabled(self) -> None: self.assertFalse(user.enable_marketing_emails) @override_settings(OPEN_REALM_CREATION=True) - def test_create_regular_realm_welcome_bot_pm(self) -> None: + def test_create_regular_realm_welcome_bot_direct_message(self) -> None: password = "test" string_id = "zuliptest" email = "[email protected]" realm_name = "Test" - # Create new realm with the email + # Create new realm with the email. result = self.submit_realm_creation_form( email, realm_subdomain=string_id, realm_name=realm_name ) @@ -1623,28 +1623,36 @@ def test_create_regular_realm_welcome_bot_pm(self) -> None: ) self.assertEqual(result.status_code, 302) - # Make sure the correct Welcome Bot PM is sent + # Make sure the correct Welcome Bot direct message is sent. welcome_msg = Message.objects.filter( sender__email="[email protected]", recipient__type=Recipient.PERSONAL ).latest("id") self.assertTrue(welcome_msg.content.startswith("Hello, and welcome to Zulip!")) + + # Organization type is not education or education_nonprofit, + # and organization is not a demo organization. + self.assertIn("Getting started guide", welcome_msg.content) + self.assertNotIn("Using Zulip for a class guide", welcome_msg.content) self.assertNotIn("demo organization", welcome_msg.content) @override_settings(OPEN_REALM_CREATION=True) - def test_create_demo_realm_welcome_bot_pm(self) -> None: + def test_create_education_demo_organiztion_welcome_bot_direct_message(self) -> None: password = "test" string_id = "zuliptest" email = "[email protected]" realm_name = "Test" - # Create new realm with the email + # Create new realm with the email. result = self.submit_realm_creation_form( - email, realm_subdomain=string_id, realm_name=realm_name + email, + realm_subdomain=string_id, + realm_name=realm_name, + realm_type=Realm.ORG_TYPES["education"]["id"], ) self.assertEqual(result.status_code, 302) self.assertTrue( result["Location"].endswith( - f"/accounts/new/send_confirm/?email={urllib.parse.quote(email)}&realm_name={urllib.parse.quote_plus(realm_name)}&realm_type=10&realm_subdomain={string_id}" + f"/accounts/new/send_confirm/?email={urllib.parse.quote(email)}&realm_name={urllib.parse.quote_plus(realm_name)}&realm_type=35&realm_subdomain={string_id}" ) ) result = self.client_get(result["Location"]) @@ -1661,15 +1669,20 @@ def test_create_demo_realm_welcome_bot_pm(self) -> None: realm_subdomain=string_id, realm_name=realm_name, enable_marketing_emails=False, + realm_type=Realm.ORG_TYPES["education"]["id"], is_demo_organization=True, ) self.assertEqual(result.status_code, 302) - # Make sure the correct Welcome Bot PM is sent + # Make sure the correct Welcome Bot direct message is sent. welcome_msg = Message.objects.filter( sender__email="[email protected]", recipient__type=Recipient.PERSONAL ).latest("id") self.assertTrue(welcome_msg.content.startswith("Hello, and welcome to Zulip!")) + + # Organization type is education, and organization is a demo organization. + self.assertNotIn("Getting started guide", welcome_msg.content) + self.assertIn("Using Zulip for a class guide", welcome_msg.content) self.assertIn("demo organization", welcome_msg.content) @override_settings(OPEN_REALM_CREATION=True, FREE_TRIAL_DAYS=30)
Customize Welcome Bot for education organizations Welcome Bot should take into account organization type in order to provide a tailored onboarding experience. In particular, it should link to specialized onboarding help center content for education organizations. Organization types: - Education (non-profit), Education (for-profit) Line in Welcome Bot message to replace: > If you are new to Zulip, check out our [Getting started guide](/help/getting-started-with-zulip)! We also have a guide for [Setting up your organization](http://zulipdev.com:9991/help/getting-your-organization-started-with-zulip). Instead, it should be: > If you are new to Zulip, check out our [Using Zulip for a class guide](/help/using-zulip-for-a-class)! We also have a guide for [Setting up Zulip for a class](/help/setting-up-zulip-for-a-class). The line should be modified for non-admin users as well, in the analogous way.
Hello @zulip/server-onboarding members, this issue was labeled with the "area: onboarding" label, so you may want to check it out! <!-- areaLabelAddition --> @zulipbot claim Hello @raghupalash, you have been unassigned from this issue because you have not updated this issue or any referenced pull requests for over 14 days. You can reclaim this issue or claim any other issue by commenting `@zulipbot claim` on that issue. Thanks for your contributions, and hope to see you again soon!
2023-05-01T16:25:49
zulip/zulip
25,400
zulip__zulip-25400
[ "25314" ]
18d8fbc74be15ac20ee74433abe3263d8e8b7208
diff --git a/zerver/lib/integrations.py b/zerver/lib/integrations.py --- a/zerver/lib/integrations.py +++ b/zerver/lib/integrations.py @@ -582,6 +582,9 @@ def __init__(self, name: str, *args: Any, **kwargs: Any) -> None: stream_name="commits", ), "nagios": Integration("nagios", "nagios", ["monitoring"], doc="zerver/integrations/nagios.md"), + "notion": Integration( + "notion", "notion", ["productivity"], doc="zerver/integrations/notion.md" + ), "openshift": Integration( "openshift", "openshift",
Integration with Notion We received a feature request from a user asking for an integration with Notion. It seems like this might be possible as an incoming webhook via their Zapier integration - https://zapier.com/apps/notion/integrations/webhook/599249/trigger-post-webhooks-with-new-items-in-notion-databases to send messages in Zulip about events in Notion
Hello @zulip/server-integrations members, this issue was labeled with the "area: integrations" label, so you may want to check it out! <!-- areaLabelAddition --> @sbansal1999 Would you be up for taking a look at this one? I just had some initial thoughts that if there is a Zapier integration for Notion, users can simply use Zapier to create a Zap that will send a message when a particular event happens on Notion. The trigger event for this Zap would be 'New Database Item'. More information on how to add the Zapier integration can be found [here](https://zulip.com/integrations/doc/zapier). Instead of Zapier sending a POST request to our server, processing it, and then sending the message, I think it would be better for the Zap to send the message itself. According to me, the users can just basically use Zapier and connect it to Zulip. Let me know if I have misunderstood anything. I might be wrong as never used our Zapier integration before but is there any specific reason why they can't just use our existing zapier integration? https://zapier.com/apps/zulip/integrations/notion Seems like it is possible. In fact I think you were suggesting the same thing @sbansal1999 Yeah exactly that's what I am suggesting. Users can simply use the Zapier Integration and get messages from events on Notion. At least in my opinion there would be no good reason to try and custom build one when the only way of sending a webhook from notion is through zapier, its easier and simpler to just link straight through zapier. Not sure if we support doing it, but maybe we could just create an integrations docs page for notion which explains they can use zapier so it would still show them we supported the app but that its through zapier. Not sure what you think @alya It indeed looks like Notion doesn't have a native API at all; we could consider writing a documentation page on how to setup Zapier with Zulip if that's not trivial; we have a couple other integration doc pages along those lines. I think we already have instructions on how to set up Zapier with Zulip [here](https://zulip.com/integrations/doc/zapier). Also, I think the information given there is pretty straightforward and easy to follow as well. Since Notion is a popular product, I think it's worth adding a dedicated documentation page, especially if there are any specific setup suggestions we can make for the Zapier integration. @sbansal1999 would you be up for taking a pass at that? You can use https://zulip.com/integrations/doc/asana as an example/starting point. I got your point; Notion is pretty popular so creating a dedicated documentation for it is surely worth it. I will work on creating the documentation for this and thanks for giving a heads-up on the example.
2023-05-02T17:59:23
zulip/zulip
25,583
zulip__zulip-25583
[ "25523" ]
90cc2716f0d422bfb8403490dcbebe82f3098642
diff --git a/zerver/actions/message_send.py b/zerver/actions/message_send.py --- a/zerver/actions/message_send.py +++ b/zerver/actions/message_send.py @@ -590,6 +590,7 @@ def create_user_messages( mentioned_user_ids: AbstractSet[int], mark_as_read_user_ids: Set[int], limit_unread_user_ids: Optional[Set[int]], + scheduled_message_to_self: bool, ) -> List[UserMessageLite]: # These properties on the Message are set via # render_markdown by code in the Markdown inline patterns @@ -626,7 +627,14 @@ def create_user_messages( for user_profile_id in um_eligible_user_ids: flags = base_flags if ( - (user_profile_id == sender_id and message.sent_by_human()) + ( + # Messages you sent from a non-API client are + # automatically marked as read for yourself; scheduled + # messages to yourself only are not. + user_profile_id == sender_id + and message.sent_by_human() + and not scheduled_message_to_self + ) or user_profile_id in mark_as_read_user_ids or (limit_unread_user_ids is not None and user_profile_id not in limit_unread_user_ids) ): @@ -705,7 +713,9 @@ def get_active_presence_idle_user_ids( def do_send_messages( send_message_requests_maybe_none: Sequence[Optional[SendMessageRequest]], + *, email_gateway: bool = False, + scheduled_message_to_self: bool = False, mark_as_read: Sequence[int] = [], ) -> List[int]: """See @@ -753,6 +763,7 @@ def do_send_messages( mentioned_user_ids=mentioned_user_ids, mark_as_read_user_ids=mark_as_read_user_ids, limit_unread_user_ids=send_request.limit_unread_user_ids, + scheduled_message_to_self=scheduled_message_to_self, ) for um in user_messages: diff --git a/zerver/actions/scheduled_messages.py b/zerver/actions/scheduled_messages.py --- a/zerver/actions/scheduled_messages.py +++ b/zerver/actions/scheduled_messages.py @@ -230,7 +230,10 @@ def send_scheduled_message(scheduled_message: ScheduledMessage) -> None: scheduled_message.realm, ) - message_id = do_send_messages([send_request])[0] + scheduled_message_to_self = scheduled_message.recipient == scheduled_message.sender.recipient + message_id = do_send_messages( + [send_request], scheduled_message_to_self=scheduled_message_to_self + )[0] scheduled_message.delivered_message_id = message_id scheduled_message.delivered = True scheduled_message.save(update_fields=["delivered", "delivered_message_id"])
diff --git a/zerver/tests/test_scheduled_messages.py b/zerver/tests/test_scheduled_messages.py --- a/zerver/tests/test_scheduled_messages.py +++ b/zerver/tests/test_scheduled_messages.py @@ -18,7 +18,7 @@ from zerver.lib.exceptions import JsonableError from zerver.lib.test_classes import ZulipTestCase from zerver.lib.timestamp import timestamp_to_datetime -from zerver.models import Attachment, Message, ScheduledMessage +from zerver.models import Attachment, Message, ScheduledMessage, UserMessage if TYPE_CHECKING: from django.test.client import _MonkeyPatchedWSGIResponse as TestHttpResponse @@ -152,6 +152,7 @@ def test_successful_deliver_private_scheduled_message(self) -> None: content = "Test message" scheduled_delivery_datetime = timezone_now() + datetime.timedelta(minutes=5) scheduled_delivery_timestamp = int(scheduled_delivery_datetime.timestamp()) + sender = self.example_user("hamlet") othello = self.example_user("othello") response = self.do_schedule_message( "direct", [othello.id], content + " 3", scheduled_delivery_timestamp @@ -189,6 +190,10 @@ def test_successful_deliver_private_scheduled_message(self) -> None: delivered_message.rendered_content, scheduled_message.rendered_content ) self.assertEqual(delivered_message.date_sent, more_than_scheduled_delivery_datetime) + sender_user_message = UserMessage.objects.get( + message_id=scheduled_message.delivered_message_id, user_profile_id=sender.id + ) + self.assertTrue(sender_user_message.flags.read) # Check error is sent if an edit happens after the scheduled # message is successfully sent. @@ -203,6 +208,56 @@ def test_successful_deliver_private_scheduled_message(self) -> None: ) self.assert_json_error(updated_response, "Scheduled message was already sent") + def test_successful_deliver_private_scheduled_message_to_self(self) -> None: + logger = mock.Mock() + # No scheduled message + self.assertFalse(try_deliver_one_scheduled_message(logger)) + + content = "Test message to self" + scheduled_delivery_datetime = timezone_now() + datetime.timedelta(minutes=5) + scheduled_delivery_timestamp = int(scheduled_delivery_datetime.timestamp()) + sender = self.example_user("hamlet") + response = self.do_schedule_message( + "direct", [sender.id], content, scheduled_delivery_timestamp + ) + self.assert_json_success(response) + scheduled_message = self.last_scheduled_message() + + # mock current time to be greater than the scheduled time. + more_than_scheduled_delivery_datetime = scheduled_delivery_datetime + datetime.timedelta( + minutes=1 + ) + with mock.patch( + "zerver.actions.scheduled_messages.timezone_now", + return_value=more_than_scheduled_delivery_datetime, + ): + with mock.patch( + "zerver.actions.message_send.timezone_now", + return_value=more_than_scheduled_delivery_datetime, + ): + result = try_deliver_one_scheduled_message(logger) + self.assertTrue(result) + logger.info.assert_called_once_with( + "Sending scheduled message %s with date %s (sender: %s)", + scheduled_message.id, + scheduled_message.scheduled_timestamp, + scheduled_message.sender_id, + ) + scheduled_message.refresh_from_db() + assert isinstance(scheduled_message.delivered_message_id, int) + self.assertEqual(scheduled_message.delivered, True) + self.assertEqual(scheduled_message.failed, False) + delivered_message = Message.objects.get(id=scheduled_message.delivered_message_id) + self.assertEqual(delivered_message.content, scheduled_message.content) + self.assertEqual( + delivered_message.rendered_content, scheduled_message.rendered_content + ) + self.assertEqual(delivered_message.date_sent, more_than_scheduled_delivery_datetime) + sender_user_message = UserMessage.objects.get( + message_id=scheduled_message.delivered_message_id, user_profile_id=sender.id + ) + self.assertFalse(sender_user_message.flags.read) + def verify_deliver_scheduled_message_failure( self, scheduled_message: ScheduledMessage, logger: mock.Mock, expected_failure_message: str ) -> None:
Scheduled messages to yourself should be marked as unread In general, when a user sends a message, that message is automatically marked as read for the sender. However, in the special case when a user **schedules** a DM to themselves (no other recipients), the message should be marked as unread when it's received. This serves a common use case for scheduling such a message, which is setting yourself a reminder. [CZO discussion](https://chat.zulip.org/#narrow/stream/101-design/topic/scheduled.20messages.20to.20yourself/near/1566119)
2023-05-12T23:20:47
zulip/zulip
25,586
zulip__zulip-25586
[ "24969" ]
546ecc38d61e3090bec1dea47c9f1a619ec95557
diff --git a/zerver/lib/push_notifications.py b/zerver/lib/push_notifications.py --- a/zerver/lib/push_notifications.py +++ b/zerver/lib/push_notifications.py @@ -547,6 +547,9 @@ def add_push_device_token( post_data = { "server_uuid": settings.ZULIP_ORG_ID, "user_uuid": str(user_profile.uuid), + # user_id is sent so that the bouncer can delete any pre-existing registrations + # for this user+device to avoid duplication upon adding the uuid registration. + "user_id": str(user_profile.id), "token": token_str, "token_kind": kind, } diff --git a/zilencer/views.py b/zilencer/views.py --- a/zilencer/views.py +++ b/zilencer/views.py @@ -1,5 +1,6 @@ import datetime import logging +from collections import Counter from typing import Any, Dict, List, Optional, Type, TypeVar from uuid import UUID @@ -157,23 +158,26 @@ def register_remote_push_device( if user_id is None and user_uuid is None: raise JsonableError(_("Missing user_id or user_uuid")) if user_id is not None and user_uuid is not None: - # We don't want "hybrid" registrations with both. - # Our RemotePushDeviceToken should be either in the new uuid format - # or the legacy id one. - raise JsonableError(_("Specify only one of user_id or user_uuid")) - + kwargs: Dict[str, object] = {"user_uuid": user_uuid, "user_id": None} + # Delete pre-existing user_id registration for this user+device to avoid + # duplication. Further down, uuid registration will be created. + RemotePushDeviceToken.objects.filter( + server=server, token=token, kind=token_kind, user_id=user_id + ).delete() + else: + # One of these is None, so these kwargs will lead to a proper registration + # of either user_id or user_uuid type + kwargs = {"user_id": user_id, "user_uuid": user_uuid} try: with transaction.atomic(): RemotePushDeviceToken.objects.create( - # Exactly one of these two user identity fields will be None. - user_id=user_id, - user_uuid=user_uuid, server=server, kind=token_kind, token=token, ios_app_id=ios_app_id, # last_updated is to be renamed to date_created. last_updated=timezone.now(), + **kwargs, ) except IntegrityError: pass @@ -216,13 +220,73 @@ def unregister_all_remote_push_devices( return json_success(request) +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 - 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 push notification request + to us, it sends both user_id and user_uuid of the user. + See https://github.com/zulip/zulip/issues/24969 for reference. + + This function, knowing the user_id and user_uuid of the user, can detect duplicates + and delete the legacy user_id registration if appropriate. + + Return the list of registrations with the user_id-based duplicates removed. + """ + + # All registrations passed here should be of the same kind (apple vs android). + assert len({registration.kind for registration in registrations}) == 1 + kind = registrations[0].kind + + tokens_counter = Counter(device.token for device in registrations) + + tokens_to_deduplicate = [] + for key in tokens_counter: + if tokens_counter[key] <= 1: + continue + if tokens_counter[key] > 2: + raise AssertionError( + f"More than two registrations for token {key} for user id:{user_id} uuid:{user_uuid}, shouldn't be possible" + ) + assert tokens_counter[key] == 2 + tokens_to_deduplicate.append(key) + + if not tokens_to_deduplicate: + return registrations + + logger.info( + "Deduplicating push registrations for server id:%s user id:%s uuid:%s and tokens:%s", + server_id, + user_id, + user_uuid, + sorted(tokens_to_deduplicate), + ) + RemotePushDeviceToken.objects.filter( + token__in=tokens_to_deduplicate, kind=kind, server_id=server_id, user_id=user_id + ).delete() + + deduplicated_registrations_to_return = [] + for registration in registrations: + if registration.token in tokens_to_deduplicate and registration.user_id is not None: + # user_id registrations are the ones we deleted + continue + deduplicated_registrations_to_return.append(registration) + + return deduplicated_registrations_to_return + + @has_request_variables def remote_server_notify_push( request: HttpRequest, server: RemoteZulipServer, payload: Dict[str, Any] = REQ(argument_type="body"), ) -> HttpResponse: - user_identity = UserPushIdentityCompat(payload.get("user_id"), payload.get("user_uuid")) + user_id = payload.get("user_id") + user_uuid = payload.get("user_uuid") + user_identity = UserPushIdentityCompat(user_id, user_uuid) gcm_payload = payload["gcm_payload"] apns_payload = payload["apns_payload"] @@ -235,6 +299,10 @@ def remote_server_notify_push( server=server, ) ) + if android_devices and user_id is not None and user_uuid is not None: + android_devices = delete_duplicate_registrations( + android_devices, server.id, user_id, user_uuid + ) apple_devices = list( RemotePushDeviceToken.objects.filter( @@ -243,6 +311,8 @@ def remote_server_notify_push( server=server, ) ) + if apple_devices and user_id is not None and user_uuid is not None: + apple_devices = delete_duplicate_registrations(apple_devices, server.id, user_id, user_uuid) logger.info( "Sending mobile push notifications for remote user %s:%s: %s via FCM devices, %s via APNs devices",
diff --git a/zerver/tests/test_push_notifications.py b/zerver/tests/test_push_notifications.py --- a/zerver/tests/test_push_notifications.py +++ b/zerver/tests/test_push_notifications.py @@ -192,12 +192,6 @@ def test_register_remote_push_user_params(self) -> None: self.server_uuid, endpoint, {"token": token, "token_kind": token_kind} ) self.assert_json_error(result, "Missing user_id or user_uuid") - result = self.uuid_post( - self.server_uuid, - endpoint, - {"user_id": user_id, "user_uuid": "xxx", "token": token, "token_kind": token_kind}, - ) - self.assert_json_error(result, "Specify only one of user_id or user_uuid") result = self.uuid_post( self.server_uuid, endpoint, {"user_id": user_id, "token": token, "token_kind": 17} ) @@ -280,6 +274,40 @@ def test_register_remote_push_user_params(self) -> None: 401, ) + def test_register_device_deduplication(self) -> None: + hamlet = self.example_user("hamlet") + token = "111222" + user_id = hamlet.id + user_uuid = str(hamlet.uuid) + token_kind = PushDeviceToken.GCM + + endpoint = "/api/v1/remotes/push/register" + + # First we create a legacy user_id registration. + result = self.uuid_post( + self.server_uuid, + endpoint, + {"user_id": user_id, "token_kind": token_kind, "token": token}, + ) + self.assert_json_success(result) + + registrations = list(RemotePushDeviceToken.objects.filter(token=token)) + self.assert_length(registrations, 1) + self.assertEqual(registrations[0].user_id, user_id) + self.assertEqual(registrations[0].user_uuid, None) + + # Register same user+device with uuid now. The old registration should be deleted + # to avoid duplication. + result = self.uuid_post( + self.server_uuid, + endpoint, + {"user_id": user_id, "user_uuid": user_uuid, "token_kind": token_kind, "token": token}, + ) + registrations = list(RemotePushDeviceToken.objects.filter(token=token)) + self.assert_length(registrations, 1) + self.assertEqual(registrations[0].user_id, None) + self.assertEqual(str(registrations[0].user_uuid), user_uuid) + def test_remote_push_user_endpoints(self) -> None: endpoints = [ ("/api/v1/remotes/push/register", "register"), @@ -308,6 +336,7 @@ def test_send_notification_endpoint(self) -> None: server = RemoteZulipServer.objects.get(uuid=self.server_uuid) token = "aaaa" android_tokens = [] + uuid_android_tokens = [] for i in ["aa", "bb"]: android_tokens.append( RemotePushDeviceToken.objects.create( @@ -317,6 +346,19 @@ def test_send_notification_endpoint(self) -> None: server=server, ) ) + + # Create a duplicate, newer uuid-based registration for the same user to verify + # the bouncer will handle that correctly, without triggering a duplicate notification, + # and will delete the old, legacy registration. + uuid_android_tokens.append( + RemotePushDeviceToken.objects.create( + kind=RemotePushDeviceToken.GCM, + token=hex_to_b64(token + i), + user_uuid=str(hamlet.uuid), + server=server, + ) + ) + apple_token = RemotePushDeviceToken.objects.create( kind=RemotePushDeviceToken.APNS, token=hex_to_b64(token), @@ -326,6 +368,7 @@ def test_send_notification_endpoint(self) -> None: many_ids = ",".join(str(i) for i in range(1, 250)) payload = { "user_id": hamlet.id, + "user_uuid": str(hamlet.uuid), "gcm_payload": {"event": "remove", "zulip_message_ids": many_ids}, "apns_payload": { "badge": 0, @@ -355,12 +398,14 @@ def test_send_notification_endpoint(self) -> None: logger.output, [ "INFO:zilencer.views:" - f"Sending mobile push notifications for remote user 6cde5f7a-1f7e-4978-9716-49f69ebfc9fe:<id:{hamlet.id}>: " - "2 via FCM devices, 1 via APNs devices" + f"Deduplicating push registrations for server id:{server.id} user id:{hamlet.id} uuid:{str(hamlet.uuid)} and tokens:{sorted([t.token for t in android_tokens[:]])}", + "INFO:zilencer.views:" + f"Sending mobile push notifications for remote user 6cde5f7a-1f7e-4978-9716-49f69ebfc9fe:<id:{hamlet.id}><uuid:{str(hamlet.uuid)}>: " + "2 via FCM devices, 1 via APNs devices", ], ) - user_identity = UserPushIdentityCompat(user_id=hamlet.id) + user_identity = UserPushIdentityCompat(user_id=hamlet.id, user_uuid=str(hamlet.uuid)) apple_push.assert_called_once_with( user_identity, [apple_token], @@ -377,7 +422,7 @@ def test_send_notification_endpoint(self) -> None: ) android_push.assert_called_once_with( user_identity, - list(reversed(android_tokens)), + list(reversed(uuid_android_tokens)), {"event": "remove", "zulip_message_ids": ",".join(str(i) for i in range(50, 250))}, {}, remote=server,
Push bouncer: Deduplicate device registrations In the migration to using uuid instead of simple id as the user identifier in the push bouncer (d800ac33a0322b0d3ef327bcebf318a27448bbee) we preserved legacy `id`-based registrations to avoid breaking notifications for all the devices already registered. However this means the possibility of duplicate registrations for one device - if a device was registered with `id` originally and then re-registered at some point after this migration, creating a new, `uuid`-based registration. The bouncer will send duplicate notifications to such a device. The `RemotePushDeviceToken` data model doesn't have a way of linking `id`s to `uuid`s of a user, so we can't just write a database migration to detect and delete duplicates. The proposed solution is the following: 1. Currently, when a Zulip server sends a notification to the bouncer (https://github.com/zulip/zulip/blob/3f199d570d5b238e28ee6b0e7c7a0ca72156a790/zerver/lib/push_notifications.py#L487) it sends both the `user_id` and `user_uuid` to the bouncer. Thus we can tweak the bouncer to detect in that moment if both registrations exist for the same `token` - and if so, delete the old `user_id` registration. This will over time clean up existing duplicates. 2. When the bouncer receives a new `uuid` registration request to `remotes/push/register` it should check if there isn't already an existing `id` registration for the `token` and if there is, delete it. This will prevent future duplications. https://chat.zulip.org/#narrow/stream/48-mobile/topic/iOS.20duplicate.20notifications for more background
Hello @zulip/server-production members, this issue was labeled with the "area: production" label, so you may want to check it out! <!-- areaLabelAddition -->
2023-05-13T01:13:41
zulip/zulip
25,587
zulip__zulip-25587
[ "25501" ]
16aa7c09238c893c5485eae33eb2133267a6a0ad
diff --git a/zerver/actions/scheduled_messages.py b/zerver/actions/scheduled_messages.py --- a/zerver/actions/scheduled_messages.py +++ b/zerver/actions/scheduled_messages.py @@ -133,6 +133,17 @@ def do_schedule_messages( return [scheduled_message.id for scheduled_message, ignored in scheduled_messages] +def notify_update_scheduled_message( + user_profile: UserProfile, scheduled_message: ScheduledMessage +) -> None: + event = { + "type": "scheduled_messages", + "op": "update", + "scheduled_message": scheduled_message.to_dict(), + } + send_event(user_profile.realm, event, [user_profile.id]) + + def edit_scheduled_message( scheduled_message_id: int, send_request: SendMessageRequest, sender: UserProfile ) -> int: @@ -170,12 +181,7 @@ def edit_scheduled_message( scheduled_message_object.save() - event = { - "type": "scheduled_messages", - "op": "update", - "scheduled_message": scheduled_message_object.to_dict(), - } - send_event(sender.realm, event, [sender.id]) + notify_update_scheduled_message(sender, scheduled_message_object) return scheduled_message_id @@ -344,6 +350,7 @@ def try_deliver_one_scheduled_message(logger: logging.Logger) -> bool: and not isinstance(e, RealmDeactivatedError) and not isinstance(e, UserDeactivatedError) ): + notify_update_scheduled_message(scheduled_message.sender, scheduled_message) send_failed_scheduled_message_notification( scheduled_message.sender, scheduled_message.id )
Inform user when scheduled message fails to send In some cases, a scheduled message cannot be sent at the scheduled time. For example, this can happen if organization permissions have changed, and the user no longer has permissions to send the message. In this situation, we should inform the user about what happened. Specifically, the user should receive the following message from Notification Bot: --- The message you scheduled for [time] was not sent because of the following error: > [error message] [View scheduled messages](/#scheduled) --- We also need to communicate the error in the Scheduled messages UI. We can try putting a red error icon (perhaps https://fonts.google.com/icons?selected=Material%20Symbols%20Outlined%3Aerror%3AFILL%400%3Bwght%40400%3BGRAD%400%3Bopsz%4048) to the left of the scheduled time, with a tooltip that says: > "Error: Your message was not sent." [CZO discussion](https://chat.zulip.org/#narrow/stream/101-design/topic/scheduled.20message.20error.20handling/near/1565151)
As noted in https://github.com/zulip/zulip/pull/25440#discussion_r1189046564, we'll want to make sure we use the recipient user's language for the notification. With #25553 now merged, what remains is just the part to display it in the #scheduled UI.
2023-05-13T08:54:14
zulip/zulip
25,590
zulip__zulip-25590
[ "25506" ]
16aa7c09238c893c5485eae33eb2133267a6a0ad
diff --git a/zerver/lib/url_redirects.py b/zerver/lib/url_redirects.py --- a/zerver/lib/url_redirects.py +++ b/zerver/lib/url_redirects.py @@ -74,6 +74,7 @@ class URLRedirect: URLRedirect("/help/night-mode", "/help/dark-theme"), URLRedirect("/help/enable-emoticon-translations", "/help/configure-emoticon-translations"), URLRedirect("/help/web-public-streams", "/help/public-access-option"), + URLRedirect("/help/starting-a-new-private-thread", "/help/starting-a-new-direct-message"), ] LANDING_PAGE_REDIRECTS = [
Rename "Starting a new private thread" to "Starting a new direct message" With the private messages -> direct messages migration, we should rename the "Starting a new private thread" help center article to "Starting a new direct message". The URL should be changed to /help/starting-a-new-direct-message. We also need to update /help/getting-started-with-zulip#starting-a-new-private-thread, and any links to this article or section.
@drrosa would be great if you could take care of this one this week.
2023-05-14T01:44:36
zulip/zulip
25,746
zulip__zulip-25746
[ "25629" ]
3e2d5b3c8698a731adf892dfd7cd40c956d9ab5f
diff --git a/zerver/webhooks/github/view.py b/zerver/webhooks/github/view.py --- a/zerver/webhooks/github/view.py +++ b/zerver/webhooks/github/view.py @@ -639,6 +639,10 @@ def is_commit_push_event(payload: WildValue) -> bool: return bool(re.match(r"^refs/heads/", payload["ref"].tame(check_string))) +def is_merge_queue_push_event(payload: WildValue) -> bool: + return bool(re.match(r"^refs/heads/gh-readonly-queue/", payload["ref"].tame(check_string))) + + def get_subject_based_on_type(payload: WildValue, event: str) -> str: if "pull_request" in event: return TOPIC_WITH_PR_OR_ISSUE_INFO_TEMPLATE.format( @@ -733,6 +737,7 @@ def get_subject_based_on_type(payload: WildValue, event: str) -> str: "milestone", "organization", "project_card", + "push__merge_queue", "repository_vulnerability_alert", ] @@ -827,6 +832,8 @@ def get_zulip_event_name( if action in IGNORED_PULL_REQUEST_ACTIONS: return None elif header_event == "push": + if is_merge_queue_push_event(payload): + return None if is_commit_push_event(payload): if branches is not None: branch = get_branch_name_from_ref(payload["ref"].tame(check_string))
diff --git a/zerver/webhooks/github/tests.py b/zerver/webhooks/github/tests.py --- a/zerver/webhooks/github/tests.py +++ b/zerver/webhooks/github/tests.py @@ -51,6 +51,11 @@ def test_push_local_branch_without_commits(self) -> None: "push__local_branch_without_commits", "public-repo / feature", expected_message ) + def test_push_merege_queue_ignore(self) -> None: + self.url = self.build_webhook_url() + payload = self.get_body("push__merge_queue") + self.verify_post_is_ignored(payload, "push") + def test_push_1_commit(self) -> None: expected_message = "baxterthehacker [pushed](https://github.com/baxterthehacker/public-repo/compare/9049f1265b7d...0d1a26e67d8f) 1 commit to branch changes.\n\n* Update README.md ([0d1a26e67d8](https://github.com/baxterthehacker/public-repo/commit/0d1a26e67d8f5eaf1f6ba5c57fc3c7d91ac0fd1c))" self.check_webhook("push__1_commit", TOPIC_BRANCH, expected_message)
GitHub integration can send ref deletion events with no `sender.login` We assume there's a `sender` key with a `login`, in that some authenticated user was responsible for the ref deletion: https://github.com/zulip/zulip/blob/e0cb3c6908c33957b8f42a5313b801419b016446/zerver/webhooks/github/view.py#L626-L627 But some events -- possibly only those from [Merge Queues](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/configuring-pull-request-merges/managing-a-merge-queue) -- don't have such a key: ```json { "after": "0000000000000000000000000000000000000000", "base_ref": null, "before": "3a9808b22742d5bd906ef5d1a562f2f1ae57406d", "created": false, "deleted": true, "forced": false, "organization": { "events_url": "https://api.github.com/orgs/nvim-treesitter/events", "hooks_url": "https://api.github.com/orgs/nvim-treesitter/hooks", "id": 63916357, "issues_url": "https://api.github.com/orgs/nvim-treesitter/issues", "login": "nvim-treesitter", "members_url": "https://api.github.com/orgs/nvim-treesitter/members{/member}", "node_id": "MDEyOk9yZ2FuaXphdGlvbjYzOTE2MzU3", "public_members_url": "https://api.github.com/orgs/nvim-treesitter/public_members{/member}", "repos_url": "https://api.github.com/orgs/nvim-treesitter/repos", "url": "https://api.github.com/orgs/nvim-treesitter" }, "pusher": { "name": "none" }, "ref": "refs/heads/gh-readonly-queue/master/pr-24-e97504446f14f529d5a8e649667d3d60391e4dfd", "repository": { "description": "A Tree-sitter parser for tree-sitter queries.", "fork": false, "full_name": "nvim-treesitter/tree-sitter-query", "html_url": "https://github.com/nvim-treesitter/tree-sitter-query", "id": 283011708, "name": "tree-sitter-query", "node_id": "MDEwOlJlcG9zaXRvcnkyODMwMTE3MDg=", "owner": {}, "private": false, "url": "https://github.com/nvim-treesitter/tree-sitter-query" } } ``` [Stack trace here](https://zulip.sentry.io/share/issue/9c1cd1aac5924010ba13bcc1480d6daf/). We should adjust the integration to ignore these instead of 500'ing, or output something more specific to merge queues.
Hello @zulip/server-integrations members, this issue was labeled with the "area: integrations" label, so you may want to check it out! <!-- areaLabelAddition --> Thanks for assigning the issue to me. Giving this a first look makes me feel that we can for sure send a specific message for the case when the sender's info is not present in the webhook. I am not sure if ignoring the event would be a good idea. Also, will need to verify if this is only happening for Merge Queues or if are there any other event types that can have such kind of behavior.
2023-05-24T20:39:52
zulip/zulip
25,801
zulip__zulip-25801
[ "25643" ]
7e811ea1bd5f1ab7dcbdd7533f643155ee1fc30a
diff --git a/zerver/webhooks/gitlab/view.py b/zerver/webhooks/gitlab/view.py --- a/zerver/webhooks/gitlab/view.py +++ b/zerver/webhooks/gitlab/view.py @@ -45,7 +45,7 @@ def get_push_event_body(payload: WildValue, include_title: bool) -> str: def get_normal_push_event_body(payload: WildValue) -> str: - compare_url = "{}/compare/{}...{}".format( + compare_url = "{}/-/compare/{}...{}".format( get_project_homepage(payload), payload["before"].tame(check_string), payload["after"].tame(check_string), @@ -216,10 +216,7 @@ def get_commented_commit_event_body(payload: WildValue, include_title: bool) -> def get_commented_merge_request_event_body(payload: WildValue, include_title: bool) -> str: comment = payload["object_attributes"] action = "[commented]({}) on".format(comment["url"].tame(check_string)) - url = "{}/merge_requests/{}".format( - payload["project"]["web_url"].tame(check_string), - payload["merge_request"]["iid"].tame(check_int), - ) + url = payload["merge_request"]["url"].tame(check_string) return get_pull_request_event_message( user_name=get_issue_user_name(payload), @@ -235,10 +232,7 @@ def get_commented_merge_request_event_body(payload: WildValue, include_title: bo def get_commented_issue_event_body(payload: WildValue, include_title: bool) -> str: comment = payload["object_attributes"] action = "[commented]({}) on".format(comment["url"].tame(check_string)) - url = "{}/issues/{}".format( - payload["project"]["web_url"].tame(check_string), - payload["issue"]["iid"].tame(check_int), - ) + url = payload["issue"]["url"].tame(check_string) return get_pull_request_event_message( user_name=get_issue_user_name(payload), @@ -254,10 +248,14 @@ def get_commented_issue_event_body(payload: WildValue, include_title: bool) -> s def get_commented_snippet_event_body(payload: WildValue, include_title: bool) -> str: comment = payload["object_attributes"] action = "[commented]({}) on".format(comment["url"].tame(check_string)) - url = "{}/snippets/{}".format( - payload["project"]["web_url"].tame(check_string), - payload["snippet"]["id"].tame(check_int), - ) + # Snippet URL is only available in GitLab 16.1+ + if "url" in payload["snippet"]: + url = payload["snippet"]["url"].tame(check_string) + else: + url = "{}/-/snippets/{}".format( + payload["project"]["web_url"].tame(check_string), + payload["snippet"]["id"].tame(check_int), + ) return get_pull_request_event_message( user_name=get_issue_user_name(payload), @@ -308,7 +306,7 @@ def get_pipeline_event_body(payload: WildValue, include_title: bool) -> str: action = f"changed status to {pipeline_status}" project_homepage = get_project_homepage(payload) - pipeline_url = "{}/pipelines/{}".format( + pipeline_url = "{}/-/pipelines/{}".format( project_homepage, payload["object_attributes"]["id"].tame(check_int), )
diff --git a/zerver/webhooks/gitlab/tests.py b/zerver/webhooks/gitlab/tests.py --- a/zerver/webhooks/gitlab/tests.py +++ b/zerver/webhooks/gitlab/tests.py @@ -12,17 +12,17 @@ class GitlabHookTests(WebhookTestCase): def test_push_event_specified_topic(self) -> None: self.url = self.build_webhook_url("topic=Specific%20topic") expected_topic = "Specific topic" - expected_message = "[[my-awesome-project](https://gitlab.com/tomaszkolek0/my-awesome-project)] Tomasz Kolek [pushed](https://gitlab.com/tomaszkolek0/my-awesome-project/compare/5fcdd5551fc3085df79bece2c32b1400802ac407...eb6ae1e591e0819dc5bf187c6bfe18ec065a80e9) 2 commits to branch tomek.\n\n* b ([66abd2da288](https://gitlab.com/tomaszkolek0/my-awesome-project/commit/66abd2da28809ffa128ed0447965cf11d7f863a7))\n* c ([eb6ae1e591e](https://gitlab.com/tomaszkolek0/my-awesome-project/commit/eb6ae1e591e0819dc5bf187c6bfe18ec065a80e9))" + expected_message = "[[my-awesome-project](https://gitlab.com/tomaszkolek0/my-awesome-project)] Tomasz Kolek [pushed](https://gitlab.com/tomaszkolek0/my-awesome-project/-/compare/5fcdd5551fc3085df79bece2c32b1400802ac407...eb6ae1e591e0819dc5bf187c6bfe18ec065a80e9) 2 commits to branch tomek.\n\n* b ([66abd2da288](https://gitlab.com/tomaszkolek0/my-awesome-project/commit/66abd2da28809ffa128ed0447965cf11d7f863a7))\n* c ([eb6ae1e591e](https://gitlab.com/tomaszkolek0/my-awesome-project/commit/eb6ae1e591e0819dc5bf187c6bfe18ec065a80e9))" self.check_webhook("push_hook", expected_topic, expected_message) def test_push_event_message(self) -> None: expected_topic = "my-awesome-project / tomek" - expected_message = "Tomasz Kolek [pushed](https://gitlab.com/tomaszkolek0/my-awesome-project/compare/5fcdd5551fc3085df79bece2c32b1400802ac407...eb6ae1e591e0819dc5bf187c6bfe18ec065a80e9) 2 commits to branch tomek.\n\n* b ([66abd2da288](https://gitlab.com/tomaszkolek0/my-awesome-project/commit/66abd2da28809ffa128ed0447965cf11d7f863a7))\n* c ([eb6ae1e591e](https://gitlab.com/tomaszkolek0/my-awesome-project/commit/eb6ae1e591e0819dc5bf187c6bfe18ec065a80e9))" + expected_message = "Tomasz Kolek [pushed](https://gitlab.com/tomaszkolek0/my-awesome-project/-/compare/5fcdd5551fc3085df79bece2c32b1400802ac407...eb6ae1e591e0819dc5bf187c6bfe18ec065a80e9) 2 commits to branch tomek.\n\n* b ([66abd2da288](https://gitlab.com/tomaszkolek0/my-awesome-project/commit/66abd2da28809ffa128ed0447965cf11d7f863a7))\n* c ([eb6ae1e591e](https://gitlab.com/tomaszkolek0/my-awesome-project/commit/eb6ae1e591e0819dc5bf187c6bfe18ec065a80e9))" self.check_webhook("push_hook", expected_topic, expected_message) def test_push_local_branch_without_commits(self) -> None: expected_topic = "my-awesome-project / changes" - expected_message = "Eeshan Garg [pushed](https://gitlab.com/eeshangarg/my-awesome-project/compare/0000000000000000000000000000000000000000...68d7a5528cf423dfaac37dd62a56ac9cc8a884e3) the branch changes." + expected_message = "Eeshan Garg [pushed](https://gitlab.com/eeshangarg/my-awesome-project/-/compare/0000000000000000000000000000000000000000...68d7a5528cf423dfaac37dd62a56ac9cc8a884e3) the branch changes." self.check_webhook( "push_hook__push_local_branch_without_commits", expected_topic, expected_message ) @@ -30,18 +30,18 @@ def test_push_local_branch_without_commits(self) -> None: def test_push_event_message_filtered_by_branches(self) -> None: self.url = self.build_webhook_url(branches="master,tomek") expected_topic = "my-awesome-project / tomek" - expected_message = "Tomasz Kolek [pushed](https://gitlab.com/tomaszkolek0/my-awesome-project/compare/5fcdd5551fc3085df79bece2c32b1400802ac407...eb6ae1e591e0819dc5bf187c6bfe18ec065a80e9) 2 commits to branch tomek.\n\n* b ([66abd2da288](https://gitlab.com/tomaszkolek0/my-awesome-project/commit/66abd2da28809ffa128ed0447965cf11d7f863a7))\n* c ([eb6ae1e591e](https://gitlab.com/tomaszkolek0/my-awesome-project/commit/eb6ae1e591e0819dc5bf187c6bfe18ec065a80e9))" + expected_message = "Tomasz Kolek [pushed](https://gitlab.com/tomaszkolek0/my-awesome-project/-/compare/5fcdd5551fc3085df79bece2c32b1400802ac407...eb6ae1e591e0819dc5bf187c6bfe18ec065a80e9) 2 commits to branch tomek.\n\n* b ([66abd2da288](https://gitlab.com/tomaszkolek0/my-awesome-project/commit/66abd2da28809ffa128ed0447965cf11d7f863a7))\n* c ([eb6ae1e591e](https://gitlab.com/tomaszkolek0/my-awesome-project/commit/eb6ae1e591e0819dc5bf187c6bfe18ec065a80e9))" self.check_webhook("push_hook", expected_topic, expected_message) def test_push_multiple_committers(self) -> None: expected_topic = "my-awesome-project / tomek" - expected_message = "Tomasz Kolek [pushed](https://gitlab.com/tomaszkolek0/my-awesome-project/compare/5fcdd5551fc3085df79bece2c32b1400802ac407...eb6ae1e591e0819dc5bf187c6bfe18ec065a80e9) 2 commits to branch tomek. Commits by Ben (1) and Tomasz Kolek (1).\n\n* b ([66abd2da288](https://gitlab.com/tomaszkolek0/my-awesome-project/commit/66abd2da28809ffa128ed0447965cf11d7f863a7))\n* c ([eb6ae1e591e](https://gitlab.com/tomaszkolek0/my-awesome-project/commit/eb6ae1e591e0819dc5bf187c6bfe18ec065a80e9))" + expected_message = "Tomasz Kolek [pushed](https://gitlab.com/tomaszkolek0/my-awesome-project/-/compare/5fcdd5551fc3085df79bece2c32b1400802ac407...eb6ae1e591e0819dc5bf187c6bfe18ec065a80e9) 2 commits to branch tomek. Commits by Ben (1) and Tomasz Kolek (1).\n\n* b ([66abd2da288](https://gitlab.com/tomaszkolek0/my-awesome-project/commit/66abd2da28809ffa128ed0447965cf11d7f863a7))\n* c ([eb6ae1e591e](https://gitlab.com/tomaszkolek0/my-awesome-project/commit/eb6ae1e591e0819dc5bf187c6bfe18ec065a80e9))" self.check_webhook("push_hook__push_multiple_committers", expected_topic, expected_message) def test_push_multiple_committers_with_others(self) -> None: expected_topic = "my-awesome-project / tomek" commit_info = "* b ([eb6ae1e591e](https://gitlab.com/tomaszkolek0/my-awesome-project/commit/eb6ae1e591e0819dc5bf187c6bfe18ec065a80e9))\n" - expected_message = f"Tomasz Kolek [pushed](https://gitlab.com/tomaszkolek0/my-awesome-project/compare/5fcdd5551fc3085df79bece2c32b1400802ac407...eb6ae1e591e0819dc5bf187c6bfe18ec065a80e9) 7 commits to branch tomek. Commits by Ben (3), baxterthehacker (2), James (1) and others (1).\n\n{commit_info * 6}* b ([eb6ae1e591e](https://gitlab.com/tomaszkolek0/my-awesome-project/commit/eb6ae1e591e0819dc5bf187c6bfe18ec065a80e9))" + expected_message = f"Tomasz Kolek [pushed](https://gitlab.com/tomaszkolek0/my-awesome-project/-/compare/5fcdd5551fc3085df79bece2c32b1400802ac407...eb6ae1e591e0819dc5bf187c6bfe18ec065a80e9) 7 commits to branch tomek. Commits by Ben (3), baxterthehacker (2), James (1) and others (1).\n\n{commit_info * 6}* b ([eb6ae1e591e](https://gitlab.com/tomaszkolek0/my-awesome-project/commit/eb6ae1e591e0819dc5bf187c6bfe18ec065a80e9))" self.check_webhook( "push_hook__push_multiple_committers_with_others", expected_topic, expected_message ) @@ -49,7 +49,7 @@ def test_push_multiple_committers_with_others(self) -> None: def test_push_commits_more_than_limit_event_message(self) -> None: expected_topic = "my-awesome-project / tomek" commits_info = "* b ([66abd2da288](https://gitlab.com/tomaszkolek0/my-awesome-project/commit/66abd2da28809ffa128ed0447965cf11d7f863a7))\n" - expected_message = f"Tomasz Kolek [pushed](https://gitlab.com/tomaszkolek0/my-awesome-project/compare/5fcdd5551fc3085df79bece2c32b1400802ac407...eb6ae1e591e0819dc5bf187c6bfe18ec065a80e9) 50 commits to branch tomek.\n\n{commits_info * COMMITS_LIMIT}[and {50 - COMMITS_LIMIT} more commit(s)]" + expected_message = f"Tomasz Kolek [pushed](https://gitlab.com/tomaszkolek0/my-awesome-project/-/compare/5fcdd5551fc3085df79bece2c32b1400802ac407...eb6ae1e591e0819dc5bf187c6bfe18ec065a80e9) 50 commits to branch tomek.\n\n{commits_info * COMMITS_LIMIT}[and {50 - COMMITS_LIMIT} more commit(s)]" self.check_webhook( "push_hook__push_commits_more_than_limit", expected_topic, expected_message ) @@ -58,7 +58,7 @@ def test_push_commits_more_than_limit_message_filtered_by_branches(self) -> None self.url = self.build_webhook_url(branches="master,tomek") expected_topic = "my-awesome-project / tomek" commits_info = "* b ([66abd2da288](https://gitlab.com/tomaszkolek0/my-awesome-project/commit/66abd2da28809ffa128ed0447965cf11d7f863a7))\n" - expected_message = f"Tomasz Kolek [pushed](https://gitlab.com/tomaszkolek0/my-awesome-project/compare/5fcdd5551fc3085df79bece2c32b1400802ac407...eb6ae1e591e0819dc5bf187c6bfe18ec065a80e9) 50 commits to branch tomek.\n\n{commits_info * COMMITS_LIMIT}[and {50 - COMMITS_LIMIT} more commit(s)]" + expected_message = f"Tomasz Kolek [pushed](https://gitlab.com/tomaszkolek0/my-awesome-project/-/compare/5fcdd5551fc3085df79bece2c32b1400802ac407...eb6ae1e591e0819dc5bf187c6bfe18ec065a80e9) 50 commits to branch tomek.\n\n{commits_info * COMMITS_LIMIT}[and {50 - COMMITS_LIMIT} more commit(s)]" self.check_webhook( "push_hook__push_commits_more_than_limit", expected_topic, expected_message ) @@ -224,20 +224,20 @@ def test_reopen_confidential_issue_event_message(self) -> None: ) def test_note_commit_event_message(self) -> None: - expected_topic = "my-awesome-project" - expected_message = "Tomasz Kolek [commented](https://gitlab.com/tomaszkolek0/my-awesome-project/commit/66abd2da28809ffa128ed0447965cf11d7f863a7#note_14169211) on [66abd2da288](https://gitlab.com/tomaszkolek0/my-awesome-project/commit/66abd2da28809ffa128ed0447965cf11d7f863a7):\n~~~ quote\nnice commit\n~~~" + expected_topic = "testing-zulip-gitlab-integration" + expected_message = "Satyam Bansal [commented](https://gitlab.com/sbansal1999/testing-zulip-gitlab-integration/-/commit/82689ddf00fd7bdadb5c2afb3b94bd555edc9d01#note_1406241063) on [82689ddf00f](https://gitlab.com/sbansal1999/testing-zulip-gitlab-integration/-/commit/82689ddf00fd7bdadb5c2afb3b94bd555edc9d01):\n~~~ quote\nWow what a beautiful commit.\n~~~" self.check_webhook("note_hook__commit_note", expected_topic, expected_message) def test_note_merge_request_event_message(self) -> None: - expected_topic = "my-awesome-project / MR #1 Tomek" - expected_message = "Tomasz Kolek [commented](https://gitlab.com/tomaszkolek0/my-awesome-project/merge_requests/1#note_14171860) on [MR #1](https://gitlab.com/tomaszkolek0/my-awesome-project/merge_requests/1):\n\n~~~ quote\nNice merge request!\n~~~" + expected_topic = "testing-zulip-gitlab-integration / MR #1 add new-feature" + expected_message = "Satyam Bansal [commented](https://gitlab.com/sbansal1999/testing-zulip-gitlab-integration/-/merge_requests/1#note_1406328457) on [MR #1](https://gitlab.com/sbansal1999/testing-zulip-gitlab-integration/-/merge_requests/1):\n\n~~~ quote\nI am not sure if this new feature is even required or not.\n~~~" self.check_webhook("note_hook__merge_request_note", expected_topic, expected_message) def test_note_merge_request_event_message_without_merge_request_title(self) -> None: - expected_topic = "my-awesome-project / MR #1" - expected_message = "Tomasz Kolek [commented](https://gitlab.com/tomaszkolek0/my-awesome-project/merge_requests/1#note_14171860) on [MR #1](https://gitlab.com/tomaszkolek0/my-awesome-project/merge_requests/1):\n\n~~~ quote\nNice merge request!\n~~~" + expected_topic = "testing-zulip-gitlab-integration / MR #1" + expected_message = "Satyam Bansal [commented](https://gitlab.com/sbansal1999/testing-zulip-gitlab-integration/-/merge_requests/1#note_1406328457) on [MR #1](https://gitlab.com/sbansal1999/testing-zulip-gitlab-integration/-/merge_requests/1):\n\n~~~ quote\nI am not sure if this new feature is even required or not.\n~~~" # To keep things as valid JSON. self.url = self.build_webhook_url(use_merge_request_title="false") self.check_webhook("note_hook__merge_request_note", expected_topic, expected_message) @@ -245,39 +245,45 @@ def test_note_merge_request_event_message_without_merge_request_title(self) -> N def test_note_merge_request_with_custom_topic_in_url(self) -> None: self.url = self.build_webhook_url(topic="notifications") expected_topic = "notifications" - expected_message = "[[my-awesome-project](https://gitlab.com/tomaszkolek0/my-awesome-project)] Tomasz Kolek [commented](https://gitlab.com/tomaszkolek0/my-awesome-project/merge_requests/1#note_14171860) on [MR #1 Tomek](https://gitlab.com/tomaszkolek0/my-awesome-project/merge_requests/1):\n\n~~~ quote\nNice merge request!\n~~~" + expected_message = "[[testing-zulip-gitlab-integration](https://gitlab.com/sbansal1999/testing-zulip-gitlab-integration)] Satyam Bansal [commented](https://gitlab.com/sbansal1999/testing-zulip-gitlab-integration/-/merge_requests/1#note_1406328457) on [MR #1 add new-feature](https://gitlab.com/sbansal1999/testing-zulip-gitlab-integration/-/merge_requests/1):\n\n~~~ quote\nI am not sure if this new feature is even required or not.\n~~~" self.check_webhook("note_hook__merge_request_note", expected_topic, expected_message) def test_note_issue_event_message(self) -> None: - expected_topic = "my-awesome-project / issue #2 abc" - expected_message = "Tomasz Kolek [commented](https://gitlab.com/tomaszkolek0/my-awesome-project/issues/2#note_14172057) on [issue #2](https://gitlab.com/tomaszkolek0/my-awesome-project/issues/2):\n\n~~~ quote\nNice issue\n~~~" + expected_topic = "testing-zulip-gitlab-integration / issue #1 Add more lines" + expected_message = "Satyam Bansal [commented](https://gitlab.com/sbansal1999/testing-zulip-gitlab-integration/-/issues/1#note_1406279810) on [issue #1](https://gitlab.com/sbansal1999/testing-zulip-gitlab-integration/-/issues/1):\n\n~~~ quote\nThis is again a random comment.\n~~~" self.check_webhook("note_hook__issue_note", expected_topic, expected_message) def test_note_confidential_issue_event_message(self) -> None: - expected_subject = "Test / issue #3 Test" - expected_message = "Joe Bloggs [commented](https://gitlab.com/joebloggs/test/issues/3#note_101638770) on [issue #3](https://gitlab.com/joebloggs/test/issues/3):\n\n~~~ quote\nTest\n~~~" + expected_subject = "testing-zulip-gitlab-integration / issue #1 Add more lines" + expected_message = "Satyam Bansal [commented](https://gitlab.com/sbansal1999/testing-zulip-gitlab-integration/-/issues/1#note_1406130881) on [issue #1](https://gitlab.com/sbansal1999/testing-zulip-gitlab-integration/-/issues/1):\n\n~~~ quote\nSome more comments\n~~~" self.check_webhook("note_hook__confidential_issue_note", expected_subject, expected_message) def test_note_issue_with_custom_topic_in_url(self) -> None: self.url = self.build_webhook_url(topic="notifications") expected_topic = "notifications" - expected_message = "[[my-awesome-project](https://gitlab.com/tomaszkolek0/my-awesome-project)] Tomasz Kolek [commented](https://gitlab.com/tomaszkolek0/my-awesome-project/issues/2#note_14172057) on [issue #2 abc](https://gitlab.com/tomaszkolek0/my-awesome-project/issues/2):\n\n~~~ quote\nNice issue\n~~~" + expected_message = "[[testing-zulip-gitlab-integration](https://gitlab.com/sbansal1999/testing-zulip-gitlab-integration)] Satyam Bansal [commented](https://gitlab.com/sbansal1999/testing-zulip-gitlab-integration/-/issues/1#note_1406279810) on [issue #1 Add more lines](https://gitlab.com/sbansal1999/testing-zulip-gitlab-integration/-/issues/1):\n\n~~~ quote\nThis is again a random comment.\n~~~" self.check_webhook("note_hook__issue_note", expected_topic, expected_message) - def test_note_snippet_event_message(self) -> None: + def test_note_snippet_old_event_message(self) -> None: expected_topic = "my-awesome-project / snippet #2 test" - expected_message = "Tomasz Kolek [commented](https://gitlab.com/tomaszkolek0/my-awesome-project/snippets/2#note_14172058) on [snippet #2](https://gitlab.com/tomaszkolek0/my-awesome-project/snippets/2):\n\n~~~ quote\nNice snippet\n~~~" + expected_message = "Tomasz Kolek [commented](https://gitlab.com/tomaszkolek0/my-awesome-project/snippets/2#note_14172058) on [snippet #2](https://gitlab.com/tomaszkolek0/my-awesome-project/-/snippets/2):\n\n~~~ quote\nNice snippet\n~~~" + + self.check_webhook("note_hook__snippet_note_old", expected_topic, expected_message) + + def test_note_snippet_event_message(self) -> None: + expected_topic = "testing-zulip-gitlab-integration / snippet #2547713 a ver..." + expected_message = "Satyam Bansal [commented](https://gitlab.com/sbansal1999/testing-zulip-gitlab-integration/-/snippets/2547713#note_1424268837) on [snippet #2547713](https://gitlab.com/sbansal1999/testing-zulip-gitlab-integration/-/snippets/2547713):\n\n~~~ quote\nsome comment\n~~~" self.check_webhook("note_hook__snippet_note", expected_topic, expected_message) def test_note_snippet_with_custom_topic_in_url(self) -> None: self.url = self.build_webhook_url(topic="notifications") expected_topic = "notifications" - expected_message = "[[my-awesome-project](https://gitlab.com/tomaszkolek0/my-awesome-project)] Tomasz Kolek [commented](https://gitlab.com/tomaszkolek0/my-awesome-project/snippets/2#note_14172058) on [snippet #2 test](https://gitlab.com/tomaszkolek0/my-awesome-project/snippets/2):\n\n~~~ quote\nNice snippet\n~~~" + expected_message = "[[testing-zulip-gitlab-integration](https://gitlab.com/sbansal1999/testing-zulip-gitlab-integration)] Satyam Bansal [commented](https://gitlab.com/sbansal1999/testing-zulip-gitlab-integration/-/snippets/2547713#note_1424268837) on [snippet #2547713 a very new new feature](https://gitlab.com/sbansal1999/testing-zulip-gitlab-integration/-/snippets/2547713):\n\n~~~ quote\nsome comment\n~~~" self.check_webhook("note_hook__snippet_note", expected_topic, expected_message) @@ -469,7 +475,7 @@ def test_build_succeeded_event_message_legacy_event_name(self) -> None: def test_pipeline_succeeded_with_artifacts_event_message(self) -> None: expected_topic = "onlysomeproject / test/links-in-zulip-pipeline-message" - expected_message = "[Pipeline (22668)](https://gitlab.example.com/group1/onlysomeproject/pipelines/22668) changed status to success with build(s):\n* [cleanup:cleanup docker image](https://gitlab.example.com/group1/onlysomeproject/-/jobs/58592) - success\n* [pages](https://gitlab.example.com/group1/onlysomeproject/-/jobs/58591) - success\n * built artifact: *artifacts.zip* [[Browse](https://gitlab.example.com/group1/onlysomeproject/-/jobs/58591/artifacts/browse)|[Download](https://gitlab.example.com/group1/onlysomeproject/-/jobs/58591/artifacts/download)]\n* [black+pytest:future environment](https://gitlab.example.com/group1/onlysomeproject/-/jobs/58590) - success\n* [docs:anaconda environment](https://gitlab.example.com/group1/onlysomeproject/-/jobs/58589) - success\n * built artifact: *sphinx-docs.zip* [[Browse](https://gitlab.example.com/group1/onlysomeproject/-/jobs/58589/artifacts/browse)|[Download](https://gitlab.example.com/group1/onlysomeproject/-/jobs/58589/artifacts/download)]\n* [pytest:current environment](https://gitlab.example.com/group1/onlysomeproject/-/jobs/58588) - success\n* [black:current environment](https://gitlab.example.com/group1/onlysomeproject/-/jobs/58587) - success\n* [setup:docker image](https://gitlab.example.com/group1/onlysomeproject/-/jobs/58586) - success." + expected_message = "[Pipeline (22668)](https://gitlab.example.com/group1/onlysomeproject/-/pipelines/22668) changed status to success with build(s):\n* [cleanup:cleanup docker image](https://gitlab.example.com/group1/onlysomeproject/-/jobs/58592) - success\n* [pages](https://gitlab.example.com/group1/onlysomeproject/-/jobs/58591) - success\n * built artifact: *artifacts.zip* [[Browse](https://gitlab.example.com/group1/onlysomeproject/-/jobs/58591/artifacts/browse)|[Download](https://gitlab.example.com/group1/onlysomeproject/-/jobs/58591/artifacts/download)]\n* [black+pytest:future environment](https://gitlab.example.com/group1/onlysomeproject/-/jobs/58590) - success\n* [docs:anaconda environment](https://gitlab.example.com/group1/onlysomeproject/-/jobs/58589) - success\n * built artifact: *sphinx-docs.zip* [[Browse](https://gitlab.example.com/group1/onlysomeproject/-/jobs/58589/artifacts/browse)|[Download](https://gitlab.example.com/group1/onlysomeproject/-/jobs/58589/artifacts/download)]\n* [pytest:current environment](https://gitlab.example.com/group1/onlysomeproject/-/jobs/58588) - success\n* [black:current environment](https://gitlab.example.com/group1/onlysomeproject/-/jobs/58587) - success\n* [setup:docker image](https://gitlab.example.com/group1/onlysomeproject/-/jobs/58586) - success." self.check_webhook( "pipeline_hook__pipeline_succeeded_with_artifacts", @@ -479,7 +485,7 @@ def test_pipeline_succeeded_with_artifacts_event_message(self) -> None: def test_pipeline_succeeded_event_message(self) -> None: expected_topic = "my-awesome-project / master" - expected_message = "[Pipeline (4414206)](https://gitlab.com/TomaszKolek/my-awesome-project/pipelines/4414206) changed status to success with build(s):\n* [job_name2](https://gitlab.com/TomaszKolek/my-awesome-project/-/jobs/4541113) - success\n* [job_name](https://gitlab.com/TomaszKolek/my-awesome-project/-/jobs/4541112) - success." + expected_message = "[Pipeline (4414206)](https://gitlab.com/TomaszKolek/my-awesome-project/-/pipelines/4414206) changed status to success with build(s):\n* [job_name2](https://gitlab.com/TomaszKolek/my-awesome-project/-/jobs/4541113) - success\n* [job_name](https://gitlab.com/TomaszKolek/my-awesome-project/-/jobs/4541112) - success." self.check_webhook( "pipeline_hook__pipeline_succeeded", @@ -489,7 +495,7 @@ def test_pipeline_succeeded_event_message(self) -> None: def test_pipeline_started_event_message(self) -> None: expected_topic = "my-awesome-project / master" - expected_message = "[Pipeline (4414206)](https://gitlab.com/TomaszKolek/my-awesome-project/pipelines/4414206) started with build(s):\n* [job_name](https://gitlab.com/TomaszKolek/my-awesome-project/-/jobs/4541112) - running\n* [job_name2](https://gitlab.com/TomaszKolek/my-awesome-project/-/jobs/4541113) - pending." + expected_message = "[Pipeline (4414206)](https://gitlab.com/TomaszKolek/my-awesome-project/-/pipelines/4414206) started with build(s):\n* [job_name](https://gitlab.com/TomaszKolek/my-awesome-project/-/jobs/4541112) - running\n* [job_name2](https://gitlab.com/TomaszKolek/my-awesome-project/-/jobs/4541113) - pending." self.check_webhook( "pipeline_hook__pipeline_started", @@ -499,7 +505,7 @@ def test_pipeline_started_event_message(self) -> None: def test_pipeline_pending_event_message(self) -> None: expected_topic = "my-awesome-project / master" - expected_message = "[Pipeline (4414206)](https://gitlab.com/TomaszKolek/my-awesome-project/pipelines/4414206) was created with build(s):\n* [job_name2](https://gitlab.com/TomaszKolek/my-awesome-project/-/jobs/4541113) - pending\n* [job_name](https://gitlab.com/TomaszKolek/my-awesome-project/-/jobs/4541112) - created." + expected_message = "[Pipeline (4414206)](https://gitlab.com/TomaszKolek/my-awesome-project/-/pipelines/4414206) was created with build(s):\n* [job_name2](https://gitlab.com/TomaszKolek/my-awesome-project/-/jobs/4541113) - pending\n* [job_name](https://gitlab.com/TomaszKolek/my-awesome-project/-/jobs/4541112) - created." self.check_webhook( "pipeline_hook__pipeline_pending", @@ -554,7 +560,7 @@ def test_job_hook_event_topic(self) -> None: def test_system_push_event_message(self) -> None: expected_topic = "gitlab / master" - expected_message = "John Smith [pushed](http://test.example.com/gitlab/gitlab/compare/95790bf891e76fee5e1747ab589903a6a1f80f22...da1560886d4f094c3e6c9ef40349f7d38b5d27d7) 1 commit to branch master. Commits by Test User (1).\n\n* Add simple search to projects in public area ([c5feabde2d8](https://test.example.com/gitlab/gitlab/-/commit/c5feabde2d8cd023215af4d2ceeb7a64839fc428))" + expected_message = "John Smith [pushed](http://test.example.com/gitlab/gitlab/-/compare/95790bf891e76fee5e1747ab589903a6a1f80f22...da1560886d4f094c3e6c9ef40349f7d38b5d27d7) 1 commit to branch master. Commits by Test User (1).\n\n* Add simple search to projects in public area ([c5feabde2d8](https://test.example.com/gitlab/gitlab/-/commit/c5feabde2d8cd023215af4d2ceeb7a64839fc428))" self.check_webhook("system_hook__push_hook", expected_topic, expected_message) def test_system_merge_request_created_without_assignee_event_message(self) -> None:
GitLab integration is using deprecated URL formats; links to issue no longer work GitLab deprecated a URL format for projects with groups and subgroups in their version 16.0 and as of now, they have stopped redirecting the old (deprecated) URLs to the new ones in GitLab Next (their canary release). See https://docs.gitlab.com/ee/update/deprecations.html?removal_milestone=16.0#legacy-urls-replaced-or-removed This breaks part of the Zulip webhook integration where Zulip is generating URLs to GitLab issues inside the message body. It looks like this is because in https://github.com/zulip/zulip/blob/main/zerver/webhooks/gitlab/view.py#L238 the URL is assembled from other parts of the incoming data and so lacks the format change. So far I have only found this one case where it causes an issue (as many other parts of this webhook integration take the full URL directly from GitLab rather than assembling it) but it may not be the only place this happens. It seems like this could be fixed by just taking the full URL from the GitLab incoming request (which should be in `payload["issue"]["url"]`) but I'm not sure if there's a reason not to do this as I'm not really familiar with the Zulip codebase.
Hello @zulip/server-integrations members, this issue was labeled with the "area: integrations" label, so you may want to check it out! <!-- areaLabelAddition --> Thanks for the report, @craftyjon ! @sbansal1999 could you please take a look at this one? Thanks for leaving out the URL to the changelog, that will certainly help a lot. After giving them a quick look, I think the issue should be resolved by replacing the URL template to conform with the [new one](https://gitlab.com/gitlab-org/gitlab/-/issues/28848/?_gl=1%2ap8qur2%2a_ga%2aMjExNzY2NTgxMy4xNjg0NDM5NTgz%2a_ga_ENFH3X7M5Y%2aMTY4NDQzOTU4Mi4xLjAuMTY4NDQzOTU4Mi4wLjAuMA..#release-notes). Eg: On [this](https://github.com/zulip/zulip/blob/main/zerver/webhooks/gitlab/view.py#L238) line there is the following template: `{}/merge_requests/{}` which should be changed to `{}/-/merge_requests/{}` I will see what are the places in which the changes are needed to be done.
2023-05-27T19:23:27
zulip/zulip
25,813
zulip__zulip-25813
[ "25672" ]
f3684e842a87145871ef3e8e6509ad862e24be0b
diff --git a/zerver/webhooks/github/view.py b/zerver/webhooks/github/view.py --- a/zerver/webhooks/github/view.py +++ b/zerver/webhooks/github/view.py @@ -364,7 +364,7 @@ def get_team_body(helper: Helper) -> str: payload = helper.payload changes = payload["changes"] if "description" in changes: - actor = payload["sender"]["login"].tame(check_string) + actor = get_sender_name(payload) new_description = payload["team"]["description"].tame(check_string) return f"**{actor}** changed the team description to:\n```quote\n{new_description}\n```" if "name" in changes: @@ -597,9 +597,10 @@ def get_check_run_body(helper: Helper) -> str: def get_star_body(helper: Helper) -> str: payload = helper.payload - template = "{user} {action} the repository [{repo}]({url})." + template = "[{user}]({user_url}) {action} the repository [{repo}]({url})." return template.format( - user=payload["sender"]["login"].tame(check_string), + user=get_sender_name(payload), + user_url=get_sender_url(payload), action="starred" if payload["action"].tame(check_string) == "created" else "unstarred", repo=get_repository_full_name(payload), url=payload["repository"]["html_url"].tame(check_string), @@ -627,6 +628,10 @@ def get_sender_name(payload: WildValue) -> str: return payload["sender"]["login"].tame(check_string) +def get_sender_url(payload: WildValue) -> str: + return payload["sender"]["html_url"].tame(check_string) + + def get_branch_name_from_ref(ref_string: str) -> str: return re.sub(r"^refs/heads/", "", ref_string)
diff --git a/zerver/webhooks/github/tests.py b/zerver/webhooks/github/tests.py --- a/zerver/webhooks/github/tests.py +++ b/zerver/webhooks/github/tests.py @@ -25,7 +25,7 @@ def test_ping_event(self) -> None: self.check_webhook("ping", TOPIC_REPO, expected_message) def test_star_event(self) -> None: - expected_message = "Codertocat starred the repository [Codertocat/Hello-World](https://github.com/Codertocat/Hello-World)." + expected_message = "[Codertocat](https://github.com/Codertocat) starred the repository [Codertocat/Hello-World](https://github.com/Codertocat/Hello-World)." expected_topic = "Hello-World" self.check_webhook("star", expected_topic, expected_message)
GitHub integration: How about linking sender? GitHub integration includes a sender to message content. For example, `XXX starred the repository [zulip/zulip](https://github.com/zulip/zulip]` is a message content of a star event. How about making the sender part clickable like repository name? For example, `[XXX](https://github.com/XXX) starred the repository [zulip/zulip](https://github.com/zulip/zulip]` for a star event. We can do this only for a star event by the following change: ```diff diff --git a/zerver/webhooks/github/view.py b/zerver/webhooks/github/view.py index db74604bbc..a425f78bb6 100644 --- a/zerver/webhooks/github/view.py +++ b/zerver/webhooks/github/view.py @@ -597,9 +597,10 @@ Check [{name}]({html_url}) {status} ({conclusion}). ([{short_hash}]({commit_url} def get_star_body(helper: Helper) -> str: payload = helper.payload - template = "{user} {action} the repository [{repo}]({url})." + template = "[{user}]({user_url}) {action} the repository [{repo}]({url})." return template.format( - user=payload["sender"]["login"].tame(check_string), + user=get_sender_name(payload), + user_url=get_sender_url(payload), action="starred" if payload["action"].tame(check_string) == "created" else "unstarred", repo=get_repository_full_name(payload), url=payload["repository"]["html_url"].tame(check_string), @@ -627,6 +628,10 @@ def get_sender_name(payload: WildValue) -> str: return payload["sender"]["login"].tame(check_string) +def get_sender_url(payload: WildValue) -> str: + return payload["sender"]["html_url"].tame(check_string) + + def get_branch_name_from_ref(ref_string: str) -> str: return re.sub(r"^refs/heads/", "", ref_string) ``` I think that other events can be done with similar changes. What do you think about this proposal? (If this proposal is acceptable, I think that we can mark this as "good-first-issue".)
@zulipbot add "help wanted" "area: integrations" Hello @zulip/server-integrations members, this issue was labeled with the "area: integrations" label, so you may want to check it out! <!-- areaLabelAddition --> @zulipbot claim Welcome to Zulip, @dhruv302003! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @dhruv302003 We noticed that you have not made any updates to this issue or linked PRs for 10 days. Please comment here if you are still actively working on it. Otherwise, we'd appreciate a quick `@zulipbot abandon` comment so that someone else can claim this issue and continue from where you left off. If we don't hear back, you will be automatically unassigned in 4 days. Thanks! <!-- inactiveWarning --> @zulipbot I am still working on it
2023-05-29T14:10:11
zulip/zulip
25,831
zulip__zulip-25831
[ "25789" ]
d6c21c2237918f402988bd7e9463afa9253a1192
diff --git a/zerver/lib/webhooks/git.py b/zerver/lib/webhooks/git.py --- a/zerver/lib/webhooks/git.py +++ b/zerver/lib/webhooks/git.py @@ -50,6 +50,9 @@ CREATE_BRANCH_WITHOUT_URL_MESSAGE_TEMPLATE = "{user_name} created {branch_name} branch." REMOVE_BRANCH_MESSAGE_TEMPLATE = "{user_name} deleted branch {branch_name}." +ISSUE_LABELED_OR_UNLABELED_MESSAGE_TEMPLATE = "[{user_name}]({user_url}) {action} the [{label_name}]({label_url}) label {preposition} [Issue #{id}]({url})." +ISSUE_LABELED_OR_UNLABELED_MESSAGE_TEMPLATE_WITH_TITLE = "[{user_name}]({user_url}) {action} the [{label_name}]({label_url}) label {preposition} [Issue #{id} {title}]({url})." + PULL_REQUEST_OR_ISSUE_MESSAGE_TEMPLATE = "{user_name} {action} [{type}{id}]({url})" PULL_REQUEST_OR_ISSUE_MESSAGE_TEMPLATE_WITH_TITLE = ( "{user_name} {action} [{type}{id} {title}]({url})" @@ -273,6 +276,32 @@ def get_issue_event_message( ) +def get_issue_labeled_or_unlabeled_event_message( + user_name: str, + action: str, + url: str, + number: int, + label_name: str, + label_url: str, + user_url: str, + title: Optional[str] = None, +) -> str: + args = { + "user_name": user_name, + "action": action, + "url": url, + "id": number, + "label_name": label_name, + "label_url": label_url, + "user_url": user_url, + "title": title, + "preposition": "to" if action == "added" else "from", + } + if title is not None: + return ISSUE_LABELED_OR_UNLABELED_MESSAGE_TEMPLATE_WITH_TITLE.format(**args) + return ISSUE_LABELED_OR_UNLABELED_MESSAGE_TEMPLATE.format(**args) + + def get_push_tag_event_message( user_name: str, tag_name: str, tag_url: Optional[str] = None, action: str = "pushed" ) -> str: diff --git a/zerver/webhooks/github/view.py b/zerver/webhooks/github/view.py --- a/zerver/webhooks/github/view.py +++ b/zerver/webhooks/github/view.py @@ -28,6 +28,7 @@ TOPIC_WITH_PR_OR_ISSUE_INFO_TEMPLATE, get_commits_comment_action_message, get_issue_event_message, + get_issue_labeled_or_unlabeled_event_message, get_pull_request_event_message, get_push_commits_event_message, get_push_tag_event_message, @@ -204,6 +205,23 @@ def get_issue_comment_body(helper: Helper) -> str: ) +def get_issue_labeled_or_unlabeled_body(helper: Helper) -> str: + payload = helper.payload + include_title = helper.include_title + issue = payload["issue"] + + return get_issue_labeled_or_unlabeled_event_message( + user_name=get_sender_name(payload), + action="added" if payload["action"].tame(check_string) == "labeled" else "removed", + url=issue["html_url"].tame(check_string), + number=issue["number"].tame(check_int), + label_name=payload["label"]["name"].tame(check_string), + label_url=payload["label"]["url"].tame(check_string), + user_url=get_sender_url(payload), + title=issue["title"].tame(check_string) if include_title else None, + ) + + def get_fork_body(helper: Helper) -> str: payload = helper.payload forkee = payload["forkee"] @@ -710,6 +728,7 @@ def get_subject_based_on_type(payload: WildValue, event: str) -> str: "fork": get_fork_body, "gollum": get_wiki_pages_body, "issue_comment": get_issue_comment_body, + "issue_labeled_or_unlabeled": get_issue_labeled_or_unlabeled_body, "issues": get_issue_body, "member": get_member_body, "membership": get_membership_body, @@ -862,6 +881,12 @@ def get_zulip_event_name( # this means GH has actually added new actions since September 2020, # so it's a bit more cause for alarm raise UnsupportedWebhookEventTypeError(f"unsupported team action {action}") + elif header_event == "issues": + action = payload["action"].tame(check_string) + if action in ("labeled", "unlabeled"): + return "issue_labeled_or_unlabeled" + else: + return "issues" elif header_event in list(EVENT_FUNCTION_MAPPER.keys()): return header_event elif header_event in IGNORED_EVENTS:
diff --git a/zerver/webhooks/github/tests.py b/zerver/webhooks/github/tests.py --- a/zerver/webhooks/github/tests.py +++ b/zerver/webhooks/github/tests.py @@ -177,6 +177,22 @@ def test_issue_unassigned_with_custom_topic_in_url(self) -> None: expected_message = "sbansal1999 unassigned sbansal1999 from [issue #9 idk man](https://github.com/sbansal1999/testing-gh/issues/9)." self.check_webhook("issues__unassigned", expected_topic, expected_message) + def test_issue_labeled(self) -> None: + expected_topic = "testing-gh / issue #9 idk man" + expected_message = "[sbansal1999](https://github.com/sbansal1999) added the [bug](https://api.github.com/repos/sbansal1999/testing-gh/labels/bug) label to [Issue #9](https://github.com/sbansal1999/testing-gh/issues/9)." + self.check_webhook("issues__labeled", expected_topic, expected_message) + + def test_issue_labeled_with_custom_topic_in_url(self) -> None: + self.url = self.build_webhook_url(topic="notifications") + expected_topic = "notifications" + expected_message = "[sbansal1999](https://github.com/sbansal1999) added the [bug](https://api.github.com/repos/sbansal1999/testing-gh/labels/bug) label to [Issue #9 idk man](https://github.com/sbansal1999/testing-gh/issues/9)." + self.check_webhook("issues__labeled", expected_topic, expected_message) + + def test_issue_unlabeled(self) -> None: + expected_topic = "testing-gh / issue #9 idk man" + expected_message = "[sbansal1999](https://github.com/sbansal1999) removed the [bug](https://api.github.com/repos/sbansal1999/testing-gh/labels/bug) label from [Issue #9](https://github.com/sbansal1999/testing-gh/issues/9)." + self.check_webhook("issues__unlabeled", expected_topic, expected_message) + def test_membership_msg(self) -> None: expected_message = ( "baxterthehacker added [kdaigle](https://github.com/kdaigle) to the Contractors team."
Exclude label/unlabel events in GitHub integration (at least optionally) The GitHub integration sends a message when an issue (or PR, presumably) gets a label added, or a label removed. This can get extremely spammy. For example see today's messages it sent about the zulip-flutter repo, starting [here](https://chat.zulip.org/#narrow/stream/243-mobile-team/topic/zulip-flutter/near/1578003) and running for most of the next 100 messages. (But [not all of them](https://chat.zulip.org/#narrow/stream/243-mobile-team/topic/zulip-flutter/near/1578145)! As usual, one consequence of spam is that it becomes easy to miss the other, more interesting stuff.) --- I think it's probable that nobody ever actually wants this behavior. One piece of evidence for that: as is, these messages are completely useless. * They repeat the entire issue description. * They *don't* specify what label it was that was added or removed. So truly zero people are relying on these messages today; and the lack of clamor to fix them is evidence that nobody is excited about having even an improved version of them. In principle we could make it configurable whether to include these events. But given that it's probable that nobody actually wants them, I think it'd make sense instead to keep things simple and just skip them entirely.
Hello @zulip/server-integrations members, this issue was labeled with the "area: integrations" label, so you may want to check it out! <!-- areaLabelAddition --> BTW these events are also spammy even when nobody's going and labeling things en masse. For example, whenever someone opens an issue there's also an event for any labels they add, like [here](https://chat.zulip.org/#narrow/stream/243-mobile-team/topic/zulip-flutter/near/1578032). (That was a label I added before even hitting submit to create the issue — so it's not avoidable by doing that.) @sbansal1999 making sure you see this issue and https://github.com/zulip/zulip/issues/25793. This one probably comes up more often. The argument for these events being useless makes sense to me. Thanks for tagging me on this one! I will add this to my todo list for the week. So I investigated the webhooks that are sent when labels are added/removed from an issue (or PR). Every time when a label is assigned / unassigned one event is fired. So suppose if in an issue 2 labels were added and 1 other label was removed then we would receive a total of 3 events. > - They repeat the entire issue description. > - They don't specify what label it was that was added or removed. I think it's possible to fix both of the above-mentioned problems. So I am not sure if excluding those events at all is really required. So something like this can be sent when a label is added to an issue: > Issue #9 was labeled bug by sbansal1999. Let me know what you guys think about this one. I think a short message like that which doesn't repeat the entire issue description and has the label that changed would likely be worth trying. Certainly we should do that if we're going to keep sending messages for these events at all. But it wouldn't make them all that much less spammy than they are now — in particular it'd still be the same number of messages on the same occasions. For example: > This can get extremely spammy. For example see today's messages it sent about the zulip-flutter repo, starting [here](https://chat.zulip.org/#narrow/stream/243-mobile-team/topic/zulip-flutter/near/1578003) and running for most of the next 100 messages. (But [not all of them](https://chat.zulip.org/#narrow/stream/243-mobile-team/topic/zulip-flutter/near/1578145)! As usual, one consequence of spam is that it becomes easy to miss the other, more interesting stuff.) So I expect that they'd still feel pretty spammy and it'd be better to leave them out entirely. The fact that these messages are currently as broken as they are is informative because it's evidence that there is literally nobody who is currently relying on them and might be sad if we just removed them. You are right, the number of messages will still be the same. So some spam would still be there. I will get on and add this to my to-do list. @zulipbot claim
2023-05-30T15:31:17
zulip/zulip
25,861
zulip__zulip-25861
[ "25778" ]
8343cf1b4fcb58f5b3eaca1fbfce95268ab10290
diff --git a/zerver/webhooks/sentry/view.py b/zerver/webhooks/sentry/view.py --- a/zerver/webhooks/sentry/view.py +++ b/zerver/webhooks/sentry/view.py @@ -77,6 +77,7 @@ "javascript": "javascript", "node": "javascript", "python": "python3", + "ruby": "ruby", } @@ -93,9 +94,6 @@ def convert_lines_to_traceback_string(lines: Optional[List[str]]) -> str: def handle_event_payload(event: Dict[str, Any]) -> Tuple[str, str]: """Handle either an exception type event or a message type event payload.""" - # We shouldn't support the officially deprecated Raven series of SDKs. - if int(event["version"]) < 7: - raise UnsupportedWebhookEventTypeError("Raven SDK") subject = event["title"] platform_name = event["platform"] @@ -103,6 +101,14 @@ def handle_event_payload(event: Dict[str, Any]) -> Tuple[str, str]: if syntax_highlight_as == "": # nocoverage logging.info("Unknown Sentry platform: %s", platform_name) + # We shouldn't support the officially deprecated Raven series of + # Python SDKs. + if platform_name == "python" and int(event["version"]) < 7: + # The sample event is still an old "version" -- accept it even + # though we don't accept events from the old Python SDK. + tags = event.get("tags", []) + if ["sample_event", "yes"] not in tags: + raise UnsupportedWebhookEventTypeError("Raven SDK") context = { "title": subject, "level": event["level"],
diff --git a/zerver/webhooks/sentry/tests.py b/zerver/webhooks/sentry/tests.py --- a/zerver/webhooks/sentry/tests.py +++ b/zerver/webhooks/sentry/tests.py @@ -82,6 +82,46 @@ def test_event_for_exception_python(self) -> None: ```""" self.check_webhook("event_for_exception_python", expected_topic, expected_message) + def test_event_for_exception_rails(self) -> None: + expected_topic = "ZeroDivisionError: divided by 0" + expected_message = """\ +**New exception:** [ZeroDivisionError: divided by 0](https://sentry.io/organizations/nitk-46/issues/4213933362/events/49b528e13e45497ab9adc3173fd2ed34/) +```quote +**level:** error +**timestamp:** 2023-05-29 10:12:33 +**filename:** app/controllers/articles_controller.rb +``` + +Traceback: +```ruby + class ArticlesController < ApplicationController + + def index + + begin + +---> 132312 / 0 + + rescue ZeroDivisionError => exception + + Sentry.capture_exception(exception) + + end + +```""" + self.check_webhook("event_for_exception_rails", expected_topic, expected_message) + + def test_event_for_exception_vue(self) -> None: + expected_topic = "TypeError: Cannot read properties of null (reading 'inser..." + expected_message = """\ +**New exception:** [TypeError: Cannot read properties of null (reading 'insertBefore')](https://sentry.io/organizations/nitk-46/issues/4214010673/events/292f78454e774e62999506f759ad791d/) +```quote +**level:** error +**timestamp:** 2023-05-29 11:08:30 +**filename:** /node_modules/.vite/deps/chunk-G4DFXOZZ.js +```""" + self.check_webhook("event_for_exception_vue", expected_topic, expected_message) + def test_webhook_event_for_exception_python(self) -> None: expected_topic = "ValueError: new sentry error." expected_message = """\ @@ -210,3 +250,13 @@ def test_deprecated_exception_message(self) -> None: This is an example python exception ```""" self.check_webhook("deprecated_exception_message", expected_topic, expected_message) + + def test_sample_event(self) -> None: + expected_topic = "This is an example Python exception" + expected_message = """\ +**New message event:** [This is an example Python exception](https://sentry.io/organizations/nitk-46/issues/4218258981/events/b6eff1a49b1f4132850b1238d968da70/) +```quote +**level:** error +**timestamp:** 2023-05-31 11:06:16 +```""" + self.check_webhook("sample_event", expected_topic, expected_message)
Support more sources of Sentry exceptions We currently support some of the Sentry backends: https://github.com/zulip/zulip/blob/03a0a7abc65a572655d8c0e235fc8a622ce22932/zerver/webhooks/sentry/view.py#L73-L80 We should add support for more of them, like Vue and Rails. As part of this, we should probably limit the `version` check: https://github.com/zulip/zulip/blob/03a0a7abc65a572655d8c0e235fc8a622ce22932/zerver/webhooks/sentry/view.py#L96-L98 ...to only Python, since other platforms don't seem to include it. Sentry exception payloads are not standardized, so doing this will probably require building some toy applications in each of the platforms (the Sentry docs probably provide examples) to capture fixtures of the current payloads.
Hello @zulip/server-integrations members, this issue was labeled with the "area: integrations" label, so you may want to check it out! <!-- areaLabelAddition --> Thanks for assigning this issue to me. :heart_decoration: I will look into this and will try to fix this as soon as possible.
2023-05-31T20:21:11
zulip/zulip
25,987
zulip__zulip-25987
[ "25913" ]
85681546ce5046f9663bf23358a5caae27d04493
diff --git a/zerver/lib/user_groups.py b/zerver/lib/user_groups.py --- a/zerver/lib/user_groups.py +++ b/zerver/lib/user_groups.py @@ -216,6 +216,16 @@ def get_subgroup_ids(user_group: UserGroup, *, direct_subgroup_only: bool = Fals return list(subgroup_ids) +def get_recursive_subgroups_for_groups(user_group_ids: List[int]) -> List[int]: + cte = With.recursive( + lambda cte: UserGroup.objects.filter(id__in=user_group_ids) + .values(group_id=F("id")) + .union(cte.join(UserGroup, direct_supergroups=cte.col.group_id).values(group_id=F("id"))) + ) + recursive_subgroups = cte.join(UserGroup, id=cte.col.group_id).with_cte(cte) + return list(recursive_subgroups.values_list("id", flat=True)) + + @transaction.atomic(savepoint=False) def create_system_user_groups_for_realm(realm: Realm) -> Dict[int, UserGroup]: """Any changes to this function likely require a migration to adjust diff --git a/zerver/views/user_groups.py b/zerver/views/user_groups.py --- a/zerver/views/user_groups.py +++ b/zerver/views/user_groups.py @@ -25,6 +25,7 @@ access_user_group_by_id, access_user_groups_as_potential_subgroups, get_direct_memberships_of_users, + get_recursive_subgroups_for_groups, get_subgroup_ids, get_user_group_direct_member_ids, get_user_group_member_ids, @@ -238,6 +239,14 @@ def add_subgroups_to_group_backend( ) ) + subgroup_ids = [group.id for group in subgroups] + if user_group_id in get_recursive_subgroups_for_groups(subgroup_ids): + raise JsonableError( + _( + "User group {user_group_id} is already a subgroup of one of the passed subgroups." + ).format(user_group_id=user_group_id) + ) + add_subgroups_to_user_group(user_group, subgroups, acting_user=user_profile) return json_success(request)
diff --git a/zerver/tests/test_user_groups.py b/zerver/tests/test_user_groups.py --- a/zerver/tests/test_user_groups.py +++ b/zerver/tests/test_user_groups.py @@ -905,6 +905,7 @@ def test_updating_subgroups_of_user_group(self) -> None: realm, "leadership", [desdemona, iago, hamlet], acting_user=None ) support_group = check_add_user_group(realm, "support", [hamlet, othello], acting_user=None) + test_group = check_add_user_group(realm, "test", [hamlet], acting_user=None) self.login("cordelia") # Non-admin and non-moderators who are not a member of group cannot add or remove subgroups. @@ -968,6 +969,28 @@ def test_updating_subgroups_of_user_group(self) -> None: ), ) + self.login("iago") + params = {"add": orjson.dumps([support_group.id]).decode()} + result = self.client_post(f"/json/user_groups/{leadership_group.id}/subgroups", info=params) + self.assert_json_error( + result, + ( + "User group {user_group_id} is already a subgroup of one of the passed subgroups." + ).format(user_group_id=leadership_group.id), + ) + + params = {"add": orjson.dumps([support_group.id]).decode()} + result = self.client_post(f"/json/user_groups/{test_group.id}/subgroups", info=params) + + params = {"add": orjson.dumps([test_group.id]).decode()} + result = self.client_post(f"/json/user_groups/{leadership_group.id}/subgroups", info=params) + self.assert_json_error( + result, + ( + "User group {user_group_id} is already a subgroup of one of the passed subgroups." + ).format(user_group_id=leadership_group.id), + ) + lear_realm = get_realm("lear") lear_test_group = check_add_user_group( lear_realm, "test", [self.lear_user("cordelia")], acting_user=None
Enforce that the nested `UserGroup`s are free of cycles We currently do not check if there is a cycle among the `UserGroup`s in the API : https://github.com/zulip/zulip/blob/cdc94d27196846f33feb79a1701e94bb71e348b7/zerver/views/user_groups.py#L232-L239 This means that it is possible for one to create user groups `a` and `b`, such that `a` is a subgroup of `b`, and `b` is a subgroup of `a`. While this does not lead to our [recursive query](https://github.com/zulip/zulip/blob/main/zerver/lib/user_groups.py#L163-L169) for memberships to fail, we do want to enforce that the user groups are free of cycles, i.e. satisfy the [DAG](https://en.wikipedia.org/wiki/Directed_acyclic_graph) constraints. [CZO discussion](https://chat.zulip.org/#narrow/stream/3-backend/topic/Audit.20log.20for.20UserGroup/near/1586731)
@sahil839 can you pick this one up when you get back from your trip? Sure.
2023-06-12T07:27:54
zulip/zulip
26,005
zulip__zulip-26005
[ "22693" ]
27664459cb2034a24e50cf06b4765dfed24b1d80
diff --git a/version.py b/version.py --- a/version.py +++ b/version.py @@ -33,7 +33,7 @@ # Changes should be accompanied by documentation explaining what the # new level means in api_docs/changelog.md, as well as "**Changes**" # entries in the endpoint's documentation in `zulip.yaml`. -API_FEATURE_LEVEL = 185 +API_FEATURE_LEVEL = 188 # Bump the minor PROVISION_VERSION to indicate that folks should provision # only when going from an old version of the code to a newer version. Bump diff --git a/zerver/views/muted_users.py b/zerver/views/muted_users.py --- a/zerver/views/muted_users.py +++ b/zerver/views/muted_users.py @@ -16,7 +16,7 @@ def mute_user(request: HttpRequest, user_profile: UserProfile, muted_user_id: in raise JsonableError(_("Cannot mute self")) muted_user = access_user_by_id( - user_profile, muted_user_id, allow_bots=False, allow_deactivated=True, for_admin=False + user_profile, muted_user_id, allow_bots=True, allow_deactivated=True, for_admin=False ) date_muted = timezone_now() @@ -32,7 +32,7 @@ def unmute_user( request: HttpRequest, user_profile: UserProfile, muted_user_id: int ) -> HttpResponse: muted_user = access_user_by_id( - user_profile, muted_user_id, allow_bots=False, allow_deactivated=True, for_admin=False + user_profile, muted_user_id, allow_bots=True, allow_deactivated=True, for_admin=False ) mute_object = get_mute_object(user_profile, muted_user)
diff --git a/zerver/tests/test_muted_users.py b/zerver/tests/test_muted_users.py --- a/zerver/tests/test_muted_users.py +++ b/zerver/tests/test_muted_users.py @@ -59,9 +59,11 @@ def test_add_muted_user_mute_bot(self) -> None: url = f"/api/v1/users/me/muted_users/{muted_id}" result = self.api_post(hamlet, url) - # Currently we do not allow muting bots. This is the error message - # from `access_user_by_id`. - self.assert_json_error(result, "No such user") + self.assert_json_success(result) + + url = f"/api/v1/users/me/muted_users/{muted_id}" + result = self.api_delete(hamlet, url) + self.assert_json_success(result) def test_add_muted_user_mute_twice(self) -> None: hamlet = self.example_user("hamlet")
Mute Option Missing for Bots When clicking the name of a user I get the "Mute this user" option, but there is no option to do so when clicking a bot's name.
Thanks for the report! Currently, muting bot users is not supported. We might implement this in the future. Linking to this comment for backlogging purposes https://github.com/zulip/zulip/pull/16915#issuecomment-808875744. Hello @zulip/server-bots, @zulip/server-settings members, this issue was labeled with the "area: settings (user)", "area: bots" labels, so you may want to check it out! <!-- areaLabelAddition --> @Virakal can you talk about why you wanted to mute a bot user? Some context would be helpful in thinking about this feature request. There's no significant technical impediment to adding support for muting bots. @timabbott we have some bots that we'd like to use because they give quite useful information but not useful enough to warrant spamming everyone with a notification, like git commit bots and things. I've also had issues in the past where people have added bots to Slack servers that some people like but other people are just annoyed by, like the beer time bot. I suppose ideally there would be individual notification settings for bots, like a notification badge would be nice for Git commits but I don't need them making sounds or being sent to my phone. I figure muting bots would be much simpler though. @abhijeetbodas2001 do you remember why we didn't allow muting bot users when we first implemented the feature? I don't remember anything in particular apart from because we had decided on the feature set keeping in mind the "(human) user you'd rather not interact with". Allowing muting bots should not be too difficult technically, in case we want the same feature set for bots as well. Adding a "Mute bot" option sounds reasonable to me! @zulipbot claim Hello @amylcheng! Thanks for your interest in Zulip! You have attempted to claim an issue without the label "help wanted". You can only claim and submit pull requests for issues with the [help wanted](https://github.com/zulip/zulip/issues?q=is%3Aopen+is%3Aissue+no%3Aassignee+label%3A%22help+wanted%22) label. If this is your first time here, we recommend reading our [guide for new contributors](https://zulip.readthedocs.io/en/latest/overview/contributing.html) before getting started. I am just doing a quick bump on this issue, since I recently discovered this bug in the context of deploying some of my own bots. The comments indicate that a) this should be fairly easy and b) @alya signed off on the feature. Yeah, let me tag this as a priority.
2023-06-13T16:25:13
zulip/zulip
26,087
zulip__zulip-26087
[ "26055" ]
784622ee5d3e5bca4db9ebafba748acd797b427d
diff --git a/zerver/webhooks/github/view.py b/zerver/webhooks/github/view.py --- a/zerver/webhooks/github/view.py +++ b/zerver/webhooks/github/view.py @@ -501,7 +501,7 @@ def get_pull_request_review_body(helper: Helper) -> str: url=payload["review"]["html_url"].tame(check_string), type="PR review", title=title if include_title else None, - message=payload["review"]["body"].tame(check_string), + message=payload["review"]["body"].tame(check_none_or(check_string)), )
diff --git a/zerver/webhooks/github/tests.py b/zerver/webhooks/github/tests.py --- a/zerver/webhooks/github/tests.py +++ b/zerver/webhooks/github/tests.py @@ -284,6 +284,11 @@ def test_pull_request_review_msg_with_custom_topic_in_url(self) -> None: expected_message = "baxterthehacker submitted [PR review for #1 Update the README with new information](https://github.com/baxterthehacker/public-repo/pull/1#pullrequestreview-2626884):\n\n~~~ quote\nLooks great!\n~~~" self.check_webhook("pull_request_review", expected_topic, expected_message) + def test_pull_request_review_msg_with_empty_body(self) -> None: + expected_topic = "groonga / PR #1581 grn_db_value_lock: unlock GRN_TYPE obj..." + expected_message = "kou submitted [PR review](https://github.com/groonga/groonga/pull/1581#pullrequestreview-1483047907)." + self.check_webhook("pull_request_review__empty_body", expected_topic, expected_message) + def test_pull_request_review_comment_msg(self) -> None: expected_message = "baxterthehacker created [PR review comment](https://github.com/baxterthehacker/public-repo/pull/1#discussion_r29724692):\n\n~~~ quote\nMaybe you should use more emojji on this line.\n~~~" self.check_webhook("pull_request_review_comment", TOPIC_PR, expected_message)
GitHub webhook may receive a pull_request_review event with null review.body `zerver.webhooks.github.view.get_pull_request_review_body` requires `review.body` as `string` in `pull_request_review` event: https://github.com/zulip/zulip/blob/92c83c1df489975f8fe887f190e5d0af7c9534a2/zerver/webhooks/github/view.py#L504 But GitHub may send a `pull_request_review` event with `null` `review.body`. Here is an example event from https://github.com/groonga/groonga : <details> ```json { "action": "submitted", "review": { "id": 1483047907, "node_id": "PRR_kwDOAAGiws5YZYPj", "user": { "login": "kou", "id": 27350, "node_id": "MDQ6VXNlcjI3MzUw", "avatar_url": "https://avatars.githubusercontent.com/u/27350?v=4", "gravatar_id": "", "url": "https://api.github.com/users/kou", "html_url": "https://github.com/kou", "followers_url": "https://api.github.com/users/kou/followers", "following_url": "https://api.github.com/users/kou/following{/other_user}", "gists_url": "https://api.github.com/users/kou/gists{/gist_id}", "starred_url": "https://api.github.com/users/kou/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/kou/subscriptions", "organizations_url": "https://api.github.com/users/kou/orgs", "repos_url": "https://api.github.com/users/kou/repos", "events_url": "https://api.github.com/users/kou/events{/privacy}", "received_events_url": "https://api.github.com/users/kou/received_events", "type": "User", "site_admin": false }, "body": null, "commit_id": "db8dc428a0338f68b264eaf634a9b0c5ef6c07bb", "submitted_at": "2023-06-16T09:03:40Z", "state": "commented", "html_url": "https://github.com/groonga/groonga/pull/1581#pullrequestreview-1483047907", "pull_request_url": "https://api.github.com/repos/groonga/groonga/pulls/1581", "author_association": "MEMBER", "_links": { "html": { "href": "https://github.com/groonga/groonga/pull/1581#pullrequestreview-1483047907" }, "pull_request": { "href": "https://api.github.com/repos/groonga/groonga/pulls/1581" } } }, "pull_request": { "url": "https://api.github.com/repos/groonga/groonga/pulls/1581", "id": 1395030627, "node_id": "PR_kwDOAAGiws5TJnpj", "html_url": "https://github.com/groonga/groonga/pull/1581", "diff_url": "https://github.com/groonga/groonga/pull/1581.diff", "patch_url": "https://github.com/groonga/groonga/pull/1581.patch", "issue_url": "https://api.github.com/repos/groonga/groonga/issues/1581", "number": 1581, "state": "open", "locked": false, "title": "grn_db_value_lock: unlock GRN_TYPE object or GRN_EXPR object even if reference count enable", "user": { "login": "komainu8", "id": 19166236, "node_id": "MDQ6VXNlcjE5MTY2MjM2", "avatar_url": "https://avatars.githubusercontent.com/u/19166236?v=4", "gravatar_id": "", "url": "https://api.github.com/users/komainu8", "html_url": "https://github.com/komainu8", "followers_url": "https://api.github.com/users/komainu8/followers", "following_url": "https://api.github.com/users/komainu8/following{/other_user}", "gists_url": "https://api.github.com/users/komainu8/gists{/gist_id}", "starred_url": "https://api.github.com/users/komainu8/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/komainu8/subscriptions", "organizations_url": "https://api.github.com/users/komainu8/orgs", "repos_url": "https://api.github.com/users/komainu8/repos", "events_url": "https://api.github.com/users/komainu8/events{/privacy}", "received_events_url": "https://api.github.com/users/komainu8/received_events", "type": "User", "site_admin": false }, "body": "If reference count enable, also GRN_TYPE object and GRN_EXPR object maintain lock. However, if we open many object, lock count may overflow.\r\n\r\nGRN_TYPE object and GRN_EXPR don't need to maintain lock. Because There are not target of reference count.", "created_at": "2023-06-16T03:33:36Z", "updated_at": "2023-06-16T09:03:40Z", "closed_at": null, "merged_at": null, "merge_commit_sha": "dd38812e7f27a2bdb6c7d76bb274bab863b910dd", "assignee": null, "assignees": [ ], "requested_reviewers": [ ], "requested_teams": [ ], "labels": [ ], "milestone": null, "draft": false, "commits_url": "https://api.github.com/repos/groonga/groonga/pulls/1581/commits", "review_comments_url": "https://api.github.com/repos/groonga/groonga/pulls/1581/comments", "review_comment_url": "https://api.github.com/repos/groonga/groonga/pulls/comments{/number}", "comments_url": "https://api.github.com/repos/groonga/groonga/issues/1581/comments", "statuses_url": "https://api.github.com/repos/groonga/groonga/statuses/db8dc428a0338f68b264eaf634a9b0c5ef6c07bb", "head": { "label": "groonga:release-lock-type-and-expr", "ref": "release-lock-type-and-expr", "sha": "db8dc428a0338f68b264eaf634a9b0c5ef6c07bb", "user": { "login": "groonga", "id": 46466, "node_id": "MDEyOk9yZ2FuaXphdGlvbjQ2NDY2", "avatar_url": "https://avatars.githubusercontent.com/u/46466?v=4", "gravatar_id": "", "url": "https://api.github.com/users/groonga", "html_url": "https://github.com/groonga", "followers_url": "https://api.github.com/users/groonga/followers", "following_url": "https://api.github.com/users/groonga/following{/other_user}", "gists_url": "https://api.github.com/users/groonga/gists{/gist_id}", "starred_url": "https://api.github.com/users/groonga/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/groonga/subscriptions", "organizations_url": "https://api.github.com/users/groonga/orgs", "repos_url": "https://api.github.com/users/groonga/repos", "events_url": "https://api.github.com/users/groonga/events{/privacy}", "received_events_url": "https://api.github.com/users/groonga/received_events", "type": "Organization", "site_admin": false }, "repo": { "id": 107202, "node_id": "MDEwOlJlcG9zaXRvcnkxMDcyMDI=", "name": "groonga", "full_name": "groonga/groonga", "private": false, "owner": { "login": "groonga", "id": 46466, "node_id": "MDEyOk9yZ2FuaXphdGlvbjQ2NDY2", "avatar_url": "https://avatars.githubusercontent.com/u/46466?v=4", "gravatar_id": "", "url": "https://api.github.com/users/groonga", "html_url": "https://github.com/groonga", "followers_url": "https://api.github.com/users/groonga/followers", "following_url": "https://api.github.com/users/groonga/following{/other_user}", "gists_url": "https://api.github.com/users/groonga/gists{/gist_id}", "starred_url": "https://api.github.com/users/groonga/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/groonga/subscriptions", "organizations_url": "https://api.github.com/users/groonga/orgs", "repos_url": "https://api.github.com/users/groonga/repos", "events_url": "https://api.github.com/users/groonga/events{/privacy}", "received_events_url": "https://api.github.com/users/groonga/received_events", "type": "Organization", "site_admin": false }, "html_url": "https://github.com/groonga/groonga", "description": "An embeddable fulltext search engine. Groonga is the successor project to Senna.", "fork": false, "url": "https://api.github.com/repos/groonga/groonga", "forks_url": "https://api.github.com/repos/groonga/groonga/forks", "keys_url": "https://api.github.com/repos/groonga/groonga/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/groonga/groonga/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/groonga/groonga/teams", "hooks_url": "https://api.github.com/repos/groonga/groonga/hooks", "issue_events_url": "https://api.github.com/repos/groonga/groonga/issues/events{/number}", "events_url": "https://api.github.com/repos/groonga/groonga/events", "assignees_url": "https://api.github.com/repos/groonga/groonga/assignees{/user}", "branches_url": "https://api.github.com/repos/groonga/groonga/branches{/branch}", "tags_url": "https://api.github.com/repos/groonga/groonga/tags", "blobs_url": "https://api.github.com/repos/groonga/groonga/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/groonga/groonga/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/groonga/groonga/git/refs{/sha}", "trees_url": "https://api.github.com/repos/groonga/groonga/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/groonga/groonga/statuses/{sha}", "languages_url": "https://api.github.com/repos/groonga/groonga/languages", "stargazers_url": "https://api.github.com/repos/groonga/groonga/stargazers", "contributors_url": "https://api.github.com/repos/groonga/groonga/contributors", "subscribers_url": "https://api.github.com/repos/groonga/groonga/subscribers", "subscription_url": "https://api.github.com/repos/groonga/groonga/subscription", "commits_url": "https://api.github.com/repos/groonga/groonga/commits{/sha}", "git_commits_url": "https://api.github.com/repos/groonga/groonga/git/commits{/sha}", "comments_url": "https://api.github.com/repos/groonga/groonga/comments{/number}", "issue_comment_url": "https://api.github.com/repos/groonga/groonga/issues/comments{/number}", "contents_url": "https://api.github.com/repos/groonga/groonga/contents/{+path}", "compare_url": "https://api.github.com/repos/groonga/groonga/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/groonga/groonga/merges", "archive_url": "https://api.github.com/repos/groonga/groonga/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/groonga/groonga/downloads", "issues_url": "https://api.github.com/repos/groonga/groonga/issues{/number}", "pulls_url": "https://api.github.com/repos/groonga/groonga/pulls{/number}", "milestones_url": "https://api.github.com/repos/groonga/groonga/milestones{/number}", "notifications_url": "https://api.github.com/repos/groonga/groonga/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/groonga/groonga/labels{/name}", "releases_url": "https://api.github.com/repos/groonga/groonga/releases{/id}", "deployments_url": "https://api.github.com/repos/groonga/groonga/deployments", "created_at": "2009-01-14T09:30:34Z", "updated_at": "2023-06-12T17:35:09Z", "pushed_at": "2023-06-16T08:49:51Z", "git_url": "git://github.com/groonga/groonga.git", "ssh_url": "[email protected]:groonga/groonga.git", "clone_url": "https://github.com/groonga/groonga.git", "svn_url": "https://github.com/groonga/groonga", "homepage": "https://groonga.org/", "size": 97933, "stargazers_count": 736, "watchers_count": 736, "language": "C", "has_issues": true, "has_projects": true, "has_downloads": true, "has_wiki": true, "has_pages": false, "has_discussions": true, "forks_count": 116, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 137, "license": { "key": "lgpl-2.1", "name": "GNU Lesser General Public License v2.1", "spdx_id": "LGPL-2.1", "url": "https://api.github.com/licenses/lgpl-2.1", "node_id": "MDc6TGljZW5zZTEx" }, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "topics": [ "c", "full-text-search", "groonga", "mruby", "nginx" ], "visibility": "public", "forks": 116, "open_issues": 137, "watchers": 736, "default_branch": "master", "allow_squash_merge": true, "allow_merge_commit": false, "allow_rebase_merge": false, "allow_auto_merge": true, "delete_branch_on_merge": true, "allow_update_branch": false, "use_squash_pr_title_as_default": true, "squash_merge_commit_message": "PR_BODY", "squash_merge_commit_title": "PR_TITLE", "merge_commit_message": "PR_TITLE", "merge_commit_title": "MERGE_MESSAGE" } }, "base": { "label": "groonga:master", "ref": "master", "sha": "3c2132fa2c253e7d0e81521be31c3d0905138a09", "user": { "login": "groonga", "id": 46466, "node_id": "MDEyOk9yZ2FuaXphdGlvbjQ2NDY2", "avatar_url": "https://avatars.githubusercontent.com/u/46466?v=4", "gravatar_id": "", "url": "https://api.github.com/users/groonga", "html_url": "https://github.com/groonga", "followers_url": "https://api.github.com/users/groonga/followers", "following_url": "https://api.github.com/users/groonga/following{/other_user}", "gists_url": "https://api.github.com/users/groonga/gists{/gist_id}", "starred_url": "https://api.github.com/users/groonga/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/groonga/subscriptions", "organizations_url": "https://api.github.com/users/groonga/orgs", "repos_url": "https://api.github.com/users/groonga/repos", "events_url": "https://api.github.com/users/groonga/events{/privacy}", "received_events_url": "https://api.github.com/users/groonga/received_events", "type": "Organization", "site_admin": false }, "repo": { "id": 107202, "node_id": "MDEwOlJlcG9zaXRvcnkxMDcyMDI=", "name": "groonga", "full_name": "groonga/groonga", "private": false, "owner": { "login": "groonga", "id": 46466, "node_id": "MDEyOk9yZ2FuaXphdGlvbjQ2NDY2", "avatar_url": "https://avatars.githubusercontent.com/u/46466?v=4", "gravatar_id": "", "url": "https://api.github.com/users/groonga", "html_url": "https://github.com/groonga", "followers_url": "https://api.github.com/users/groonga/followers", "following_url": "https://api.github.com/users/groonga/following{/other_user}", "gists_url": "https://api.github.com/users/groonga/gists{/gist_id}", "starred_url": "https://api.github.com/users/groonga/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/groonga/subscriptions", "organizations_url": "https://api.github.com/users/groonga/orgs", "repos_url": "https://api.github.com/users/groonga/repos", "events_url": "https://api.github.com/users/groonga/events{/privacy}", "received_events_url": "https://api.github.com/users/groonga/received_events", "type": "Organization", "site_admin": false }, "html_url": "https://github.com/groonga/groonga", "description": "An embeddable fulltext search engine. Groonga is the successor project to Senna.", "fork": false, "url": "https://api.github.com/repos/groonga/groonga", "forks_url": "https://api.github.com/repos/groonga/groonga/forks", "keys_url": "https://api.github.com/repos/groonga/groonga/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/groonga/groonga/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/groonga/groonga/teams", "hooks_url": "https://api.github.com/repos/groonga/groonga/hooks", "issue_events_url": "https://api.github.com/repos/groonga/groonga/issues/events{/number}", "events_url": "https://api.github.com/repos/groonga/groonga/events", "assignees_url": "https://api.github.com/repos/groonga/groonga/assignees{/user}", "branches_url": "https://api.github.com/repos/groonga/groonga/branches{/branch}", "tags_url": "https://api.github.com/repos/groonga/groonga/tags", "blobs_url": "https://api.github.com/repos/groonga/groonga/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/groonga/groonga/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/groonga/groonga/git/refs{/sha}", "trees_url": "https://api.github.com/repos/groonga/groonga/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/groonga/groonga/statuses/{sha}", "languages_url": "https://api.github.com/repos/groonga/groonga/languages", "stargazers_url": "https://api.github.com/repos/groonga/groonga/stargazers", "contributors_url": "https://api.github.com/repos/groonga/groonga/contributors", "subscribers_url": "https://api.github.com/repos/groonga/groonga/subscribers", "subscription_url": "https://api.github.com/repos/groonga/groonga/subscription", "commits_url": "https://api.github.com/repos/groonga/groonga/commits{/sha}", "git_commits_url": "https://api.github.com/repos/groonga/groonga/git/commits{/sha}", "comments_url": "https://api.github.com/repos/groonga/groonga/comments{/number}", "issue_comment_url": "https://api.github.com/repos/groonga/groonga/issues/comments{/number}", "contents_url": "https://api.github.com/repos/groonga/groonga/contents/{+path}", "compare_url": "https://api.github.com/repos/groonga/groonga/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/groonga/groonga/merges", "archive_url": "https://api.github.com/repos/groonga/groonga/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/groonga/groonga/downloads", "issues_url": "https://api.github.com/repos/groonga/groonga/issues{/number}", "pulls_url": "https://api.github.com/repos/groonga/groonga/pulls{/number}", "milestones_url": "https://api.github.com/repos/groonga/groonga/milestones{/number}", "notifications_url": "https://api.github.com/repos/groonga/groonga/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/groonga/groonga/labels{/name}", "releases_url": "https://api.github.com/repos/groonga/groonga/releases{/id}", "deployments_url": "https://api.github.com/repos/groonga/groonga/deployments", "created_at": "2009-01-14T09:30:34Z", "updated_at": "2023-06-12T17:35:09Z", "pushed_at": "2023-06-16T08:49:51Z", "git_url": "git://github.com/groonga/groonga.git", "ssh_url": "[email protected]:groonga/groonga.git", "clone_url": "https://github.com/groonga/groonga.git", "svn_url": "https://github.com/groonga/groonga", "homepage": "https://groonga.org/", "size": 97933, "stargazers_count": 736, "watchers_count": 736, "language": "C", "has_issues": true, "has_projects": true, "has_downloads": true, "has_wiki": true, "has_pages": false, "has_discussions": true, "forks_count": 116, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 137, "license": { "key": "lgpl-2.1", "name": "GNU Lesser General Public License v2.1", "spdx_id": "LGPL-2.1", "url": "https://api.github.com/licenses/lgpl-2.1", "node_id": "MDc6TGljZW5zZTEx" }, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "topics": [ "c", "full-text-search", "groonga", "mruby", "nginx" ], "visibility": "public", "forks": 116, "open_issues": 137, "watchers": 736, "default_branch": "master", "allow_squash_merge": true, "allow_merge_commit": false, "allow_rebase_merge": false, "allow_auto_merge": true, "delete_branch_on_merge": true, "allow_update_branch": false, "use_squash_pr_title_as_default": true, "squash_merge_commit_message": "PR_BODY", "squash_merge_commit_title": "PR_TITLE", "merge_commit_message": "PR_TITLE", "merge_commit_title": "MERGE_MESSAGE" } }, "_links": { "self": { "href": "https://api.github.com/repos/groonga/groonga/pulls/1581" }, "html": { "href": "https://github.com/groonga/groonga/pull/1581" }, "issue": { "href": "https://api.github.com/repos/groonga/groonga/issues/1581" }, "comments": { "href": "https://api.github.com/repos/groonga/groonga/issues/1581/comments" }, "review_comments": { "href": "https://api.github.com/repos/groonga/groonga/pulls/1581/comments" }, "review_comment": { "href": "https://api.github.com/repos/groonga/groonga/pulls/comments{/number}" }, "commits": { "href": "https://api.github.com/repos/groonga/groonga/pulls/1581/commits" }, "statuses": { "href": "https://api.github.com/repos/groonga/groonga/statuses/db8dc428a0338f68b264eaf634a9b0c5ef6c07bb" } }, "author_association": "MEMBER", "auto_merge": null, "active_lock_reason": null }, "repository": { "id": 107202, "node_id": "MDEwOlJlcG9zaXRvcnkxMDcyMDI=", "name": "groonga", "full_name": "groonga/groonga", "private": false, "owner": { "login": "groonga", "id": 46466, "node_id": "MDEyOk9yZ2FuaXphdGlvbjQ2NDY2", "avatar_url": "https://avatars.githubusercontent.com/u/46466?v=4", "gravatar_id": "", "url": "https://api.github.com/users/groonga", "html_url": "https://github.com/groonga", "followers_url": "https://api.github.com/users/groonga/followers", "following_url": "https://api.github.com/users/groonga/following{/other_user}", "gists_url": "https://api.github.com/users/groonga/gists{/gist_id}", "starred_url": "https://api.github.com/users/groonga/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/groonga/subscriptions", "organizations_url": "https://api.github.com/users/groonga/orgs", "repos_url": "https://api.github.com/users/groonga/repos", "events_url": "https://api.github.com/users/groonga/events{/privacy}", "received_events_url": "https://api.github.com/users/groonga/received_events", "type": "Organization", "site_admin": false }, "html_url": "https://github.com/groonga/groonga", "description": "An embeddable fulltext search engine. Groonga is the successor project to Senna.", "fork": false, "url": "https://api.github.com/repos/groonga/groonga", "forks_url": "https://api.github.com/repos/groonga/groonga/forks", "keys_url": "https://api.github.com/repos/groonga/groonga/keys{/key_id}", "collaborators_url": "https://api.github.com/repos/groonga/groonga/collaborators{/collaborator}", "teams_url": "https://api.github.com/repos/groonga/groonga/teams", "hooks_url": "https://api.github.com/repos/groonga/groonga/hooks", "issue_events_url": "https://api.github.com/repos/groonga/groonga/issues/events{/number}", "events_url": "https://api.github.com/repos/groonga/groonga/events", "assignees_url": "https://api.github.com/repos/groonga/groonga/assignees{/user}", "branches_url": "https://api.github.com/repos/groonga/groonga/branches{/branch}", "tags_url": "https://api.github.com/repos/groonga/groonga/tags", "blobs_url": "https://api.github.com/repos/groonga/groonga/git/blobs{/sha}", "git_tags_url": "https://api.github.com/repos/groonga/groonga/git/tags{/sha}", "git_refs_url": "https://api.github.com/repos/groonga/groonga/git/refs{/sha}", "trees_url": "https://api.github.com/repos/groonga/groonga/git/trees{/sha}", "statuses_url": "https://api.github.com/repos/groonga/groonga/statuses/{sha}", "languages_url": "https://api.github.com/repos/groonga/groonga/languages", "stargazers_url": "https://api.github.com/repos/groonga/groonga/stargazers", "contributors_url": "https://api.github.com/repos/groonga/groonga/contributors", "subscribers_url": "https://api.github.com/repos/groonga/groonga/subscribers", "subscription_url": "https://api.github.com/repos/groonga/groonga/subscription", "commits_url": "https://api.github.com/repos/groonga/groonga/commits{/sha}", "git_commits_url": "https://api.github.com/repos/groonga/groonga/git/commits{/sha}", "comments_url": "https://api.github.com/repos/groonga/groonga/comments{/number}", "issue_comment_url": "https://api.github.com/repos/groonga/groonga/issues/comments{/number}", "contents_url": "https://api.github.com/repos/groonga/groonga/contents/{+path}", "compare_url": "https://api.github.com/repos/groonga/groonga/compare/{base}...{head}", "merges_url": "https://api.github.com/repos/groonga/groonga/merges", "archive_url": "https://api.github.com/repos/groonga/groonga/{archive_format}{/ref}", "downloads_url": "https://api.github.com/repos/groonga/groonga/downloads", "issues_url": "https://api.github.com/repos/groonga/groonga/issues{/number}", "pulls_url": "https://api.github.com/repos/groonga/groonga/pulls{/number}", "milestones_url": "https://api.github.com/repos/groonga/groonga/milestones{/number}", "notifications_url": "https://api.github.com/repos/groonga/groonga/notifications{?since,all,participating}", "labels_url": "https://api.github.com/repos/groonga/groonga/labels{/name}", "releases_url": "https://api.github.com/repos/groonga/groonga/releases{/id}", "deployments_url": "https://api.github.com/repos/groonga/groonga/deployments", "created_at": "2009-01-14T09:30:34Z", "updated_at": "2023-06-12T17:35:09Z", "pushed_at": "2023-06-16T08:49:51Z", "git_url": "git://github.com/groonga/groonga.git", "ssh_url": "[email protected]:groonga/groonga.git", "clone_url": "https://github.com/groonga/groonga.git", "svn_url": "https://github.com/groonga/groonga", "homepage": "https://groonga.org/", "size": 97933, "stargazers_count": 736, "watchers_count": 736, "language": "C", "has_issues": true, "has_projects": true, "has_downloads": true, "has_wiki": true, "has_pages": false, "has_discussions": true, "forks_count": 116, "mirror_url": null, "archived": false, "disabled": false, "open_issues_count": 137, "license": { "key": "lgpl-2.1", "name": "GNU Lesser General Public License v2.1", "spdx_id": "LGPL-2.1", "url": "https://api.github.com/licenses/lgpl-2.1", "node_id": "MDc6TGljZW5zZTEx" }, "allow_forking": true, "is_template": false, "web_commit_signoff_required": false, "topics": [ "c", "full-text-search", "groonga", "mruby", "nginx" ], "visibility": "public", "forks": 116, "open_issues": 137, "watchers": 736, "default_branch": "master" }, "organization": { "login": "groonga", "id": 46466, "node_id": "MDEyOk9yZ2FuaXphdGlvbjQ2NDY2", "url": "https://api.github.com/orgs/groonga", "repos_url": "https://api.github.com/orgs/groonga/repos", "events_url": "https://api.github.com/orgs/groonga/events", "hooks_url": "https://api.github.com/orgs/groonga/hooks", "issues_url": "https://api.github.com/orgs/groonga/issues", "members_url": "https://api.github.com/orgs/groonga/members{/member}", "public_members_url": "https://api.github.com/orgs/groonga/public_members{/member}", "avatar_url": "https://avatars.githubusercontent.com/u/46466?v=4", "description": "" }, "sender": { "login": "kou", "id": 27350, "node_id": "MDQ6VXNlcjI3MzUw", "avatar_url": "https://avatars.githubusercontent.com/u/27350?v=4", "gravatar_id": "", "url": "https://api.github.com/users/kou", "html_url": "https://github.com/kou", "followers_url": "https://api.github.com/users/kou/followers", "following_url": "https://api.github.com/users/kou/following{/other_user}", "gists_url": "https://api.github.com/users/kou/gists{/gist_id}", "starred_url": "https://api.github.com/users/kou/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/kou/subscriptions", "organizations_url": "https://api.github.com/users/kou/orgs", "repos_url": "https://api.github.com/users/kou/repos", "events_url": "https://api.github.com/users/kou/events{/privacy}", "received_events_url": "https://api.github.com/users/kou/received_events", "type": "User", "site_admin": false } } ``` </details> If Zulip receives a `pull_request_review` event with `null` `review.body`, the following error e-mails are sent: ```text Subject: [Django] zulip: Traceback (most recent call last): Logger zerver.middleware.json_error_handler, from module zerver.middleware line 432: Error generated by GitHub Bot <[email protected]> (Member) on zulip.example.com deployment Traceback (most recent call last): File "/srv/zulip-venv-cache/91d4c5430487dabd51febcce463a8e3f8c67888e/zulip-py3-venv/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/srv/zulip-venv-cache/91d4c5430487dabd51febcce463a8e3f8c67888e/zulip-py3-venv/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) File "/home/zulip/deployments/2023-06-01-18-44-07/./zerver/lib/request.py", line 459, in _wrapped_req_func return_value = req_func(request, *args, **kwargs) File "/home/zulip/deployments/2023-06-01-18-44-07/./zerver/decorator.py", line 370, in _wrapped_func_arguments raise err File "/home/zulip/deployments/2023-06-01-18-44-07/./zerver/decorator.py", line 355, in _wrapped_func_arguments return view_func(request, user_profile, *args, **kwargs) File "/home/zulip/deployments/2023-06-01-18-44-07/./zerver/lib/request.py", line 459, in _wrapped_req_func return_value = req_func(request, *args, **kwargs) File "/home/zulip/deployments/2023-06-01-18-44-07/./zerver/webhooks/github/view.py", line 800, in api_github_webhook body = body_function(helper) File "/home/zulip/deployments/2023-06-01-18-44-07/./zerver/webhooks/github/view.py", line 504, in get_pull_request_review_body message=payload["review"]["body"].tame(check_string), File "/home/zulip/deployments/2023-06-01-18-44-07/./zerver/lib/validator.py", line 682, in tame return validator(self.var_name, self.value) File "/home/zulip/deployments/2023-06-01-18-44-07/./zerver/lib/validator.py", line 76, in check_string raise ValidationError(_("{var_name} is not a string").format(var_name=var_name)) django.core.exceptions.ValidationError: ["request['review']['body'] is not a string"] Deployed code: - git: None - ZULIP_VERSION: 7.0 Request info: - path: /api/v1/external/github - POST: {} - REMOTE_ADDR: "..." - QUERY_STRING: "..." - SERVER_NAME: "" ``` ```text Subject: [Django] zulip: Internal Server Error: /api/v1/external/github Logger django.request, from module django.utils.log line 241: Error generated by GitHub Bot <[email protected]> (Member) on zulip.example.com deployment No stack trace available Deployed code: - git: None - ZULIP_VERSION: 7.0 Request info: - path: /api/v1/external/github - POST: {} - REMOTE_ADDR: "..." - QUERY_STRING: "..." - SERVER_NAME: "" ``` **Zulip Server and web app version:** - [ ] Zulip Cloud (`*.zulipchat.com`) - [x] Zulip Server 7.0+ - [ ] Zulip Server 6.0+ - [ ] Zulip Server 5.0 or older - [ ] Other or not sure
Hello @zulip/server-integrations members, this issue was labeled with the "area: integrations" label, so you may want to check it out! <!-- areaLabelAddition --> @sbansal1999 - Mentioning you here because I recall that you've been doing some work related to the Github integrations recently. @laurynmm Thanks for mentioning me. You are right I have been doing some work related to the GitHub Integration. Coming on to this issue, I think adding a check for null using `check_none_or(check_string)` should work, also I will go on and add a fixture to make sure this behavior is tested as well. I will create a PR shortly for this one. Thanks for reporting the bug @kou. @zulipbot claim Hello @sbansal1999! Thanks for your interest in Zulip! You have attempted to claim an issue without the label "help wanted". You can only claim and submit pull requests for issues with the [help wanted](https://github.com/zulip/zulip/issues?q=is%3Aopen+is%3Aissue+no%3Aassignee+label%3A%22help+wanted%22) label. If this is your first time here, we recommend reading our [guide for new contributors](https://zulip.readthedocs.io/en/latest/overview/contributing.html) before getting started.
2023-06-21T17:25:41
zulip/zulip
26,092
zulip__zulip-26092
[ "24669" ]
784622ee5d3e5bca4db9ebafba748acd797b427d
diff --git a/zerver/lib/markdown/tabbed_sections.py b/zerver/lib/markdown/tabbed_sections.py --- a/zerver/lib/markdown/tabbed_sections.py +++ b/zerver/lib/markdown/tabbed_sections.py @@ -27,11 +27,11 @@ """.strip() NAV_LIST_ITEM_TEMPLATE = """ -<li data-language="{data_language}" tabindex="0">{label}</li> +<li data-tab-key="{data_tab_key}" tabindex="0">{label}</li> """.strip() DIV_TAB_CONTENT_TEMPLATE = """ -<div data-language="{data_language}" markdown="1"> +<div data-tab-key="{data_tab_key}" markdown="1"> {content} </div> """.strip() @@ -125,7 +125,7 @@ def run(self, lines: List[str]) -> List[str]: tab_class = "no-tabs" tab_section["tabs"] = [ { - "tab_name": "instructions-for-all-platforms", + "tab_key": "instructions-for-all-platforms", "start": tab_section["start_tabs_index"], } ] @@ -155,7 +155,7 @@ def generate_content_blocks(self, tab_section: Dict[str, Any], lines: List[str]) content = "\n".join(lines[start_index:end_index]).strip() tab_content_block = DIV_TAB_CONTENT_TEMPLATE.format( - data_language=tab["tab_name"], + data_tab_key=tab["tab_key"], # Wrapping the content in two newlines is necessary here. # If we don't do this, the inner Markdown does not get # rendered properly. @@ -167,14 +167,14 @@ def generate_content_blocks(self, tab_section: Dict[str, Any], lines: List[str]) def generate_nav_bar(self, tab_section: Dict[str, Any]) -> str: li_elements = [] for tab in tab_section["tabs"]: - tab_name = tab.get("tab_name") - tab_label = TAB_SECTION_LABELS.get(tab_name) + tab_key = tab.get("tab_key") + tab_label = TAB_SECTION_LABELS.get(tab_key) if tab_label is None: raise ValueError( - f"Tab '{tab_name}' is not present in TAB_SECTION_LABELS in zerver/lib/markdown/tabbed_sections.py" + f"Tab '{tab_key}' is not present in TAB_SECTION_LABELS in zerver/lib/markdown/tabbed_sections.py" ) - li = NAV_LIST_ITEM_TEMPLATE.format(data_language=tab_name, label=tab_label) + li = NAV_LIST_ITEM_TEMPLATE.format(data_tab_key=tab_key, label=tab_label) li_elements.append(li) return NAV_BAR_TEMPLATE.format(tabs="\n".join(li_elements)) @@ -189,7 +189,7 @@ def parse_tabs(self, lines: List[str]) -> Optional[Dict[str, Any]]: tab_content_match = TAB_CONTENT_REGEX.search(line) if tab_content_match: block.setdefault("tabs", []) - tab = {"start": index, "tab_name": tab_content_match.group(1)} + tab = {"start": index, "tab_key": tab_content_match.group(1)} block["tabs"].append(tab) end_match = END_TABBED_SECTION_REGEX.search(line)
diff --git a/zerver/tests/test_templates.py b/zerver/tests/test_templates.py --- a/zerver/tests/test_templates.py +++ b/zerver/tests/test_templates.py @@ -38,14 +38,14 @@ def test_markdown_tabbed_sections_extension(self) -> None: <p> <div class="code-section has-tabs" markdown="1"> <ul class="nav"> - <li data-language="ios" tabindex="0">iOS</li> - <li data-language="desktop-web" tabindex="0">Desktop/Web</li> + <li data-tab-key="ios" tabindex="0">iOS</li> + <li data-tab-key="desktop-web" tabindex="0">Desktop/Web</li> </ul> <div class="blocks"> - <div data-language="ios" markdown="1"></p> + <div data-tab-key="ios" markdown="1"></p> <p>iOS instructions</p> <p></div> - <div data-language="desktop-web" markdown="1"></p> + <div data-tab-key="desktop-web" markdown="1"></p> <p>Desktop/browser instructions</p> <p></div> </div> @@ -56,14 +56,14 @@ def test_markdown_tabbed_sections_extension(self) -> None: <p> <div class="code-section has-tabs" markdown="1"> <ul class="nav"> - <li data-language="desktop-web" tabindex="0">Desktop/Web</li> - <li data-language="android" tabindex="0">Android</li> + <li data-tab-key="desktop-web" tabindex="0">Desktop/Web</li> + <li data-tab-key="android" tabindex="0">Android</li> </ul> <div class="blocks"> - <div data-language="desktop-web" markdown="1"></p> + <div data-tab-key="desktop-web" markdown="1"></p> <p>Desktop/browser instructions</p> <p></div> - <div data-language="android" markdown="1"></p> + <div data-tab-key="android" markdown="1"></p> <p>Android instructions</p> <p></div> </div> @@ -74,10 +74,10 @@ def test_markdown_tabbed_sections_extension(self) -> None: <p> <div class="code-section no-tabs" markdown="1"> <ul class="nav"> - <li data-language="instructions-for-all-platforms" tabindex="0">Instructions for all platforms</li> + <li data-tab-key="instructions-for-all-platforms" tabindex="0">Instructions for all platforms</li> </ul> <div class="blocks"> - <div data-language="instructions-for-all-platforms" markdown="1"></p> + <div data-tab-key="instructions-for-all-platforms" markdown="1"></p> <p>Instructions for all platforms</p> <p></div> </div>
The `tabbed_instructions.js` variable name `language` is super confusing As discovered in https://github.com/zulip/zulip/pull/24655#issuecomment-1466799308, the `tabbed_instructions` widget used for both language toggles in our API documentation and app toggles in our Help Center documentation (`git grep 'tab\|mobile'`) misleadingly calls the identifier for the tab `language` in local variables and its interface. We should rename that to something like `tab_key` or `tab_section`, which requires changes both in that file and the `zerver/lib/markdown/tabbed_sections.py` code that generates them. (I see the latter file uses `tab_name` to refer to that, which probably isn't nearly as good as something like `tab_key`. @andersk FYI in case you want to suggest we delay addressing this, since you may be in the process of rewriting `tabbed_sections.py`? See `tabbed-instructions.ts` for details.
Hello @zulip/server-api, @zulip/server-refactoring, @zulip/server-user-docs members, this issue was labeled with the "area: refactoring", "area: documentation (user)", "area: documentation (api and integrations)" labels, so you may want to check it out! <!-- areaLabelAddition --> hey, I want to work on this can anyone plz guide me @imlakshaykumar please read our community guidelines before asking to claim an issue. Hello! I would like to work on this issue. Are we simply changing all `language` in `zulip/web/src/portico/tabbed-instructions.ts` and all `tab_name` in `zerver/lib/markdown/tabbed_sections.py` into `tab_key`? @zulipbot claim Welcome to Zulip, @sivangbagri! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @zulipbot @timabbott I have successfully made the PR solving this issue @sivangbagri You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! @sivangbagri Your PR title and commit messages are not following our commit guidelines. Please see https://zulip.readthedocs.io/en/latest/contributing/commit-discipline.html#commit-messages I have made all the necessary changes keeping in mind all the guidelines Here is the corresponding PR https://github.com/zulip/zulip/pull/24760 @andersk @drrosa @zulipbot @zulipbot claim @Deekshith-S-Shetty You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks!
2023-06-22T02:17:44
zulip/zulip
26,159
zulip__zulip-26159
[ "25793" ]
f00dcf5674153ef1639241eaf0d063a3a2d78521
diff --git a/zerver/lib/webhooks/git.py b/zerver/lib/webhooks/git.py --- a/zerver/lib/webhooks/git.py +++ b/zerver/lib/webhooks/git.py @@ -55,6 +55,9 @@ ) ISSUE_LABELED_OR_UNLABELED_MESSAGE_TEMPLATE_WITH_TITLE = "[{user_name}]({user_url}) {action} the {label_name} label {preposition} [Issue #{id} {title}]({url})." +ISSUE_MILESTONED_OR_DEMILESTONED_MESSAGE_TEMPLATE = "[{user_name}]({user_url}) {action} milestone [{milestone_name}]({milestone_url}) {preposition} [issue #{id}]({url})." +ISSUE_MILESTONED_OR_DEMILESTONED_MESSAGE_TEMPLATE_WITH_TITLE = "[{user_name}]({user_url}) {action} milestone [{milestone_name}]({milestone_url}) {preposition} [issue #{id} {title}]({url})." + PULL_REQUEST_OR_ISSUE_MESSAGE_TEMPLATE = "{user_name} {action} [{type}{id}]({url})" PULL_REQUEST_OR_ISSUE_MESSAGE_TEMPLATE_WITH_TITLE = ( "{user_name} {action} [{type}{id} {title}]({url})" @@ -302,6 +305,32 @@ def get_issue_labeled_or_unlabeled_event_message( return ISSUE_LABELED_OR_UNLABELED_MESSAGE_TEMPLATE.format(**args) +def get_issue_milestoned_or_demilestoned_event_message( + user_name: str, + action: str, + url: str, + number: int, + milestone_name: str, + milestone_url: str, + user_url: str, + title: Optional[str] = None, +) -> str: + args = { + "user_name": user_name, + "action": action, + "url": url, + "id": number, + "milestone_name": milestone_name, + "milestone_url": milestone_url, + "user_url": user_url, + "title": title, + "preposition": "to" if action == "added" else "from", + } + if title is not None: + return ISSUE_MILESTONED_OR_DEMILESTONED_MESSAGE_TEMPLATE_WITH_TITLE.format(**args) + return ISSUE_MILESTONED_OR_DEMILESTONED_MESSAGE_TEMPLATE.format(**args) + + def get_push_tag_event_message( user_name: str, tag_name: str, tag_url: Optional[str] = None, action: str = "pushed" ) -> str: diff --git a/zerver/webhooks/github/view.py b/zerver/webhooks/github/view.py --- a/zerver/webhooks/github/view.py +++ b/zerver/webhooks/github/view.py @@ -29,6 +29,7 @@ get_commits_comment_action_message, get_issue_event_message, get_issue_labeled_or_unlabeled_event_message, + get_issue_milestoned_or_demilestoned_event_message, get_pull_request_event_message, get_push_commits_event_message, get_push_tag_event_message, @@ -221,6 +222,23 @@ def get_issue_labeled_or_unlabeled_body(helper: Helper) -> str: ) +def get_issue_milestoned_or_demilestoned_body(helper: Helper) -> str: + payload = helper.payload + include_title = helper.include_title + issue = payload["issue"] + + return get_issue_milestoned_or_demilestoned_event_message( + user_name=get_sender_name(payload), + action="added" if payload["action"].tame(check_string) == "milestoned" else "removed", + url=issue["html_url"].tame(check_string), + number=issue["number"].tame(check_int), + milestone_name=payload["milestone"]["title"].tame(check_string), + milestone_url=payload["milestone"]["html_url"].tame(check_string), + user_url=get_sender_url(payload), + title=issue["title"].tame(check_string) if include_title else None, + ) + + def get_fork_body(helper: Helper) -> str: payload = helper.payload forkee = payload["forkee"] @@ -728,6 +746,7 @@ def get_subject_based_on_type(payload: WildValue, event: str) -> str: "gollum": get_wiki_pages_body, "issue_comment": get_issue_comment_body, "issue_labeled_or_unlabeled": get_issue_labeled_or_unlabeled_body, + "issue_milestoned_or_demilestoned": get_issue_milestoned_or_demilestoned_body, "issues": get_issue_body, "member": get_member_body, "membership": get_membership_body, @@ -884,6 +903,8 @@ def get_zulip_event_name( action = payload["action"].tame(check_string) if action in ("labeled", "unlabeled"): return "issue_labeled_or_unlabeled" + if action in ("milestoned", "demilestoned"): + return "issue_milestoned_or_demilestoned" else: return "issues" elif header_event in list(EVENT_FUNCTION_MAPPER.keys()):
diff --git a/zerver/webhooks/github/tests.py b/zerver/webhooks/github/tests.py --- a/zerver/webhooks/github/tests.py +++ b/zerver/webhooks/github/tests.py @@ -193,6 +193,25 @@ def test_issue_unlabeled(self) -> None: expected_message = "[sbansal1999](https://github.com/sbansal1999) removed the bug label from [Issue #9](https://github.com/sbansal1999/testing-gh/issues/9)." self.check_webhook("issues__unlabeled", expected_topic, expected_message) + def test_issue_milestoned(self) -> None: + expected_topic = "testing-gh / issue #6 This is a sample issue to test GH I..." + expected_message = "[sbansal1999](https://github.com/sbansal1999) added milestone [some_random_milestone](https://github.com/sbansal1999/testing-gh/milestone/1) to [issue #6](https://github.com/sbansal1999/testing-gh/issues/6)." + + self.check_webhook("issues__milestoned", expected_topic, expected_message) + + def test_issue_milestoned_with_custom_topic_in_url(self) -> None: + self.url = self.build_webhook_url(topic="notifications") + expected_topic = "notifications" + expected_message = "[sbansal1999](https://github.com/sbansal1999) added milestone [some_random_milestone](https://github.com/sbansal1999/testing-gh/milestone/1) to [issue #6 This is a sample issue to test GH Integration Func](https://github.com/sbansal1999/testing-gh/issues/6)." + + self.check_webhook("issues__milestoned", expected_topic, expected_message) + + def test_issue_demilestoned(self) -> None: + expected_topic = "testing-gh / issue #6 This is a sample issue to test GH I..." + expected_message = "[sbansal1999](https://github.com/sbansal1999) removed milestone [some_random_milestone](https://github.com/sbansal1999/testing-gh/milestone/1) from [issue #6](https://github.com/sbansal1999/testing-gh/issues/6)." + + self.check_webhook("issues__demilestoned", expected_topic, expected_message) + def test_membership_msg(self) -> None: expected_message = ( "baxterthehacker added [kdaigle](https://github.com/kdaigle) to the Contractors team."
Exclude milestone events in GitHub integration (at least optionally) This is a very similar story to: * #25789 Basically all the same facts and reasons apply: * [Here's](https://chat.zulip.org/#narrow/stream/243-mobile-team/topic/zulip-flutter/near/1578205) the start of a ton of spam from this event type. * Like label/unlabel events, milestone events are liable to be quite spammy because one naturally has one of them just when creating an issue, and may often have bursts of lots of them when doing triage. * Like label/unlabel events, we know that zero people today are actually relying on these, because the existing messages we show are completely useless in the same way: they repeat the entire issue description, but don't mention the specific milestone that was set.
Hello @zulip/server-integrations members, this issue was labeled with the "area: integrations" label, so you may want to check it out! <!-- areaLabelAddition -->
2023-06-30T08:32:34
zulip/zulip
26,200
zulip__zulip-26200
[ "26186" ]
233b4866187f42c5606f52d9645ee9a62f554aa0
diff --git a/zerver/lib/markdown/__init__.py b/zerver/lib/markdown/__init__.py --- a/zerver/lib/markdown/__init__.py +++ b/zerver/lib/markdown/__init__.py @@ -1130,15 +1130,15 @@ def find_proper_insertion_index( return insertion_index uncle = grandparent[insertion_index] - inline_image_classes = [ + inline_image_classes = { "message_inline_image", "message_inline_ref", "inline-preview-twitter", - ] + } if ( uncle.tag != "div" or "class" not in uncle.keys() - or uncle.attrib["class"] not in inline_image_classes + or not (set(uncle.attrib["class"].split()) & inline_image_classes) ): return insertion_index
diff --git a/zerver/tests/test_markdown.py b/zerver/tests/test_markdown.py --- a/zerver/tests/test_markdown.py +++ b/zerver/tests/test_markdown.py @@ -933,6 +933,14 @@ def test_inline_youtube_preview(self) -> None: f"""<p><a href="https://www.youtube.com/watch?v=0c46YHS3RY8">https://www.youtube.com/watch?v=0c46YHS3RY8</a></p>\n<div class="youtube-video message_inline_image"><a data-id="0c46YHS3RY8" href="https://www.youtube.com/watch?v=0c46YHS3RY8"><img src="{get_camo_url("https://i.ytimg.com/vi/0c46YHS3RY8/default.jpg")}"></a></div><p>Sample text</p>\n<p><a href="https://www.youtube.com/watch?v=lXFO2ULktEI">https://www.youtube.com/watch?v=lXFO2ULktEI</a></p>\n<div class="youtube-video message_inline_image"><a data-id="lXFO2ULktEI" href="https://www.youtube.com/watch?v=lXFO2ULktEI"><img src="{get_camo_url("https://i.ytimg.com/vi/lXFO2ULktEI/default.jpg")}"></a></div>""", ) + # Test order of YouTube inline previews in same paragraph. + msg = "https://www.youtube.com/watch?v=0c46YHS3RY8\nhttps://www.youtube.com/watch?v=lXFO2ULktEI" + converted = markdown_convert_wrapper(msg) + self.assertEqual( + converted, + f"""<p><a href="https://www.youtube.com/watch?v=0c46YHS3RY8">https://www.youtube.com/watch?v=0c46YHS3RY8</a><br>\n<a href="https://www.youtube.com/watch?v=lXFO2ULktEI">https://www.youtube.com/watch?v=lXFO2ULktEI</a></p>\n<div class="youtube-video message_inline_image"><a data-id="0c46YHS3RY8" href="https://www.youtube.com/watch?v=0c46YHS3RY8"><img src="{get_camo_url("https://i.ytimg.com/vi/0c46YHS3RY8/default.jpg")}"></a></div><div class="youtube-video message_inline_image"><a data-id="lXFO2ULktEI" href="https://www.youtube.com/watch?v=lXFO2ULktEI"><img src="{get_camo_url("https://i.ytimg.com/vi/lXFO2ULktEI/default.jpg")}"></a></div>""", + ) + def test_twitter_id_extraction(self) -> None: self.assertEqual( get_tweet_id("http://twitter.com/#!/VizzQuotes/status/409030735191097344"),
Video embed previews are displayed in the wrong order (reversed) ![image](https://github.com/zulip/zulip/assets/11392207/d6f815b8-31a1-4cf5-870e-ddecc6e77be6) Video embeds are displayed in the wrong order, the first linked video is displayed last, the second one second last, etc. I'd expect these to be displayed in the same order in which they are linked to in the message. **Zulip Server and web app version:** - [x] Zulip Cloud (`*.zulipchat.com`) - [ ] Zulip Server 7.0+ - [ ] Zulip Server 6.0+ - [ ] Zulip Server 5.0 or older - [ ] Other or not sure
@void4 - Thanks for the report! Question are the video preview links from the screenshot above all from YouTube? Or another source? Yes, they are all from YouTube Started a conversation about the issue in the Zulip development community here for more visibility: https://chat.zulip.org/#narrow/stream/9-issues/topic/Youtube.20inline.20previews.20in.20reverse.20order.2C.20.2326186/near/1604282. Thank you :)
2023-07-06T14:51:42
zulip/zulip
26,231
zulip__zulip-26231
[ "26173" ]
88b200c298d66fcb8a9e437d4670e568c10d9032
diff --git a/zerver/webhooks/sentry/view.py b/zerver/webhooks/sentry/view.py --- a/zerver/webhooks/sentry/view.py +++ b/zerver/webhooks/sentry/view.py @@ -81,6 +81,15 @@ } +def is_sample_event(event: Dict[str, Any]) -> bool: + # This is just a heuristic to detect the sample event, this should + # not be used for making important behavior decisions. + title = event.get("title", "") + if title == "This is an example Python exception": + return True + return False + + def convert_lines_to_traceback_string(lines: Optional[List[str]]) -> str: traceback = "" if lines is not None: @@ -103,12 +112,10 @@ def handle_event_payload(event: Dict[str, Any]) -> Tuple[str, str]: # We shouldn't support the officially deprecated Raven series of # Python SDKs. - if platform_name == "python" and int(event["version"]) < 7: + if platform_name == "python" and int(event["version"]) < 7 and not is_sample_event(event): # The sample event is still an old "version" -- accept it even # though we don't accept events from the old Python SDK. - tags = event.get("tags", []) - if ["sample_event", "yes"] not in tags: - raise UnsupportedWebhookEventTypeError("Raven SDK") + raise UnsupportedWebhookEventTypeError("Raven SDK") context = { "title": subject, "level": event["level"],
diff --git a/zerver/webhooks/sentry/tests.py b/zerver/webhooks/sentry/tests.py --- a/zerver/webhooks/sentry/tests.py +++ b/zerver/webhooks/sentry/tests.py @@ -251,7 +251,7 @@ def test_deprecated_exception_message(self) -> None: ```""" self.check_webhook("deprecated_exception_message", expected_topic, expected_message) - def test_sample_event(self) -> None: + def test_sample_event_through_alert(self) -> None: expected_topic = "This is an example Python exception" expected_message = """\ **New message event:** [This is an example Python exception](https://sentry.io/organizations/nitk-46/issues/4218258981/events/b6eff1a49b1f4132850b1238d968da70/) @@ -259,4 +259,27 @@ def test_sample_event(self) -> None: **level:** error **timestamp:** 2023-05-31 11:06:16 ```""" - self.check_webhook("sample_event", expected_topic, expected_message) + self.check_webhook("sample_event_through_alert", expected_topic, expected_message) + + def test_sample_event_through_plugin(self) -> None: + expected_topic = "This is an example Python exception" + expected_message = """\ +**New message event:** [This is an example Python exception](https://nitk-46.sentry.io/issues/4218258981/events/4dc4fc2858aa450eb658be9e5b8ad149/) +```quote +**level:** error +**timestamp:** 2023-07-09 20:41:24 +```""" + self.check_webhook("sample_event_through_plugin", expected_topic, expected_message) + + def test_raven_sdk_python_event(self) -> None: + payload = self.get_body("raven_sdk_python_event") + result = self.client_post( + self.url, + payload, + content_type="application/json", + ) + self.assert_json_success(result) + self.assert_in_response( + "The 'Raven SDK' event isn't currently supported by the Sentry webhook; ignoring", + result, + )
Sentry integration "Test Plugin" failure Hello, I'm setting up Sentry.io integration and got this error when I tried "Test Plugin" (meaning "Test Outgoing Webhook to Zulip"); I'm assuming it's the response payload that came back from Zulip Cloud: >"There was an internal error with the Plugin, {\"result\":\"error\",\"msg\":\"The 'Raven SDK' event isn't currently supported by the Sentry webhook\",\"webhook_name\":\"Sentry\",\"event_type\":\"Raven SDK\",\"code\":\"UNSUPPORTED_WEBHOOK_EVENT_TYPE\"}\n" I'm not sure if there are any events that do work because I'm new to Sentry and not sure how to trigger test events other than the Test Plugin event. **Zulip Server and web app version:** - [x] Zulip Cloud (`*.zulipchat.com`) - [ ] Zulip Server 7.0+ - [ ] Zulip Server 6.0+ - [ ] Zulip Server 5.0 or older - [ ] Other or not sure
@zulipbot add "area: integrations" Hello @zulip/server-integrations members, this issue was labeled with the "area: integrations" label, so you may want to check it out! <!-- areaLabelAddition --> @aryairani Thanks for reporting this issue. This issue was recently fixed in 16563a321. I tried to reproduce this by pressing the **Send Test Notification** button while creating an alert rule and a notification was received as expected. I also inspected the received webhook and all seems to be alright. Can you confirm if you are creating an "Alert Rule" as mentioned in the [documentation](https://zulip.com/integrations/doc/sentry)? Hi @sbansal1999, This is under `https://<myorg>.sentry.io/settings/projects/<myproj>/plugins/webhooks/` Pressing [Test Plugin], with Callback Url `https://<myzulip>.zulipchat.com/api/v1/external/sentry?api_key=<mykey>&stream=<mystream>` Is this expected to work? I'm working on getting permission to "Create New Integration"; fwiw the don't currently have permissions to create a custom integration for the whole org, I'm "only" admin for the project. The webhook also appears under` https://<myorg>.sentry.io/settings/projects/<myproj>/alerts/`. Is this also not right? Ok thanks! Alright, I guess I got it sorted out, thanks for the hint. I wonder if it might be worthwhile to add to a note that the Sentry Webhook integration is not the right way to configure Sentry alerts via Webhook to Zulip? @aryairani Our [Sentry documentation](https://zulip.com/integrations/doc/sentry) says: >NOTE: Zulip also supports configuring this as a webhook in Sentry — which, while easier to configure (Navigate to Settings > Integrations > WebHooks) may not include the full breadth of event types. I tried creating a webhook using the `Integrations` list -- as you did. I was able to trigger issues on my sample project and then the events resulted in correct messages being sent by the bot. But as you pointed out when testing it by using the "Test Plugin" button it returns an error. So practically speaking, the webhook will still be able to receive events related to issues but won't respond to the test The only problematic thing here is that Sentry doesn't explicitly mention its condition for the sample event; hence making it difficult to identify them. So, I don't think there is a need to delete this from the documentation. I see, sorry I missed that. Fwiw I find the integration docs to have a bit of a "wall of text" vibe, which makes it hard to follow (not just the Sentry integration docs); but I'm not a designer myself so I don't have any concrete suggestions on that front. Thanks for your help! Should I close the ticket? #25976 is actively being worked on, which should help address the big block of text in various integrations documentation pages for generating the URL. But until that's done, I don't think there's much to be done about that block of text in step 2. I did a little revision pass of the Sentry specific instructions (steps 3 and 4), and have #26224 up with an updated version of the current documentation that breaks up that text a bit and emphasized that warning/note about the alternative implementation via Sentry webhook.
2023-07-10T20:46:37
zulip/zulip
26,236
zulip__zulip-26236
[ "601" ]
0c656731ac306563ce5ccee69f9b506a07fa4ed9
diff --git a/zerver/actions/streams.py b/zerver/actions/streams.py --- a/zerver/actions/streams.py +++ b/zerver/actions/streams.py @@ -6,6 +6,7 @@ import orjson from django.conf import settings from django.db import transaction +from django.db.models import Q, QuerySet from django.utils.timezone import now as timezone_now from django.utils.translation import gettext as _ from django.utils.translation import override as override_language @@ -131,6 +132,105 @@ def do_deactivate_stream(stream: Stream, *, acting_user: Optional[UserProfile]) ) +def deactivated_streams_by_old_name(realm: Realm, stream_name: str) -> QuerySet[Stream]: + fixed_length_prefix = ".......!DEACTIVATED:" + truncated_name = stream_name[0 : Stream.MAX_NAME_LENGTH - len(fixed_length_prefix)] + + old_names: List[str] = [] + for bang_length in range(1, 21): + name = "!" * bang_length + "DEACTIVATED:" + stream_name + old_names.append(name[0 : Stream.MAX_NAME_LENGTH]) + + possible_streams = Stream.objects.filter(realm=realm, deactivated=True).filter( + # We go looking for names as they are post-1b6f68bb59dc; 8 + # characters, followed by `!DEACTIVATED:`, followed by at + # most MAX_NAME_LENGTH-(length of the prefix) of the name + # they provided: + Q(name__regex=rf"^{fixed_length_prefix}{truncated_name}") + # Finally, we go looking for the pre-1b6f68bb59dc version, + # which is any number of `!` followed by `DEACTIVATED:` + # and a prefix of the old stream name + | Q(name__in=old_names), + ) + + return possible_streams + + [email protected](savepoint=False) +def do_reactivate_stream( + stream: Stream, new_name: str, *, acting_user: Optional[UserProfile] +) -> None: + realm = stream.realm + if not stream.deactivated: + raise JsonableError(_("Stream is not currently deactivated")) + if Stream.objects.filter(realm=realm, name=new_name).exists(): + raise JsonableError( + _("Stream named {stream_name} already exists").format(stream_name=new_name) + ) + assert stream.recipient_id is not None + + stream.deactivated = False + stream.name = new_name + + # We only set invite_only=True during deactivation, which can lead + # to the invalid state of to invite-only but also web-public + # streams. Explicitly reset the access; we do not use + # do_change_stream_permission because no users need be notified, + # and it cannot handle the broken state that may currently exist. + stream.is_web_public = False + stream.invite_only = True + stream.history_public_to_subscribers = True + stream.save( + update_fields=[ + "name", + "deactivated", + "is_web_public", + "invite_only", + "history_public_to_subscribers", + ] + ) + + # Update caches + cache_set(display_recipient_cache_key(stream.recipient_id), new_name) + messages = Message.objects.filter(recipient_id=stream.recipient_id).only("id") + cache_delete_many(to_dict_cache_key_id(message.id) for message in messages) + + # Unset the is_web_public cache on attachments, since the stream is now private. + Attachment.objects.filter(messages__recipient_id=stream.recipient_id).update(is_web_public=None) + ArchivedAttachment.objects.filter(messages__recipient_id=stream.recipient_id).update( + is_web_public=None + ) + + RealmAuditLog.objects.create( + realm=realm, + acting_user=acting_user, + modified_stream=stream, + event_type=RealmAuditLog.STREAM_REACTIVATED, + event_time=timezone_now(), + ) + + # All admins always get to know about private streams' existence, + # but we only subscribe the realm owners. + send_stream_creation_event( + realm, stream, [user.id for user in realm.get_admin_users_and_bots()] + ) + bulk_add_subscriptions( + realm=realm, + streams=[stream], + users=realm.get_human_owner_users(), + acting_user=acting_user, + ) + + sender = get_system_bot(settings.NOTIFICATION_BOT, stream.realm_id) + with override_language(stream.realm.default_language): + internal_send_stream_message( + sender, + stream, + str(Realm.STREAM_EVENTS_NOTIFICATION_TOPIC), + _("Stream {stream_name} un-archived.").format(stream_name=new_name), + ) + + def bulk_delete_cache_keys(message_ids_to_clear: List[int]) -> None: while len(message_ids_to_clear) > 0: batch = message_ids_to_clear[0:5000] diff --git a/zerver/management/commands/reactivate_stream.py b/zerver/management/commands/reactivate_stream.py new file mode 100644 --- /dev/null +++ b/zerver/management/commands/reactivate_stream.py @@ -0,0 +1,91 @@ +from argparse import ArgumentParser +from typing import Any, Optional + +from django.core.management.base import CommandError + +from zerver.actions.streams import deactivated_streams_by_old_name, do_reactivate_stream +from zerver.lib.management import ZulipBaseCommand +from zerver.models import RealmAuditLog, Stream + + +class Command(ZulipBaseCommand): + help = """Reactivate a stream that was deactivated.""" + + def add_arguments(self, parser: ArgumentParser) -> None: + specify_stream = parser.add_mutually_exclusive_group(required=True) + specify_stream.add_argument( + "-s", + "--stream", + help="Name of a deactivated stream in the realm.", + ) + specify_stream.add_argument( + "--stream-id", + help="ID of a deactivated stream in the realm.", + ) + parser.add_argument( + "-n", + "--new-name", + required=False, + help="Name to reactivate as; defaults to the old name.", + ) + self.add_realm_args(parser, required=True) + + def handle(self, *args: Any, **options: Optional[str]) -> None: + realm = self.get_realm(options) + assert realm is not None # Should be ensured by parser + + # Looking up the stream is complicated, since they get renamed + # when they are deactivated, in a transformation which may be + # lossy. + + if options["stream_id"] is not None: + stream = Stream.objects.get(id=options["stream_id"]) + if not stream.deactivated: + raise CommandError( + f"Stream id {stream.id}, named '{stream.name}', is not deactivated" + ) + if options["new_name"] is None: + raise CommandError("--new-name flag is required with --stream-id") + new_name = options["new_name"] + else: + stream_name = options["stream"] + assert stream_name is not None + + possible_streams = deactivated_streams_by_old_name(realm, stream_name) + if len(possible_streams) == 0: + raise CommandError("No matching deactivated streams found!") + + if len(possible_streams) > 1: + # Print ids of all possible streams, support passing by id + print("Matching streams:") + for stream in possible_streams: + last_deactivation = ( + RealmAuditLog.objects.filter( + realm=realm, + modified_stream=stream, + event_type=RealmAuditLog.STREAM_DEACTIVATED, + ) + .order_by("-id") + .first() + ) + assert last_deactivation is not None + print( + f" ({stream.id}) {stream.name}, deactivated on {last_deactivation.event_time}" + ) + raise CommandError( + "More than one matching stream found! Specify which with --stream-id" + ) + + stream = possible_streams[0] + if options["new_name"] is not None: + new_name = options["new_name"] + else: + new_name = stream_name + + if Stream.objects.filter(realm=realm, name=new_name).exists(): + raise CommandError( + f"Stream with name '{new_name}' already exists; pass a different --new-name" + ) + + assert stream is not None + do_reactivate_stream(stream, new_name, acting_user=None)
diff --git a/zerver/tests/test_subs.py b/zerver/tests/test_subs.py --- a/zerver/tests/test_subs.py +++ b/zerver/tests/test_subs.py @@ -28,9 +28,11 @@ from zerver.actions.streams import ( bulk_add_subscriptions, bulk_remove_subscriptions, + deactivated_streams_by_old_name, do_change_stream_group_based_setting, do_change_stream_post_policy, do_deactivate_stream, + do_reactivate_stream, ) from zerver.actions.user_groups import add_subgroups_to_user_group, check_add_user_group from zerver.actions.users import do_change_user_role, do_deactivate_user @@ -1334,6 +1336,95 @@ def test_deactivate_stream_marks_messages_as_read(self) -> None: self.assertTrue(new_stream_usermessage.flags.read) self.assertFalse(denmark_usermessage.flags.read) + def test_deactivated_streams_by_old_name(self) -> None: + realm = get_realm("zulip") + stream = self.make_stream("new_stream") + do_deactivate_stream(stream, acting_user=None) + self.assertEqual(set(deactivated_streams_by_old_name(realm, "new_stream")), {stream}) + + second_stream = self.make_stream("new_stream") + do_deactivate_stream(second_stream, acting_user=None) + self.assertEqual( + set(deactivated_streams_by_old_name(realm, "new_stream")), {stream, second_stream} + ) + + self.make_stream("!DEACTIVATED:old_style") # This is left active + old_style = self.make_stream("old_style") + do_deactivate_stream(old_style, acting_user=None) + old_style.name = "!!DEACTIVATED:old_style" + old_style.save() + self.assertEqual(set(deactivated_streams_by_old_name(realm, "old_style")), {old_style}) + + def test_reactivate_stream_active_stream(self) -> None: + stream = self.make_stream("new_stream") + with self.assertRaisesRegex(JsonableError, "Stream is not currently deactivated"): + do_reactivate_stream(stream, new_name="new_stream", acting_user=None) + + def test_reactivate_stream_existing_name(self) -> None: + stream = self.make_stream("new_stream") + self.make_stream("existing") + do_deactivate_stream(stream, acting_user=None) + with self.assertRaisesRegex(JsonableError, "Stream named existing already exists"): + do_reactivate_stream(stream, new_name="existing", acting_user=None) + + def test_reactivate_stream(self) -> None: + desdemona = self.example_user("desdemona") + iago = self.example_user("iago") + hamlet = self.example_user("hamlet") + cordelia = self.example_user("cordelia") + + stream = self.make_stream("new_stream", is_web_public=True) + self.subscribe(hamlet, stream.name) + self.subscribe(cordelia, stream.name) + do_deactivate_stream(stream, acting_user=None) + with self.capture_send_event_calls(expected_num_events=4) as events: + do_reactivate_stream(stream, new_name="new_stream", acting_user=None) + + # Tell all admins and owners that the stream exists + self.assertEqual(events[0]["event"]["op"], "create") + self.assertEqual(events[0]["event"]["streams"][0]["name"], "new_stream") + self.assertEqual(events[0]["event"]["streams"][0]["stream_id"], stream.id) + self.assertEqual(set(events[0]["users"]), {iago.id, desdemona.id}) + + # Tell the owners that they're subscribed to it + self.assertEqual(events[1]["event"]["op"], "add") + self.assertEqual(events[1]["event"]["subscriptions"][0]["name"], "new_stream") + self.assertEqual(events[1]["event"]["subscriptions"][0]["stream_id"], stream.id) + self.assertEqual(events[1]["users"], [desdemona.id]) + + # Send a message there logging the reactivation + self.assertEqual(events[2]["event"]["type"], "message") + + # iago (as an admin) gets to know that desdemona (the owner) is now subscribed. + self.assertEqual( + events[3], + { + "event": { + "op": "peer_add", + "stream_ids": [stream.id], + "type": "subscription", + "user_ids": [desdemona.id], + }, + "users": [iago.id], + }, + ) + + stream = Stream.objects.get(id=stream.id) + self.assertFalse(stream.deactivated) + self.assertTrue(stream.invite_only) + self.assertFalse(stream.is_web_public) + self.assertTrue(stream.history_public_to_subscribers) + + self.assertEqual( + [desdemona.id], + [ + sub.user_profile_id + for sub in get_active_subscriptions_for_stream_id( + stream.id, include_deactivated_users=True + ) + ], + ) + def test_vacate_private_stream_removes_default_stream(self) -> None: stream = self.make_stream("new_stream", invite_only=True) self.subscribe(self.example_user("hamlet"), stream.name)
Reactivate a Stream On the backend, would it be possible to implement a `do_reactivate_stream()` method? I took a swing at it ... I can get the Stream back, but none of the topics / messages come with it ... I suspect it's because `do_deactivate_stream()` deletes the stream's cache key: ``` old_cache_key = get_stream_cache_key(old_name, stream.realm) cache_delete(old_cache_key) ``` Is there a way to "re-construct" the stream's messages, etc.?
Would be happy to have a "Reactivate stream" function added to the codebase, at least as a management command. If you post a PR with the code you're trying I can take a look, but the caching thing is definitely not relevant (if there's a cache miss, it would just go to the DB). But my guess is the problem is that you can't see history on streams with `invite_only=True` that were sent while you were not were subscribed, and the deactivation code path sets that bit. Turns out, it wasn't a problem. Instead, since the list of messages & topics is cached, the Stream can be re-activated, but it won't be apparent on the front-end until the cache is updated. .. Came to this realize when I started up the dev server again this morning. I'll make the PR in a bit. Sorry, probably shouldn't have closed this. @timabbott If I wanted the change to be immediately noticeable on the front-end, which cache key would I need to delete? My intention is to give the owner the option in settings.py to cause the cache delete or not. It's not a cache issue (though you should probably delete the cache key for the DELETED name). You'd need to do a `send_event` to notify the frontend about the new stream (might have a bit of complexity here where for browsers that had access to old messages it should be treated as a rename). The new feature tutorial on readthedocs has a bit of info on how send_event works... It must be an old_messages issue; I have the send_event component piece working. I suppose the front-end clients need to be told to fetch messages associated with the re-activated stream? Yeah, so you may need to do some sort of combined rename/create stream logic on the frontend, where if the frontend knows about the DEACTIVATED name, it'll rename that, otherwise it'll add a new stream with the new name. One area where we need clarity is how much effort we're going to go through to automatically re-subscribe users, or at least notify them that they can re-subscribe. At deactivation time we set all users subscriptions to active=False, but that doesn't allow us to distinguish users who deactivated themselves earlier vs. users who got deactivated when the stream itself was deactivated. For public streams, I recommend we just let folks re-subscribe themselves, and we can basically have them see an announcement that the stream has been reactivated. For private streams, I don't know what we should do. One thing about private streams is that they tend to have pretty few subscribers, so at deactivation time, we could probably serial the list of currently subscribed users. And then at reactivation we notify those users. @zulipbot claim @zulipbot claim Hello @edith007, you claimed this issue to work on it, but this issue and any referenced pull requests haven't been updated for 10 days. Are you still working on this issue? If so, please update this issue by leaving a comment on this issue to let me know that you're still working on it. Otherwise, I'll automatically remove you from this issue in 4 days. If you've decided to work on something else, simply comment `@zulipbot abandon` so that someone else can claim it and continue from where you left off. Thank you for your valuable contributions to Zulip! <!-- inactiveWarning --> @zulipbot claim
2023-07-11T16:41:55
zulip/zulip
26,511
zulip__zulip-26511
[ "25498" ]
89f9e097dbbbe6f65d272c550731133c05bfbe58
diff --git a/zerver/actions/presence.py b/zerver/actions/presence.py --- a/zerver/actions/presence.py +++ b/zerver/actions/presence.py @@ -113,20 +113,17 @@ def do_update_user_presence( defaults=defaults, ) + # We initialize these values as a large delta so that if the user + # was never active, we always treat the user as newly online. + time_since_last_active_for_comparison = timedelta(days=1) + time_since_last_connected_for_comparison = timedelta(days=1) if presence.last_active_time is not None: - time_since_last_active = log_time - presence.last_active_time - else: - # The user was never active, so let's consider this large to go over any thresholds - # we may have. - time_since_last_active = timedelta(days=1) + time_since_last_active_for_comparison = log_time - presence.last_active_time if presence.last_connected_time is not None: - time_since_last_connected = log_time - presence.last_connected_time - else: - # Same approach as above. - time_since_last_connected = timedelta(days=1) + time_since_last_connected_for_comparison = log_time - presence.last_connected_time assert (3 * settings.PRESENCE_PING_INTERVAL_SECS + 20) <= settings.OFFLINE_THRESHOLD_SECS - now_online = time_since_last_active > timedelta( + now_online = time_since_last_active_for_comparison > timedelta( # Here, we decide whether the user is newly online, and we need to consider # sending an immediate presence update via the events system that this user is now online, # rather than waiting for other clients to poll the presence update. @@ -148,7 +145,7 @@ def do_update_user_presence( # times per minute with multiple connected browser windows. # We also need to be careful not to wrongly "update" the timestamp if we actually already # have newer presence than the reported log_time. - if not created and time_since_last_connected > timedelta( + if not created and time_since_last_connected_for_comparison > timedelta( seconds=settings.PRESENCE_UPDATE_MIN_FREQ_SECONDS ): presence.last_connected_time = log_time @@ -156,7 +153,8 @@ def do_update_user_presence( if ( not created and status == UserPresence.LEGACY_STATUS_ACTIVE_INT - and time_since_last_active > timedelta(seconds=settings.PRESENCE_UPDATE_MIN_FREQ_SECONDS) + and time_since_last_active_for_comparison + > timedelta(seconds=settings.PRESENCE_UPDATE_MIN_FREQ_SECONDS) ): presence.last_active_time = log_time update_fields.append("last_active_time")
Get `zerver/actions/*.py` to 100% test coverage. Lines missing coverage: ``` ERROR: zerver/actions/create_realm.py no longer has complete backend test coverage Lines missing coverage: [167, 194] ERROR: zerver/actions/message_delete.py no longer has complete backend test coverage Lines missing coverage: [27] ERROR: zerver/actions/message_edit.py no longer has complete backend test coverage Lines missing coverage: [925, 1098, 1166] ERROR: zerver/actions/presence.py no longer has complete backend test coverage Lines missing coverage: [119] ERROR: zerver/actions/scheduled_messages.py no longer has complete backend test coverage Lines missing coverage: [111] ```
Hello @zulip/server-testing members, this issue was labeled with the "area: testing-coverage" label, so you may want to check it out! <!-- areaLabelAddition --> The `message_delete.py` one is already fixed by https://github.com/zulip/zulip/pull/25494. @zulipbot claim Welcome to Zulip, @CertifiedJoon! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @adityanarayanm095 You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! @zulipbot abandon @zulipbot claim Welcome to Zulip, @adityanarayanm095! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @timabbott 1) How to produce this error locally? to confirm after code change? 2) How to understand the method to write test-covergage for any particular file? Thanks @adityanarayanm095 for picking up this issue. This issue is related to the coverage provided by the tests for some; whose details are in the issue description. You can check if your code works by checking out the test coverage by running `./tools/test-backend --coverage` -- this will generate an HTML page from which you can find out the current coverage for each file related to the backend. Also, I see there are five files mentioned in the issue description, but I just generated the coverage report. It looks like only `zerver/actions/presence.py` is missing 100% test coverage, and the rest of the files in `zerver/actions` have got full test coverage. So you need to just get one file to full test coverage to solve this issue. The tests are located in `zerver/tests` -- try taking a look at `zerver/tests/test_presence.py` to see how they are laid out. > Thanks @adityanarayanm095 for picking up this issue. This issue is related to the coverage provided by the tests for some; whose details are in the issue description. > > You can check if your code works by checking out the test coverage by running `./tools/test-backend --coverage` -- this will generate an HTML page from which you can find out the current coverage for each file related to the backend. > > Also, I see there are five files mentioned in the issue description, but I just generated the coverage report. It looks like only `zerver/actions/presence.py` is missing 100% test coverage, and the rest of the files in `zerver/actions` have got full test coverage. So you need to just get one file to full test coverage to solve this issue. > > The tests are located in `zerver/tests` -- try taking a look at `zerver/tests/test_presence.py` to see how they are laid out. @sbansal1999, Below and few other lines are not covered so how to get idea to write test coverage for them?, i have read `zerver/tests/test_presence.py` but not able to relate with the missing code coverage. ![image](https://github.com/zulip/zulip/assets/91023072/a28c76b5-bc41-4409-9390-be2ac1173785) @adityanarayanm095 I ran the tests again just to double check and there is only one line (line no. 119) that is missing test coverage in `zerver/actions/presence.py`. I would recommend updating your fork as it could be a possible reason for the discrepancy. Read - [keeping your fork updated](https://zulip.readthedocs.io/en/latest/git/using.html#keep-your-fork-up-to-date). Also for help on writing tests, you can have a look at [this](https://zulip.readthedocs.io/en/latest/testing/testing-with-django.html#writing-tests) page. Feel free to join [The Zulip development community](https://zulip.com/development-community/) to discuss related things. @zulipbot claim **ERROR:** Unexpected response from GitHub API. @zulipbot claim @adityanarayanm095 You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! @zulipbot claim Welcome to Zulip, @aakash1408! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @Haider8 You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! @zulipbot abandon @zulipbot claim Welcome to Zulip, @Haider8! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @Haider8 Are you working on this issue? Let me work on this @amanagr assign @zulipbot claim Welcome to Zulip, @dhruvpal05! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @zulipbot claim Welcome to Zulip, @ro4i7! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @sbansal1999 is this issue has been solved by #26511 or been solving by him? @zulipbot abandon @zulipbot claim @vizerion07 You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! @zulipbot claim
2023-08-16T17:58:11
zulip/zulip
26,588
zulip__zulip-26588
[ "26549" ]
965a25d91b6ee2db54038f5df855215fa25146b0
diff --git a/version.py b/version.py --- a/version.py +++ b/version.py @@ -33,7 +33,7 @@ # Changes should be accompanied by documentation explaining what the # new level means in api_docs/changelog.md, as well as "**Changes**" # entries in the endpoint's documentation in `zulip.yaml`. -API_FEATURE_LEVEL = 205 +API_FEATURE_LEVEL = 206 # Bump the minor PROVISION_VERSION to indicate that folks should provision # only when going from an old version of the code to a newer version. Bump diff --git a/zerver/views/video_calls.py b/zerver/views/video_calls.py --- a/zerver/views/video_calls.py +++ b/zerver/views/video_calls.py @@ -31,7 +31,7 @@ from zerver.lib.response import json_success from zerver.lib.subdomains import get_subdomain from zerver.lib.url_encoding import append_url_query_string -from zerver.lib.validator import check_dict, check_string +from zerver.lib.validator import check_bool, check_dict, check_string from zerver.models import UserProfile, get_realm @@ -142,13 +142,30 @@ def complete_zoom_user_in_realm( return render(request, "zerver/close_window.html") -def make_zoom_video_call(request: HttpRequest, user: UserProfile) -> HttpResponse: +@has_request_variables +def make_zoom_video_call( + request: HttpRequest, + user: UserProfile, + is_video_call: bool = REQ(json_validator=check_bool, default=True), +) -> HttpResponse: oauth = get_zoom_session(user) if not oauth.authorized: raise InvalidZoomTokenError + # The meeting host has the ability to configure both their own and + # participants' default video on/off state for the meeting. That's + # why when creating a meeting, configure the video on/off default + # according to the desired call type. Each Zoom user can still have + # their own personal setting to not start video by default. + payload = { + "settings": { + "host_video": is_video_call, + "participant_video": is_video_call, + } + } + try: - res = oauth.post("https://api.zoom.us/v2/users/me/meetings", json={}) + res = oauth.post("https://api.zoom.us/v2/users/me/meetings", json=payload) except OAuth2Error: do_set_zoom_token(user, None) raise InvalidZoomTokenError
diff --git a/web/tests/compose_video.test.js b/web/tests/compose_video.test.js --- a/web/tests/compose_video.test.js +++ b/web/tests/compose_video.test.js @@ -132,7 +132,7 @@ test("videos", ({override}) => { assert.match(syntax_to_insert, video_link_regex); })(); - (function test_zoom_video_link_compose_clicked() { + (function test_zoom_video_and_audio_links_compose_clicked() { let syntax_to_insert; let called = false; @@ -152,9 +152,6 @@ test("videos", ({override}) => { called = true; }); - const handler = $("body").get_on_handler("click", ".video_link"); - $("#compose-textarea").val(""); - page_params.realm_video_chat_provider = realm_available_video_chat_providers.zoom.id; page_params.has_zoom_token = false; @@ -172,10 +169,19 @@ test("videos", ({override}) => { return {abort() {}}; }; - handler(ev); + $("#compose-textarea").val(""); + const video_handler = $("body").get_on_handler("click", ".video_link"); + video_handler(ev); const video_link_regex = /\[translated: Join video call\.]\(example\.zoom\.com\)/; assert.ok(called); assert.match(syntax_to_insert, video_link_regex); + + $("#compose-textarea").val(""); + const audio_handler = $("body").get_on_handler("click", ".audio_link"); + audio_handler(ev); + const audio_link_regex = /\[translated: Join audio call\.]\(example\.zoom\.com\)/; + assert.ok(called); + assert.match(syntax_to_insert, audio_link_regex); })(); (function test_bbb_video_link_compose_clicked() { diff --git a/zerver/tests/test_create_video_call.py b/zerver/tests/test_create_video_call.py --- a/zerver/tests/test_create_video_call.py +++ b/zerver/tests/test_create_video_call.py @@ -36,7 +36,7 @@ def test_register_video_request(self) -> None: self.assertEqual(response.status_code, 302) @responses.activate - def test_create_video_request_success(self) -> None: + def test_create_zoom_video_and_audio_links(self) -> None: responses.add( responses.POST, "https://zoom.us/oauth/token", @@ -49,6 +49,7 @@ def test_create_video_request_success(self) -> None: ) self.assertEqual(response.status_code, 200) + # Test creating a video link responses.replace( responses.POST, "https://zoom.us/oauth/token", @@ -61,7 +62,32 @@ def test_create_video_request_success(self) -> None: json={"join_url": "example.com"}, ) - response = self.client_post("/json/calls/zoom/create") + response = self.client_post("/json/calls/zoom/create", {"is_video_call": "true"}) + self.assertEqual( + responses.calls[-1].request.url, + "https://api.zoom.us/v2/users/me/meetings", + ) + self.assertEqual( + responses.calls[-1].request.headers["Authorization"], + "Bearer newtoken", + ) + json = self.assert_json_success(response) + self.assertEqual(json["url"], "example.com") + + # Test creating an audio link + responses.replace( + responses.POST, + "https://zoom.us/oauth/token", + json={"access_token": "newtoken", "expires_in": 60}, + ) + + responses.add( + responses.POST, + "https://api.zoom.us/v2/users/me/meetings", + json={"join_url": "example.com"}, + ) + + response = self.client_post("/json/calls/zoom/create", {"is_video_call": "false"}) self.assertEqual( responses.calls[-1].request.url, "https://api.zoom.us/v2/users/me/meetings", @@ -73,6 +99,7 @@ def test_create_video_request_success(self) -> None: json = self.assert_json_success(response) self.assertEqual(json["url"], "example.com") + # Test for authentication error self.logout() self.login_user(self.user)
Add Zoom support for audio-only calls Following #25922, we now have support for audio calls in Zulip, but the Zoom integration doesn't yet support it. We should figure out what parameters we need to pass when creating a Zoom call to support an "Audio call" button for Zoom users as well. Tagged as an 8.0 release goal, since we'll want to document the audio calls feature as available for all call providers.
2023-08-27T00:57:15
zulip/zulip
26,601
zulip__zulip-26601
[ "26593" ]
52e2298d65b4d6a7f9594820e70ce699df3853ac
diff --git a/version.py b/version.py --- a/version.py +++ b/version.py @@ -33,7 +33,7 @@ # Changes should be accompanied by documentation explaining what the # new level means in api_docs/changelog.md, as well as "**Changes**" # entries in the endpoint's documentation in `zulip.yaml`. -API_FEATURE_LEVEL = 207 +API_FEATURE_LEVEL = 208 # Bump the minor PROVISION_VERSION to indicate that folks should provision # only when going from an old version of the code to a newer version. Bump diff --git a/zerver/views/streams.py b/zerver/views/streams.py --- a/zerver/views/streams.py +++ b/zerver/views/streams.py @@ -83,6 +83,7 @@ ) from zerver.lib.types import Validator from zerver.lib.user_groups import access_user_group_for_setting +from zerver.lib.users import access_user_by_email, access_user_by_id from zerver.lib.utils import assert_is_not_none from zerver.lib.validator import ( check_bool, @@ -98,43 +99,18 @@ check_union, to_non_negative_int, ) -from zerver.models import ( - Realm, - Stream, - UserGroup, - UserMessage, - UserProfile, - get_active_user, - get_active_user_profile_by_id_in_realm, - get_system_bot, -) - - -class PrincipalError(JsonableError): - code = ErrorCode.UNAUTHORIZED_PRINCIPAL - data_fields = ["principal"] - http_status_code = 403 - - def __init__(self, principal: Union[int, str]) -> None: - self.principal: Union[int, str] = principal - - @staticmethod - def msg_format() -> str: - return _("User not authorized to execute queries on behalf of '{principal}'") +from zerver.models import Realm, Stream, UserGroup, UserMessage, UserProfile, get_system_bot def principal_to_user_profile(agent: UserProfile, principal: Union[str, int]) -> UserProfile: - try: - if isinstance(principal, str): - return get_active_user(principal, agent.realm) - else: - return get_active_user_profile_by_id_in_realm(principal, agent.realm) - except UserProfile.DoesNotExist: - # We have to make sure we don't leak information about which users - # are registered for Zulip in a different realm. We could do - # something a little more clever and check the domain part of the - # principal to maybe give a better error message - raise PrincipalError(principal) + if isinstance(principal, str): + return access_user_by_email( + agent, principal, allow_deactivated=False, allow_bots=True, for_admin=False + ) + else: + return access_user_by_id( + agent, principal, allow_deactivated=False, allow_bots=True, for_admin=False + ) def user_directly_controls_user(user_profile: UserProfile, target: UserProfile) -> bool:
diff --git a/zerver/tests/test_subs.py b/zerver/tests/test_subs.py --- a/zerver/tests/test_subs.py +++ b/zerver/tests/test_subs.py @@ -2834,9 +2834,7 @@ def test_remove_invalid_user(self) -> None: "principals": orjson.dumps([99]).decode(), }, ) - self.assert_json_error( - result, "User not authorized to execute queries on behalf of '99'", status_code=403 - ) + self.assert_json_error(result, "No such user", status_code=400) class DefaultStreamTest(ZulipTestCase): @@ -5091,11 +5089,7 @@ def test_subscriptions_add_for_principal_deactivated(self) -> None: result = self.common_subscribe_to_streams( self.test_user, "Denmark", post_data, allow_fail=True ) - self.assert_json_error( - result, - f"User not authorized to execute queries on behalf of '{target_profile.id}'", - status_code=403, - ) + self.assert_json_error(result, "User is deactivated", status_code=400) def test_subscriptions_add_for_principal_invite_only(self) -> None: """ @@ -5138,11 +5132,7 @@ def test_subscription_add_invalid_principal_legacy_emails(self) -> None: {"principals": orjson.dumps([invalid_principal]).decode()}, allow_fail=True, ) - self.assert_json_error( - result, - f"User not authorized to execute queries on behalf of '{invalid_principal}'", - status_code=403, - ) + self.assert_json_error(result, "No such user", status_code=400) def test_subscription_add_invalid_principal(self) -> None: invalid_principal = 999 @@ -5155,11 +5145,7 @@ def test_subscription_add_invalid_principal(self) -> None: {"principals": orjson.dumps([invalid_principal]).decode()}, allow_fail=True, ) - self.assert_json_error( - result, - f"User not authorized to execute queries on behalf of '{invalid_principal}'", - status_code=403, - ) + self.assert_json_error(result, "No such user", status_code=400) def test_subscription_add_principal_other_realm(self) -> None: """ @@ -5176,11 +5162,7 @@ def test_subscription_add_principal_other_realm(self) -> None: {"principals": orjson.dumps([principal]).decode()}, allow_fail=True, ) - self.assert_json_error( - result, - f"User not authorized to execute queries on behalf of '{principal}'", - status_code=403, - ) + self.assert_json_error(result, "No such user", status_code=400) def helper_check_subs_before_and_after_remove( self,
Improve error messages for unexpected users in subscribe/unsubscribe endpoints As noted in https://github.com/zulip/zulip/pull/26183/commits/85fcc5e1f21675a4b281c32671ec41979adeab55#r1303446347, if you try to subscribe a deactivated user to a stream, you get a pretty weird error message. Here's the code responsible (used in the endpoints for editing another user's stream subscriptions): ``` class PrincipalError(JsonableError): code = ErrorCode.UNAUTHORIZED_PRINCIPAL data_fields = ["principal"] http_status_code = 403 def __init__(self, principal: Union[int, str]) -> None: self.principal: Union[int, str] = principal @staticmethod def msg_format() -> str: return _("User not authorized to execute queries on behalf of '{principal}'") def principal_to_user_profile(agent: UserProfile, principal: Union[str, int]) -> UserProfile: try: if isinstance(principal, str): return get_active_user(principal, agent.realm) else: return get_active_user_profile_by_id_in_realm(principal, agent.realm) except UserProfile.DoesNotExist: # We have to make sure we don't leak information about which users # are registered for Zulip in a different realm. We could do # something a little more clever and check the domain part of the # principal to maybe give a better error message raise PrincipalError(principal) ``` I think probably `principal_to_user_profile` should get rewritten to use the `access_user_*` set of code paths, which already have better error messages for this class of issue. @laurynmm it might be nice for you to take this issue, just because it's a bit of a thorny API/error handling issue, and it'd be nice if this were fixed close to when we fix #26183.
Hello @zulip/server-api members, this issue was labeled with the "area: api" label, so you may want to check it out! <!-- areaLabelAddition -->
2023-08-29T16:07:17
zulip/zulip
26,631
zulip__zulip-26631
[ "26368" ]
8c91c91d865e431a94dc93f1a5df52e96a26bece
diff --git a/zerver/lib/markdown/__init__.py b/zerver/lib/markdown/__init__.py --- a/zerver/lib/markdown/__init__.py +++ b/zerver/lib/markdown/__init__.py @@ -2284,7 +2284,7 @@ def make_md_engine(linkifiers_key: int, email_gateway: bool) -> None: # Split the topic name into multiple sections so that we can easily use # our common single link matching regex on it. -basic_link_splitter = re.compile(r"[ !;\?\),\'\"]") +basic_link_splitter = re.compile(r"[ !;\),\'\"]") def percent_escape_format_string(format_string: str) -> str:
diff --git a/zerver/tests/test_markdown.py b/zerver/tests/test_markdown.py --- a/zerver/tests/test_markdown.py +++ b/zerver/tests/test_markdown.py @@ -1160,6 +1160,36 @@ def test_links_in_topic_name(self) -> None: ], ) + # Query strings in a URL should be included in the link. + msg.set_topic_name("https://google.com/test?foo=bar") + converted_topic = topic_links(realm.id, msg.topic_name()) + self.assertEqual( + converted_topic, + [ + { + "url": "https://google.com/test?foo=bar", + "text": "https://google.com/test?foo=bar", + }, + ], + ) + # But question marks at the end of sentence are not part of the URL. + msg.set_topic_name("Have you seen github.com/zulip?") + converted_topic = topic_links(realm.id, msg.topic_name()) + self.assertEqual( + converted_topic, + [ + {"url": "https://github.com/zulip", "text": "github.com/zulip"}, + ], + ) + msg.set_topic_name("Do you like https://example.com? I love it.") + converted_topic = topic_links(realm.id, msg.topic_name()) + self.assertEqual( + converted_topic, + [ + {"url": "https://example.com", "text": "https://example.com"}, + ], + ) + def check_add_linkifiers( self, linkifiers: List[RealmFilter], expected_linkifier_reprs: List[str] ) -> None:
Open link button in topic skips part of link Clicking open link with a topic such as `https://client.atomontage.app/view?m=8GvRSx5LVIXSQhQSEChhx` will open just `https://client.atomontage.app/view` **Zulip Server and web app version:** - [ ] Zulip Cloud (`*.zulipchat.com`) - [x] Zulip Server 7.0+ - [ ] Zulip Server 6.0+ - [ ] Zulip Server 5.0 or older - [ ] Other or not sure
Hello @zulip/server-markdown members, this issue was labeled with the "area: markdown" label, so you may want to check it out! <!-- areaLabelAddition --> I started a conversation about this issue in the [Zulip development community](https://zulip.com/development-community/) here: https://chat.zulip.org/#narrow/stream/9-issues/topic/URL.20link.20for.20topic.20name.20not.20exact.20match.2C.20.2326368/near/1617354 Hi @laurynmm , Can I work on this issue based on the solution in [community chat](https://chat.zulip.org/#narrow/stream/9-issues/topic/URL.20link.20for.20topic.20name.20not.20exact.20match.2C.20.2326368/near/1624943) ? Btw were also getting long links truncated due to the character limit of topics, perhaps the open link button could use the full link anyways > Btw were also getting long links truncated due to the character limit of topics, perhaps the open link button could use the full link anyways sure can you please assign this issue to me? @mkster - Topics are limited in length (I'm not sure if this is documented in the help center, but it's in the API documentation e.g. here for the [topic parameter](https://zulip.com/api/send-message#parameter-topic) for sending a message). So, the server would have no way to know what the full link is as it's just linking the text of the topic. For your use case, would it be possible to use [custom linkifiers](https://zulip.com/help/add-a-custom-linkifier) in your topics? @sayyedarib - Thanks for your interest in this issue. Let me follow-up on on the conversation on CZO and go from there. I don't think the aspect of topics being limited in length was addressed. aha great I didnt know about linkifiers
2023-09-01T22:19:04
zulip/zulip
26,647
zulip__zulip-26647
[ "26640" ]
7d683018bdef0d3dd91b072017ab1427017b1bca
diff --git a/zerver/management/commands/makemessages.py b/zerver/management/commands/makemessages.py --- a/zerver/management/commands/makemessages.py +++ b/zerver/management/commands/makemessages.py @@ -52,9 +52,9 @@ ) regexes = [ - r"{{#tr}}([\s\S]*?)(?:{{/tr}}|{{#\*inline )", # '.' doesn't match '\n' by default - r'{{\s*t "([\s\S]*?)"\W*}}', - r"{{\s*t '([\s\S]*?)'\W*}}", + r"{{~?#tr}}([\s\S]*?)(?:~?{{/tr}}|{{#\*inline )", # '.' doesn't match '\n' by default + r'{{~?\s*t "([\s\S]*?)"\W*~?}}', + r"{{~?\s*t '([\s\S]*?)'\W*~?}}", r'\(t "([\s\S]*?)"\)', r'=\(t "([\s\S]*?)"\)(?=[^{]*}})', r"=\(t '([\s\S]*?)'\)(?=[^{]*}})",
Internationalization of "Browse 1 more stream" and two more strings <!-- Describe what you were expecting to see, what you saw instead, and steps to take in order to reproduce the buggy behavior. Screenshots can be helpful. --> I am missing "Browse 1 more stream" https://github.com/zulip/zulip/blob/81bd63cb46273b8c94ef9e92c00893ed97110119/web/templates/subscribe_to_more_streams.hbs#L4 and "Browse # more streams" https://github.com/zulip/zulip/blob/81bd63cb46273b8c94ef9e92c00893ed97110119/web/templates/subscribe_to_more_streams.hbs#L9 in the internationalization files (translation.json or django.po). ![image](https://github.com/zulip/zulip/assets/38357406/a8049e56-0fc1-42c9-82e7-869d54d18205) Syntax above differs from syntax in https://github.com/zulip/zulip/blob/81bd63cb46273b8c94ef9e92c00893ed97110119/web/templates/subscribe_to_more_streams.hbs#L14 which has an entry in translation.json. I am also missing a translation of "Direct messages" in the first column of recent conversations. May be it is generated by the following code and missing internationalization. https://github.com/zulip/zulip/blob/81bd63cb46273b8c94ef9e92c00893ed97110119/web/templates/recent_topic_row.hbs#L7 <!-- Check the box for the version of Zulip you are using (see https://zulip.com/help/view-zulip-version).--> **Zulip Server and web app version:** - [ ] Zulip Cloud (`*.zulipchat.com`) - [x] Zulip Server 7.0+ - [ ] Zulip Server 6.0+ - [ ] Zulip Server 5.0 or older - [ ] Other or not sure
Hello @zulip/server-i18n members, this issue was labeled with the "area: internationalization" label, so you may want to check it out! <!-- areaLabelAddition --> @idandr - Thanks for the report! I put up a quick PR to fix those two templates so that the strings are correctly marked for translation/internationalization.
2023-09-06T10:17:31
zulip/zulip
26,770
zulip__zulip-26770
[ "26736" ]
e5f7f1701ff4423170c88ec1ade4eef0e8663b18
diff --git a/zerver/views/realm.py b/zerver/views/realm.py --- a/zerver/views/realm.py +++ b/zerver/views/realm.py @@ -424,7 +424,7 @@ def realm_reactivation(request: HttpRequest, confirmation_key: str) -> HttpRespo emojiset_choices = {emojiset["key"] for emojiset in RealmUserDefault.emojiset_choices()} -default_view_options = ["recent_topics", "all_messages"] +default_view_options = ["recent_topics", "inbox", "all_messages"] @require_realm_admin diff --git a/zerver/views/user_settings.py b/zerver/views/user_settings.py --- a/zerver/views/user_settings.py +++ b/zerver/views/user_settings.py @@ -127,7 +127,7 @@ def confirm_email_change(request: HttpRequest, confirmation_key: str) -> HttpRes emojiset_choices = {emojiset["key"] for emojiset in UserProfile.emojiset_choices()} -default_view_options = ["recent_topics", "all_messages"] +default_view_options = ["recent_topics", "inbox", "all_messages"] def check_settings_values(
diff --git a/zerver/tests/test_events.py b/zerver/tests/test_events.py --- a/zerver/tests/test_events.py +++ b/zerver/tests/test_events.py @@ -3090,7 +3090,7 @@ def do_set_realm_user_default_setting_test(self, name: str) -> None: bool_tests: List[bool] = [True, False, True] test_values: Dict[str, Any] = dict( color_scheme=UserProfile.COLOR_SCHEME_CHOICES, - default_view=["recent_topics", "all_messages"], + default_view=["recent_topics", "inbox", "all_messages"], emojiset=[emojiset["key"] for emojiset in RealmUserDefault.emojiset_choices()], demote_inactive_streams=UserProfile.DEMOTE_STREAMS_CHOICES, web_mark_read_on_scroll_policy=UserProfile.WEB_MARK_READ_ON_SCROLL_POLICY_CHOICES, @@ -3171,7 +3171,7 @@ def do_change_user_settings_test(self, setting_name: str) -> None: test_changes: Dict[str, Any] = dict( emojiset=["twitter"], default_language=["es", "de", "en"], - default_view=["all_messages", "recent_topics"], + default_view=["all_messages", "inbox", "recent_topics"], demote_inactive_streams=[2, 3, 1], web_mark_read_on_scroll_policy=[2, 3, 1], user_list_style=[1, 2, 3], diff --git a/zerver/tests/test_realm.py b/zerver/tests/test_realm.py --- a/zerver/tests/test_realm.py +++ b/zerver/tests/test_realm.py @@ -1299,7 +1299,7 @@ def do_test_realm_default_setting_update_api(self, name: str) -> None: bool_tests: List[bool] = [False, True] test_values: Dict[str, Any] = dict( color_scheme=UserProfile.COLOR_SCHEME_CHOICES, - default_view=["recent_topics", "all_messages"], + default_view=["recent_topics", "inbox", "all_messages"], emojiset=[emojiset["key"] for emojiset in RealmUserDefault.emojiset_choices()], demote_inactive_streams=UserProfile.DEMOTE_STREAMS_CHOICES, web_mark_read_on_scroll_policy=UserProfile.WEB_MARK_READ_ON_SCROLL_POLICY_CHOICES,
Add inbox view to set of allowed default views.
2023-09-18T15:48:00
zulip/zulip
26,839
zulip__zulip-26839
[ "27801" ]
3958743b33e4e4f7d24cd43e9dec740be9c674d7
diff --git a/zerver/lib/url_redirects.py b/zerver/lib/url_redirects.py --- a/zerver/lib/url_redirects.py +++ b/zerver/lib/url_redirects.py @@ -80,6 +80,7 @@ class URLRedirect: URLRedirect("/help/configure-default-view", "/help/configure-home-view"), URLRedirect("/help/reading-topics", "/help/reading-conversations"), URLRedirect("/help/finding-a-topic-to-read", "/help/finding-a-conversation-to-read"), + URLRedirect("/help/view-and-browse-images", "/help/view-images-and-videos"), ] LANDING_PAGE_REDIRECTS = [
Update documentation on previews permissions The help center should be updated following #27783.
2023-09-23T00:27:03
zulip/zulip
26,842
zulip__zulip-26842
[ "15029" ]
08bf7efeb81a73bcb302313ee5c1b80f900c9030
diff --git a/tools/lib/provision_inner.py b/tools/lib/provision_inner.py --- a/tools/lib/provision_inner.py +++ b/tools/lib/provision_inner.py @@ -93,8 +93,16 @@ def write_command(command: str) -> None: with open(shell_profile_path, "w") as shell_profile_file: shell_profile_file.writelines(command + "\n") - source_activate_command = "source " + os.path.join(VENV_PATH, "bin", "activate") - write_command(source_activate_command) + # Check if the environment is one of the dedicated containers: Vagrant, Docker, Droplet or WSL2 + WSL = os.path.exists("/proc/sys/fs/binfmt_misc/WSLInterop") + vagrant = os.path.exists("/vagrant") + docker = os.path.exists("/var/run/docker.sock") + droplet = os.path.exists("/etc/digitalocean") + # If the environment matches one of the containers, write the activation command to the user's bash profile + if WSL or vagrant or docker or droplet: + source_activate_command = "source " + os.path.join(VENV_PATH, "bin", "activate") + write_command(source_activate_command) + if os.path.exists("/srv/zulip"): write_command("cd /srv/zulip")
Don't activate zulip_py3_venv at the launch of shell on direct system dev setups. As a part of `./tools/provision` we add `"source " + os.path.join(VENV_PATH, "bin", "activate")` to the bash profile of the user which is responsible for automatic activation of the zulip's virtualenv when a new shell is launched. While this is handy for Vagrant/Docker/Droplet setups, which are dedicated machines for running Zulip, this is not a desired behaviour in other setups like [Direct Installation on systems](https://zulip.readthedocs.io/en/latest/development/setup-advanced.html#installing-directly-on-ubuntu-debian-centos-or-fedora). Solution would be to extract the script which writes the venv activation to bash profile and call it via Vagrantfile/Dockerfile/Droplet setup script.
Hello @zulip/server-development members, this issue was labeled with the "area: provision" label, so you may want to check it out! <!-- areaLabelAddition --> @zulipbot claim Welcome to Zulip, @HausCloud! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: * Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. * [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @zulipbot claim Hello @Krishna-Sivakumar, you have been unassigned from this issue because you have not updated this issue or any referenced pull requests for over 14 days. You can reclaim this issue or claim any other issue by commenting `@zulipbot claim` on that issue. Thanks for your contributions, and hope to see you again soon! @zulipbot abandon @zulipbot claim Welcome to Zulip, @Krishna-Sivakumar! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: * Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. * [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! Can you take a look at this? @amanagr @zulipbot claim Hello @Krishna-Sivakumar, you have been unassigned from this issue because you have not updated this issue or any referenced pull requests for over 14 days. You can reclaim this issue or claim any other issue by commenting `@zulipbot claim` on that issue. Thanks for your contributions, and hope to see you again soon! @zulipbot claim Welcome to Zulip, @Purhan! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: * Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. * [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @Krishna-Sivakumar I just noticed you have an open PR. Are you still working on this? If so, please tell me and I will drop this issue. Didn't see that before claiming it. > @Krishna-Sivakumar I just noticed you have an open PR. Are you still working on this? If so, please tell me and I will drop this issue. Didn't see that before claiming it. nope, I'm not working on it anymore. Please go ahead. @berniev9 You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! @zulipbot abandon @zulipbot claim Welcome to Zulip, @skamranahmed! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: * Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. * [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @zulipbot claim Hello @Abhirup-99, it looks like you've currently claimed 1 issue in this repository. We encourage new contributors to focus their efforts on at most 1 issue at a time, so please complete your work on your other claimed issues before trying to claim this issue again. We look forward to your valuable contributions! @zulipbot claim @zulipbot claim @zulipbot claim @zulipbot claim @zulipbot claim Welcome to Zulip, @daniellf99! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: * Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. * [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @amanagr I was thinking if maybe we could add an option to `./tools/provision` like `--no-bash-profile` to prevent the script from writing to the bash profile. That way the user could choose what works best for him, while the Vagrantfile/Dockerfile/Droplet setup script just continues working the way it is. This is actually a good idea. We just need to document it properly in https://zulip.readthedocs.io/en/latest/development/setup-advanced.html alteast after adding it. Will do, thanks for the advice! @zulipbot claim Hello @gvarun1, it looks like you've currently claimed 1 issue in this repository. We encourage new contributors to focus their efforts on at most 1 issue at a time, so please complete your work on your other claimed issues before trying to claim this issue again. We look forward to your valuable contributions! @zulipbot claim @zulipbot abandon @amanagr is this issue still relevant? I cannot see the discussed points in /tools/provision. If you could point out what needs to be done for this issue, i might try it :) @zulipbot claim @amanagr  This issue of automatic activation of zulip-py3-venv also applies to WSL2 setup on a Windows 10 or 11 machine. So, as you suggested, this should be only for machines that are dedicated to running Zulip and avoid automatic activation for other setups. I was looking through this **tools/setup/setup_venvs.py** file, and I figured what if we could add a condition that checks for what kind of container this is? We would only execute this script (making the assumption that this is the script that runs automatically when we enter the shell) for vagrant, docker, and droplet machines and ignore other machines. If I'm right, that will solve the problem. I don't have the whole picture, but if you could push me a bit in the right direction, that would be a great help. I can then claim this issue. Thanks.   @zulipbot claim Welcome to Zulip, @s-bose7! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)!
2023-09-23T22:38:58
zulip/zulip
26,882
zulip__zulip-26882
[ "26874" ]
6c1f99385588749c0eabb06c1ec34d1598096aac
diff --git a/zerver/lib/hotspots.py b/zerver/lib/hotspots.py --- a/zerver/lib/hotspots.py +++ b/zerver/lib/hotspots.py @@ -27,7 +27,7 @@ "intro_gear": { "title": gettext_lazy("Settings"), "description": gettext_lazy( - "Go to Settings to configure your notifications and display settings." + "Go to Settings to configure your notifications and preferences." ), }, "intro_compose": { diff --git a/zerver/models.py b/zerver/models.py --- a/zerver/models.py +++ b/zerver/models.py @@ -1496,7 +1496,7 @@ class UserBaseSettings(models.Model): ### Generic UI settings enter_sends = models.BooleanField(default=False) - ### Display settings. ### + ### Preferences. ### # left_side_userlist was removed from the UI in Zulip 6.0; the # database model is being temporarily preserved in case we want to # restore a version of the setting, preserving who had it enabled.
Finish renaming Display settings -> Preferences To finish out the work in #25945, we should update the following uses of "display settings" -> "preferences": ``` zerver/lib/hotspots.py: "Go to Settings to configure your notifications and display settings." zerver/models.py: ### Display settings. ### ``` as well as many other variables in the code (https://github.com/zulip/zulip/issues/26874#issuecomment-1737885164): [CZO thread](https://chat.zulip.org/#narrow/stream/9-issues/topic/finish.20renaming.20.22display.20settings.22/near/1647592)
Hello @zulip/server-onboarding members, this issue was labeled with the "area: onboarding" label, so you may want to check it out! <!-- areaLabelAddition --> @zulipbot claim Welcome to Zulip, @Ciggzy1312! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @zulipbot claim @arnavchhokra This issue cannot be claimed, as someone else is already working on it. Please see our [contributor guide](https://zulip.readthedocs.io/en/latest/overview/contributing.html#your-first-codebase-contribution) for advice on finding an issue to work on. Thanks!
2023-09-27T08:56:16
zulip/zulip
26,956
zulip__zulip-26956
[ "26797" ]
4c57b3f2895396c0672d05007cdaf58cab86471d
diff --git a/zerver/lib/events.py b/zerver/lib/events.py --- a/zerver/lib/events.py +++ b/zerver/lib/events.py @@ -512,8 +512,10 @@ def fetch_initial_state_data( for bot in EMBEDDED_BOTS ] - # This does not have an apply_events counterpart either since - # this data is mostly static. + # This does not have an apply_events counterpart either since this + # data is mostly static. This excludes the legacy webhook + # integrations as those do not follow the same URL construction + # patterns as other integrations. if want("realm_incoming_webhook_bots"): state["realm_incoming_webhook_bots"] = [ { @@ -523,6 +525,7 @@ def fetch_initial_state_data( "config": {c[1]: c[0] for c in integration.config_options}, } for integration in WEBHOOK_INTEGRATIONS + if integration.legacy is False ] if want("recent_private_conversations"):
Improve "Generate URL for an integration" modal Following up on #26201, we should: - [ ] Change the Integration selector to a typeahead dropdown, just like the stream picker. Default text: "Select an integration". That will make it more clear what you are supposed to input in that field. - [ ] "Send all notifications to a single topic" is checked, but no topic name is configured, disable the "Copy URL" button. Otherwise, the user may be confused about why the integration doesn't work in accordance with the checkbox. <img width="552" alt="Screen Shot 2023-09-20 at 2 51 34 PM" src="https://github.com/zulip/zulip/assets/2090066/7a569992-d52f-4b58-bade-abf83ac13277">
Hello @zulip/server-integrations members, this issue was labeled with the "area: integrations" label, so you may want to check it out! <!-- areaLabelAddition --> @zulipbot claim claim
2023-10-01T06:46:22
zulip/zulip
27,186
zulip__zulip-27186
[ "26903" ]
417b29638ccaf1ec5f117754a8d8a5710bdc8724
diff --git a/zerver/lib/markdown/help_relative_links.py b/zerver/lib/markdown/help_relative_links.py --- a/zerver/lib/markdown/help_relative_links.py +++ b/zerver/lib/markdown/help_relative_links.py @@ -88,12 +88,12 @@ def stream_handle_match(key: str) -> str: recent_instructions = """ 1. Click on <i class="fa fa-clock-o"></i> **Recent conversations** in the left - sidebar. + sidebar, or use the <kbd>T</kbd> keyboard shortcut.. """ all_instructions = """ 1. Click on <i class="fa fa-align-left"></i> **All messages** in the left - sidebar or use the <kbd>A</kbd> keyboard shortcut. + sidebar, or use the <kbd>A</kbd> keyboard shortcut. """ starred_instructions = """ @@ -108,6 +108,11 @@ def stream_handle_match(key: str) -> str: keyboard shortcut. """ +inbox_instructions = """ +1. Click on <i class="zulip-icon zulip-icon-inbox"></i> **Inbox** in the left + sidebar, or use the <kbd>Shift</kbd> + <kbd>I</kbd> keyboard shortcut. +""" + message_info = { "drafts": ["Drafts", "/#drafts", draft_instructions], "scheduled": ["Scheduled messages", "/#scheduled", scheduled_instructions], @@ -115,6 +120,7 @@ def stream_handle_match(key: str) -> str: "all": ["All messages", "/#all_messages", all_instructions], "starred": ["Starred messages", "/#narrow/is/starred", starred_instructions], "direct": ["All direct messages", "/#narrow/is/dm", direct_instructions], + "inbox": ["Inbox", "/#inbox", inbox_instructions], } diff --git a/zerver/lib/markdown/tabbed_sections.py b/zerver/lib/markdown/tabbed_sections.py --- a/zerver/lib/markdown/tabbed_sections.py +++ b/zerver/lib/markdown/tabbed_sections.py @@ -72,6 +72,7 @@ "stream": "From a stream view", "not-stream": "From other views", "via-recent-conversations": "Via recent conversations", + "via-inbox-view": "Via inbox view", "via-left-sidebar": "Via left sidebar", "instructions-for-all-platforms": "Instructions for all platforms", "public-streams": "Public streams",
Document Inbox view We should document the new webapp Inbox view. Affected pages include: - [ ] https://zulip.com/help/inbox - [ ] https://zulip.com/help/configure-default-view: - In addition to listing Inbox wherever appropriate, we should change: > "Recent conversations is especially recommended for high-traffic organizations, and is configured by default." > -> > "**Inbox** works best if you regularly clear all unread messages in most streams you follow. Otherwise, **Recent conversations** works well in high-traffic organizations." (or something along those lines) - [ ] https://zulip.com/help/reading-strategies We should also audit for pages that mention Recent conversations, as Inbox may often provide an alternative way to take the same action (e.g., https://zulip.com/help/marking-messages-as-read).
Hello @zulip/server-user-docs members, this issue was labeled with the "area: documentation (user)" label, so you may want to check it out! <!-- areaLabelAddition -->
2023-10-12T18:40:51
zulip/zulip
27,204
zulip__zulip-27204
[ "26902" ]
d1f82c47fd08a5df55f93a669590450a07c8fea6
diff --git a/zerver/lib/markdown/tabbed_sections.py b/zerver/lib/markdown/tabbed_sections.py --- a/zerver/lib/markdown/tabbed_sections.py +++ b/zerver/lib/markdown/tabbed_sections.py @@ -83,6 +83,7 @@ "via-user-profile": "Via user profile", "via-organization-settings": "Via organization settings", "via-personal-settings": "Via personal settings", + "via-stream-settings": "Via stream settings", "default-subdomain": "Default subdomain", "custom-subdomain": "Custom subdomain", "zulip-cloud": "Zulip Cloud",
Document stream management via user profile On https://zulip.com/help/manage-user-stream-subscriptions, we should document the ability to subscribe/unsubscribe users via the user profile. This documentation should follow the pattern in `/help/change-a-users-role` and `/help/change-a-users-name`, as they are after #26901. (Let's put off updating https://zulip.com/help/user-groups until the new groups UI is live.)
Hello @zulip/server-user-docs members, this issue was labeled with the "area: documentation (user)" label, so you may want to check it out! <!-- areaLabelAddition --> @drrosa You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! I went through the docs, and the portion regarding **unsubscribing users via *user profile*** is already documented (screenshot below), and the **subscribing users via *user profile*** is missing. Shall I proceed forward towards documenting that ? ![Screenshot_20231013_074547](https://github.com/zulip/zulip/assets/11803841/d1947394-c30e-4f58-86b3-a8768026a356) @zulipbot claim Welcome to Zulip, @ecxtacy! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! Adding the **Subscribe via profile** portion, the documentation looks as follows :- ![Screenshot_20231013_081042](https://github.com/zulip/zulip/assets/11803841/91081d12-818a-4d4d-9526-3a3d3a17a73c) Is there any additional information that should be included here? @ecxtacy Your proposal does not implement this part of the issue: > This documentation should follow the pattern in /help/change-a-users-role and /help/change-a-users-name, as they are after https://github.com/zulip/zulip/pull/26901. Understood! Thank you for the correction and clarification. I'll incorporate the required pattern into this proposal. :smiley: After applying the pattern, this is how it looks. ![Screenshot_20231013_141026](https://github.com/zulip/zulip/assets/11803841/ca56fab7-a96d-44fa-bd59-cf1dd51a4632)
2023-10-13T17:16:24
zulip/zulip
27,249
zulip__zulip-27249
[ "27243" ]
56ccaa571e9991adf643f2a37ce7a6635d3a6a78
diff --git a/zerver/actions/create_user.py b/zerver/actions/create_user.py --- a/zerver/actions/create_user.py +++ b/zerver/actions/create_user.py @@ -254,7 +254,7 @@ def process_new_human_user( get_system_bot(settings.NOTIFICATION_BOT, prereg_user.referred_by.realm_id), prereg_user.referred_by, _("{user} accepted your invitation to join Zulip!").format( - user=f"{user_profile.full_name} <`{user_profile.email}`>" + user=silent_mention_syntax_for_user(user_profile) ), )
diff --git a/zerver/tests/test_invite.py b/zerver/tests/test_invite.py --- a/zerver/tests/test_invite.py +++ b/zerver/tests/test_invite.py @@ -957,7 +957,7 @@ def test_invite_user_signup_initial_history(self) -> None: self.assertEqual(inviter_msg.sender.email, "[email protected]") self.assertTrue( inviter_msg.content.startswith( - f"alice_zulip.com <`{invitee_profile.email}`> accepted your", + f"@_**{invitee_profile.full_name}|{invitee_profile.id}** accepted your", ) ) diff --git a/zerver/tests/test_users.py b/zerver/tests/test_users.py --- a/zerver/tests/test_users.py +++ b/zerver/tests/test_users.py @@ -826,7 +826,7 @@ def test_create_user_with_multiple_streams(self) -> None: prereg_user = PreregistrationUser.objects.get(email="[email protected]") - with self.assert_database_query_count(92): + with self.assert_database_query_count(93): with self.assert_memcached_count(23): with self.capture_send_event_calls(expected_num_events=11) as events: fred = do_create_user(
Use silent mentions in personal notification that invite was accepted At present, if an organization has enabled stream notifications for new users joining, we send a message with a silent mention of the user who just joined: <img width="438" alt="Screenshot 2023-10-16 at 10 38 30 PM" src="https://github.com/zulip/zulip/assets/2090066/a392805d-7245-4d6b-a55d-6ce58b6705a6"> However, the DM notification to the user who invited the person who just registered has the new user's name and email instead. We should replace the name/email with a silent mention in this message as well, which is a nicer interface for checking who the user is, especially if the new user's email is private. Current: <img width="644" alt="Screenshot 2023-10-16 at 10 38 44 PM" src="https://github.com/zulip/zulip/assets/2090066/5a0840a1-e583-408b-bb1c-7177676a69c9"> New: `@_**fsad** accepted your invitation to join Zulip!`
Hello @zulip/server-bots, @zulip/server-onboarding members, this issue was labeled with the "area: onboarding", "area: bots" labels, so you may want to check it out! <!-- areaLabelAddition --> @zulipbot claim ![Screenshot from 2023-10-17 14-19-35](https://github.com/zulip/zulip/assets/90370535/c75994a8-acfe-4d6e-900b-29cca813e004) before generating the PR I just wanted to confirm , if it's what you expect?
2023-10-17T18:24:25
zulip/zulip
27,386
zulip__zulip-27386
[ "27384" ]
e442a9d11e464daf08049e0927d6605b4600e80b
diff --git a/zerver/lib/markdown/help_relative_links.py b/zerver/lib/markdown/help_relative_links.py --- a/zerver/lib/markdown/help_relative_links.py +++ b/zerver/lib/markdown/help_relative_links.py @@ -29,15 +29,6 @@ "stats": ['<i class="fa fa-bar-chart"></i> Usage statistics', "/stats"], "plans": ['<i class="fa fa-rocket"></i> Plans and pricing', "/plans/"], "billing": ['<i class="fa fa-credit-card"></i> Billing', "/billing/"], - "keyboard-shortcuts": [ - '<i class="fa fa-keyboard-o"></i> Keyboard shortcuts (?)', - "/#keyboard-shortcuts", - ], - "message-formatting": [ - '<i class="fa fa-pencil"></i> Message formatting', - "/#message-formatting", - ], - "search-filters": ['<i class="fa fa-search"></i> Search filters', "/#search-operators"], "about-zulip": ["About Zulip", "/#about-zulip"], } @@ -57,6 +48,41 @@ def gear_handle_match(key: str) -> str: return gear_instructions.format(item=item) +help_info = { + # The pattern is key: [name, link] + # key is from REGEXP: `{relative|help|key}` + # name is what the item is called in the help menu: `Select **name**.` + # link is used for relative links: `Select [name](link).` + "keyboard-shortcuts": [ + '<i class="zulip-icon zulip-icon-keyboard"></i> Keyboard shortcuts', + "/#keyboard-shortcuts", + ], + "message-formatting": [ + '<i class="zulip-icon zulip-icon-edit"></i> Message formatting', + "/#message-formatting", + ], + "search-filters": [ + '<i class="zulip-icon zulip-icon-manage-search"></i> Search filters', + "/#search-operators", + ], +} + +help_instructions = """ +1. Click on the **Help menu** (<i class="zulip-icon zulip-icon-help"></i>) icon + in the upper right corner of the app. + +1. Select {item}. +""" + + +def help_handle_match(key: str) -> str: + if relative_help_links: + item = f"[{help_info[key][0]}]({help_info[key][1]})" + else: + item = f"**{help_info[key][0]}**" + return help_instructions.format(item=item) + + stream_info = { "all": ["All streams", "/#streams/all"], "subscribed": ["Subscribed streams", "/#streams/subscribed"], @@ -136,6 +162,7 @@ def message_handle_match(key: str) -> str: "gear": gear_handle_match, "stream": stream_handle_match, "message": message_handle_match, + "help": help_handle_match, }
Document new help menu We should update the help center docs to reflect the new dedicated help menu. Known pages to update: - https://zulip.com/help/keyboard-shortcuts#keyboard-shortcuts-reference - https://zulip.com/help/format-your-message-using-markdown#message-formatting-reference - https://zulip.com/help/search-for-messages#search-filters-reference We should also add a keyboard tip to /help/keyboard-shortcuts#keyboard-shortcuts-reference, documenting the `?` keyboard shortcut.
Hello @zulip/server-user-docs members, this issue was labeled with the "area: documentation (user)" label, so you may want to check it out! <!-- areaLabelAddition -->
2023-10-26T02:07:03
zulip/zulip
27,417
zulip__zulip-27417
[ "26892" ]
6819ecee92a0a3c1e2253c77f2bd89cc3fe808fa
diff --git a/zerver/lib/markdown/tabbed_sections.py b/zerver/lib/markdown/tabbed_sections.py --- a/zerver/lib/markdown/tabbed_sections.py +++ b/zerver/lib/markdown/tabbed_sections.py @@ -98,6 +98,7 @@ "user": "User", "bot": "Bot", "on-sign-up": "On sign-up", + "via-paste": "Via paste", "via-markdown": "Via Markdown", "via-compose-box-buttons": "Via compose box buttons", "stream-compose": "Compose to a stream",
Document option to paste URL to create a named link We should document the new functionality in #18692. I would add a "Via paste" tab to https://zulip.com/help/insert-a-link#insert-a-link_1, probably as the first tab, since that's often the most handy option.
Hello @zulip/server-user-docs members, this issue was labeled with the "area: documentation (user)" label, so you may want to check it out! <!-- areaLabelAddition --> @drrosa You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! @zulipbot claim
2023-10-27T23:33:17
zulip/zulip
27,515
zulip__zulip-27515
[ "26913" ]
0b3f7a5a6bc0736ec8eb209fe951f487969e86a6
diff --git a/zerver/lib/mention.py b/zerver/lib/mention.py --- a/zerver/lib/mention.py +++ b/zerver/lib/mention.py @@ -3,6 +3,7 @@ from dataclasses import dataclass from typing import Dict, List, Match, Optional, Set, Tuple +from django.conf import settings from django.db.models import Q from zerver.models import UserGroup, UserProfile, get_linkable_streams @@ -91,9 +92,9 @@ def get_full_name_info_list(self, user_filters: List[UserFilter]) -> List[FullNa rows = ( UserProfile.objects.filter( - realm_id=self.realm_id, - is_active=True, + Q(realm_id=self.realm_id) | Q(email__in=settings.CROSS_REALM_BOT_EMAILS), ) + .filter(is_active=True) .filter( functools.reduce(lambda a, b: a | b, q_list), )
Display mentions of cross realm bots as mention pills <!-- Issue description --> As reported on CZO, cross realm bots aren't being included in the data set available for rendering user mentions. As a result, their mentions don't appear as user pills. E.g., in a quote-and-reply: ![Screenshot-from-2023-07-12-12-25-44](https://github.com/zulip/zulip/assets/2090066/b86d4ed9-7e42-4022-87e2-0a2d6236b5dc) We should fix this. <!-- Link to a message in the chat.zulip.org discussion. Message links will still work even if the topic is renamed or resolved. Link back to this issue from the chat.zulip.org thread. --> [CZO thread](https://chat.zulip.org/#narrow/stream/9-issues/topic/silent.20mentions.20of.20system.20bots.20in.20quote.20and.20reply/near/1608266)
Good Day @alya i'm an Outreachy Contributor and i'd like to fix this as my first contribution @zulipbot claim Welcome to Zulip, @Tochukwu-Omeja! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @Tochukwu-Omeja You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks!
2023-11-03T06:39:02
zulip/zulip
27,536
zulip__zulip-27536
[ "26894" ]
5c73744aca2c400dbbea5b6bc64d7bb8ef13da17
diff --git a/zerver/lib/markdown/tabbed_sections.py b/zerver/lib/markdown/tabbed_sections.py --- a/zerver/lib/markdown/tabbed_sections.py +++ b/zerver/lib/markdown/tabbed_sections.py @@ -99,6 +99,7 @@ "bot": "Bot", "on-sign-up": "On sign-up", "via-paste": "Via paste", + "via-drag-and-drop": "Via drag-and-drop", "via-markdown": "Via Markdown", "via-compose-box-buttons": "Via compose box buttons", "stream-compose": "Compose to a stream",
Document ability to drag-and-drop anywhere to upload a file We should document the functionality introduced in #14579 / https://github.com/zulip/zulip/pull/26041. I would probably replace the "Via Markdown" tab with "Via drag-and-drop", and modify the instructions to explain that you can drag anywhere, whether or not the compose box is open.
@zulipbot claim @Victoria-27 This issue cannot be claimed, as someone else is already working on it. Please see our [contributor guide](https://zulip.readthedocs.io/en/latest/overview/contributing.html#your-first-codebase-contribution) for advice on finding an issue to work on. Thanks! @drrosa You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! @zulipbot claim Welcome to Zulip, @thejaysharma! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @zulipbot claim
2023-11-03T23:49:50
zulip/zulip
27,541
zulip__zulip-27541
[ "26857" ]
f2deb8da465ba9c3cc98ffbe5f9835c6e17fc655
diff --git a/zerver/lib/markdown/__init__.py b/zerver/lib/markdown/__init__.py --- a/zerver/lib/markdown/__init__.py +++ b/zerver/lib/markdown/__init__.py @@ -1895,6 +1895,8 @@ def handleMatch( # type: ignore[override] # https://github.com/python/mypy/issu self.zmd.zulip_rendering_result.mentions_topic_wildcard = True elif user is not None: assert isinstance(user, FullNameInfo) + if not user.is_active: + silent = True if not silent: self.zmd.zulip_rendering_result.mentions_user_ids.add(user.id) diff --git a/zerver/lib/mention.py b/zerver/lib/mention.py --- a/zerver/lib/mention.py +++ b/zerver/lib/mention.py @@ -27,6 +27,7 @@ class FullNameInfo: id: int full_name: str + is_active: bool @dataclass @@ -94,17 +95,20 @@ def get_full_name_info_list(self, user_filters: List[UserFilter]) -> List[FullNa UserProfile.objects.filter( Q(realm_id=self.realm_id) | Q(email__in=settings.CROSS_REALM_BOT_EMAILS), ) - .filter(is_active=True) .filter( functools.reduce(lambda a, b: a | b, q_list), ) .only( "id", "full_name", + "is_active", ) ) - user_list = [FullNameInfo(id=row.id, full_name=row.full_name) for row in rows] + user_list = [ + FullNameInfo(id=row.id, full_name=row.full_name, is_active=row.is_active) + for row in rows + ] # We expect callers who take advantage of our cache to supply both # id and full_name in the user mentions in their messages.
diff --git a/zerver/tests/test_markdown.py b/zerver/tests/test_markdown.py --- a/zerver/tests/test_markdown.py +++ b/zerver/tests/test_markdown.py @@ -253,6 +253,7 @@ def make_user(email: str, full_name: str) -> UserProfile: FullNameInfo( full_name="Fred Flintstone", id=fred2.id, + is_active=True, ), ) self.assertEqual( @@ -260,6 +261,7 @@ def make_user(email: str, full_name: str) -> UserProfile: FullNameInfo( full_name="Fred Flintstone", id=fred4.id, + is_active=True, ), ) @@ -276,6 +278,7 @@ def test_mention_data(self) -> None: FullNameInfo( full_name=hamlet.full_name, id=hamlet.id, + is_active=True, ), ) @@ -2110,6 +2113,48 @@ def test_mention_silent(self) -> None: ) self.assertEqual(rendering_result.mentions_user_ids, set()) + def test_mention_deactivated_users(self) -> None: + sender_user_profile = self.example_user("othello") + user_profile = self.example_user("hamlet") + change_user_is_active(user_profile, False) + msg = Message( + sender=sender_user_profile, + sending_client=get_client("test"), + realm=sender_user_profile.realm, + ) + user_id = user_profile.id + + content = "@**King Hamlet**" + rendering_result = render_markdown(msg, content) + self.assertEqual( + rendering_result.rendered_content, + '<p><span class="user-mention silent" ' + f'data-user-id="{user_id}">' + "King Hamlet</span></p>", + ) + self.assertEqual(rendering_result.mentions_user_ids, set()) + + def test_mention_silent_deactivated_users(self) -> None: + sender_user_profile = self.example_user("othello") + user_profile = self.example_user("hamlet") + change_user_is_active(user_profile, False) + msg = Message( + sender=sender_user_profile, + sending_client=get_client("test"), + realm=sender_user_profile.realm, + ) + user_id = user_profile.id + + content = "@_**King Hamlet**" + rendering_result = render_markdown(msg, content) + self.assertEqual( + rendering_result.rendered_content, + '<p><span class="user-mention silent" ' + f'data-user-id="{user_id}">' + "King Hamlet</span></p>", + ) + self.assertEqual(rendering_result.mentions_user_ids, set()) + def test_silent_stream_wildcard_mention(self) -> None: user_profile = self.example_user("othello") msg = Message(
User pills for mentions of deactivated users <!-- Issue description --> At present, we do not display mentions of deactivated users as user pills. This looks like a bug -- we should use pills for both active and deactivated users. However, deactivated users should *not* be shown in mention typeahead (just as now). Related issues: - #26833 - #26858 <!-- Link to a message in the chat.zulip.org discussion. Message links will still work even if the topic is renamed or resolved. Link back to this issue from the chat.zulip.org thread. --> [CZO thread](https://chat.zulip.org/#narrow/stream/9-issues/topic/.40-mentioning.20deactivated.20users/near/1645092)
Hi @alya and @zulipbot kindly assign this task to me .I would love to work on it. @zulipbot claim Welcome to Zulip, @henilGondalia! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @henilGondalia You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! @zulipbot claim
2023-11-04T11:20:05
zulip/zulip
27,542
zulip__zulip-27542
[ "27479" ]
8cf436370ccc44f9d6927b6054954fb18f70c9c2
diff --git a/zerver/lib/email_notifications.py b/zerver/lib/email_notifications.py --- a/zerver/lib/email_notifications.py +++ b/zerver/lib/email_notifications.py @@ -642,7 +642,7 @@ def handle_missedmessage_emails( for msg_list in messages_by_bucket.values(): msg = min(msg_list, key=lambda msg: msg.date_sent) - if msg.is_stream_message(): + if msg.is_stream_message() and UserMessage.has_any_mentions(user_profile_id, msg.id): context_messages = get_context_for_message(msg) filtered_context_messages = bulk_access_messages(user_profile, context_messages) msg_list.extend(filtered_context_messages) diff --git a/zerver/models.py b/zerver/models.py --- a/zerver/models.py +++ b/zerver/models.py @@ -3662,6 +3662,20 @@ def select_for_update_query() -> QuerySet["UserMessage"]: """ return UserMessage.objects.select_for_update().order_by("message_id") + @staticmethod + def has_any_mentions(user_profile_id: int, message_id: int) -> bool: + # The query uses the 'zerver_usermessage_any_mentioned_message_id' index. + return UserMessage.objects.filter( + Q( + flags__andnz=UserMessage.flags.mentioned.mask + | UserMessage.flags.wildcard_mentioned.mask + | UserMessage.flags.topic_wildcard_mentioned.mask + | UserMessage.flags.group_mentioned.mask + ), + user_profile_id=user_profile_id, + message_id=message_id, + ).exists() + def get_usermessage_by_message_id( user_profile: UserProfile, message_id: int
diff --git a/zerver/tests/test_message_notification_emails.py b/zerver/tests/test_message_notification_emails.py --- a/zerver/tests/test_message_notification_emails.py +++ b/zerver/tests/test_message_notification_emails.py @@ -1,7 +1,7 @@ import random import re from email.headerregistry import Address -from typing import List, Optional, Sequence, Union +from typing import Dict, List, Optional, Sequence, Union from unittest import mock from unittest.mock import patch @@ -216,18 +216,36 @@ def _extra_context_in_missed_stream_messages_mention( ) def _extra_context_in_missed_stream_messages_topic_wildcard_mention_in_followed_topic( - self, show_message_content: bool = True + self, + show_message_content: bool = True, + *, + receiver_is_participant: bool, ) -> None: - for i in range(1, 6): + for i in range(1, 3): self.send_stream_message(self.example_user("othello"), "Denmark", content=str(i)) self.send_stream_message(self.example_user("othello"), "Denmark", "11", topic_name="test2") + + if receiver_is_participant: + self.send_stream_message(self.example_user("hamlet"), "Denmark", content="hello") + msg_id = self.send_stream_message(self.example_user("othello"), "Denmark", "@**topic**") + trigger = NotificationTriggers.TOPIC_WILDCARD_MENTION_IN_FOLLOWED_TOPIC + if not receiver_is_participant: + trigger = NotificationTriggers.STREAM_EMAIL if show_message_content: - verify_body_include = [ - "Othello, the Moor of Venice: > 1 > 2 > 3 > 4 > 5 > @**topic** -- ", - "You are receiving this because all topic participants were mentioned in #Denmark > test.", - ] + # If Hamlet (receiver) is not a topic participant, @topic doesn't mention him, + # so he won't receive added context (previous messages) in the email. + if receiver_is_participant: + verify_body_include = [ + "Othello, the Moor of Venice: > 1 > 2 King Hamlet: > hello Othello, the Moor of Venice: > @**topic** -- ", + "You are receiving this because all topic participants were mentioned in #Denmark > test.", + ] + else: + verify_body_include = [ + "Othello, the Moor of Venice: > @**topic** -- ", + "You are receiving this because you have email notifications enabled for #Denmark.", + ] email_subject = "#Denmark > test" verify_body_does_not_include: List[str] = [] else: @@ -252,7 +270,7 @@ def _extra_context_in_missed_stream_messages_topic_wildcard_mention_in_followed_ email_subject, show_message_content=show_message_content, verify_body_does_not_include=verify_body_does_not_include, - trigger=NotificationTriggers.TOPIC_WILDCARD_MENTION_IN_FOLLOWED_TOPIC, + trigger=trigger, ) def _extra_context_in_missed_stream_messages_stream_wildcard_mention_in_followed_topic( @@ -297,18 +315,36 @@ def _extra_context_in_missed_stream_messages_stream_wildcard_mention_in_followed ) def _extra_context_in_missed_stream_messages_topic_wildcard_mention( - self, show_message_content: bool = True + self, + show_message_content: bool = True, + *, + receiver_is_participant: bool, ) -> None: - for i in range(1, 6): + for i in range(1, 3): self.send_stream_message(self.example_user("othello"), "Denmark", content=str(i)) self.send_stream_message(self.example_user("othello"), "Denmark", "11", topic_name="test2") + + if receiver_is_participant: + self.send_stream_message(self.example_user("hamlet"), "Denmark", content="hello") + msg_id = self.send_stream_message(self.example_user("othello"), "denmark", "@**topic**") + trigger = NotificationTriggers.TOPIC_WILDCARD_MENTION + if not receiver_is_participant: + trigger = NotificationTriggers.STREAM_EMAIL if show_message_content: - verify_body_include = [ - "Othello, the Moor of Venice: > 1 > 2 > 3 > 4 > 5 > @**topic** -- ", - "You are receiving this because all topic participants were mentioned in #Denmark > test.", - ] + # If Hamlet (receiver) is not a topic participant, @topic doesn't mention him, + # so he won't receive added context (previous messages) in the email. + if receiver_is_participant: + verify_body_include = [ + "Othello, the Moor of Venice: > 1 > 2 King Hamlet: > hello Othello, the Moor of Venice: > @**topic** -- ", + "You are receiving this because all topic participants were mentioned in #Denmark > test.", + ] + else: + verify_body_include = [ + "Othello, the Moor of Venice: > @**topic** -- ", + "You are receiving this because you have email notifications enabled for #Denmark.", + ] email_subject = "#Denmark > test" verify_body_does_not_include: List[str] = [] else: @@ -333,7 +369,7 @@ def _extra_context_in_missed_stream_messages_topic_wildcard_mention( email_subject, show_message_content=show_message_content, verify_body_does_not_include=verify_body_does_not_include, - trigger=NotificationTriggers.TOPIC_WILDCARD_MENTION, + trigger=trigger, ) def _extra_context_in_missed_stream_messages_stream_wildcard_mention( @@ -383,7 +419,7 @@ def _extra_context_in_missed_stream_messages_email_notify(self) -> None: self.send_stream_message(self.example_user("othello"), "Denmark", "11", topic_name="test2") msg_id = self.send_stream_message(self.example_user("othello"), "denmark", "12") verify_body_include = [ - "Othello, the Moor of Venice: > 1 > 2 > 3 > 4 > 5 > 6 > 7 > 8 > 9 > 10 > 12 -- ", + "Othello, the Moor of Venice: > 12 -- ", "You are receiving this because you have email notifications enabled for #Denmark.", ] email_subject = "#Denmark > test" @@ -432,7 +468,7 @@ def _resolved_topic_missed_stream_messages_thread_friendly(self) -> None: self.assert_json_success(self.resolve_topic_containing_message(othello_user, msg_id)) verify_body_include = [ - "Othello, the Moor of Venice: > 0 > 1 > 2 -- ", + "Othello, the Moor of Venice: > 2 -- ", "You are receiving this because you have email notifications enabled for #Denmark.", ] email_subject = "[resolved] #Denmark > threading and so forth" @@ -987,7 +1023,8 @@ def test_message_content_disabled_in_missed_message_notifications(self) -> None: self._extra_context_in_missed_stream_messages_mention(show_message_content=False) mail.outbox = [] self._extra_context_in_missed_stream_messages_topic_wildcard_mention_in_followed_topic( - show_message_content=False + show_message_content=False, + receiver_is_participant=True, ) mail.outbox = [] self._extra_context_in_missed_stream_messages_stream_wildcard_mention_in_followed_topic( @@ -995,7 +1032,8 @@ def test_message_content_disabled_in_missed_message_notifications(self) -> None: ) mail.outbox = [] self._extra_context_in_missed_stream_messages_topic_wildcard_mention( - show_message_content=False + show_message_content=False, + receiver_is_participant=True, ) mail.outbox = [] self._extra_context_in_missed_stream_messages_stream_wildcard_mention( @@ -1014,7 +1052,16 @@ def test_extra_context_in_missed_stream_messages(self) -> None: def test_extra_context_in_missed_stream_messages_topic_wildcard_in_followed_topic( self, ) -> None: - self._extra_context_in_missed_stream_messages_topic_wildcard_mention_in_followed_topic() + self._extra_context_in_missed_stream_messages_topic_wildcard_mention_in_followed_topic( + receiver_is_participant=True + ) + + def test_extra_context_in_missed_stream_messages_topic_wildcard_in_followed_topic_receiver_not_participant( + self, + ) -> None: + self._extra_context_in_missed_stream_messages_topic_wildcard_mention_in_followed_topic( + receiver_is_participant=False + ) def test_extra_context_in_missed_stream_messages_stream_wildcard_in_followed_topic( self, @@ -1022,7 +1069,16 @@ def test_extra_context_in_missed_stream_messages_stream_wildcard_in_followed_top self._extra_context_in_missed_stream_messages_stream_wildcard_mention_in_followed_topic() def test_extra_context_in_missed_stream_messages_topic_wildcard(self) -> None: - self._extra_context_in_missed_stream_messages_topic_wildcard_mention() + self._extra_context_in_missed_stream_messages_topic_wildcard_mention( + receiver_is_participant=True + ) + + def test_extra_context_in_missed_stream_messages_topic_wildcard_receiver_not_participant( + self, + ) -> None: + self._extra_context_in_missed_stream_messages_topic_wildcard_mention( + receiver_is_participant=False + ) def test_extra_context_in_missed_stream_messages_stream_wildcard(self) -> None: self._extra_context_in_missed_stream_messages_stream_wildcard_mention() @@ -1258,19 +1314,32 @@ def test_multiple_missed_personal_messages(self) -> None: def test_multiple_stream_messages(self) -> None: hamlet = self.example_user("hamlet") - msg_id_1 = self.send_stream_message(self.example_user("othello"), "Denmark", "Message1") - msg_id_2 = self.send_stream_message(self.example_user("iago"), "Denmark", "Message2") + othello = self.example_user("othello") + iago = self.example_user("iago") + + message_ids: Dict[int, MissedMessageData] = {} + for i in range(1, 4): + msg_id = self.send_stream_message(othello, "Denmark", content=str(i)) + message_ids[msg_id] = MissedMessageData(trigger=NotificationTriggers.STREAM_EMAIL) + for i in range(4, 7): + msg_id = self.send_stream_message(iago, "Denmark", content=str(i)) + message_ids[msg_id] = MissedMessageData(trigger=NotificationTriggers.STREAM_EMAIL) handle_missedmessage_emails( hamlet.id, - { - msg_id_1: MissedMessageData(trigger=NotificationTriggers.STREAM_EMAIL), - msg_id_2: MissedMessageData(trigger=NotificationTriggers.STREAM_EMAIL), - }, + message_ids, ) - self.assert_length(mail.outbox, 1) + email_subject = "#Denmark > test" - self.assertEqual(mail.outbox[0].subject, email_subject) + verify_body_include = [ + "Othello, the Moor of Venice: > 1 > 2 > 3 Iago: > 4 > 5 > 6 -- ", + "You are receiving this because you have email notifications enabled for #Denmark.", + ] + self.assert_length(mail.outbox, 1) + msg = mail.outbox[0] + self.assertEqual(msg.subject, email_subject) + for text in verify_body_include: + self.assertIn(text, self.normalize_string(msg.body)) def test_multiple_stream_messages_and_mentions(self) -> None: """Subject should be stream name and topic as usual."""
Include preceding context in new message email notifications only for @-mention notifications <!-- Issue description --> Zulip's email message notifications include prior messages sent to the same topic for context. This is more confusing than helpful for messages for which the user is likely to have received notifications for all the prior messages in the conversation already (or read them in the Zulip UI). Therefore, we should only include prior context for @-mention notifications. There is probably a follow-up here for exactly how much context to include. <!-- Link to a message in the chat.zulip.org discussion. Message links will still work even if the topic is renamed or resolved. Link back to this issue from the chat.zulip.org thread. --> [CZO thread](https://chat.zulip.org/#narrow/stream/138-user-community/topic/E-mail.20notification.3A.20send.20only.20the.20latest.20message.20in.20topic.3F/near/1645312) (with some detailed discussion)
Hello @zulip/server-development members, this issue was labeled with the "area: emails" label, so you may want to check it out! <!-- areaLabelAddition --> **ERROR:** Unexpected response from GitHub API.
2023-11-04T14:19:38
zulip/zulip
27,672
zulip__zulip-27672
[ "27634" ]
5591d6f65c2a3a62d7097a1b8a477b6b7c25d0cb
diff --git a/zerver/actions/streams.py b/zerver/actions/streams.py --- a/zerver/actions/streams.py +++ b/zerver/actions/streams.py @@ -93,6 +93,13 @@ def do_deactivate_stream(stream: Stream, *, acting_user: Optional[UserProfile]) ) was_invite_only = stream.invite_only + was_public = stream.is_public() + was_web_public = stream.is_web_public + + # We do not use do_change_stream_permission because no users need to + # be notified, and we do not want to create audit log entries for + # changing stream privacy. And due to this we also need to duplicate + # the code to unset is_web_public field on attachments below. stream.deactivated = True stream.invite_only = True # Preserve as much as possible the original stream name while giving it a @@ -110,6 +117,26 @@ def do_deactivate_stream(stream: Stream, *, acting_user: Optional[UserProfile]) stream.name = new_name[: Stream.MAX_NAME_LENGTH] stream.save(update_fields=["name", "deactivated", "invite_only"]) + assert stream.recipient_id is not None + if was_web_public: + assert was_public + # Unset the is_web_public and is_realm_public cache on attachments, + # since the stream is now private. + Attachment.objects.filter(messages__recipient_id=stream.recipient_id).update( + is_web_public=None, is_realm_public=None + ) + ArchivedAttachment.objects.filter(messages__recipient_id=stream.recipient_id).update( + is_web_public=None, is_realm_public=None + ) + elif was_public: + # Unset the is_realm_public cache on attachments, since the stream is now private. + Attachment.objects.filter(messages__recipient_id=stream.recipient_id).update( + is_realm_public=None + ) + ArchivedAttachment.objects.filter(messages__recipient_id=stream.recipient_id).update( + is_realm_public=None + ) + # If this is a default stream, remove it, properly sending a # notification to browser clients. if DefaultStream.objects.filter(realm_id=stream.realm_id, stream_id=stream.id).exists(): @@ -201,10 +228,13 @@ def do_unarchive_stream( ).only("id") cache_delete_many(to_dict_cache_key_id(message.id) for message in messages) - # Unset the is_web_public cache on attachments, since the stream is now private. - Attachment.objects.filter(messages__recipient_id=stream.recipient_id).update(is_web_public=None) + # Unset the is_web_public and is_realm_public cache on attachments, + # since the stream is now private. + Attachment.objects.filter(messages__recipient_id=stream.recipient_id).update( + is_web_public=None, is_realm_public=None + ) ArchivedAttachment.objects.filter(messages__recipient_id=stream.recipient_id).update( - is_web_public=None + is_web_public=None, is_realm_public=None ) RealmAuditLog.objects.create(
Deactivating a web-public stream should un-mark all attachments as web-public. If a web-public stream is deactivated, it leaves all of the URLs of attachments which were sent to that stream still web-public accessible. Ideally we would reuse `do_change_stream_permission` in the deactivation process to unset this cached property, except that this creates audit log entries that we don't want, and also events (`send_change_stream_permission_notification`). The right fix is likely to: ``` Attachment.objects.filter(messages__recipient_id=stream.recipient_id).update( is_realm_public=None ) ArchivedAttachment.objects.filter(messages__recipient_id=stream.recipient_id).update( is_realm_public=None ) ``` ...with a comment there and `do_change_stream_permission` about the duplicated functionality. `do_unarchive_stream` is already doing step, and already has a reference to why it does not use `do_change_stream_permission` in it. **Zulip Server and web app version:** - [x] Zulip Cloud (`*.zulipchat.com`) - [x] Zulip Server 7.0+ - [ ] Zulip Server 6.0+ - [ ] Zulip Server 5.0 or older - [ ] Other or not sure
@sahil839 do you have time to pick this one up? Hello @zulip/server-streams members, this issue was labeled with the "area: stream settings" label, so you may want to check it out! <!-- areaLabelAddition --> Yeah, I can work on this.
2023-11-12T04:09:37
zulip/zulip
27,673
zulip__zulip-27673
[ "27600" ]
b5a6742adc707f25aad3c2e448449624267f07a0
diff --git a/corporate/migrations/0019_zulipsponsorshiprequest_expected_total_users_and_more.py b/corporate/migrations/0019_zulipsponsorshiprequest_expected_total_users_and_more.py new file mode 100644 --- /dev/null +++ b/corporate/migrations/0019_zulipsponsorshiprequest_expected_total_users_and_more.py @@ -0,0 +1,27 @@ +# Generated by Django 4.2.6 on 2023-11-11 14:16 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("corporate", "0018_customer_cloud_xor_self_hosted"), + ] + + operations = [ + migrations.AddField( + model_name="zulipsponsorshiprequest", + name="expected_total_users", + field=models.TextField(default=""), + ), + migrations.AddField( + model_name="zulipsponsorshiprequest", + name="paid_users_count", + field=models.TextField(default=""), + ), + migrations.AddField( + model_name="zulipsponsorshiprequest", + name="paid_users_description", + field=models.TextField(default=""), + ), + ] diff --git a/corporate/models.py b/corporate/models.py --- a/corporate/models.py +++ b/corporate/models.py @@ -360,3 +360,6 @@ class ZulipSponsorshipRequest(models.Model): org_website = models.URLField(max_length=MAX_ORG_URL_LENGTH, blank=True, null=True) org_description = models.TextField(default="") + expected_total_users = models.TextField(default="") + paid_users_count = models.TextField(default="") + paid_users_description = models.TextField(default="") diff --git a/corporate/views/upgrade.py b/corporate/views/upgrade.py --- a/corporate/views/upgrade.py +++ b/corporate/views/upgrade.py @@ -233,6 +233,9 @@ class SponsorshipRequestForm(forms.Form): website = forms.URLField(max_length=ZulipSponsorshipRequest.MAX_ORG_URL_LENGTH, required=False) organization_type = forms.IntegerField() description = forms.CharField(widget=forms.Textarea) + expected_total_users = forms.CharField(widget=forms.Textarea) + paid_users_count = forms.CharField(widget=forms.Textarea) + paid_users_description = forms.CharField(widget=forms.Textarea, required=False) @require_organization_member @@ -243,6 +246,9 @@ def sponsorship( organization_type: str = REQ("organization-type"), website: str = REQ(), description: str = REQ(), + expected_total_users: str = REQ(), + paid_users_count: str = REQ(), + paid_users_description: str = REQ(), ) -> HttpResponse: realm = user.realm billing_session = RealmBillingSession(user) @@ -266,6 +272,9 @@ def sponsorship( org_website=form.cleaned_data["website"], org_description=form.cleaned_data["description"], org_type=form.cleaned_data["organization_type"], + expected_total_users=form.cleaned_data["expected_total_users"], + paid_users_count=form.cleaned_data["paid_users_count"], + paid_users_description=form.cleaned_data["paid_users_description"], ) sponsorship_request.save() @@ -287,6 +296,9 @@ def sponsorship( "organization_type": org_type_display_name, "website": website, "description": description, + "expected_total_users": expected_total_users, + "paid_users_count": paid_users_count, + "paid_users_description": paid_users_description, } send_email( "zerver/emails/sponsorship_request",
diff --git a/corporate/tests/test_stripe.py b/corporate/tests/test_stripe.py --- a/corporate/tests/test_stripe.py +++ b/corporate/tests/test_stripe.py @@ -2159,6 +2159,9 @@ def test_request_sponsorship_form_with_invalid_url(self) -> None: "organization-type": Realm.ORG_TYPES["opensource"]["id"], "website": "invalid-url", "description": "Infinispan is a distributed in-memory key/value data store with optional schema.", + "expected_total_users": "10 users", + "paid_users_count": "1 user", + "paid_users_description": "We have 1 paid user.", } response = self.client_post("/json/billing/sponsorship", data) @@ -2172,6 +2175,9 @@ def test_request_sponsorship_form_with_blank_url(self) -> None: "organization-type": Realm.ORG_TYPES["opensource"]["id"], "website": "", "description": "Infinispan is a distributed in-memory key/value data store with optional schema.", + "expected_total_users": "10 users", + "paid_users_count": "1 user", + "paid_users_description": "We have 1 paid user.", } response = self.client_post("/json/billing/sponsorship", data) @@ -2223,6 +2229,9 @@ def test_request_sponsorship(self) -> None: "organization-type": Realm.ORG_TYPES["opensource"]["id"], "website": "https://infinispan.org/", "description": "Infinispan is a distributed in-memory key/value data store with optional schema.", + "expected_total_users": "10 users", + "paid_users_count": "1 user", + "paid_users_description": "We have 1 paid user.", } response = self.client_post("/json/billing/sponsorship", data) self.assert_json_success(response)
Collect additional information on sponsorship request form To avoid unnecessary back-and-forth, we should collect some more info on the sponsorship request form. We should add the following fields below "organization type": * Expected number of users (approximate range) * How many paid staff does your organization have? * If more than zero, please describe - The first two fields should be required, but don't have to be numeric. Should be large enough to allow a brief comment, e.g., "probably no more than 100", etc. - For simplicity, we can always show "If more than zero, please describe", rather than making it conditional on the value of the paid staff field.
2023-11-12T06:35:02
zulip/zulip
27,759
zulip__zulip-27759
[ "2775" ]
c71f62089b3422231589f73ddc91850d66125642
diff --git a/zerver/lib/markdown/help_relative_links.py b/zerver/lib/markdown/help_relative_links.py --- a/zerver/lib/markdown/help_relative_links.py +++ b/zerver/lib/markdown/help_relative_links.py @@ -19,7 +19,7 @@ # key is from REGEXP: `{relative|gear|key}` # name is what the item is called in the gear menu: `Select **name**.` # link is used for relative links: `Select [name](link).` - "manage-streams": ['<i class="fa fa-exchange"></i> Manage streams', "/#streams/subscribed"], + "stream-settings": ['<i class="fa fa-exchange"></i> Stream settings', "/#streams/subscribed"], "settings": ['<i class="fa fa-wrench"></i> Personal Settings', "/#settings/profile"], "organization-settings": [ '<i class="fa fa-bolt"></i> Organization settings', @@ -92,7 +92,7 @@ def help_handle_match(key: str) -> str: 1. Click on the **gear** (<i class="fa fa-cog"></i>) icon in the upper right corner of the web or desktop app. -1. Click **Manage streams**. +1. Click **Stream settings**. """
diff --git a/docs/testing/manual-testing.md b/docs/testing/manual-testing.md --- a/docs/testing/manual-testing.md +++ b/docs/testing/manual-testing.md @@ -446,7 +446,7 @@ Test subscribe/unsubscribe: - Log in as Hamlet and go to his stream settings. - As Cordelia, unsubscribe from "public1" using the checkmark in the - streams settings page. + stream settings page. - Verify that Hamlet sees that Cordelia has unsubscribed (and the subscriber count should decrement). - As Cordelia, resubscribe to "public1." diff --git a/zerver/tests/test_docs.py b/zerver/tests/test_docs.py --- a/zerver/tests/test_docs.py +++ b/zerver/tests/test_docs.py @@ -429,7 +429,7 @@ def test_help_relative_links_for_stream(self) -> None: with self.settings(ROOT_DOMAIN_LANDING_PAGE=True): result = self.client_get("/help/message-a-stream-by-email", subdomain="") self.assertEqual(result.status_code, 200) - self.assertIn("<strong>Manage streams</strong>", str(result.content)) + self.assertIn("<strong>Stream settings</strong>", str(result.content)) self.assertNotIn("/#streams", str(result.content))
docs: Add user guide for pin a stream
*Automated message from Dropbox CLA bot* @KingxBanana, it looks like you've already signed the Dropbox CLA. Thanks! @KingxBanana In general looks good - thanks for working on it! Please read my comments and just think about it - I'm not native ;-) @showell could you check the English grammar? Additional comments - I'd change images names: `arrow` -> `streams-arrow` `pinX` -> `streams-something` @TomaszKolek Alright, thanks for the tips :). I'll try to fix all of it once I get home I checked the English grammar and didn't find anything, but we should wrap the text. Alright, I made every line shorter than 76 characters and changed the file names of the images. Anything else? Merged! Thanks, @KingxBanana!
2023-11-17T03:17:54
zulip/zulip
27,763
zulip__zulip-27763
[ "27503" ]
11cb37c9a4c852508f45b35117711d4677de656a
diff --git a/version.py b/version.py --- a/version.py +++ b/version.py @@ -33,7 +33,7 @@ # Changes should be accompanied by documentation explaining what the # new level means in api_docs/changelog.md, as well as "**Changes**" # entries in the endpoint's documentation in `zulip.yaml`. -API_FEATURE_LEVEL = 226 +API_FEATURE_LEVEL = 227 # Bump the minor PROVISION_VERSION to indicate that folks should provision # only when going from an old version of the code to a newer version. Bump diff --git a/zerver/migrations/0490_renumber_options_desktop_icon_count_display.py b/zerver/migrations/0490_renumber_options_desktop_icon_count_display.py new file mode 100644 --- /dev/null +++ b/zerver/migrations/0490_renumber_options_desktop_icon_count_display.py @@ -0,0 +1,64 @@ +# Generated by Django 4.2.7 on 2023-11-17 04:55 + +from django.db import migrations +from django.db.backends.base.schema import BaseDatabaseSchemaEditor +from django.db.migrations.state import StateApps + +OLD_DESKTOP_ICON_COUNT_DISPLAY_DM_MENTION = 2 +NEW_DESKTOP_ICON_COUNT_DISPLAY_DM_MENTION = 3 +OLD_DESKTOP_ICON_COUNT_DISPLAY_NONE = 3 +NEW_DESKTOP_ICON_COUNT_DISPLAY_NONE = 4 + + +def renumber_options(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None: + # We added a new option 'DESKTOP_ICON_COUNT_DISPLAY_DM_MENTION_FOLLOWED_TOPIC' + # for 'desktop_icon_count_display' setting. It has the value 2. + # The following options are renumbered: + # * 'DESKTOP_ICON_COUNT_DISPLAY_DM_MENTION' from 2 to 3 + # * 'DESKTOP_ICON_COUNT_DISPLAY_NONE' from 3 to 4 + # The migration is to update these values. + RealmUserDefault = apps.get_model("zerver", "RealmUserDefault") + UserProfile = apps.get_model("zerver", "UserProfile") + + UserProfile.objects.filter( + desktop_icon_count_display=OLD_DESKTOP_ICON_COUNT_DISPLAY_NONE + ).update(desktop_icon_count_display=NEW_DESKTOP_ICON_COUNT_DISPLAY_NONE) + RealmUserDefault.objects.filter( + desktop_icon_count_display=OLD_DESKTOP_ICON_COUNT_DISPLAY_NONE + ).update(desktop_icon_count_display=NEW_DESKTOP_ICON_COUNT_DISPLAY_NONE) + + UserProfile.objects.filter( + desktop_icon_count_display=OLD_DESKTOP_ICON_COUNT_DISPLAY_DM_MENTION + ).update(desktop_icon_count_display=NEW_DESKTOP_ICON_COUNT_DISPLAY_DM_MENTION) + RealmUserDefault.objects.filter( + desktop_icon_count_display=OLD_DESKTOP_ICON_COUNT_DISPLAY_DM_MENTION + ).update(desktop_icon_count_display=NEW_DESKTOP_ICON_COUNT_DISPLAY_DM_MENTION) + + +def reverse_code(apps: StateApps, schema_editor: BaseDatabaseSchemaEditor) -> None: + RealmUserDefault = apps.get_model("zerver", "RealmUserDefault") + UserProfile = apps.get_model("zerver", "UserProfile") + + UserProfile.objects.filter( + desktop_icon_count_display=NEW_DESKTOP_ICON_COUNT_DISPLAY_NONE + ).update(desktop_icon_count_display=OLD_DESKTOP_ICON_COUNT_DISPLAY_NONE) + RealmUserDefault.objects.filter( + desktop_icon_count_display=NEW_DESKTOP_ICON_COUNT_DISPLAY_NONE + ).update(desktop_icon_count_display=OLD_DESKTOP_ICON_COUNT_DISPLAY_NONE) + + UserProfile.objects.filter( + desktop_icon_count_display=NEW_DESKTOP_ICON_COUNT_DISPLAY_DM_MENTION + ).update(desktop_icon_count_display=OLD_DESKTOP_ICON_COUNT_DISPLAY_DM_MENTION) + RealmUserDefault.objects.filter( + desktop_icon_count_display=NEW_DESKTOP_ICON_COUNT_DISPLAY_DM_MENTION + ).update(desktop_icon_count_display=OLD_DESKTOP_ICON_COUNT_DISPLAY_DM_MENTION) + + +class Migration(migrations.Migration): + dependencies = [ + ("zerver", "0489_alter_realm_can_access_all_users_group"), + ] + + operations = [ + migrations.RunPython(renumber_options, reverse_code=reverse_code, elidable=True), + ] diff --git a/zerver/models.py b/zerver/models.py --- a/zerver/models.py +++ b/zerver/models.py @@ -1680,11 +1680,13 @@ class UserBaseSettings(models.Model): enable_online_push_notifications = models.BooleanField(default=True) DESKTOP_ICON_COUNT_DISPLAY_MESSAGES = 1 - DESKTOP_ICON_COUNT_DISPLAY_NOTIFIABLE = 2 - DESKTOP_ICON_COUNT_DISPLAY_NONE = 3 + DESKTOP_ICON_COUNT_DISPLAY_DM_MENTION_FOLLOWED_TOPIC = 2 + DESKTOP_ICON_COUNT_DISPLAY_DM_MENTION = 3 + DESKTOP_ICON_COUNT_DISPLAY_NONE = 4 DESKTOP_ICON_COUNT_DISPLAY_CHOICES = [ DESKTOP_ICON_COUNT_DISPLAY_MESSAGES, - DESKTOP_ICON_COUNT_DISPLAY_NOTIFIABLE, + DESKTOP_ICON_COUNT_DISPLAY_DM_MENTION, + DESKTOP_ICON_COUNT_DISPLAY_DM_MENTION_FOLLOWED_TOPIC, DESKTOP_ICON_COUNT_DISPLAY_NONE, ] desktop_icon_count_display = models.PositiveSmallIntegerField(
diff --git a/web/tests/unread.test.js b/web/tests/unread.test.js --- a/web/tests/unread.test.js +++ b/web/tests/unread.test.js @@ -59,6 +59,9 @@ function test_notifiable_count(home_unread_messages, expected_notifiable_count) assert.deepEqual(notifiable_counts, expected_notifiable_count); user_settings.desktop_icon_count_display = 3; notifiable_counts = unread.get_notifiable_count(); + assert.deepEqual(notifiable_counts, expected_notifiable_count); + user_settings.desktop_icon_count_display = 4; + notifiable_counts = unread.get_notifiable_count(); assert.deepEqual(notifiable_counts, 0); }
Add option for followed topics to unread count badge setting <!-- Issue description --> As [suggested in the Rust community](https://rust-lang.zulipchat.com/#narrow/stream/122653-zulip/topic/.22Follow.20Topic.22.20feature/near/400008533), we should add a new unread count badge option (in SETTINGS / NOTIFICATIONS > Desktop message notifications) for including followed topics but not others. Specifically, let's have the options be: - All unread messages - DMs and mentions - DMs, mentions, and followed topics - None (Some existing options are relabeled for clarity/consisency.)
Hello @zulip/server-settings members, this issue was labeled with the "area: settings (user)" label, so you may want to check it out! <!-- areaLabelAddition --> @prakhar1144 Adding this to your 8.0 list. Please flag if it turns out to be tricky! @prakhar1144 We noticed that you have not made any updates to this issue or linked PRs for 10 days. Please comment here if you are still actively working on it. Otherwise, we'd appreciate a quick `@zulipbot abandon` comment so that someone else can claim this issue and continue from where you left off. If we don't hear back, you will be automatically unassigned in 4 days. Thanks! <!-- inactiveWarning --> In progress
2023-11-17T06:46:56
zulip/zulip
27,872
zulip__zulip-27872
[ "27526" ]
ff19dda71cc502586f064b3666b620dae7508239
diff --git a/corporate/lib/stripe.py b/corporate/lib/stripe.py --- a/corporate/lib/stripe.py +++ b/corporate/lib/stripe.py @@ -99,6 +99,19 @@ def format_money(cents: float) -> str: return f"{dollars:.{precision}f}" +def format_discount_percentage(discount: Optional[Decimal]) -> Optional[str]: + if type(discount) is not Decimal: + return None + + # Even though it looks like /activity/support only finds integers valid, + # this will look good for any custom discounts that we apply. + if discount * 100 % 100 == 0: + precision = 0 + else: + precision = 2 # nocoverage + return f"{discount:.{precision}f}" + + def get_latest_seat_count(realm: Realm) -> int: return get_seat_count(realm, extra_non_guests_count=0, extra_guests_count=0) @@ -1194,7 +1207,6 @@ def get_billing_page_context(self) -> Dict[str, Any]: if plan.fixed_price is not None else None ) - context = { "plan_name": plan.name, "has_active_plan": True, @@ -1215,6 +1227,8 @@ def get_billing_page_context(self) -> Dict[str, Any]: "billing_frequency": billing_frequency, "fixed_price": fixed_price, "price_per_license": price_per_license, + "is_sponsorship_pending": customer.sponsorship_pending, + "discount_percent": format_discount_percentage(customer.default_discount), } return context @@ -1256,6 +1270,7 @@ def get_initial_upgrade_context( "monthly_price": get_price_per_license(tier, CustomerPlan.MONTHLY, percent_off), }, "manual_license_management": initial_upgrade_request.manual_license_management, + "discount_percent": format_discount_percentage(percent_off), } # Check if user was successful in adding a card and we are rendering the page again. diff --git a/corporate/views/billing_page.py b/corporate/views/billing_page.py --- a/corporate/views/billing_page.py +++ b/corporate/views/billing_page.py @@ -6,7 +6,7 @@ from django.urls import reverse from corporate.lib.stripe import RealmBillingSession, UpdatePlanRequest -from corporate.models import CustomerPlan, get_customer_by_realm +from corporate.models import CustomerPlan, get_current_plan_by_customer, get_customer_by_realm from zerver.decorator import require_billing_access, zulip_login_required from zerver.lib.request import REQ, has_request_variables from zerver.lib.response import json_success @@ -15,6 +15,15 @@ billing_logger = logging.getLogger("corporate.stripe") +PAID_PLANS = [ + Realm.PLAN_TYPE_STANDARD, + Realm.PLAN_TYPE_PLUS, +] + + +def is_realm_on_paid_plan(realm: Realm) -> bool: + return realm.plan_type in PAID_PLANS + def add_sponsorship_info_to_context(context: Dict[str, Any], user_profile: UserProfile) -> None: def key_helper(d: Any) -> int: @@ -42,11 +51,22 @@ def sponsorship_request(request: HttpRequest) -> HttpResponse: customer = get_customer_by_realm(user.realm) if customer is not None and customer.sponsorship_pending: + if is_realm_on_paid_plan(user.realm): + return HttpResponseRedirect(reverse("billing_home")) + context["is_sponsorship_pending"] = True if user.realm.plan_type == user.realm.PLAN_TYPE_STANDARD_FREE: context["is_sponsored"] = True + if customer is not None: + plan = get_current_plan_by_customer(customer) + if plan is not None: + context["plan_name"] = plan.name + context["free_trial"] = plan.is_free_trial() + else: + context["plan_name"] = "Zulip Cloud Free" + add_sponsorship_info_to_context(context, user) return render(request, "corporate/sponsorship.html", context=context) @@ -72,15 +92,10 @@ def billing_home( if user.realm.plan_type == user.realm.PLAN_TYPE_STANDARD_FREE: return HttpResponseRedirect(reverse("sponsorship_request")) - PAID_PLANS = [ - Realm.PLAN_TYPE_STANDARD, - Realm.PLAN_TYPE_PLUS, - ] - customer = get_customer_by_realm(user.realm) if customer is not None and customer.sponsorship_pending: # Don't redirect to sponsorship page if the realm is on a paid plan - if user.realm.plan_type not in PAID_PLANS: + if not is_realm_on_paid_plan(user.realm): return HttpResponseRedirect(reverse("sponsorship_request")) # If the realm is on a paid plan, show the sponsorship pending message # TODO: Add a sponsorship pending message to the billing page
diff --git a/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Customer.create.1.json b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Customer.create.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Customer.create.1.json @@ -0,0 +1,33 @@ +{ + "address": null, + "balance": 0, + "created": 1000000000, + "currency": null, + "default_currency": null, + "default_source": null, + "delinquent": false, + "description": "zulip (Zulip Dev)", + "discount": null, + "email": "[email protected]", + "id": "cus_NORMALIZED0001", + "invoice_prefix": "NORMA01", + "invoice_settings": { + "custom_fields": null, + "default_payment_method": null, + "footer": null, + "rendering_options": null + }, + "livemode": false, + "metadata": { + "realm_id": "1", + "realm_str": "zulip" + }, + "name": null, + "next_invoice_sequence": 1, + "object": "customer", + "phone": null, + "preferred_locales": [], + "shipping": null, + "tax_exempt": "none", + "test_clock": null +} diff --git a/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Customer.modify.1.json b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Customer.modify.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Customer.modify.1.json @@ -0,0 +1,33 @@ +{ + "address": null, + "balance": 0, + "created": 1000000000, + "currency": null, + "default_currency": null, + "default_source": null, + "delinquent": false, + "description": "zulip (Zulip Dev)", + "discount": null, + "email": "[email protected]", + "id": "cus_NORMALIZED0001", + "invoice_prefix": "NORMA01", + "invoice_settings": { + "custom_fields": null, + "default_payment_method": "pm_1OFf15DEQaroqDjs1q9XiIYO", + "footer": null, + "rendering_options": null + }, + "livemode": false, + "metadata": { + "realm_id": "1", + "realm_str": "zulip" + }, + "name": null, + "next_invoice_sequence": 1, + "object": "customer", + "phone": null, + "preferred_locales": [], + "shipping": null, + "tax_exempt": "none", + "test_clock": null +} diff --git a/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Customer.retrieve.1.json b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Customer.retrieve.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Customer.retrieve.1.json @@ -0,0 +1,79 @@ +{ + "address": null, + "balance": 0, + "created": 1000000000, + "currency": null, + "default_currency": null, + "default_source": null, + "delinquent": false, + "description": "zulip (Zulip Dev)", + "discount": null, + "email": "[email protected]", + "id": "cus_NORMALIZED0001", + "invoice_prefix": "NORMA01", + "invoice_settings": { + "custom_fields": null, + "default_payment_method": { + "billing_details": { + "address": { + "city": null, + "country": null, + "line1": null, + "line2": null, + "postal_code": null, + "state": null + }, + "email": null, + "name": null, + "phone": null + }, + "card": { + "brand": "visa", + "checks": { + "address_line1_check": null, + "address_postal_code_check": null, + "cvc_check": "pass" + }, + "country": "US", + "exp_month": 11, + "exp_year": 2024, + "fingerprint": "NORMALIZED000001", + "funding": "credit", + "generated_from": null, + "last4": "4242", + "networks": { + "available": [ + "visa" + ], + "preferred": null + }, + "three_d_secure_usage": { + "supported": true + }, + "wallet": null + }, + "created": 1000000000, + "customer": "cus_NORMALIZED0001", + "id": "pm_1OFf15DEQaroqDjs1q9XiIYO", + "livemode": false, + "metadata": {}, + "object": "payment_method", + "type": "card" + }, + "footer": null, + "rendering_options": null + }, + "livemode": false, + "metadata": { + "realm_id": "1", + "realm_str": "zulip" + }, + "name": null, + "next_invoice_sequence": 1, + "object": "customer", + "phone": null, + "preferred_locales": [], + "shipping": null, + "tax_exempt": "none", + "test_clock": null +} diff --git a/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Customer.retrieve.2.json b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Customer.retrieve.2.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Customer.retrieve.2.json @@ -0,0 +1,79 @@ +{ + "address": null, + "balance": 0, + "created": 1000000000, + "currency": null, + "default_currency": null, + "default_source": null, + "delinquent": false, + "description": "zulip (Zulip Dev)", + "discount": null, + "email": "[email protected]", + "id": "cus_NORMALIZED0001", + "invoice_prefix": "NORMA01", + "invoice_settings": { + "custom_fields": null, + "default_payment_method": { + "billing_details": { + "address": { + "city": null, + "country": null, + "line1": null, + "line2": null, + "postal_code": null, + "state": null + }, + "email": null, + "name": null, + "phone": null + }, + "card": { + "brand": "visa", + "checks": { + "address_line1_check": null, + "address_postal_code_check": null, + "cvc_check": "pass" + }, + "country": "US", + "exp_month": 11, + "exp_year": 2024, + "fingerprint": "NORMALIZED000001", + "funding": "credit", + "generated_from": null, + "last4": "4242", + "networks": { + "available": [ + "visa" + ], + "preferred": null + }, + "three_d_secure_usage": { + "supported": true + }, + "wallet": null + }, + "created": 1000000000, + "customer": "cus_NORMALIZED0001", + "id": "pm_1OFf15DEQaroqDjs1q9XiIYO", + "livemode": false, + "metadata": {}, + "object": "payment_method", + "type": "card" + }, + "footer": null, + "rendering_options": null + }, + "livemode": false, + "metadata": { + "realm_id": "1", + "realm_str": "zulip" + }, + "name": null, + "next_invoice_sequence": 1, + "object": "customer", + "phone": null, + "preferred_locales": [], + "shipping": null, + "tax_exempt": "none", + "test_clock": null +} diff --git a/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Customer.retrieve.3.json b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Customer.retrieve.3.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Customer.retrieve.3.json @@ -0,0 +1,79 @@ +{ + "address": null, + "balance": 0, + "created": 1000000000, + "currency": null, + "default_currency": null, + "default_source": null, + "delinquent": false, + "description": "zulip (Zulip Dev)", + "discount": null, + "email": "[email protected]", + "id": "cus_NORMALIZED0001", + "invoice_prefix": "NORMA01", + "invoice_settings": { + "custom_fields": null, + "default_payment_method": { + "billing_details": { + "address": { + "city": null, + "country": null, + "line1": null, + "line2": null, + "postal_code": null, + "state": null + }, + "email": null, + "name": null, + "phone": null + }, + "card": { + "brand": "visa", + "checks": { + "address_line1_check": null, + "address_postal_code_check": null, + "cvc_check": "pass" + }, + "country": "US", + "exp_month": 11, + "exp_year": 2024, + "fingerprint": "NORMALIZED000001", + "funding": "credit", + "generated_from": null, + "last4": "4242", + "networks": { + "available": [ + "visa" + ], + "preferred": null + }, + "three_d_secure_usage": { + "supported": true + }, + "wallet": null + }, + "created": 1000000000, + "customer": "cus_NORMALIZED0001", + "id": "pm_1OFf15DEQaroqDjs1q9XiIYO", + "livemode": false, + "metadata": {}, + "object": "payment_method", + "type": "card" + }, + "footer": null, + "rendering_options": null + }, + "livemode": false, + "metadata": { + "realm_id": "1", + "realm_str": "zulip" + }, + "name": null, + "next_invoice_sequence": 1, + "object": "customer", + "phone": null, + "preferred_locales": [], + "shipping": null, + "tax_exempt": "none", + "test_clock": null +} diff --git a/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Customer.retrieve.4.json b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Customer.retrieve.4.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Customer.retrieve.4.json @@ -0,0 +1,79 @@ +{ + "address": null, + "balance": 0, + "created": 1000000000, + "currency": null, + "default_currency": null, + "default_source": null, + "delinquent": false, + "description": "zulip (Zulip Dev)", + "discount": null, + "email": "[email protected]", + "id": "cus_NORMALIZED0001", + "invoice_prefix": "NORMA01", + "invoice_settings": { + "custom_fields": null, + "default_payment_method": { + "billing_details": { + "address": { + "city": null, + "country": null, + "line1": null, + "line2": null, + "postal_code": null, + "state": null + }, + "email": null, + "name": null, + "phone": null + }, + "card": { + "brand": "visa", + "checks": { + "address_line1_check": null, + "address_postal_code_check": null, + "cvc_check": "pass" + }, + "country": "US", + "exp_month": 11, + "exp_year": 2024, + "fingerprint": "NORMALIZED000001", + "funding": "credit", + "generated_from": null, + "last4": "4242", + "networks": { + "available": [ + "visa" + ], + "preferred": null + }, + "three_d_secure_usage": { + "supported": true + }, + "wallet": null + }, + "created": 1000000000, + "customer": "cus_NORMALIZED0001", + "id": "pm_1OFf15DEQaroqDjs1q9XiIYO", + "livemode": false, + "metadata": {}, + "object": "payment_method", + "type": "card" + }, + "footer": null, + "rendering_options": null + }, + "livemode": false, + "metadata": { + "realm_id": "1", + "realm_str": "zulip" + }, + "name": null, + "next_invoice_sequence": 1, + "object": "customer", + "phone": null, + "preferred_locales": [], + "shipping": null, + "tax_exempt": "none", + "test_clock": null +} diff --git a/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Event.list.1.json b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Event.list.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Event.list.1.json @@ -0,0 +1,60 @@ +{ + "data": [ + { + "api_version": "2020-08-27", + "created": 1000000000, + "data": { + "object": { + "address": null, + "balance": 0, + "created": 1000000000, + "currency": null, + "default_currency": null, + "default_source": null, + "delinquent": false, + "description": "zulip (Zulip Dev)", + "discount": null, + "email": "[email protected]", + "id": "cus_NORMALIZED0001", + "invoice_prefix": "NORMA01", + "invoice_settings": { + "custom_fields": null, + "default_payment_method": "pm_1OFf15DEQaroqDjs1q9XiIYO", + "footer": null, + "rendering_options": null + }, + "livemode": false, + "metadata": { + "realm_id": "1", + "realm_str": "zulip" + }, + "name": null, + "next_invoice_sequence": 1, + "object": "customer", + "phone": null, + "preferred_locales": [], + "shipping": null, + "tax_exempt": "none", + "test_clock": null + }, + "previous_attributes": { + "invoice_settings": { + "default_payment_method": null + } + } + }, + "id": "evt_1OFf17DEQaroqDjsU1s8LSFB", + "livemode": false, + "object": "event", + "pending_webhooks": 0, + "request": { + "id": "req_NORMALIZED0001", + "idempotency_key": "94a6e570-9c1e-45bc-bfdf-e1990be34b10" + }, + "type": "customer.updated" + } + ], + "has_more": true, + "object": "list", + "url": "/v1/events" +} diff --git a/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Event.list.2.json b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Event.list.2.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Event.list.2.json @@ -0,0 +1,358 @@ +{ + "data": [ + { + "api_version": "2020-08-27", + "created": 1000000000, + "data": { + "object": { + "amount": 48000, + "amount_capturable": 0, + "amount_details": { + "tip": {} + }, + "amount_received": 48000, + "application": null, + "application_fee_amount": null, + "automatic_payment_methods": null, + "canceled_at": null, + "cancellation_reason": null, + "capture_method": "automatic", + "charges": { + "data": [ + { + "amount": 48000, + "amount_captured": 48000, + "amount_refunded": 0, + "application": null, + "application_fee": null, + "application_fee_amount": null, + "balance_transaction": "txn_NORMALIZED00000000000001", + "billing_details": { + "address": { + "city": null, + "country": null, + "line1": null, + "line2": null, + "postal_code": null, + "state": null + }, + "email": null, + "name": null, + "phone": null + }, + "calculated_statement_descriptor": "ZULIP CLOUD STANDARD", + "captured": true, + "created": 1000000000, + "currency": "usd", + "customer": "cus_NORMALIZED0001", + "description": "Upgrade to Zulip Cloud Standard, $80.0 x 6", + "destination": null, + "dispute": null, + "disputed": false, + "failure_balance_transaction": null, + "failure_code": null, + "failure_message": null, + "fraud_details": {}, + "id": "ch_NORMALIZED00000000000001", + "invoice": null, + "livemode": false, + "metadata": { + "billing_modality": "charge_automatically", + "billing_schedule": "1", + "license_management": "automatic", + "licenses": "6", + "price_per_license": "8000", + "realm_id": "1", + "realm_str": "zulip", + "seat_count": "6", + "type": "upgrade", + "user_email": "[email protected]", + "user_id": "10" + }, + "object": "charge", + "on_behalf_of": null, + "order": null, + "outcome": { + "network_status": "approved_by_network", + "reason": null, + "risk_level": "normal", + "risk_score": 0, + "seller_message": "Payment complete.", + "type": "authorized" + }, + "paid": true, + "payment_intent": "pi_NORMALIZED00000000000001", + "payment_method": "pm_1OFf15DEQaroqDjs1q9XiIYO", + "payment_method_details": { + "card": { + "amount_authorized": 48000, + "brand": "visa", + "checks": { + "address_line1_check": null, + "address_postal_code_check": null, + "cvc_check": "pass" + }, + "country": "US", + "exp_month": 11, + "exp_year": 2024, + "extended_authorization": { + "status": "disabled" + }, + "fingerprint": "NORMALIZED000001", + "funding": "credit", + "incremental_authorization": { + "status": "unavailable" + }, + "installments": null, + "last4": "4242", + "mandate": null, + "multicapture": { + "status": "unavailable" + }, + "network": "visa", + "network_token": { + "used": false + }, + "overcapture": { + "maximum_amount_capturable": 48000, + "status": "unavailable" + }, + "three_d_secure": null, + "wallet": null + }, + "type": "card" + }, + "receipt_email": "[email protected]", + "receipt_number": null, + "receipt_url": "https://pay.stripe.com/receipts/payment/CAcaFwoVYWNjdF8xN3ZUa3dERVFhcm9xRGpzKPjk_aoGMgYcZbjY3nY6LBanVRp3LdlPDRfe31_DM9Sx6RUhHlzPIQE47LWMcCfNYRm50P8LebxIg6cZ", + "refunded": false, + "refunds": { + "data": [], + "has_more": false, + "object": "list", + "total_count": 0, + "url": "/v1/charges/ch_NORMALIZED00000000000001/refunds" + }, + "review": null, + "shipping": null, + "source": null, + "source_transfer": null, + "statement_descriptor": "Zulip Cloud Standard", + "statement_descriptor_suffix": null, + "status": "succeeded", + "transfer_data": null, + "transfer_group": null + } + ], + "has_more": false, + "object": "list", + "total_count": 1, + "url": "/v1/charges?payment_intent=pi_NORMALIZED00000000000001" + }, + "client_secret": "pi_NORMALIZED00000000000001_secret_M6ApwY4vAGFmAi20dvhDBb0IR", + "confirmation_method": "automatic", + "created": 1000000000, + "currency": "usd", + "customer": "cus_NORMALIZED0001", + "description": "Upgrade to Zulip Cloud Standard, $80.0 x 6", + "id": "pi_NORMALIZED00000000000001", + "invoice": null, + "last_payment_error": null, + "latest_charge": "ch_NORMALIZED00000000000001", + "livemode": false, + "metadata": { + "billing_modality": "charge_automatically", + "billing_schedule": "1", + "license_management": "automatic", + "licenses": "6", + "price_per_license": "8000", + "realm_id": "1", + "realm_str": "zulip", + "seat_count": "6", + "type": "upgrade", + "user_email": "[email protected]", + "user_id": "10" + }, + "next_action": null, + "object": "payment_intent", + "on_behalf_of": null, + "payment_method": "pm_1OFf15DEQaroqDjs1q9XiIYO", + "payment_method_configuration_details": null, + "payment_method_options": { + "card": { + "installments": null, + "mandate_options": null, + "network": null, + "request_three_d_secure": "automatic" + } + }, + "payment_method_types": [ + "card" + ], + "processing": null, + "receipt_email": "[email protected]", + "review": null, + "setup_future_usage": null, + "shipping": null, + "source": null, + "statement_descriptor": "Zulip Cloud Standard", + "statement_descriptor_suffix": null, + "status": "succeeded", + "transfer_data": null, + "transfer_group": null + } + }, + "id": "evt_3OFf19DEQaroqDjs0qiviyEA", + "livemode": false, + "object": "event", + "pending_webhooks": 2, + "request": { + "id": "req_NORMALIZED0002", + "idempotency_key": "a3574bba-9be7-4b32-a238-558b051dfb96" + }, + "type": "payment_intent.succeeded" + }, + { + "api_version": "2020-08-27", + "created": 1000000000, + "data": { + "object": { + "amount": 48000, + "amount_captured": 48000, + "amount_refunded": 0, + "application": null, + "application_fee": null, + "application_fee_amount": null, + "balance_transaction": "txn_NORMALIZED00000000000001", + "billing_details": { + "address": { + "city": null, + "country": null, + "line1": null, + "line2": null, + "postal_code": null, + "state": null + }, + "email": null, + "name": null, + "phone": null + }, + "calculated_statement_descriptor": "ZULIP CLOUD STANDARD", + "captured": true, + "created": 1000000000, + "currency": "usd", + "customer": "cus_NORMALIZED0001", + "description": "Upgrade to Zulip Cloud Standard, $80.0 x 6", + "destination": null, + "dispute": null, + "disputed": false, + "failure_balance_transaction": null, + "failure_code": null, + "failure_message": null, + "fraud_details": {}, + "id": "ch_NORMALIZED00000000000001", + "invoice": null, + "livemode": false, + "metadata": { + "billing_modality": "charge_automatically", + "billing_schedule": "1", + "license_management": "automatic", + "licenses": "6", + "price_per_license": "8000", + "realm_id": "1", + "realm_str": "zulip", + "seat_count": "6", + "type": "upgrade", + "user_email": "[email protected]", + "user_id": "10" + }, + "object": "charge", + "on_behalf_of": null, + "order": null, + "outcome": { + "network_status": "approved_by_network", + "reason": null, + "risk_level": "normal", + "risk_score": 0, + "seller_message": "Payment complete.", + "type": "authorized" + }, + "paid": true, + "payment_intent": "pi_NORMALIZED00000000000001", + "payment_method": "pm_1OFf15DEQaroqDjs1q9XiIYO", + "payment_method_details": { + "card": { + "amount_authorized": 48000, + "brand": "visa", + "checks": { + "address_line1_check": null, + "address_postal_code_check": null, + "cvc_check": "pass" + }, + "country": "US", + "exp_month": 11, + "exp_year": 2024, + "extended_authorization": { + "status": "disabled" + }, + "fingerprint": "NORMALIZED000001", + "funding": "credit", + "incremental_authorization": { + "status": "unavailable" + }, + "installments": null, + "last4": "4242", + "mandate": null, + "multicapture": { + "status": "unavailable" + }, + "network": "visa", + "network_token": { + "used": false + }, + "overcapture": { + "maximum_amount_capturable": 48000, + "status": "unavailable" + }, + "three_d_secure": null, + "wallet": null + }, + "type": "card" + }, + "receipt_email": "[email protected]", + "receipt_number": null, + "receipt_url": "https://pay.stripe.com/receipts/payment/CAcaFwoVYWNjdF8xN3ZUa3dERVFhcm9xRGpzKPjk_aoGMgZTMbwVPPA6LBYOFAnAQNWX3oHYRTeyBRUbEddYOzstDN76W_doC3tz9_453G4jbZAARiny", + "refunded": false, + "refunds": { + "data": [], + "has_more": false, + "object": "list", + "total_count": 0, + "url": "/v1/charges/ch_NORMALIZED00000000000001/refunds" + }, + "review": null, + "shipping": null, + "source": null, + "source_transfer": null, + "statement_descriptor": "Zulip Cloud Standard", + "statement_descriptor_suffix": null, + "status": "succeeded", + "transfer_data": null, + "transfer_group": null + } + }, + "id": "evt_3OFf19DEQaroqDjs0ugYOOnJ", + "livemode": false, + "object": "event", + "pending_webhooks": 0, + "request": { + "id": "req_NORMALIZED0002", + "idempotency_key": "a3574bba-9be7-4b32-a238-558b051dfb96" + }, + "type": "charge.succeeded" + } + ], + "has_more": false, + "object": "list", + "url": "/v1/events" +} diff --git a/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Event.list.3.json b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Event.list.3.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Event.list.3.json @@ -0,0 +1,650 @@ +{ + "data": [ + { + "api_version": "2020-08-27", + "created": 1000000000, + "data": { + "object": { + "account_country": "US", + "account_name": "Kandra Labs, Inc.", + "account_tax_ids": null, + "amount_due": 0, + "amount_paid": 0, + "amount_remaining": 0, + "amount_shipping": 0, + "application": null, + "application_fee_amount": null, + "attempt_count": 0, + "attempted": true, + "auto_advance": false, + "automatic_tax": { + "enabled": false, + "status": null + }, + "billing_reason": "manual", + "charge": null, + "collection_method": "charge_automatically", + "created": 1000000000, + "currency": "usd", + "custom_fields": null, + "customer": "cus_NORMALIZED0001", + "customer_address": null, + "customer_email": "[email protected]", + "customer_name": null, + "customer_phone": null, + "customer_shipping": null, + "customer_tax_exempt": "none", + "customer_tax_ids": [], + "default_payment_method": null, + "default_source": null, + "default_tax_rates": [], + "description": null, + "discount": null, + "discounts": [], + "due_date": null, + "effective_at": 1000000000, + "ending_balance": 0, + "footer": null, + "from_invoice": null, + "hosted_invoice_url": "https://invoice.stripe.com/i/acct_NORMALIZED000001/test_NORMALIZED01a3dERVFhcm9xRGpzLF9QM21hVDlsakpzWHpqaUk2ZkRncEx2cWlNektoczlCLDkxMjk0ODQz0200lVZQw1fc?s=ap", + "id": "in_NORMALIZED00000000000001", + "invoice_pdf": "https://pay.stripe.com/invoice/acct_NORMALIZED000001/test_NORMALIZED01a3dERVFhcm9xRGpzLF9QM21hVDlsakpzWHpqaUk2ZkRncEx2cWlNektoczlCLDkxMjk0ODQz0200lVZQw1fc/pdf?s=ap", + "last_finalization_error": null, + "latest_revision": null, + "lines": { + "data": [ + { + "amount": 48000, + "amount_excluding_tax": 48000, + "currency": "usd", + "description": "Zulip Cloud Standard", + "discount_amounts": [], + "discountable": false, + "discounts": [], + "id": "il_NORMALIZED00000000000001", + "invoice_item": "ii_NORMALIZED00000000000001", + "livemode": false, + "metadata": {}, + "object": "line_item", + "period": { + "end": 1357095845, + "start": 1325473445 + }, + "plan": null, + "price": { + "active": false, + "billing_scheme": "per_unit", + "created": 1000000000, + "currency": "usd", + "custom_unit_amount": null, + "id": "price_NORMALIZED00000000000001", + "livemode": false, + "lookup_key": null, + "metadata": {}, + "nickname": null, + "object": "price", + "product": "prod_NORMALIZED0001", + "recurring": null, + "tax_behavior": "unspecified", + "tiers_mode": null, + "transform_quantity": null, + "type": "one_time", + "unit_amount": 8000, + "unit_amount_decimal": "8000" + }, + "proration": false, + "proration_details": { + "credited_items": null + }, + "quantity": 6, + "subscription": null, + "tax_amounts": [], + "tax_rates": [], + "type": "invoiceitem", + "unit_amount_excluding_tax": "8000" + }, + { + "amount": -48000, + "amount_excluding_tax": -48000, + "currency": "usd", + "description": "Payment (Card ending in 4242)", + "discount_amounts": [], + "discountable": false, + "discounts": [], + "id": "il_NORMALIZED00000000000002", + "invoice_item": "ii_NORMALIZED00000000000002", + "livemode": false, + "metadata": {}, + "object": "line_item", + "period": { + "end": 1000000000, + "start": 1000000000 + }, + "plan": null, + "price": { + "active": false, + "billing_scheme": "per_unit", + "created": 1000000000, + "currency": "usd", + "custom_unit_amount": null, + "id": "price_NORMALIZED00000000000002", + "livemode": false, + "lookup_key": null, + "metadata": {}, + "nickname": null, + "object": "price", + "product": "prod_NORMALIZED0002", + "recurring": null, + "tax_behavior": "unspecified", + "tiers_mode": null, + "transform_quantity": null, + "type": "one_time", + "unit_amount": -48000, + "unit_amount_decimal": "-48000" + }, + "proration": false, + "proration_details": { + "credited_items": null + }, + "quantity": 1, + "subscription": null, + "tax_amounts": [], + "tax_rates": [], + "type": "invoiceitem", + "unit_amount_excluding_tax": "-48000" + } + ], + "has_more": false, + "object": "list", + "total_count": 2, + "url": "/v1/invoices/in_NORMALIZED00000000000001/lines" + }, + "livemode": false, + "metadata": {}, + "next_payment_attempt": null, + "number": "NORMALI-0001", + "object": "invoice", + "on_behalf_of": null, + "paid": true, + "paid_out_of_band": false, + "payment_intent": null, + "payment_settings": { + "default_mandate": null, + "payment_method_options": null, + "payment_method_types": null + }, + "period_end": 1000000000, + "period_start": 1000000000, + "post_payment_credit_notes_amount": 0, + "pre_payment_credit_notes_amount": 0, + "quote": null, + "receipt_number": null, + "rendering": { + "amount_tax_display": null, + "pdf": { + "page_size": "letter" + } + }, + "rendering_options": null, + "shipping_cost": null, + "shipping_details": null, + "starting_balance": 0, + "statement_descriptor": "Zulip Cloud Standard", + "status": "paid", + "status_transitions": { + "finalized_at": 1000000000, + "marked_uncollectible_at": null, + "paid_at": 1000000000, + "voided_at": null + }, + "subscription": null, + "subscription_details": { + "metadata": null + }, + "subtotal": 0, + "subtotal_excluding_tax": 0, + "tax": null, + "test_clock": null, + "total": 0, + "total_discount_amounts": [], + "total_excluding_tax": 0, + "total_tax_amounts": [], + "transfer_data": null, + "webhooks_delivered_at": null + }, + "previous_attributes": { + "attempted": false, + "auto_advance": true, + "effective_at": null, + "ending_balance": null, + "hosted_invoice_url": null, + "invoice_pdf": null, + "next_payment_attempt": 1000000000, + "number": null, + "paid": false, + "rendering": { + "pdf": { + "page_size": "auto" + } + }, + "status": "draft", + "status_transitions": { + "finalized_at": null, + "paid_at": null + } + } + }, + "id": "evt_1OFf1DDEQaroqDjsNV7v85uL", + "livemode": false, + "object": "event", + "pending_webhooks": 2, + "request": { + "id": "req_NORMALIZED0003", + "idempotency_key": "04b05b83-138d-47f5-b93e-1c8868d16aeb" + }, + "type": "invoice.updated" + }, + { + "api_version": "2020-08-27", + "created": 1000000000, + "data": { + "object": { + "account_country": "US", + "account_name": "Kandra Labs, Inc.", + "account_tax_ids": null, + "amount_due": 0, + "amount_paid": 0, + "amount_remaining": 0, + "amount_shipping": 0, + "application": null, + "application_fee_amount": null, + "attempt_count": 0, + "attempted": false, + "auto_advance": true, + "automatic_tax": { + "enabled": false, + "status": null + }, + "billing_reason": "manual", + "charge": null, + "collection_method": "charge_automatically", + "created": 1000000000, + "currency": "usd", + "custom_fields": null, + "customer": "cus_NORMALIZED0001", + "customer_address": null, + "customer_email": "[email protected]", + "customer_name": null, + "customer_phone": null, + "customer_shipping": null, + "customer_tax_exempt": "none", + "customer_tax_ids": [], + "default_payment_method": null, + "default_source": null, + "default_tax_rates": [], + "description": null, + "discount": null, + "discounts": [], + "due_date": null, + "effective_at": null, + "ending_balance": null, + "footer": null, + "from_invoice": null, + "hosted_invoice_url": null, + "id": "in_NORMALIZED00000000000001", + "invoice_pdf": null, + "last_finalization_error": null, + "latest_revision": null, + "lines": { + "data": [ + { + "amount": 48000, + "amount_excluding_tax": 48000, + "currency": "usd", + "description": "Zulip Cloud Standard", + "discount_amounts": [], + "discountable": false, + "discounts": [], + "id": "il_NORMALIZED00000000000001", + "invoice_item": "ii_NORMALIZED00000000000001", + "livemode": false, + "metadata": {}, + "object": "line_item", + "period": { + "end": 1357095845, + "start": 1325473445 + }, + "plan": null, + "price": { + "active": false, + "billing_scheme": "per_unit", + "created": 1000000000, + "currency": "usd", + "custom_unit_amount": null, + "id": "price_NORMALIZED00000000000001", + "livemode": false, + "lookup_key": null, + "metadata": {}, + "nickname": null, + "object": "price", + "product": "prod_NORMALIZED0001", + "recurring": null, + "tax_behavior": "unspecified", + "tiers_mode": null, + "transform_quantity": null, + "type": "one_time", + "unit_amount": 8000, + "unit_amount_decimal": "8000" + }, + "proration": false, + "proration_details": { + "credited_items": null + }, + "quantity": 6, + "subscription": null, + "tax_amounts": [], + "tax_rates": [], + "type": "invoiceitem", + "unit_amount_excluding_tax": "8000" + }, + { + "amount": -48000, + "amount_excluding_tax": -48000, + "currency": "usd", + "description": "Payment (Card ending in 4242)", + "discount_amounts": [], + "discountable": false, + "discounts": [], + "id": "il_NORMALIZED00000000000002", + "invoice_item": "ii_NORMALIZED00000000000002", + "livemode": false, + "metadata": {}, + "object": "line_item", + "period": { + "end": 1000000000, + "start": 1000000000 + }, + "plan": null, + "price": { + "active": false, + "billing_scheme": "per_unit", + "created": 1000000000, + "currency": "usd", + "custom_unit_amount": null, + "id": "price_NORMALIZED00000000000002", + "livemode": false, + "lookup_key": null, + "metadata": {}, + "nickname": null, + "object": "price", + "product": "prod_NORMALIZED0002", + "recurring": null, + "tax_behavior": "unspecified", + "tiers_mode": null, + "transform_quantity": null, + "type": "one_time", + "unit_amount": -48000, + "unit_amount_decimal": "-48000" + }, + "proration": false, + "proration_details": { + "credited_items": null + }, + "quantity": 1, + "subscription": null, + "tax_amounts": [], + "tax_rates": [], + "type": "invoiceitem", + "unit_amount_excluding_tax": "-48000" + } + ], + "has_more": false, + "object": "list", + "total_count": 2, + "url": "/v1/invoices/in_NORMALIZED00000000000001/lines" + }, + "livemode": false, + "metadata": {}, + "next_payment_attempt": 1000000000, + "number": null, + "object": "invoice", + "on_behalf_of": null, + "paid": false, + "paid_out_of_band": false, + "payment_intent": null, + "payment_settings": { + "default_mandate": null, + "payment_method_options": null, + "payment_method_types": null + }, + "period_end": 1000000000, + "period_start": 1000000000, + "post_payment_credit_notes_amount": 0, + "pre_payment_credit_notes_amount": 0, + "quote": null, + "receipt_number": null, + "rendering": { + "amount_tax_display": null, + "pdf": { + "page_size": "auto" + } + }, + "rendering_options": null, + "shipping_cost": null, + "shipping_details": null, + "starting_balance": 0, + "statement_descriptor": "Zulip Cloud Standard", + "status": "draft", + "status_transitions": { + "finalized_at": null, + "marked_uncollectible_at": null, + "paid_at": null, + "voided_at": null + }, + "subscription": null, + "subscription_details": { + "metadata": null + }, + "subtotal": 0, + "subtotal_excluding_tax": 0, + "tax": null, + "test_clock": null, + "total": 0, + "total_discount_amounts": [], + "total_excluding_tax": 0, + "total_tax_amounts": [], + "transfer_data": null, + "webhooks_delivered_at": null + } + }, + "id": "evt_1OFf1CDEQaroqDjsZg6gZ4uO", + "livemode": false, + "object": "event", + "pending_webhooks": 0, + "request": { + "id": "req_NORMALIZED0004", + "idempotency_key": "7993c516-09b3-4ce7-85d3-64435d27cdb3" + }, + "type": "invoice.created" + }, + { + "api_version": "2020-08-27", + "created": 1000000000, + "data": { + "object": { + "amount": 48000, + "currency": "usd", + "customer": "cus_NORMALIZED0001", + "date": 1000000000, + "description": "Zulip Cloud Standard", + "discountable": false, + "discounts": [], + "id": "ii_NORMALIZED00000000000001", + "invoice": null, + "livemode": false, + "metadata": {}, + "object": "invoiceitem", + "period": { + "end": 1357095845, + "start": 1325473445 + }, + "plan": null, + "price": { + "active": false, + "billing_scheme": "per_unit", + "created": 1000000000, + "currency": "usd", + "custom_unit_amount": null, + "id": "price_NORMALIZED00000000000001", + "livemode": false, + "lookup_key": null, + "metadata": {}, + "nickname": null, + "object": "price", + "product": "prod_NORMALIZED0001", + "recurring": null, + "tax_behavior": "unspecified", + "tiers_mode": null, + "transform_quantity": null, + "type": "one_time", + "unit_amount": 8000, + "unit_amount_decimal": "8000" + }, + "proration": false, + "quantity": 6, + "subscription": null, + "tax_rates": [], + "test_clock": null, + "unit_amount": 8000, + "unit_amount_decimal": "8000" + } + }, + "id": "evt_1OFf1BDEQaroqDjsbR7QE22k", + "livemode": false, + "object": "event", + "pending_webhooks": 0, + "request": { + "id": "req_NORMALIZED0005", + "idempotency_key": "765364b4-10a9-4f5a-b210-559f97cb9a7b" + }, + "type": "invoiceitem.created" + }, + { + "api_version": "2020-08-27", + "created": 1000000000, + "data": { + "object": { + "amount": -48000, + "currency": "usd", + "customer": "cus_NORMALIZED0001", + "date": 1000000000, + "description": "Payment (Card ending in 4242)", + "discountable": false, + "discounts": [], + "id": "ii_NORMALIZED00000000000002", + "invoice": null, + "livemode": false, + "metadata": {}, + "object": "invoiceitem", + "period": { + "end": 1000000000, + "start": 1000000000 + }, + "plan": null, + "price": { + "active": false, + "billing_scheme": "per_unit", + "created": 1000000000, + "currency": "usd", + "custom_unit_amount": null, + "id": "price_NORMALIZED00000000000002", + "livemode": false, + "lookup_key": null, + "metadata": {}, + "nickname": null, + "object": "price", + "product": "prod_NORMALIZED0002", + "recurring": null, + "tax_behavior": "unspecified", + "tiers_mode": null, + "transform_quantity": null, + "type": "one_time", + "unit_amount": -48000, + "unit_amount_decimal": "-48000" + }, + "proration": false, + "quantity": 1, + "subscription": null, + "tax_rates": [], + "test_clock": null, + "unit_amount": -48000, + "unit_amount_decimal": "-48000" + } + }, + "id": "evt_1OFf1BDEQaroqDjsmNut4lRS", + "livemode": false, + "object": "event", + "pending_webhooks": 0, + "request": { + "id": "req_NORMALIZED0006", + "idempotency_key": "82aa6384-75e9-450d-af66-a70db31b4e42" + }, + "type": "invoiceitem.created" + }, + { + "api_version": "2020-08-27", + "created": 1000000000, + "data": { + "object": { + "address": null, + "balance": 0, + "created": 1000000000, + "currency": "usd", + "default_currency": "usd", + "default_source": null, + "delinquent": false, + "description": "zulip (Zulip Dev)", + "discount": null, + "email": "[email protected]", + "id": "cus_NORMALIZED0001", + "invoice_prefix": "NORMA01", + "invoice_settings": { + "custom_fields": null, + "default_payment_method": "pm_1OFf15DEQaroqDjs1q9XiIYO", + "footer": null, + "rendering_options": null + }, + "livemode": false, + "metadata": { + "realm_id": "1", + "realm_str": "zulip" + }, + "name": null, + "next_invoice_sequence": 1, + "object": "customer", + "phone": null, + "preferred_locales": [], + "shipping": null, + "tax_exempt": "none", + "test_clock": null + }, + "previous_attributes": { + "currency": null, + "default_currency": null + } + }, + "id": "evt_1OFf1BDEQaroqDjs421MxAts", + "livemode": false, + "object": "event", + "pending_webhooks": 0, + "request": { + "id": "req_NORMALIZED0006", + "idempotency_key": "82aa6384-75e9-450d-af66-a70db31b4e42" + }, + "type": "customer.updated" + } + ], + "has_more": false, + "object": "list", + "url": "/v1/events" +} diff --git a/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Event.list.4.json b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Event.list.4.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Event.list.4.json @@ -0,0 +1,453 @@ +{ + "data": [ + { + "api_version": "2020-08-27", + "created": 1000000000, + "data": { + "object": { + "account_country": "US", + "account_name": "Kandra Labs, Inc.", + "account_tax_ids": null, + "amount_due": 0, + "amount_paid": 0, + "amount_remaining": 0, + "amount_shipping": 0, + "application": null, + "application_fee_amount": null, + "attempt_count": 0, + "attempted": true, + "auto_advance": false, + "automatic_tax": { + "enabled": false, + "status": null + }, + "billing_reason": "manual", + "charge": null, + "collection_method": "charge_automatically", + "created": 1000000000, + "currency": "usd", + "custom_fields": null, + "customer": "cus_NORMALIZED0001", + "customer_address": null, + "customer_email": "[email protected]", + "customer_name": null, + "customer_phone": null, + "customer_shipping": null, + "customer_tax_exempt": "none", + "customer_tax_ids": [], + "default_payment_method": null, + "default_source": null, + "default_tax_rates": [], + "description": null, + "discount": null, + "discounts": [], + "due_date": null, + "effective_at": 1000000000, + "ending_balance": 0, + "footer": null, + "from_invoice": null, + "hosted_invoice_url": "https://invoice.stripe.com/i/acct_NORMALIZED000001/test_NORMALIZED01a3dERVFhcm9xRGpzLF9QM21hVDlsakpzWHpqaUk2ZkRncEx2cWlNektoczlCLDkxMjk0ODQz0200lVZQw1fc?s=ap", + "id": "in_NORMALIZED00000000000001", + "invoice_pdf": "https://pay.stripe.com/invoice/acct_NORMALIZED000001/test_NORMALIZED01a3dERVFhcm9xRGpzLF9QM21hVDlsakpzWHpqaUk2ZkRncEx2cWlNektoczlCLDkxMjk0ODQz0200lVZQw1fc/pdf?s=ap", + "last_finalization_error": null, + "latest_revision": null, + "lines": { + "data": [ + { + "amount": 48000, + "amount_excluding_tax": 48000, + "currency": "usd", + "description": "Zulip Cloud Standard", + "discount_amounts": [], + "discountable": false, + "discounts": [], + "id": "il_NORMALIZED00000000000001", + "invoice_item": "ii_NORMALIZED00000000000001", + "livemode": false, + "metadata": {}, + "object": "line_item", + "period": { + "end": 1357095845, + "start": 1325473445 + }, + "plan": null, + "price": { + "active": false, + "billing_scheme": "per_unit", + "created": 1000000000, + "currency": "usd", + "custom_unit_amount": null, + "id": "price_NORMALIZED00000000000001", + "livemode": false, + "lookup_key": null, + "metadata": {}, + "nickname": null, + "object": "price", + "product": "prod_NORMALIZED0001", + "recurring": null, + "tax_behavior": "unspecified", + "tiers_mode": null, + "transform_quantity": null, + "type": "one_time", + "unit_amount": 8000, + "unit_amount_decimal": "8000" + }, + "proration": false, + "proration_details": { + "credited_items": null + }, + "quantity": 6, + "subscription": null, + "tax_amounts": [], + "tax_rates": [], + "type": "invoiceitem", + "unit_amount_excluding_tax": "8000" + }, + { + "amount": -48000, + "amount_excluding_tax": -48000, + "currency": "usd", + "description": "Payment (Card ending in 4242)", + "discount_amounts": [], + "discountable": false, + "discounts": [], + "id": "il_NORMALIZED00000000000002", + "invoice_item": "ii_NORMALIZED00000000000002", + "livemode": false, + "metadata": {}, + "object": "line_item", + "period": { + "end": 1000000000, + "start": 1000000000 + }, + "plan": null, + "price": { + "active": false, + "billing_scheme": "per_unit", + "created": 1000000000, + "currency": "usd", + "custom_unit_amount": null, + "id": "price_NORMALIZED00000000000002", + "livemode": false, + "lookup_key": null, + "metadata": {}, + "nickname": null, + "object": "price", + "product": "prod_NORMALIZED0002", + "recurring": null, + "tax_behavior": "unspecified", + "tiers_mode": null, + "transform_quantity": null, + "type": "one_time", + "unit_amount": -48000, + "unit_amount_decimal": "-48000" + }, + "proration": false, + "proration_details": { + "credited_items": null + }, + "quantity": 1, + "subscription": null, + "tax_amounts": [], + "tax_rates": [], + "type": "invoiceitem", + "unit_amount_excluding_tax": "-48000" + } + ], + "has_more": false, + "object": "list", + "total_count": 2, + "url": "/v1/invoices/in_NORMALIZED00000000000001/lines" + }, + "livemode": false, + "metadata": {}, + "next_payment_attempt": null, + "number": "NORMALI-0002", + "object": "invoice", + "on_behalf_of": null, + "paid": true, + "paid_out_of_band": false, + "payment_intent": null, + "payment_settings": { + "default_mandate": null, + "payment_method_options": null, + "payment_method_types": null + }, + "period_end": 1000000000, + "period_start": 1000000000, + "post_payment_credit_notes_amount": 0, + "pre_payment_credit_notes_amount": 0, + "quote": null, + "receipt_number": null, + "rendering": { + "amount_tax_display": null, + "pdf": { + "page_size": "letter" + } + }, + "rendering_options": null, + "shipping_cost": null, + "shipping_details": null, + "starting_balance": 0, + "statement_descriptor": "Zulip Cloud Standard", + "status": "paid", + "status_transitions": { + "finalized_at": 1000000000, + "marked_uncollectible_at": null, + "paid_at": 1000000000, + "voided_at": null + }, + "subscription": null, + "subscription_details": { + "metadata": null + }, + "subtotal": 0, + "subtotal_excluding_tax": 0, + "tax": null, + "test_clock": null, + "total": 0, + "total_discount_amounts": [], + "total_excluding_tax": 0, + "total_tax_amounts": [], + "transfer_data": null, + "webhooks_delivered_at": null + } + }, + "id": "evt_1OFf1DDEQaroqDjsJWyQlBeS", + "livemode": false, + "object": "event", + "pending_webhooks": 2, + "request": { + "id": "req_NORMALIZED0003", + "idempotency_key": "04b05b83-138d-47f5-b93e-1c8868d16aeb" + }, + "type": "invoice.paid" + }, + { + "api_version": "2020-08-27", + "created": 1000000000, + "data": { + "object": { + "account_country": "US", + "account_name": "Kandra Labs, Inc.", + "account_tax_ids": null, + "amount_due": 0, + "amount_paid": 0, + "amount_remaining": 0, + "amount_shipping": 0, + "application": null, + "application_fee_amount": null, + "attempt_count": 0, + "attempted": true, + "auto_advance": false, + "automatic_tax": { + "enabled": false, + "status": null + }, + "billing_reason": "manual", + "charge": null, + "collection_method": "charge_automatically", + "created": 1000000000, + "currency": "usd", + "custom_fields": null, + "customer": "cus_NORMALIZED0001", + "customer_address": null, + "customer_email": "[email protected]", + "customer_name": null, + "customer_phone": null, + "customer_shipping": null, + "customer_tax_exempt": "none", + "customer_tax_ids": [], + "default_payment_method": null, + "default_source": null, + "default_tax_rates": [], + "description": null, + "discount": null, + "discounts": [], + "due_date": null, + "effective_at": 1000000000, + "ending_balance": 0, + "footer": null, + "from_invoice": null, + "hosted_invoice_url": "https://invoice.stripe.com/i/acct_NORMALIZED000001/test_NORMALIZED01a3dERVFhcm9xRGpzLF9QM21hVDlsakpzWHpqaUk2ZkRncEx2cWlNektoczlCLDkxMjk0ODQz0200lVZQw1fc?s=ap", + "id": "in_NORMALIZED00000000000001", + "invoice_pdf": "https://pay.stripe.com/invoice/acct_NORMALIZED000001/test_NORMALIZED01a3dERVFhcm9xRGpzLF9QM21hVDlsakpzWHpqaUk2ZkRncEx2cWlNektoczlCLDkxMjk0ODQz0200lVZQw1fc/pdf?s=ap", + "last_finalization_error": null, + "latest_revision": null, + "lines": { + "data": [ + { + "amount": 48000, + "amount_excluding_tax": 48000, + "currency": "usd", + "description": "Zulip Cloud Standard", + "discount_amounts": [], + "discountable": false, + "discounts": [], + "id": "il_NORMALIZED00000000000001", + "invoice_item": "ii_NORMALIZED00000000000001", + "livemode": false, + "metadata": {}, + "object": "line_item", + "period": { + "end": 1357095845, + "start": 1325473445 + }, + "plan": null, + "price": { + "active": false, + "billing_scheme": "per_unit", + "created": 1000000000, + "currency": "usd", + "custom_unit_amount": null, + "id": "price_NORMALIZED00000000000001", + "livemode": false, + "lookup_key": null, + "metadata": {}, + "nickname": null, + "object": "price", + "product": "prod_NORMALIZED0001", + "recurring": null, + "tax_behavior": "unspecified", + "tiers_mode": null, + "transform_quantity": null, + "type": "one_time", + "unit_amount": 8000, + "unit_amount_decimal": "8000" + }, + "proration": false, + "proration_details": { + "credited_items": null + }, + "quantity": 6, + "subscription": null, + "tax_amounts": [], + "tax_rates": [], + "type": "invoiceitem", + "unit_amount_excluding_tax": "8000" + }, + { + "amount": -48000, + "amount_excluding_tax": -48000, + "currency": "usd", + "description": "Payment (Card ending in 4242)", + "discount_amounts": [], + "discountable": false, + "discounts": [], + "id": "il_NORMALIZED00000000000002", + "invoice_item": "ii_NORMALIZED00000000000002", + "livemode": false, + "metadata": {}, + "object": "line_item", + "period": { + "end": 1000000000, + "start": 1000000000 + }, + "plan": null, + "price": { + "active": false, + "billing_scheme": "per_unit", + "created": 1000000000, + "currency": "usd", + "custom_unit_amount": null, + "id": "price_NORMALIZED00000000000002", + "livemode": false, + "lookup_key": null, + "metadata": {}, + "nickname": null, + "object": "price", + "product": "prod_NORMALIZED0002", + "recurring": null, + "tax_behavior": "unspecified", + "tiers_mode": null, + "transform_quantity": null, + "type": "one_time", + "unit_amount": -48000, + "unit_amount_decimal": "-48000" + }, + "proration": false, + "proration_details": { + "credited_items": null + }, + "quantity": 1, + "subscription": null, + "tax_amounts": [], + "tax_rates": [], + "type": "invoiceitem", + "unit_amount_excluding_tax": "-48000" + } + ], + "has_more": false, + "object": "list", + "total_count": 2, + "url": "/v1/invoices/in_NORMALIZED00000000000001/lines" + }, + "livemode": false, + "metadata": {}, + "next_payment_attempt": null, + "number": "NORMALI-0002", + "object": "invoice", + "on_behalf_of": null, + "paid": true, + "paid_out_of_band": false, + "payment_intent": null, + "payment_settings": { + "default_mandate": null, + "payment_method_options": null, + "payment_method_types": null + }, + "period_end": 1000000000, + "period_start": 1000000000, + "post_payment_credit_notes_amount": 0, + "pre_payment_credit_notes_amount": 0, + "quote": null, + "receipt_number": null, + "rendering": { + "amount_tax_display": null, + "pdf": { + "page_size": "letter" + } + }, + "rendering_options": null, + "shipping_cost": null, + "shipping_details": null, + "starting_balance": 0, + "statement_descriptor": "Zulip Cloud Standard", + "status": "paid", + "status_transitions": { + "finalized_at": 1000000000, + "marked_uncollectible_at": null, + "paid_at": 1000000000, + "voided_at": null + }, + "subscription": null, + "subscription_details": { + "metadata": null + }, + "subtotal": 0, + "subtotal_excluding_tax": 0, + "tax": null, + "test_clock": null, + "total": 0, + "total_discount_amounts": [], + "total_excluding_tax": 0, + "total_tax_amounts": [], + "transfer_data": null, + "webhooks_delivered_at": null + } + }, + "id": "evt_1OFf1DDEQaroqDjs4sPApaUM", + "livemode": false, + "object": "event", + "pending_webhooks": 0, + "request": { + "id": "req_NORMALIZED0003", + "idempotency_key": "04b05b83-138d-47f5-b93e-1c8868d16aeb" + }, + "type": "invoice.finalized" + } + ], + "has_more": false, + "object": "list", + "url": "/v1/events" +} diff --git a/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Event.list.5.json b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Event.list.5.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Event.list.5.json @@ -0,0 +1,230 @@ +{ + "data": [ + { + "api_version": "2020-08-27", + "created": 1000000000, + "data": { + "object": { + "account_country": "US", + "account_name": "Kandra Labs, Inc.", + "account_tax_ids": null, + "amount_due": 0, + "amount_paid": 0, + "amount_remaining": 0, + "amount_shipping": 0, + "application": null, + "application_fee_amount": null, + "attempt_count": 0, + "attempted": true, + "auto_advance": false, + "automatic_tax": { + "enabled": false, + "status": null + }, + "billing_reason": "manual", + "charge": null, + "collection_method": "charge_automatically", + "created": 1000000000, + "currency": "usd", + "custom_fields": null, + "customer": "cus_NORMALIZED0001", + "customer_address": null, + "customer_email": "[email protected]", + "customer_name": null, + "customer_phone": null, + "customer_shipping": null, + "customer_tax_exempt": "none", + "customer_tax_ids": [], + "default_payment_method": null, + "default_source": null, + "default_tax_rates": [], + "description": null, + "discount": null, + "discounts": [], + "due_date": null, + "effective_at": 1000000000, + "ending_balance": 0, + "footer": null, + "from_invoice": null, + "hosted_invoice_url": "https://invoice.stripe.com/i/acct_NORMALIZED000001/test_NORMALIZED01a3dERVFhcm9xRGpzLF9QM21hVDlsakpzWHpqaUk2ZkRncEx2cWlNektoczlCLDkxMjk0ODQz0200lVZQw1fc?s=ap", + "id": "in_NORMALIZED00000000000001", + "invoice_pdf": "https://pay.stripe.com/invoice/acct_NORMALIZED000001/test_NORMALIZED01a3dERVFhcm9xRGpzLF9QM21hVDlsakpzWHpqaUk2ZkRncEx2cWlNektoczlCLDkxMjk0ODQz0200lVZQw1fc/pdf?s=ap", + "last_finalization_error": null, + "latest_revision": null, + "lines": { + "data": [ + { + "amount": 48000, + "amount_excluding_tax": 48000, + "currency": "usd", + "description": "Zulip Cloud Standard", + "discount_amounts": [], + "discountable": false, + "discounts": [], + "id": "il_NORMALIZED00000000000001", + "invoice_item": "ii_NORMALIZED00000000000001", + "livemode": false, + "metadata": {}, + "object": "line_item", + "period": { + "end": 1357095845, + "start": 1325473445 + }, + "plan": null, + "price": { + "active": false, + "billing_scheme": "per_unit", + "created": 1000000000, + "currency": "usd", + "custom_unit_amount": null, + "id": "price_NORMALIZED00000000000001", + "livemode": false, + "lookup_key": null, + "metadata": {}, + "nickname": null, + "object": "price", + "product": "prod_NORMALIZED0001", + "recurring": null, + "tax_behavior": "unspecified", + "tiers_mode": null, + "transform_quantity": null, + "type": "one_time", + "unit_amount": 8000, + "unit_amount_decimal": "8000" + }, + "proration": false, + "proration_details": { + "credited_items": null + }, + "quantity": 6, + "subscription": null, + "tax_amounts": [], + "tax_rates": [], + "type": "invoiceitem", + "unit_amount_excluding_tax": "8000" + }, + { + "amount": -48000, + "amount_excluding_tax": -48000, + "currency": "usd", + "description": "Payment (Card ending in 4242)", + "discount_amounts": [], + "discountable": false, + "discounts": [], + "id": "il_NORMALIZED00000000000002", + "invoice_item": "ii_NORMALIZED00000000000002", + "livemode": false, + "metadata": {}, + "object": "line_item", + "period": { + "end": 1000000000, + "start": 1000000000 + }, + "plan": null, + "price": { + "active": false, + "billing_scheme": "per_unit", + "created": 1000000000, + "currency": "usd", + "custom_unit_amount": null, + "id": "price_NORMALIZED00000000000002", + "livemode": false, + "lookup_key": null, + "metadata": {}, + "nickname": null, + "object": "price", + "product": "prod_NORMALIZED0002", + "recurring": null, + "tax_behavior": "unspecified", + "tiers_mode": null, + "transform_quantity": null, + "type": "one_time", + "unit_amount": -48000, + "unit_amount_decimal": "-48000" + }, + "proration": false, + "proration_details": { + "credited_items": null + }, + "quantity": 1, + "subscription": null, + "tax_amounts": [], + "tax_rates": [], + "type": "invoiceitem", + "unit_amount_excluding_tax": "-48000" + } + ], + "has_more": false, + "object": "list", + "total_count": 2, + "url": "/v1/invoices/in_NORMALIZED00000000000001/lines" + }, + "livemode": false, + "metadata": {}, + "next_payment_attempt": null, + "number": "NORMALI-0002", + "object": "invoice", + "on_behalf_of": null, + "paid": true, + "paid_out_of_band": false, + "payment_intent": null, + "payment_settings": { + "default_mandate": null, + "payment_method_options": null, + "payment_method_types": null + }, + "period_end": 1000000000, + "period_start": 1000000000, + "post_payment_credit_notes_amount": 0, + "pre_payment_credit_notes_amount": 0, + "quote": null, + "receipt_number": null, + "rendering": { + "amount_tax_display": null, + "pdf": { + "page_size": "letter" + } + }, + "rendering_options": null, + "shipping_cost": null, + "shipping_details": null, + "starting_balance": 0, + "statement_descriptor": "Zulip Cloud Standard", + "status": "paid", + "status_transitions": { + "finalized_at": 1000000000, + "marked_uncollectible_at": null, + "paid_at": 1000000000, + "voided_at": null + }, + "subscription": null, + "subscription_details": { + "metadata": null + }, + "subtotal": 0, + "subtotal_excluding_tax": 0, + "tax": null, + "test_clock": null, + "total": 0, + "total_discount_amounts": [], + "total_excluding_tax": 0, + "total_tax_amounts": [], + "transfer_data": null, + "webhooks_delivered_at": null + } + }, + "id": "evt_1OFf1DDEQaroqDjs7ihhQ4sQ", + "livemode": false, + "object": "event", + "pending_webhooks": 0, + "request": { + "id": "req_NORMALIZED0003", + "idempotency_key": "04b05b83-138d-47f5-b93e-1c8868d16aeb" + }, + "type": "invoice.payment_succeeded" + } + ], + "has_more": false, + "object": "list", + "url": "/v1/events" +} diff --git a/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Event.list.6.json b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Event.list.6.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Event.list.6.json @@ -0,0 +1,6 @@ +{ + "data": [], + "has_more": false, + "object": "list", + "url": "/v1/events" +} diff --git a/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Invoice.create.1.json b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Invoice.create.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Invoice.create.1.json @@ -0,0 +1,208 @@ +{ + "account_country": "US", + "account_name": "Kandra Labs, Inc.", + "account_tax_ids": null, + "amount_due": 0, + "amount_paid": 0, + "amount_remaining": 0, + "amount_shipping": 0, + "application": null, + "application_fee_amount": null, + "attempt_count": 0, + "attempted": false, + "auto_advance": true, + "automatic_tax": { + "enabled": false, + "status": null + }, + "billing_reason": "manual", + "charge": null, + "collection_method": "charge_automatically", + "created": 1000000000, + "currency": "usd", + "custom_fields": null, + "customer": "cus_NORMALIZED0001", + "customer_address": null, + "customer_email": "[email protected]", + "customer_name": null, + "customer_phone": null, + "customer_shipping": null, + "customer_tax_exempt": "none", + "customer_tax_ids": [], + "default_payment_method": null, + "default_source": null, + "default_tax_rates": [], + "description": null, + "discount": null, + "discounts": [], + "due_date": null, + "effective_at": null, + "ending_balance": null, + "footer": null, + "from_invoice": null, + "hosted_invoice_url": null, + "id": "in_NORMALIZED00000000000001", + "invoice_pdf": null, + "last_finalization_error": null, + "latest_revision": null, + "lines": { + "data": [ + { + "amount": 48000, + "amount_excluding_tax": 48000, + "currency": "usd", + "description": "Zulip Cloud Standard", + "discount_amounts": [], + "discountable": false, + "discounts": [], + "id": "il_NORMALIZED00000000000001", + "invoice_item": "ii_NORMALIZED00000000000001", + "livemode": false, + "metadata": {}, + "object": "line_item", + "period": { + "end": 1357095845, + "start": 1325473445 + }, + "plan": null, + "price": { + "active": false, + "billing_scheme": "per_unit", + "created": 1000000000, + "currency": "usd", + "custom_unit_amount": null, + "id": "price_NORMALIZED00000000000001", + "livemode": false, + "lookup_key": null, + "metadata": {}, + "nickname": null, + "object": "price", + "product": "prod_NORMALIZED0001", + "recurring": null, + "tax_behavior": "unspecified", + "tiers_mode": null, + "transform_quantity": null, + "type": "one_time", + "unit_amount": 8000, + "unit_amount_decimal": "8000" + }, + "proration": false, + "proration_details": { + "credited_items": null + }, + "quantity": 6, + "subscription": null, + "tax_amounts": [], + "tax_rates": [], + "type": "invoiceitem", + "unit_amount_excluding_tax": "8000" + }, + { + "amount": -48000, + "amount_excluding_tax": -48000, + "currency": "usd", + "description": "Payment (Card ending in 4242)", + "discount_amounts": [], + "discountable": false, + "discounts": [], + "id": "il_NORMALIZED00000000000002", + "invoice_item": "ii_NORMALIZED00000000000002", + "livemode": false, + "metadata": {}, + "object": "line_item", + "period": { + "end": 1000000000, + "start": 1000000000 + }, + "plan": null, + "price": { + "active": false, + "billing_scheme": "per_unit", + "created": 1000000000, + "currency": "usd", + "custom_unit_amount": null, + "id": "price_NORMALIZED00000000000002", + "livemode": false, + "lookup_key": null, + "metadata": {}, + "nickname": null, + "object": "price", + "product": "prod_NORMALIZED0002", + "recurring": null, + "tax_behavior": "unspecified", + "tiers_mode": null, + "transform_quantity": null, + "type": "one_time", + "unit_amount": -48000, + "unit_amount_decimal": "-48000" + }, + "proration": false, + "proration_details": { + "credited_items": null + }, + "quantity": 1, + "subscription": null, + "tax_amounts": [], + "tax_rates": [], + "type": "invoiceitem", + "unit_amount_excluding_tax": "-48000" + } + ], + "has_more": false, + "object": "list", + "total_count": 2, + "url": "/v1/invoices/in_NORMALIZED00000000000001/lines" + }, + "livemode": false, + "metadata": {}, + "next_payment_attempt": 1000000000, + "number": null, + "object": "invoice", + "on_behalf_of": null, + "paid": false, + "paid_out_of_band": false, + "payment_intent": null, + "payment_settings": { + "default_mandate": null, + "payment_method_options": null, + "payment_method_types": null + }, + "period_end": 1000000000, + "period_start": 1000000000, + "post_payment_credit_notes_amount": 0, + "pre_payment_credit_notes_amount": 0, + "quote": null, + "receipt_number": null, + "rendering": { + "amount_tax_display": null, + "pdf": { + "page_size": "auto" + } + }, + "rendering_options": null, + "shipping_cost": null, + "shipping_details": null, + "starting_balance": 0, + "statement_descriptor": "Zulip Cloud Standard", + "status": "draft", + "status_transitions": { + "finalized_at": null, + "marked_uncollectible_at": null, + "paid_at": null, + "voided_at": null + }, + "subscription": null, + "subscription_details": { + "metadata": null + }, + "subtotal": 0, + "subtotal_excluding_tax": 0, + "tax": null, + "test_clock": null, + "total": 0, + "total_discount_amounts": [], + "total_excluding_tax": 0, + "total_tax_amounts": [], + "transfer_data": null, + "webhooks_delivered_at": null +} diff --git a/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Invoice.finalize_invoice.1.json b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Invoice.finalize_invoice.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Invoice.finalize_invoice.1.json @@ -0,0 +1,208 @@ +{ + "account_country": "US", + "account_name": "Kandra Labs, Inc.", + "account_tax_ids": null, + "amount_due": 0, + "amount_paid": 0, + "amount_remaining": 0, + "amount_shipping": 0, + "application": null, + "application_fee_amount": null, + "attempt_count": 0, + "attempted": true, + "auto_advance": false, + "automatic_tax": { + "enabled": false, + "status": null + }, + "billing_reason": "manual", + "charge": null, + "collection_method": "charge_automatically", + "created": 1000000000, + "currency": "usd", + "custom_fields": null, + "customer": "cus_NORMALIZED0001", + "customer_address": null, + "customer_email": "[email protected]", + "customer_name": null, + "customer_phone": null, + "customer_shipping": null, + "customer_tax_exempt": "none", + "customer_tax_ids": [], + "default_payment_method": null, + "default_source": null, + "default_tax_rates": [], + "description": null, + "discount": null, + "discounts": [], + "due_date": null, + "effective_at": 1000000000, + "ending_balance": 0, + "footer": null, + "from_invoice": null, + "hosted_invoice_url": "https://invoice.stripe.com/i/acct_NORMALIZED000001/test_NORMALIZED01a3dERVFhcm9xRGpzLF9QM21hVDlsakpzWHpqaUk2ZkRncEx2cWlNektoczlCLDkxMjk0ODQy0200Or6SDpzt?s=ap", + "id": "in_NORMALIZED00000000000001", + "invoice_pdf": "https://pay.stripe.com/invoice/acct_NORMALIZED000001/test_NORMALIZED01a3dERVFhcm9xRGpzLF9QM21hVDlsakpzWHpqaUk2ZkRncEx2cWlNektoczlCLDkxMjk0ODQy0200Or6SDpzt/pdf?s=ap", + "last_finalization_error": null, + "latest_revision": null, + "lines": { + "data": [ + { + "amount": 48000, + "amount_excluding_tax": 48000, + "currency": "usd", + "description": "Zulip Cloud Standard", + "discount_amounts": [], + "discountable": false, + "discounts": [], + "id": "il_NORMALIZED00000000000001", + "invoice_item": "ii_NORMALIZED00000000000001", + "livemode": false, + "metadata": {}, + "object": "line_item", + "period": { + "end": 1357095845, + "start": 1325473445 + }, + "plan": null, + "price": { + "active": false, + "billing_scheme": "per_unit", + "created": 1000000000, + "currency": "usd", + "custom_unit_amount": null, + "id": "price_NORMALIZED00000000000001", + "livemode": false, + "lookup_key": null, + "metadata": {}, + "nickname": null, + "object": "price", + "product": "prod_NORMALIZED0001", + "recurring": null, + "tax_behavior": "unspecified", + "tiers_mode": null, + "transform_quantity": null, + "type": "one_time", + "unit_amount": 8000, + "unit_amount_decimal": "8000" + }, + "proration": false, + "proration_details": { + "credited_items": null + }, + "quantity": 6, + "subscription": null, + "tax_amounts": [], + "tax_rates": [], + "type": "invoiceitem", + "unit_amount_excluding_tax": "8000" + }, + { + "amount": -48000, + "amount_excluding_tax": -48000, + "currency": "usd", + "description": "Payment (Card ending in 4242)", + "discount_amounts": [], + "discountable": false, + "discounts": [], + "id": "il_NORMALIZED00000000000002", + "invoice_item": "ii_NORMALIZED00000000000002", + "livemode": false, + "metadata": {}, + "object": "line_item", + "period": { + "end": 1000000000, + "start": 1000000000 + }, + "plan": null, + "price": { + "active": false, + "billing_scheme": "per_unit", + "created": 1000000000, + "currency": "usd", + "custom_unit_amount": null, + "id": "price_NORMALIZED00000000000002", + "livemode": false, + "lookup_key": null, + "metadata": {}, + "nickname": null, + "object": "price", + "product": "prod_NORMALIZED0002", + "recurring": null, + "tax_behavior": "unspecified", + "tiers_mode": null, + "transform_quantity": null, + "type": "one_time", + "unit_amount": -48000, + "unit_amount_decimal": "-48000" + }, + "proration": false, + "proration_details": { + "credited_items": null + }, + "quantity": 1, + "subscription": null, + "tax_amounts": [], + "tax_rates": [], + "type": "invoiceitem", + "unit_amount_excluding_tax": "-48000" + } + ], + "has_more": false, + "object": "list", + "total_count": 2, + "url": "/v1/invoices/in_NORMALIZED00000000000001/lines" + }, + "livemode": false, + "metadata": {}, + "next_payment_attempt": null, + "number": "NORMALI-0002", + "object": "invoice", + "on_behalf_of": null, + "paid": true, + "paid_out_of_band": false, + "payment_intent": null, + "payment_settings": { + "default_mandate": null, + "payment_method_options": null, + "payment_method_types": null + }, + "period_end": 1000000000, + "period_start": 1000000000, + "post_payment_credit_notes_amount": 0, + "pre_payment_credit_notes_amount": 0, + "quote": null, + "receipt_number": null, + "rendering": { + "amount_tax_display": null, + "pdf": { + "page_size": "letter" + } + }, + "rendering_options": null, + "shipping_cost": null, + "shipping_details": null, + "starting_balance": 0, + "statement_descriptor": "Zulip Cloud Standard", + "status": "paid", + "status_transitions": { + "finalized_at": 1000000000, + "marked_uncollectible_at": null, + "paid_at": 1000000000, + "voided_at": null + }, + "subscription": null, + "subscription_details": { + "metadata": null + }, + "subtotal": 0, + "subtotal_excluding_tax": 0, + "tax": null, + "test_clock": null, + "total": 0, + "total_discount_amounts": [], + "total_excluding_tax": 0, + "total_tax_amounts": [], + "transfer_data": null, + "webhooks_delivered_at": null +} diff --git a/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Invoice.list.1.json b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Invoice.list.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--Invoice.list.1.json @@ -0,0 +1,6 @@ +{ + "data": [], + "has_more": false, + "object": "list", + "url": "/v1/invoices" +} diff --git a/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--InvoiceItem.create.1.json b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--InvoiceItem.create.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--InvoiceItem.create.1.json @@ -0,0 +1,47 @@ +{ + "amount": -48000, + "currency": "usd", + "customer": "cus_NORMALIZED0001", + "date": 1000000000, + "description": "Payment (Card ending in 4242)", + "discountable": false, + "discounts": [], + "id": "ii_NORMALIZED00000000000002", + "invoice": null, + "livemode": false, + "metadata": {}, + "object": "invoiceitem", + "period": { + "end": 1000000000, + "start": 1000000000 + }, + "plan": null, + "price": { + "active": false, + "billing_scheme": "per_unit", + "created": 1000000000, + "currency": "usd", + "custom_unit_amount": null, + "id": "price_NORMALIZED00000000000002", + "livemode": false, + "lookup_key": null, + "metadata": {}, + "nickname": null, + "object": "price", + "product": "prod_NORMALIZED0002", + "recurring": null, + "tax_behavior": "unspecified", + "tiers_mode": null, + "transform_quantity": null, + "type": "one_time", + "unit_amount": -48000, + "unit_amount_decimal": "-48000" + }, + "proration": false, + "quantity": 1, + "subscription": null, + "tax_rates": [], + "test_clock": null, + "unit_amount": -48000, + "unit_amount_decimal": "-48000" +} diff --git a/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--InvoiceItem.create.2.json b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--InvoiceItem.create.2.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--InvoiceItem.create.2.json @@ -0,0 +1,47 @@ +{ + "amount": 48000, + "currency": "usd", + "customer": "cus_NORMALIZED0001", + "date": 1000000000, + "description": "Zulip Cloud Standard", + "discountable": false, + "discounts": [], + "id": "ii_NORMALIZED00000000000001", + "invoice": null, + "livemode": false, + "metadata": {}, + "object": "invoiceitem", + "period": { + "end": 1357095845, + "start": 1325473445 + }, + "plan": null, + "price": { + "active": false, + "billing_scheme": "per_unit", + "created": 1000000000, + "currency": "usd", + "custom_unit_amount": null, + "id": "price_NORMALIZED00000000000001", + "livemode": false, + "lookup_key": null, + "metadata": {}, + "nickname": null, + "object": "price", + "product": "prod_NORMALIZED0001", + "recurring": null, + "tax_behavior": "unspecified", + "tiers_mode": null, + "transform_quantity": null, + "type": "one_time", + "unit_amount": 8000, + "unit_amount_decimal": "8000" + }, + "proration": false, + "quantity": 6, + "subscription": null, + "tax_rates": [], + "test_clock": null, + "unit_amount": 8000, + "unit_amount_decimal": "8000" +} diff --git a/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--PaymentIntent.create.1.json b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--PaymentIntent.create.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--PaymentIntent.create.1.json @@ -0,0 +1,197 @@ +{ + "amount": 48000, + "amount_capturable": 0, + "amount_details": { + "tip": {} + }, + "amount_received": 48000, + "application": null, + "application_fee_amount": null, + "automatic_payment_methods": null, + "canceled_at": null, + "cancellation_reason": null, + "capture_method": "automatic", + "charges": { + "data": [ + { + "amount": 48000, + "amount_captured": 48000, + "amount_refunded": 0, + "application": null, + "application_fee": null, + "application_fee_amount": null, + "balance_transaction": "txn_NORMALIZED00000000000001", + "billing_details": { + "address": { + "city": null, + "country": null, + "line1": null, + "line2": null, + "postal_code": null, + "state": null + }, + "email": null, + "name": null, + "phone": null + }, + "calculated_statement_descriptor": "ZULIP CLOUD STANDARD", + "captured": true, + "created": 1000000000, + "currency": "usd", + "customer": "cus_NORMALIZED0001", + "description": "Upgrade to Zulip Cloud Standard, $80.0 x 6", + "destination": null, + "dispute": null, + "disputed": false, + "failure_balance_transaction": null, + "failure_code": null, + "failure_message": null, + "fraud_details": {}, + "id": "ch_NORMALIZED00000000000001", + "invoice": null, + "livemode": false, + "metadata": { + "billing_modality": "charge_automatically", + "billing_schedule": "1", + "license_management": "automatic", + "licenses": "6", + "price_per_license": "8000", + "realm_id": "1", + "realm_str": "zulip", + "seat_count": "6", + "type": "upgrade", + "user_email": "[email protected]", + "user_id": "10" + }, + "object": "charge", + "on_behalf_of": null, + "order": null, + "outcome": { + "network_status": "approved_by_network", + "reason": null, + "risk_level": "normal", + "risk_score": 0, + "seller_message": "Payment complete.", + "type": "authorized" + }, + "paid": true, + "payment_intent": "pi_NORMALIZED00000000000001", + "payment_method": "pm_1OFf15DEQaroqDjs1q9XiIYO", + "payment_method_details": { + "card": { + "amount_authorized": 48000, + "brand": "visa", + "checks": { + "address_line1_check": null, + "address_postal_code_check": null, + "cvc_check": "pass" + }, + "country": "US", + "exp_month": 11, + "exp_year": 2024, + "extended_authorization": { + "status": "disabled" + }, + "fingerprint": "NORMALIZED000001", + "funding": "credit", + "incremental_authorization": { + "status": "unavailable" + }, + "installments": null, + "last4": "4242", + "mandate": null, + "multicapture": { + "status": "unavailable" + }, + "network": "visa", + "network_token": { + "used": false + }, + "overcapture": { + "maximum_amount_capturable": 48000, + "status": "unavailable" + }, + "three_d_secure": null, + "wallet": null + }, + "type": "card" + }, + "receipt_email": "[email protected]", + "receipt_number": null, + "receipt_url": "https://pay.stripe.com/receipts/payment/CAcaFwoVYWNjdF8xN3ZUa3dERVFhcm9xRGpzKPjk_aoGMgZ2xhla3UQ6LBZ1xB9jef8E7cgmIXMzB-HUUA6ELeya1StU6zBxLj5-JYRe97hmmqZd3S-C", + "refunded": false, + "refunds": { + "data": [], + "has_more": false, + "object": "list", + "total_count": 0, + "url": "/v1/charges/ch_NORMALIZED00000000000001/refunds" + }, + "review": null, + "shipping": null, + "source": null, + "source_transfer": null, + "statement_descriptor": "Zulip Cloud Standard", + "statement_descriptor_suffix": null, + "status": "succeeded", + "transfer_data": null, + "transfer_group": null + } + ], + "has_more": false, + "object": "list", + "total_count": 1, + "url": "/v1/charges?payment_intent=pi_NORMALIZED00000000000001" + }, + "client_secret": "pi_NORMALIZED00000000000001_secret_M6ApwY4vAGFmAi20dvhDBb0IR", + "confirmation_method": "automatic", + "created": 1000000000, + "currency": "usd", + "customer": "cus_NORMALIZED0001", + "description": "Upgrade to Zulip Cloud Standard, $80.0 x 6", + "id": "pi_NORMALIZED00000000000001", + "invoice": null, + "last_payment_error": null, + "latest_charge": "ch_NORMALIZED00000000000001", + "livemode": false, + "metadata": { + "billing_modality": "charge_automatically", + "billing_schedule": "1", + "license_management": "automatic", + "licenses": "6", + "price_per_license": "8000", + "realm_id": "1", + "realm_str": "zulip", + "seat_count": "6", + "type": "upgrade", + "user_email": "[email protected]", + "user_id": "10" + }, + "next_action": null, + "object": "payment_intent", + "on_behalf_of": null, + "payment_method": "pm_1OFf15DEQaroqDjs1q9XiIYO", + "payment_method_configuration_details": null, + "payment_method_options": { + "card": { + "installments": null, + "mandate_options": null, + "network": null, + "request_three_d_secure": "automatic" + } + }, + "payment_method_types": [ + "card" + ], + "processing": null, + "receipt_email": "[email protected]", + "review": null, + "setup_future_usage": null, + "shipping": null, + "source": null, + "statement_descriptor": "Zulip Cloud Standard", + "statement_descriptor_suffix": null, + "status": "succeeded", + "transfer_data": null, + "transfer_group": null +} diff --git a/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--SetupIntent.create.1.json b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--SetupIntent.create.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--SetupIntent.create.1.json @@ -0,0 +1,34 @@ +{ + "application": null, + "automatic_payment_methods": null, + "cancellation_reason": null, + "client_secret": "seti_1OFf15DEQaroqDjsmBBQn3qT_secret_P3maEbzXpQL4Xc7h5qZnIdFY4d5J69J", + "created": 1000000000, + "customer": "cus_NORMALIZED0001", + "description": null, + "flow_directions": null, + "id": "seti_1OFf15DEQaroqDjsmBBQn3qT", + "last_setup_error": null, + "latest_attempt": "setatt_1OFf15DEQaroqDjsBypUu14v", + "livemode": false, + "mandate": null, + "metadata": {}, + "next_action": null, + "object": "setup_intent", + "on_behalf_of": null, + "payment_method": "pm_1OFf15DEQaroqDjs1q9XiIYO", + "payment_method_configuration_details": null, + "payment_method_options": { + "card": { + "mandate_options": null, + "network": null, + "request_three_d_secure": "automatic" + } + }, + "payment_method_types": [ + "card" + ], + "single_use_mandate": null, + "status": "succeeded", + "usage": "off_session" +} diff --git a/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--SetupIntent.list.1.json b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--SetupIntent.list.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--SetupIntent.list.1.json @@ -0,0 +1,41 @@ +{ + "data": [ + { + "application": null, + "automatic_payment_methods": null, + "cancellation_reason": null, + "client_secret": "seti_1OFf13DEQaroqDjsH1JB6YyD_secret_P3maeH1qbveHJgbfDxuzjKEgLmEstlk", + "created": 1000000000, + "customer": "cus_NORMALIZED0001", + "description": null, + "flow_directions": null, + "id": "seti_1OFf13DEQaroqDjsH1JB6YyD", + "last_setup_error": null, + "latest_attempt": null, + "livemode": false, + "mandate": null, + "metadata": {}, + "next_action": null, + "object": "setup_intent", + "on_behalf_of": null, + "payment_method": null, + "payment_method_configuration_details": null, + "payment_method_options": { + "card": { + "mandate_options": null, + "network": null, + "request_three_d_secure": "automatic" + } + }, + "payment_method_types": [ + "card" + ], + "single_use_mandate": null, + "status": "requires_payment_method", + "usage": "off_session" + } + ], + "has_more": true, + "object": "list", + "url": "/v1/setup_intents" +} diff --git a/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--SetupIntent.retrieve.1.json b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--SetupIntent.retrieve.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--SetupIntent.retrieve.1.json @@ -0,0 +1,34 @@ +{ + "application": null, + "automatic_payment_methods": null, + "cancellation_reason": null, + "client_secret": "seti_1OFf15DEQaroqDjsmBBQn3qT_secret_P3maEbzXpQL4Xc7h5qZnIdFY4d5J69J", + "created": 1000000000, + "customer": "cus_NORMALIZED0001", + "description": null, + "flow_directions": null, + "id": "seti_1OFf15DEQaroqDjsmBBQn3qT", + "last_setup_error": null, + "latest_attempt": "setatt_1OFf15DEQaroqDjsBypUu14v", + "livemode": false, + "mandate": null, + "metadata": {}, + "next_action": null, + "object": "setup_intent", + "on_behalf_of": null, + "payment_method": "pm_1OFf15DEQaroqDjs1q9XiIYO", + "payment_method_configuration_details": null, + "payment_method_options": { + "card": { + "mandate_options": null, + "network": null, + "request_three_d_secure": "automatic" + } + }, + "payment_method_types": [ + "card" + ], + "single_use_mandate": null, + "status": "succeeded", + "usage": "off_session" +} diff --git a/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--checkout.Session.create.1.json b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--checkout.Session.create.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--checkout.Session.create.1.json @@ -0,0 +1,73 @@ +{ + "after_expiration": null, + "allow_promotion_codes": null, + "amount_subtotal": null, + "amount_total": null, + "automatic_tax": { + "enabled": false, + "status": null + }, + "billing_address_collection": null, + "cancel_url": "http://zulip.testserver/upgrade/", + "client_reference_id": null, + "client_secret": null, + "consent": null, + "consent_collection": null, + "created": 1000000000, + "currency": null, + "currency_conversion": null, + "custom_fields": [], + "custom_text": { + "shipping_address": null, + "submit": null, + "terms_of_service_acceptance": null + }, + "customer": "cus_NORMALIZED0001", + "customer_creation": null, + "customer_details": { + "address": null, + "email": "[email protected]", + "name": null, + "phone": null, + "tax_exempt": null, + "tax_ids": null + }, + "customer_email": null, + "expires_at": 1000000000, + "id": "cs_test_NORMALIZED029J746LIJLVM1nRf0gzX4s3NghkCEmbEfSuCLoCQvPuv1VR", + "invoice": null, + "invoice_creation": null, + "livemode": false, + "locale": null, + "metadata": { + "type": "card_update", + "user_id": "10" + }, + "mode": "setup", + "object": "checkout.session", + "payment_intent": null, + "payment_link": null, + "payment_method_collection": "always", + "payment_method_configuration_details": null, + "payment_method_options": {}, + "payment_method_types": [ + "card" + ], + "payment_status": "no_payment_required", + "phone_number_collection": { + "enabled": false + }, + "recovered_from": null, + "setup_intent": "seti_1OFf13DEQaroqDjsH1JB6YyD", + "shipping": null, + "shipping_address_collection": null, + "shipping_options": [], + "shipping_rate": null, + "status": "open", + "submit_type": null, + "subscription": null, + "success_url": "http://zulip.testserver/billing/event_status?stripe_session_id={CHECKOUT_SESSION_ID}", + "total_details": null, + "ui_mode": "hosted", + "url": "https://checkout.stripe.com/c/pay/cs_test_NORMALIZED029J746LIJLVM1nRf0gzX4s3NghkCEmbEfSuCLoCQvPuv1VR#fidkdWxOYHwnPyd1blpxYHZxWl1UZjFOczZJXUE2PUpzUWNPV2ZpdlFzUCcpJ2N3amhWYHdzYHcnP3F3cGApJ2lkfGpwcVF8dWAnPyd2bGtiaWBaZmppcGhrJyknYGtkZ2lgVWlkZmBtamlhYHd2Jz9xd3BgeCUl" +} diff --git a/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--checkout.Session.list.1.json b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--checkout.Session.list.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/sponsorship_access_for_realms_on_paid_plan--checkout.Session.list.1.json @@ -0,0 +1,80 @@ +{ + "data": [ + { + "after_expiration": null, + "allow_promotion_codes": null, + "amount_subtotal": null, + "amount_total": null, + "automatic_tax": { + "enabled": false, + "status": null + }, + "billing_address_collection": null, + "cancel_url": "http://zulip.testserver/upgrade/", + "client_reference_id": null, + "client_secret": null, + "consent": null, + "consent_collection": null, + "created": 1000000000, + "currency": null, + "currency_conversion": null, + "custom_fields": [], + "custom_text": { + "shipping_address": null, + "submit": null, + "terms_of_service_acceptance": null + }, + "customer": "cus_NORMALIZED0001", + "customer_creation": null, + "customer_details": { + "address": null, + "email": "[email protected]", + "name": null, + "phone": null, + "tax_exempt": null, + "tax_ids": null + }, + "customer_email": null, + "expires_at": 1000000000, + "id": "cs_test_NORMALIZED029J746LIJLVM1nRf0gzX4s3NghkCEmbEfSuCLoCQvPuv1VR", + "invoice": null, + "invoice_creation": null, + "livemode": false, + "locale": null, + "metadata": { + "type": "card_update", + "user_id": "10" + }, + "mode": "setup", + "object": "checkout.session", + "payment_intent": null, + "payment_link": null, + "payment_method_collection": "always", + "payment_method_configuration_details": null, + "payment_method_options": {}, + "payment_method_types": [ + "card" + ], + "payment_status": "no_payment_required", + "phone_number_collection": { + "enabled": false + }, + "recovered_from": null, + "setup_intent": "seti_1OFf13DEQaroqDjsH1JB6YyD", + "shipping": null, + "shipping_address_collection": null, + "shipping_options": [], + "shipping_rate": null, + "status": "open", + "submit_type": null, + "subscription": null, + "success_url": "http://zulip.testserver/billing/event_status?stripe_session_id={CHECKOUT_SESSION_ID}", + "total_details": null, + "ui_mode": "hosted", + "url": "https://checkout.stripe.com/c/pay/cs_test_NORMALIZED029J746LIJLVM1nRf0gzX4s3NghkCEmbEfSuCLoCQvPuv1VR#fidkdWxOYHwnPyd1blpxYHZxWl1UZjFOczZJXUE2PUpzUWNPV2ZpdlFzUCcpJ2N3amhWYHdzYHcnP3F3cGApJ2lkfGpwcVF8dWAnPyd2bGtiaWBaZmppcGhrJyknYGtkZ2lgVWlkZmBtamlhYHd2Jz9xd3BgeCUl" + } + ], + "has_more": true, + "object": "list", + "url": "/v1/checkout/sessions" +} diff --git a/corporate/tests/test_stripe.py b/corporate/tests/test_stripe.py --- a/corporate/tests/test_stripe.py +++ b/corporate/tests/test_stripe.py @@ -1739,6 +1739,19 @@ def test_request_sponsorship_form_with_blank_url(self) -> None: self.assert_json_success(response) + @mock_stripe() + def test_sponsorship_access_for_realms_on_paid_plan(self, *mocks: Mock) -> None: + user = self.example_user("hamlet") + self.login_user(user) + self.add_card_and_upgrade(user) + response = self.client_get("/sponsorship/") + self.assert_in_success_response( + [ + "How many paid staff does your organization have?", + ], + response, + ) + def test_support_request(self) -> None: user = self.example_user("hamlet") self.assertIsNone(get_customer_by_realm(user.realm)) @@ -1835,13 +1848,7 @@ def test_request_sponsorship(self) -> None: response = self.client_get("/sponsorship/") self.assert_in_success_response( [ - 'This organization has requested sponsorship for a free or discounted <a href="/plans/">Zulip Cloud Standard</a> plan.' - ], - response, - ) - self.assert_in_success_response( - [ - 'Please feel free to <a href="mailto:[email protected]">contact Zulip support</a> with any questions or updates to your request.' + 'This organization has requested sponsorship for a <a href="/plans/">Zulip Cloud Standard</a> plan. <a href="mailto:[email protected]">Contact Zulip support</a> with any questions or updates.' ], response, ) @@ -1853,13 +1860,19 @@ def test_request_sponsorship(self) -> None: response, ) + user.realm.plan_type = Realm.PLAN_TYPE_PLUS + user.realm.save() + response = self.client_get("/sponsorship/") + self.assertEqual(response.status_code, 302) + self.assertEqual(response["Location"], "/billing/") + user.realm.plan_type = Realm.PLAN_TYPE_STANDARD_FREE user.realm.save() self.login_user(self.example_user("hamlet")) response = self.client_get("/sponsorship/") self.assert_in_success_response( [ - 'Zulip is sponsoring free <a href="/plans/">Zulip Cloud Standard</a> hosting for this organization.' + 'Zulip is sponsoring a free <a href="/plans/">Zulip Cloud Standard</a> plan for this organization. 🎉' ], response, )
Explicitly note discount on /upgrade and /billing pages Following up on #27379 and #27356, we should explicitly note when an organization has a discounted rate. - Text to add: "_(includes X% discount)_" - Location: - On /upgrade, under "Due today", on the "$6.67 x 10 users x 1 month" line. - On /billing, on the "Expected charge: $66.70 ($6.67 x 10 users x 1 month)" line. Blockers: - #27379 - #27356
Just a note that we'll need to revert the one line of 476b44ae671cd480b69bcabebe209e028359a137 that dropped the discount percent from the parameters passed to the client (but I think we're keeping the model that the other numbers are all shown with discount included).
2023-11-23T15:54:56
zulip/zulip
27,904
zulip__zulip-27904
[ "27823" ]
a3f5332844780f7317fc32ab131e9e7f40b11b67
diff --git a/zerver/lib/users.py b/zerver/lib/users.py --- a/zerver/lib/users.py +++ b/zerver/lib/users.py @@ -42,6 +42,7 @@ get_fake_email_domain, get_realm_user_dicts, get_user, + get_user_by_id_in_realm_including_cross_realm, get_user_profile_by_id_in_realm, is_cross_realm_bot_email, ) @@ -284,6 +285,23 @@ def access_user_by_id( return access_user_common(target, user_profile, allow_deactivated, allow_bots, for_admin) +def access_user_by_id_including_cross_realm( + user_profile: UserProfile, + target_user_id: int, + *, + allow_deactivated: bool = False, + allow_bots: bool = False, + for_admin: bool, +) -> UserProfile: + """Variant of access_user_by_id allowing cross-realm bots to be accessed.""" + try: + target = get_user_by_id_in_realm_including_cross_realm(target_user_id, user_profile.realm) + except UserProfile.DoesNotExist: + raise JsonableError(_("No such user")) + + return access_user_common(target, user_profile, allow_deactivated, allow_bots, for_admin) + + def access_user_by_email( user_profile: UserProfile, email: str, diff --git a/zerver/views/muted_users.py b/zerver/views/muted_users.py --- a/zerver/views/muted_users.py +++ b/zerver/views/muted_users.py @@ -7,7 +7,7 @@ from zerver.lib.exceptions import JsonableError from zerver.lib.muted_users import get_mute_object from zerver.lib.response import json_success -from zerver.lib.users import access_user_by_id +from zerver.lib.users import access_user_by_id_including_cross_realm from zerver.models import UserProfile @@ -23,7 +23,7 @@ def mute_user(request: HttpRequest, user_profile: UserProfile, muted_user_id: in # # But it's quite possibly something nobody will try to do, so we # just reuse the existing shared code path. - muted_user = access_user_by_id( + muted_user = access_user_by_id_including_cross_realm( user_profile, muted_user_id, allow_bots=True, allow_deactivated=True, for_admin=False ) date_muted = timezone_now() @@ -39,7 +39,7 @@ def mute_user(request: HttpRequest, user_profile: UserProfile, muted_user_id: in def unmute_user( request: HttpRequest, user_profile: UserProfile, muted_user_id: int ) -> HttpResponse: - muted_user = access_user_by_id( + muted_user = access_user_by_id_including_cross_realm( user_profile, muted_user_id, allow_bots=True, allow_deactivated=True, for_admin=False ) mute_object = get_mute_object(user_profile, muted_user)
diff --git a/zerver/tests/test_users.py b/zerver/tests/test_users.py --- a/zerver/tests/test_users.py +++ b/zerver/tests/test_users.py @@ -50,6 +50,7 @@ from zerver.lib.users import ( Account, access_user_by_id, + access_user_by_id_including_cross_realm, get_accounts_for_email, get_cross_realm_dicts, user_ids_to_users, @@ -428,37 +429,76 @@ def test_admin_cannot_set_full_name_with_invalid_characters(self) -> None: def test_access_user_by_id(self) -> None: iago = self.example_user("iago") + internal_realm = get_realm(settings.SYSTEM_BOT_REALM) # Must be a valid user ID in the realm with self.assertRaises(JsonableError): access_user_by_id(iago, 1234, for_admin=False) + with self.assertRaises(JsonableError): + access_user_by_id_including_cross_realm(iago, 1234, for_admin=False) with self.assertRaises(JsonableError): access_user_by_id(iago, self.mit_user("sipbtest").id, for_admin=False) + with self.assertRaises(JsonableError): + access_user_by_id_including_cross_realm( + iago, self.mit_user("sipbtest").id, for_admin=False + ) # Can only access bot users if allow_bots is passed bot = self.example_user("default_bot") access_user_by_id(iago, bot.id, allow_bots=True, for_admin=True) + access_user_by_id_including_cross_realm(iago, bot.id, allow_bots=True, for_admin=True) with self.assertRaises(JsonableError): access_user_by_id(iago, bot.id, for_admin=True) + with self.assertRaises(JsonableError): + access_user_by_id_including_cross_realm(iago, bot.id, for_admin=True) + + # Only the including_cross_realm variant works for system bots. + system_bot = get_system_bot(settings.WELCOME_BOT, internal_realm.id) + with self.assertRaises(JsonableError): + access_user_by_id(iago, system_bot.id, allow_bots=True, for_admin=False) + access_user_by_id_including_cross_realm( + iago, system_bot.id, allow_bots=True, for_admin=False + ) + # And even then, only if `allow_bots` was passed. + with self.assertRaises(JsonableError): + access_user_by_id(iago, system_bot.id, for_admin=False) + with self.assertRaises(JsonableError): + access_user_by_id_including_cross_realm(iago, system_bot.id, for_admin=False) # Can only access deactivated users if allow_deactivated is passed hamlet = self.example_user("hamlet") do_deactivate_user(hamlet, acting_user=None) with self.assertRaises(JsonableError): access_user_by_id(iago, hamlet.id, for_admin=False) + with self.assertRaises(JsonableError): + access_user_by_id_including_cross_realm(iago, hamlet.id, for_admin=False) + with self.assertRaises(JsonableError): access_user_by_id(iago, hamlet.id, for_admin=True) + with self.assertRaises(JsonableError): + access_user_by_id_including_cross_realm(iago, hamlet.id, for_admin=True) access_user_by_id(iago, hamlet.id, allow_deactivated=True, for_admin=True) + access_user_by_id_including_cross_realm( + iago, hamlet.id, allow_deactivated=True, for_admin=True + ) # Non-admin user can't admin another user with self.assertRaises(JsonableError): access_user_by_id( self.example_user("cordelia"), self.example_user("aaron").id, for_admin=True ) + with self.assertRaises(JsonableError): + access_user_by_id_including_cross_realm( + self.example_user("cordelia"), self.example_user("aaron").id, for_admin=True + ) + # But does have read-only access to it. access_user_by_id( self.example_user("cordelia"), self.example_user("aaron").id, for_admin=False ) + access_user_by_id_including_cross_realm( + self.example_user("cordelia"), self.example_user("aaron").id, for_admin=False + ) def check_property_for_role(self, user_profile: UserProfile, role: int) -> bool: if role == UserProfile.ROLE_REALM_ADMINISTRATOR:
Make "Mute this bot" work for system bots <!-- Issue description --> While system bots have a "Mute this bot" option in their user card, it doesn't actually seem to do anything. We should fix this. If making it work is complicated, we can temporarily improve the situation by dropping the option for system bots. <!-- Link to a message in the chat.zulip.org discussion. Message links will still work even if the topic is renamed or resolved. Link back to this issue from the chat.zulip.org thread. --> [CZO thread](https://chat.zulip.org/#narrow/stream/9-issues/topic/.F0.9F.8E.AF.20muting.20system.20bots.20not.20working/near/1675450)
@sahil839 Adding this to your list as a low-priority release goal. Hello @arnavchhokra! Thanks for your interest in Zulip! You have attempted to claim an issue without the label "help wanted". You can only claim and submit pull requests for issues with the [help wanted](https://github.com/zulip/zulip/issues?q=is%3Aopen+is%3Aissue+no%3Aassignee+label%3A%22help+wanted%22) label. If this is your first time here, we recommend reading our [guide for new contributors](https://zulip.readthedocs.io/en/latest/overview/contributing.html) before getting started.
2023-11-27T04:46:34
zulip/zulip
27,905
zulip__zulip-27905
[ "25289" ]
9fe1e38f982cfb2341700181aacda22f80a32f87
diff --git a/zerver/lib/email_notifications.py b/zerver/lib/email_notifications.py --- a/zerver/lib/email_notifications.py +++ b/zerver/lib/email_notifications.py @@ -27,6 +27,7 @@ from zerver.lib.queue import queue_json_publish from zerver.lib.send_email import FromAddress, send_future_email from zerver.lib.soft_deactivation import soft_reactivate_if_personal_notification +from zerver.lib.tex import change_katex_to_raw_latex from zerver.lib.topic import get_topic_resolution_and_bare_name from zerver.lib.url_encoding import ( huddle_narrow_url, @@ -248,19 +249,7 @@ def build_message_payload(message: Message, sender: Optional[str] = None) -> Dic relative_to_full_url(fragment, user.realm.uri) fix_emojis(fragment, user.emojiset) fix_spoilers_in_html(fragment, user.default_language) - - # Selecting the <span> elements with class 'katex' - katex_spans = fragment.xpath("//span[@class='katex']") - - # Iterate through 'katex_spans' and replace with a new <span> having LaTeX text. - for katex_span in katex_spans: - latex_text = katex_span.xpath(".//annotation[@encoding='application/x-tex']")[0].text - # We store 'tail' to insert them back as the replace operation removes it. - tail = katex_span.tail - latex_span = lxml.html.Element("span") - latex_span.text = f"$${latex_text}$$" - katex_span.getparent().replace(katex_span, latex_span) - latex_span.tail = tail + change_katex_to_raw_latex(fragment) html = lxml.html.tostring(fragment, encoding="unicode") if sender: diff --git a/zerver/lib/push_notifications.py b/zerver/lib/push_notifications.py --- a/zerver/lib/push_notifications.py +++ b/zerver/lib/push_notifications.py @@ -40,6 +40,7 @@ from zerver.lib.outgoing_http import OutgoingSession from zerver.lib.remote_server import send_json_to_push_bouncer, send_to_push_bouncer from zerver.lib.soft_deactivation import soft_reactivate_if_personal_notification +from zerver.lib.tex import change_katex_to_raw_latex from zerver.lib.timestamp import datetime_to_timestamp from zerver.models import ( AbstractPushDeviceToken, @@ -812,6 +813,7 @@ def process(elem: lxml.html.HtmlElement) -> str: ) elem = lxml.html.fragment_fromstring(rendered_content, create_parent=True) + change_katex_to_raw_latex(elem) plain_text = process(elem) return plain_text diff --git a/zerver/lib/tex.py b/zerver/lib/tex.py --- a/zerver/lib/tex.py +++ b/zerver/lib/tex.py @@ -3,6 +3,7 @@ import subprocess from typing import Optional +import lxml.html from django.conf import settings from zerver.lib.storage import static_path @@ -39,3 +40,18 @@ def render_tex(tex: str, is_inline: bool = True) -> Optional[str]: return stdout.strip() except subprocess.CalledProcessError: return None + + +def change_katex_to_raw_latex(fragment: lxml.html.HtmlElement) -> None: + # Selecting the <span> elements with class 'katex' + katex_spans = fragment.xpath("//span[@class='katex']") + + # Iterate through 'katex_spans' and replace with a new <span> having LaTeX text. + for katex_span in katex_spans: + latex_text = katex_span.xpath(".//annotation[@encoding='application/x-tex']")[0].text + # We store 'tail' to insert them back as the replace operation removes it. + tail = katex_span.tail + latex_span = lxml.html.Element("span") + latex_span.text = f"$${latex_text}$$" + katex_span.getparent().replace(katex_span, latex_span) + latex_span.tail = tail
diff --git a/web/tests/notifications.test.js b/web/tests/notifications.test.js --- a/web/tests/notifications.test.js +++ b/web/tests/notifications.test.js @@ -340,6 +340,7 @@ test("message_is_notifiable", () => { test("basic_notifications", () => { $("<div>").set_find_results(".emoji", {replaceWith() {}}); + $("<div>").set_find_results("span.katex", {each() {}}); let n; // Object for storing all notification data for assertions. let last_closed_message_id = null; diff --git a/zerver/tests/fixtures/markdown_test_cases.json b/zerver/tests/fixtures/markdown_test_cases.json --- a/zerver/tests/fixtures/markdown_test_cases.json +++ b/zerver/tests/fixtures/markdown_test_cases.json @@ -847,7 +847,8 @@ { "name": "tex_inline", "input": "$$1 \\oplus 0 = 1$$", - "expected_output": "<p><span class=\"katex\"><span class=\"katex-mathml\"><math xmlns=\"http://www.w3.org/1998/Math/MathML\"><semantics><mrow><mn>1</mn><mo>⊕</mo><mn>0</mn><mo>=</mo><mn>1</mn></mrow><annotation encoding=\"application/x-tex\">1 \\oplus 0 = 1</annotation></semantics></math></span><span class=\"katex-html\" aria-hidden=\"true\"><span class=\"base\"><span class=\"strut\" style=\"height:0.7278em;vertical-align:-0.0833em;\"></span><span class=\"mord\">1</span><span class=\"mspace\" style=\"margin-right:0.2222em;\"></span><span class=\"mbin\">⊕</span><span class=\"mspace\" style=\"margin-right:0.2222em;\"></span></span><span class=\"base\"><span class=\"strut\" style=\"height:0.6444em;\"></span><span class=\"mord\">0</span><span class=\"mspace\" style=\"margin-right:0.2778em;\"></span><span class=\"mrel\">=</span><span class=\"mspace\" style=\"margin-right:0.2778em;\"></span></span><span class=\"base\"><span class=\"strut\" style=\"height:0.6444em;\"></span><span class=\"mord\">1</span></span></span></span></p>" + "expected_output": "<p><span class=\"katex\"><span class=\"katex-mathml\"><math xmlns=\"http://www.w3.org/1998/Math/MathML\"><semantics><mrow><mn>1</mn><mo>⊕</mo><mn>0</mn><mo>=</mo><mn>1</mn></mrow><annotation encoding=\"application/x-tex\">1 \\oplus 0 = 1</annotation></semantics></math></span><span class=\"katex-html\" aria-hidden=\"true\"><span class=\"base\"><span class=\"strut\" style=\"height:0.7278em;vertical-align:-0.0833em;\"></span><span class=\"mord\">1</span><span class=\"mspace\" style=\"margin-right:0.2222em;\"></span><span class=\"mbin\">⊕</span><span class=\"mspace\" style=\"margin-right:0.2222em;\"></span></span><span class=\"base\"><span class=\"strut\" style=\"height:0.6444em;\"></span><span class=\"mord\">0</span><span class=\"mspace\" style=\"margin-right:0.2778em;\"></span><span class=\"mrel\">=</span><span class=\"mspace\" style=\"margin-right:0.2778em;\"></span></span><span class=\"base\"><span class=\"strut\" style=\"height:0.6444em;\"></span><span class=\"mord\">1</span></span></span></span></p>", + "text_content": "$$1 \\oplus 0 = 1$$" }, { "name": "tex_complex", @@ -862,7 +863,8 @@ { "name": "tex_fenced_math", "input": "```math\na^2 = b^2 + c^2\n```", - "expected_output": "<p><span class=\"katex-display\"><span class=\"katex\"><span class=\"katex-mathml\"><math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><semantics><mrow><msup><mi>a</mi><mn>2</mn></msup><mo>=</mo><msup><mi>b</mi><mn>2</mn></msup><mo>+</mo><msup><mi>c</mi><mn>2</mn></msup></mrow><annotation encoding=\"application/x-tex\">a^2 = b^2 + c^2</annotation></semantics></math></span><span class=\"katex-html\" aria-hidden=\"true\"><span class=\"base\"><span class=\"strut\" style=\"height:0.8641em;\"></span><span class=\"mord\"><span class=\"mord mathnormal\">a</span><span class=\"msupsub\"><span class=\"vlist-t\"><span class=\"vlist-r\"><span class=\"vlist\" style=\"height:0.8641em;\"><span style=\"top:-3.113em;margin-right:0.05em;\"><span class=\"pstrut\" style=\"height:2.7em;\"></span><span class=\"sizing reset-size6 size3 mtight\"><span class=\"mord mtight\">2</span></span></span></span></span></span></span></span><span class=\"mspace\" style=\"margin-right:0.2778em;\"></span><span class=\"mrel\">=</span><span class=\"mspace\" style=\"margin-right:0.2778em;\"></span></span><span class=\"base\"><span class=\"strut\" style=\"height:0.9474em;vertical-align:-0.0833em;\"></span><span class=\"mord\"><span class=\"mord mathnormal\">b</span><span class=\"msupsub\"><span class=\"vlist-t\"><span class=\"vlist-r\"><span class=\"vlist\" style=\"height:0.8641em;\"><span style=\"top:-3.113em;margin-right:0.05em;\"><span class=\"pstrut\" style=\"height:2.7em;\"></span><span class=\"sizing reset-size6 size3 mtight\"><span class=\"mord mtight\">2</span></span></span></span></span></span></span></span><span class=\"mspace\" style=\"margin-right:0.2222em;\"></span><span class=\"mbin\">+</span><span class=\"mspace\" style=\"margin-right:0.2222em;\"></span></span><span class=\"base\"><span class=\"strut\" style=\"height:0.8641em;\"></span><span class=\"mord\"><span class=\"mord mathnormal\">c</span><span class=\"msupsub\"><span class=\"vlist-t\"><span class=\"vlist-r\"><span class=\"vlist\" style=\"height:0.8641em;\"><span style=\"top:-3.113em;margin-right:0.05em;\"><span class=\"pstrut\" style=\"height:2.7em;\"></span><span class=\"sizing reset-size6 size3 mtight\"><span class=\"mord mtight\">2</span></span></span></span></span></span></span></span></span></span></span></span></p>" + "expected_output": "<p><span class=\"katex-display\"><span class=\"katex\"><span class=\"katex-mathml\"><math xmlns=\"http://www.w3.org/1998/Math/MathML\" display=\"block\"><semantics><mrow><msup><mi>a</mi><mn>2</mn></msup><mo>=</mo><msup><mi>b</mi><mn>2</mn></msup><mo>+</mo><msup><mi>c</mi><mn>2</mn></msup></mrow><annotation encoding=\"application/x-tex\">a^2 = b^2 + c^2</annotation></semantics></math></span><span class=\"katex-html\" aria-hidden=\"true\"><span class=\"base\"><span class=\"strut\" style=\"height:0.8641em;\"></span><span class=\"mord\"><span class=\"mord mathnormal\">a</span><span class=\"msupsub\"><span class=\"vlist-t\"><span class=\"vlist-r\"><span class=\"vlist\" style=\"height:0.8641em;\"><span style=\"top:-3.113em;margin-right:0.05em;\"><span class=\"pstrut\" style=\"height:2.7em;\"></span><span class=\"sizing reset-size6 size3 mtight\"><span class=\"mord mtight\">2</span></span></span></span></span></span></span></span><span class=\"mspace\" style=\"margin-right:0.2778em;\"></span><span class=\"mrel\">=</span><span class=\"mspace\" style=\"margin-right:0.2778em;\"></span></span><span class=\"base\"><span class=\"strut\" style=\"height:0.9474em;vertical-align:-0.0833em;\"></span><span class=\"mord\"><span class=\"mord mathnormal\">b</span><span class=\"msupsub\"><span class=\"vlist-t\"><span class=\"vlist-r\"><span class=\"vlist\" style=\"height:0.8641em;\"><span style=\"top:-3.113em;margin-right:0.05em;\"><span class=\"pstrut\" style=\"height:2.7em;\"></span><span class=\"sizing reset-size6 size3 mtight\"><span class=\"mord mtight\">2</span></span></span></span></span></span></span></span><span class=\"mspace\" style=\"margin-right:0.2222em;\"></span><span class=\"mbin\">+</span><span class=\"mspace\" style=\"margin-right:0.2222em;\"></span></span><span class=\"base\"><span class=\"strut\" style=\"height:0.8641em;\"></span><span class=\"mord\"><span class=\"mord mathnormal\">c</span><span class=\"msupsub\"><span class=\"vlist-t\"><span class=\"vlist-r\"><span class=\"vlist\" style=\"height:0.8641em;\"><span style=\"top:-3.113em;margin-right:0.05em;\"><span class=\"pstrut\" style=\"height:2.7em;\"></span><span class=\"sizing reset-size6 size3 mtight\"><span class=\"mord mtight\">2</span></span></span></span></span></span></span></span></span></span></span></span></p>", + "text_content": "$$a^2 = b^2 + c^2$$" }, { "name": "tex_fenced_tex",
Notifications triple-include latex math formulas When I receive a message with latex math, the notification (in all of email, android, and desktop) includes the math three times in a row (once as unicode, once as latex, again as unicode). This seems to happen every time. One recent example: someone sent me "...we have <span>$$</span>d^* = +\infty$$, but..." and I got the email: "...we have d∗=+∞d^*=+\inftyd∗=+∞, but..."
Thanks for the report @ecprice! The root cause is that this is what happens when you display KaTeX HTML without the CSS :). We might be able to do something fancy with including the CSS in emails, but that's definitely not possible with push notifications. The discussion in https://chat.zulip.org/#narrow/stream/9-issues/topic/Notifications.20triple-include.20latex.20math.20formulas.20.2325289/near/1556210 concluded that our immediate plan should be to just transform the KaTeX HTML blocks back into the raw LaTeX source, and then we can potentially as a follow-up look at whether `css-inline` (and the annoying limitations in CSS in email clients) is capable of allowing us to display the actual rendered LaTeX in that context.
2023-11-27T05:24:46
zulip/zulip
27,915
zulip__zulip-27915
[ "27855" ]
30891bfc542eab2c7fad8a28ae9a37ded70f4fda
diff --git a/corporate/lib/stripe.py b/corporate/lib/stripe.py --- a/corporate/lib/stripe.py +++ b/corporate/lib/stripe.py @@ -491,6 +491,7 @@ class UpdatePlanRequest: status: Optional[int] licenses: Optional[int] licenses_at_next_renewal: Optional[int] + schedule: Optional[int] @dataclass @@ -539,6 +540,7 @@ class UpgradePageContext(TypedDict): email: str exempt_from_license_number_check: bool free_trial_days: Optional[int] + free_trial_end_date: Optional[str] is_demo_organization: bool manual_license_management: bool min_invoiced_licenses: int @@ -1034,25 +1036,101 @@ def do_upgrade(self, upgrade_request: UpgradeRequest) -> Dict[str, Any]: data["stripe_payment_intent_id"] = stripe_payment_intent_id return data - # event_time should roughly be timezone_now(). Not designed to handle - # event_times in the past or future - @transaction.atomic - def make_end_of_cycle_updates_if_needed( - self, plan: CustomerPlan, event_time: datetime - ) -> Tuple[Optional[CustomerPlan], Optional[LicenseLedger]]: + def do_change_schedule_after_free_trial(self, plan: CustomerPlan, schedule: int) -> None: + # Change the billing frequency of the plan after the free trial ends. + assert schedule in (CustomerPlan.MONTHLY, CustomerPlan.ANNUAL) last_ledger_entry = LicenseLedger.objects.filter(plan=plan).order_by("-id").first() + assert last_ledger_entry is not None + licenses_at_next_renewal = last_ledger_entry.licenses_at_next_renewal + assert licenses_at_next_renewal is not None + assert plan.next_invoice_date is not None + next_billing_cycle = plan.next_invoice_date + + if plan.fixed_price is not None: # nocoverage + raise BillingError("Customer is already on monthly fixed plan.") + + plan.status = CustomerPlan.ENDED + plan.save(update_fields=["status"]) + + discount = plan.customer.default_discount or plan.discount + _, _, _, price_per_license = compute_plan_parameters( + tier=plan.tier, + automanage_licenses=plan.automanage_licenses, + billing_schedule=schedule, + discount=plan.discount, + ) + + new_plan = CustomerPlan.objects.create( + customer=plan.customer, + billing_schedule=schedule, + automanage_licenses=plan.automanage_licenses, + charge_automatically=plan.charge_automatically, + price_per_license=price_per_license, + discount=discount, + billing_cycle_anchor=plan.billing_cycle_anchor, + tier=plan.tier, + status=CustomerPlan.FREE_TRIAL, + next_invoice_date=next_billing_cycle, + invoiced_through=None, + invoicing_status=CustomerPlan.INITIAL_INVOICE_TO_BE_SENT, + ) + + LicenseLedger.objects.create( + plan=new_plan, + is_renewal=True, + event_time=plan.billing_cycle_anchor, + licenses=licenses_at_next_renewal, + licenses_at_next_renewal=licenses_at_next_renewal, + ) + + if schedule == CustomerPlan.ANNUAL: + self.write_to_audit_log( + event_type=AuditLogEventType.CUSTOMER_SWITCHED_FROM_MONTHLY_TO_ANNUAL_PLAN, + event_time=timezone_now(), + extra_data={ + "monthly_plan_id": plan.id, + "annual_plan_id": new_plan.id, + }, + ) + else: + self.write_to_audit_log( + event_type=AuditLogEventType.CUSTOMER_SWITCHED_FROM_ANNUAL_TO_MONTHLY_PLAN, + event_time=timezone_now(), + extra_data={ + "annual_plan_id": plan.id, + "monthly_plan_id": new_plan.id, + }, + ) + + def get_next_billing_cycle(self, plan: CustomerPlan) -> datetime: last_ledger_renewal = ( LicenseLedger.objects.filter(plan=plan, is_renewal=True).order_by("-id").first() ) assert last_ledger_renewal is not None last_renewal = last_ledger_renewal.event_time - if plan.is_free_trial(): + if plan.status in ( + CustomerPlan.FREE_TRIAL, + CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL, + ): assert plan.next_invoice_date is not None next_billing_cycle = plan.next_invoice_date else: next_billing_cycle = start_of_next_billing_cycle(plan, last_renewal) - if next_billing_cycle <= event_time and last_ledger_entry is not None: + + return next_billing_cycle + + # event_time should roughly be timezone_now(). Not designed to handle + # event_times in the past or future + @transaction.atomic + def make_end_of_cycle_updates_if_needed( + self, plan: CustomerPlan, event_time: datetime + ) -> Tuple[Optional[CustomerPlan], Optional[LicenseLedger]]: + last_ledger_entry = LicenseLedger.objects.filter(plan=plan).order_by("-id").first() + next_billing_cycle = self.get_next_billing_cycle(plan) + event_in_next_billing_cycle = next_billing_cycle <= event_time + + if event_in_next_billing_cycle and last_ledger_entry is not None: licenses_at_next_renewal = last_ledger_entry.licenses_at_next_renewal assert licenses_at_next_renewal is not None if plan.status == CustomerPlan.ACTIVE: @@ -1172,8 +1250,12 @@ def make_end_of_cycle_updates_if_needed( ) return new_plan, new_plan_ledger_entry + if plan.status == CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL: + self.downgrade_now_without_creating_additional_invoices(plan) + if plan.status == CustomerPlan.DOWNGRADE_AT_END_OF_CYCLE: self.process_downgrade(plan) + return None, None return None, last_ledger_entry @@ -1190,6 +1272,9 @@ def get_billing_page_context(self) -> Dict[str, Any]: plan = new_plan assert plan is not None # for mypy downgrade_at_end_of_cycle = plan.status == CustomerPlan.DOWNGRADE_AT_END_OF_CYCLE + downgrade_at_end_of_free_trial = ( + plan.status == CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL + ) switch_to_annual_at_end_of_cycle = ( plan.status == CustomerPlan.SWITCH_TO_ANNUAL_AT_END_OF_CYCLE ) @@ -1202,7 +1287,7 @@ def get_billing_page_context(self) -> Dict[str, Any]: seat_count = self.current_count_for_billed_licenses() # Should do this in JavaScript, using the user's time zone - if plan.is_free_trial(): + if plan.is_free_trial() or downgrade_at_end_of_free_trial: assert plan.next_invoice_date is not None renewal_date = "{dt:%B} {dt.day}, {dt.year}".format(dt=plan.next_invoice_date) else: @@ -1252,6 +1337,7 @@ def get_billing_page_context(self) -> Dict[str, Any]: "has_active_plan": True, "free_trial": plan.is_free_trial(), "downgrade_at_end_of_cycle": downgrade_at_end_of_cycle, + "downgrade_at_end_of_free_trial": downgrade_at_end_of_free_trial, "automanage_licenses": plan.automanage_licenses, "switch_to_annual_at_end_of_cycle": switch_to_annual_at_end_of_cycle, "switch_to_monthly_at_end_of_cycle": switch_to_monthly_at_end_of_cycle, @@ -1305,13 +1391,23 @@ def get_initial_upgrade_context( seat_count = self.current_count_for_billed_licenses() signed_seat_count, salt = sign_string(str(seat_count)) tier = initial_upgrade_request.tier + + free_trial_days = settings.FREE_TRIAL_DAYS + free_trial_end_date = None + if free_trial_days is not None: + _, _, free_trial_end, _ = compute_plan_parameters( + CustomerPlan.STANDARD, False, CustomerPlan.ANNUAL, None, True + ) + free_trial_end_date = f"{free_trial_end:%B} {free_trial_end.day}, {free_trial_end.year}" + context: UpgradePageContext = { "customer_name": customer_specific_context["customer_name"], "default_invoice_days_until_due": DEFAULT_INVOICE_DAYS_UNTIL_DUE, "discount_percent": format_discount_percentage(percent_off), "email": customer_specific_context["email"], "exempt_from_license_number_check": exempt_from_license_number_check, - "free_trial_days": settings.FREE_TRIAL_DAYS, + "free_trial_days": free_trial_days, + "free_trial_end_date": free_trial_end_date, "is_demo_organization": customer_specific_context["is_demo_organization"], "manual_license_management": initial_upgrade_request.manual_license_management, "min_invoiced_licenses": max(seat_count, MIN_INVOICED_LICENSES), @@ -1385,6 +1481,7 @@ def do_update_plan(self, update_plan_request: UpdatePlanRequest) -> None: assert plan.status < CustomerPlan.LIVE_STATUS_THRESHOLD do_change_plan_status(plan, status) elif status == CustomerPlan.DOWNGRADE_AT_END_OF_CYCLE: + assert not plan.is_free_trial() assert plan.status < CustomerPlan.LIVE_STATUS_THRESHOLD self.downgrade_at_the_end_of_billing_cycle(plan=plan) elif status == CustomerPlan.SWITCH_TO_ANNUAL_AT_END_OF_CYCLE: @@ -1392,6 +1489,8 @@ def do_update_plan(self, update_plan_request: UpdatePlanRequest) -> None: assert plan.status < CustomerPlan.LIVE_STATUS_THRESHOLD # Customer needs to switch to an active plan first to avoid unexpected behavior. assert plan.status != CustomerPlan.DOWNGRADE_AT_END_OF_CYCLE + # Switching billing frequency for free trial should happen instantly. + assert not plan.is_free_trial() assert plan.fixed_price is None do_change_plan_status(plan, status) elif status == CustomerPlan.SWITCH_TO_MONTHLY_AT_END_OF_CYCLE: @@ -1399,11 +1498,23 @@ def do_update_plan(self, update_plan_request: UpdatePlanRequest) -> None: assert plan.status < CustomerPlan.LIVE_STATUS_THRESHOLD # Customer needs to switch to an active plan first to avoid unexpected behavior. assert plan.status != CustomerPlan.DOWNGRADE_AT_END_OF_CYCLE + # Switching billing frequency for free trial should happen instantly. + assert not plan.is_free_trial() assert plan.fixed_price is None do_change_plan_status(plan, status) elif status == CustomerPlan.ENDED: + # Not used right now on billing page but kept in case we need it. assert plan.is_free_trial() self.downgrade_now_without_creating_additional_invoices(plan=plan) + elif status == CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL: + assert plan.is_free_trial() + do_change_plan_status(plan, status) + elif status == CustomerPlan.FREE_TRIAL: + if update_plan_request.schedule is not None: + self.do_change_schedule_after_free_trial(plan, update_plan_request.schedule) + else: + assert plan.status == CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL + do_change_plan_status(plan, status) return licenses = update_plan_request.licenses diff --git a/corporate/models.py b/corporate/models.py --- a/corporate/models.py +++ b/corporate/models.py @@ -267,6 +267,7 @@ class CustomerPlan(models.Model): SWITCH_TO_ANNUAL_AT_END_OF_CYCLE = 4 SWITCH_PLAN_TIER_NOW = 5 SWITCH_TO_MONTHLY_AT_END_OF_CYCLE = 6 + DOWNGRADE_AT_END_OF_FREE_TRIAL = 7 # "Live" plans should have a value < LIVE_STATUS_THRESHOLD. # There should be at most one live plan per customer. LIVE_STATUS_THRESHOLD = 10 @@ -290,6 +291,9 @@ def get_plan_status_as_text(self) -> str: self.ACTIVE: "Active", self.DOWNGRADE_AT_END_OF_CYCLE: "Scheduled for downgrade at end of cycle", self.FREE_TRIAL: "Free trial", + self.SWITCH_TO_ANNUAL_AT_END_OF_CYCLE: "Scheduled for switch to annual at end of cycle", + self.SWITCH_TO_MONTHLY_AT_END_OF_CYCLE: "Scheduled for switch to monthly at end of cycle", + self.DOWNGRADE_AT_END_OF_FREE_TRIAL: "Scheduled for downgrade at end of free trial", self.ENDED: "Ended", self.NEVER_STARTED: "Never started", }[self.status] @@ -300,7 +304,10 @@ def licenses(self) -> int: return ledger_entry.licenses def licenses_at_next_renewal(self) -> Optional[int]: - if self.status == CustomerPlan.DOWNGRADE_AT_END_OF_CYCLE: + if self.status in ( + CustomerPlan.DOWNGRADE_AT_END_OF_CYCLE, + CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL, + ): return None ledger_entry = LicenseLedger.objects.filter(plan=self).order_by("id").last() assert ledger_entry is not None diff --git a/corporate/views/billing_page.py b/corporate/views/billing_page.py --- a/corporate/views/billing_page.py +++ b/corporate/views/billing_page.py @@ -99,6 +99,8 @@ def update_plan( CustomerPlan.DOWNGRADE_AT_END_OF_CYCLE, CustomerPlan.SWITCH_TO_ANNUAL_AT_END_OF_CYCLE, CustomerPlan.SWITCH_TO_MONTHLY_AT_END_OF_CYCLE, + CustomerPlan.FREE_TRIAL, + CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL, CustomerPlan.ENDED, ] ), @@ -108,11 +110,13 @@ def update_plan( licenses_at_next_renewal: Optional[int] = REQ( "licenses_at_next_renewal", json_validator=check_int, default=None ), + schedule: Optional[int] = REQ("schedule", json_validator=check_int, default=None), ) -> HttpResponse: update_plan_request = UpdatePlanRequest( status=status, licenses=licenses, licenses_at_next_renewal=licenses_at_next_renewal, + schedule=schedule, ) billing_session = RealmBillingSession(user=user) billing_session.do_update_plan(update_plan_request)
diff --git a/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--Customer.create.1.json b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--Customer.create.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--Customer.create.1.json @@ -0,0 +1,33 @@ +{ + "address": null, + "balance": 0, + "created": 1701007131, + "currency": null, + "default_currency": null, + "default_source": null, + "delinquent": false, + "description": "zulip (Zulip Dev)", + "discount": null, + "email": "[email protected]", + "id": "cus_P4scN21egyF63j", + "invoice_prefix": "BFEDDCEB", + "invoice_settings": { + "custom_fields": null, + "default_payment_method": null, + "footer": null, + "rendering_options": null + }, + "livemode": false, + "metadata": { + "realm_id": "2", + "realm_str": "zulip" + }, + "name": null, + "next_invoice_sequence": 1, + "object": "customer", + "phone": null, + "preferred_locales": [], + "shipping": null, + "tax_exempt": "none", + "test_clock": null +} diff --git a/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--Customer.modify.1.json b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--Customer.modify.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--Customer.modify.1.json @@ -0,0 +1,33 @@ +{ + "address": null, + "balance": 0, + "created": 1701007131, + "currency": null, + "default_currency": null, + "default_source": null, + "delinquent": false, + "description": "zulip (Zulip Dev)", + "discount": null, + "email": "[email protected]", + "id": "cus_P4scN21egyF63j", + "invoice_prefix": "BFEDDCEB", + "invoice_settings": { + "custom_fields": null, + "default_payment_method": "pm_1OGirJDEQaroqDjs0fg5PtPl", + "footer": null, + "rendering_options": null + }, + "livemode": false, + "metadata": { + "realm_id": "2", + "realm_str": "zulip" + }, + "name": null, + "next_invoice_sequence": 1, + "object": "customer", + "phone": null, + "preferred_locales": [], + "shipping": null, + "tax_exempt": "none", + "test_clock": null +} diff --git a/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--Customer.retrieve.1.json b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--Customer.retrieve.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--Customer.retrieve.1.json @@ -0,0 +1,79 @@ +{ + "address": null, + "balance": 0, + "created": 1701007131, + "currency": null, + "default_currency": null, + "default_source": null, + "delinquent": false, + "description": "zulip (Zulip Dev)", + "discount": null, + "email": "[email protected]", + "id": "cus_P4scN21egyF63j", + "invoice_prefix": "BFEDDCEB", + "invoice_settings": { + "custom_fields": null, + "default_payment_method": { + "billing_details": { + "address": { + "city": null, + "country": null, + "line1": null, + "line2": null, + "postal_code": null, + "state": null + }, + "email": null, + "name": null, + "phone": null + }, + "card": { + "brand": "visa", + "checks": { + "address_line1_check": null, + "address_postal_code_check": null, + "cvc_check": "pass" + }, + "country": "US", + "exp_month": 11, + "exp_year": 2024, + "fingerprint": "9XKsMixKBi6kIIzd", + "funding": "credit", + "generated_from": null, + "last4": "4242", + "networks": { + "available": [ + "visa" + ], + "preferred": null + }, + "three_d_secure_usage": { + "supported": true + }, + "wallet": null + }, + "created": 1701007133, + "customer": "cus_P4scN21egyF63j", + "id": "pm_1OGirJDEQaroqDjs0fg5PtPl", + "livemode": false, + "metadata": {}, + "object": "payment_method", + "type": "card" + }, + "footer": null, + "rendering_options": null + }, + "livemode": false, + "metadata": { + "realm_id": "2", + "realm_str": "zulip" + }, + "name": null, + "next_invoice_sequence": 1, + "object": "customer", + "phone": null, + "preferred_locales": [], + "shipping": null, + "tax_exempt": "none", + "test_clock": null +} diff --git a/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--Customer.retrieve.2.json b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--Customer.retrieve.2.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--Customer.retrieve.2.json @@ -0,0 +1,79 @@ +{ + "address": null, + "balance": 0, + "created": 1701007131, + "currency": null, + "default_currency": null, + "default_source": null, + "delinquent": false, + "description": "zulip (Zulip Dev)", + "discount": null, + "email": "[email protected]", + "id": "cus_P4scN21egyF63j", + "invoice_prefix": "BFEDDCEB", + "invoice_settings": { + "custom_fields": null, + "default_payment_method": { + "billing_details": { + "address": { + "city": null, + "country": null, + "line1": null, + "line2": null, + "postal_code": null, + "state": null + }, + "email": null, + "name": null, + "phone": null + }, + "card": { + "brand": "visa", + "checks": { + "address_line1_check": null, + "address_postal_code_check": null, + "cvc_check": "pass" + }, + "country": "US", + "exp_month": 11, + "exp_year": 2024, + "fingerprint": "9XKsMixKBi6kIIzd", + "funding": "credit", + "generated_from": null, + "last4": "4242", + "networks": { + "available": [ + "visa" + ], + "preferred": null + }, + "three_d_secure_usage": { + "supported": true + }, + "wallet": null + }, + "created": 1701007133, + "customer": "cus_P4scN21egyF63j", + "id": "pm_1OGirJDEQaroqDjs0fg5PtPl", + "livemode": false, + "metadata": {}, + "object": "payment_method", + "type": "card" + }, + "footer": null, + "rendering_options": null + }, + "livemode": false, + "metadata": { + "realm_id": "2", + "realm_str": "zulip" + }, + "name": null, + "next_invoice_sequence": 1, + "object": "customer", + "phone": null, + "preferred_locales": [], + "shipping": null, + "tax_exempt": "none", + "test_clock": null +} diff --git a/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--Customer.retrieve.3.json b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--Customer.retrieve.3.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--Customer.retrieve.3.json @@ -0,0 +1,79 @@ +{ + "address": null, + "balance": 0, + "created": 1701007131, + "currency": null, + "default_currency": null, + "default_source": null, + "delinquent": false, + "description": "zulip (Zulip Dev)", + "discount": null, + "email": "[email protected]", + "id": "cus_P4scN21egyF63j", + "invoice_prefix": "BFEDDCEB", + "invoice_settings": { + "custom_fields": null, + "default_payment_method": { + "billing_details": { + "address": { + "city": null, + "country": null, + "line1": null, + "line2": null, + "postal_code": null, + "state": null + }, + "email": null, + "name": null, + "phone": null + }, + "card": { + "brand": "visa", + "checks": { + "address_line1_check": null, + "address_postal_code_check": null, + "cvc_check": "pass" + }, + "country": "US", + "exp_month": 11, + "exp_year": 2024, + "fingerprint": "9XKsMixKBi6kIIzd", + "funding": "credit", + "generated_from": null, + "last4": "4242", + "networks": { + "available": [ + "visa" + ], + "preferred": null + }, + "three_d_secure_usage": { + "supported": true + }, + "wallet": null + }, + "created": 1701007133, + "customer": "cus_P4scN21egyF63j", + "id": "pm_1OGirJDEQaroqDjs0fg5PtPl", + "livemode": false, + "metadata": {}, + "object": "payment_method", + "type": "card" + }, + "footer": null, + "rendering_options": null + }, + "livemode": false, + "metadata": { + "realm_id": "2", + "realm_str": "zulip" + }, + "name": null, + "next_invoice_sequence": 1, + "object": "customer", + "phone": null, + "preferred_locales": [], + "shipping": null, + "tax_exempt": "none", + "test_clock": null +} diff --git a/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--Customer.retrieve.4.json b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--Customer.retrieve.4.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--Customer.retrieve.4.json @@ -0,0 +1,79 @@ +{ + "address": null, + "balance": 0, + "created": 1701007131, + "currency": null, + "default_currency": null, + "default_source": null, + "delinquent": false, + "description": "zulip (Zulip Dev)", + "discount": null, + "email": "[email protected]", + "id": "cus_P4scN21egyF63j", + "invoice_prefix": "BFEDDCEB", + "invoice_settings": { + "custom_fields": null, + "default_payment_method": { + "billing_details": { + "address": { + "city": null, + "country": null, + "line1": null, + "line2": null, + "postal_code": null, + "state": null + }, + "email": null, + "name": null, + "phone": null + }, + "card": { + "brand": "visa", + "checks": { + "address_line1_check": null, + "address_postal_code_check": null, + "cvc_check": "pass" + }, + "country": "US", + "exp_month": 11, + "exp_year": 2024, + "fingerprint": "9XKsMixKBi6kIIzd", + "funding": "credit", + "generated_from": null, + "last4": "4242", + "networks": { + "available": [ + "visa" + ], + "preferred": null + }, + "three_d_secure_usage": { + "supported": true + }, + "wallet": null + }, + "created": 1701007133, + "customer": "cus_P4scN21egyF63j", + "id": "pm_1OGirJDEQaroqDjs0fg5PtPl", + "livemode": false, + "metadata": {}, + "object": "payment_method", + "type": "card" + }, + "footer": null, + "rendering_options": null + }, + "livemode": false, + "metadata": { + "realm_id": "2", + "realm_str": "zulip" + }, + "name": null, + "next_invoice_sequence": 1, + "object": "customer", + "phone": null, + "preferred_locales": [], + "shipping": null, + "tax_exempt": "none", + "test_clock": null +} diff --git a/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--Event.list.1.json b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--Event.list.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--Event.list.1.json @@ -0,0 +1,60 @@ +{ + "data": [ + { + "api_version": "2020-08-27", + "created": 1701007135, + "data": { + "object": { + "address": null, + "balance": 0, + "created": 1701007131, + "currency": null, + "default_currency": null, + "default_source": null, + "delinquent": false, + "description": "zulip (Zulip Dev)", + "discount": null, + "email": "[email protected]", + "id": "cus_P4scN21egyF63j", + "invoice_prefix": "BFEDDCEB", + "invoice_settings": { + "custom_fields": null, + "default_payment_method": "pm_1OGirJDEQaroqDjs0fg5PtPl", + "footer": null, + "rendering_options": null + }, + "livemode": false, + "metadata": { + "realm_id": "2", + "realm_str": "zulip" + }, + "name": null, + "next_invoice_sequence": 1, + "object": "customer", + "phone": null, + "preferred_locales": [], + "shipping": null, + "tax_exempt": "none", + "test_clock": null + }, + "previous_attributes": { + "invoice_settings": { + "default_payment_method": null + } + } + }, + "id": "evt_1OGirLDEQaroqDjsz8SKiaqo", + "livemode": false, + "object": "event", + "pending_webhooks": 0, + "request": { + "id": "req_AyeuVEyieC6onh", + "idempotency_key": "89b1c0ff-4445-484e-a46d-edb738e19727" + }, + "type": "customer.updated" + } + ], + "has_more": true, + "object": "list", + "url": "/v1/events" +} diff --git a/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--Invoice.list.1.json b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--Invoice.list.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--Invoice.list.1.json @@ -0,0 +1,6 @@ +{ + "data": [], + "has_more": false, + "object": "list", + "url": "/v1/invoices" +} diff --git a/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--SetupIntent.create.1.json b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--SetupIntent.create.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--SetupIntent.create.1.json @@ -0,0 +1,34 @@ +{ + "application": null, + "automatic_payment_methods": null, + "cancellation_reason": null, + "client_secret": "seti_1OGirJDEQaroqDjsYpipSEB0_secret_P4scaxG6yYSKO4CtptkXClW7kitH4Z5", + "created": 1701007133, + "customer": "cus_P4scN21egyF63j", + "description": null, + "flow_directions": null, + "id": "seti_1OGirJDEQaroqDjsYpipSEB0", + "last_setup_error": null, + "latest_attempt": "setatt_1OGirJDEQaroqDjskmjNC3F7", + "livemode": false, + "mandate": null, + "metadata": {}, + "next_action": null, + "object": "setup_intent", + "on_behalf_of": null, + "payment_method": "pm_1OGirJDEQaroqDjs0fg5PtPl", + "payment_method_configuration_details": null, + "payment_method_options": { + "card": { + "mandate_options": null, + "network": null, + "request_three_d_secure": "automatic" + } + }, + "payment_method_types": [ + "card" + ], + "single_use_mandate": null, + "status": "succeeded", + "usage": "off_session" +} diff --git a/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--SetupIntent.list.1.json b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--SetupIntent.list.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--SetupIntent.list.1.json @@ -0,0 +1,41 @@ +{ + "data": [ + { + "application": null, + "automatic_payment_methods": null, + "cancellation_reason": null, + "client_secret": "seti_1OGirHDEQaroqDjsWRgeKxys_secret_P4scp8ZoQF4uJncgCdd4XzNWWTw16yl", + "created": 1701007131, + "customer": "cus_P4scN21egyF63j", + "description": null, + "flow_directions": null, + "id": "seti_1OGirHDEQaroqDjsWRgeKxys", + "last_setup_error": null, + "latest_attempt": null, + "livemode": false, + "mandate": null, + "metadata": {}, + "next_action": null, + "object": "setup_intent", + "on_behalf_of": null, + "payment_method": null, + "payment_method_configuration_details": null, + "payment_method_options": { + "card": { + "mandate_options": null, + "network": null, + "request_three_d_secure": "automatic" + } + }, + "payment_method_types": [ + "card" + ], + "single_use_mandate": null, + "status": "requires_payment_method", + "usage": "off_session" + } + ], + "has_more": true, + "object": "list", + "url": "/v1/setup_intents" +} diff --git a/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--SetupIntent.retrieve.1.json b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--SetupIntent.retrieve.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--SetupIntent.retrieve.1.json @@ -0,0 +1,34 @@ +{ + "application": null, + "automatic_payment_methods": null, + "cancellation_reason": null, + "client_secret": "seti_1OGirJDEQaroqDjsYpipSEB0_secret_P4scaxG6yYSKO4CtptkXClW7kitH4Z5", + "created": 1701007133, + "customer": "cus_P4scN21egyF63j", + "description": null, + "flow_directions": null, + "id": "seti_1OGirJDEQaroqDjsYpipSEB0", + "last_setup_error": null, + "latest_attempt": "setatt_1OGirJDEQaroqDjskmjNC3F7", + "livemode": false, + "mandate": null, + "metadata": {}, + "next_action": null, + "object": "setup_intent", + "on_behalf_of": null, + "payment_method": "pm_1OGirJDEQaroqDjs0fg5PtPl", + "payment_method_configuration_details": null, + "payment_method_options": { + "card": { + "mandate_options": null, + "network": null, + "request_three_d_secure": "automatic" + } + }, + "payment_method_types": [ + "card" + ], + "single_use_mandate": null, + "status": "succeeded", + "usage": "off_session" +} diff --git a/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--checkout.Session.create.1.json b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--checkout.Session.create.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--checkout.Session.create.1.json @@ -0,0 +1,73 @@ +{ + "after_expiration": null, + "allow_promotion_codes": null, + "amount_subtotal": null, + "amount_total": null, + "automatic_tax": { + "enabled": false, + "status": null + }, + "billing_address_collection": null, + "cancel_url": "http://zulip.testserver/upgrade/", + "client_reference_id": null, + "client_secret": null, + "consent": null, + "consent_collection": null, + "created": 1701007131, + "currency": null, + "currency_conversion": null, + "custom_fields": [], + "custom_text": { + "shipping_address": null, + "submit": null, + "terms_of_service_acceptance": null + }, + "customer": "cus_P4scN21egyF63j", + "customer_creation": null, + "customer_details": { + "address": null, + "email": "[email protected]", + "name": null, + "phone": null, + "tax_exempt": null, + "tax_ids": null + }, + "customer_email": null, + "expires_at": 1701093531, + "id": "cs_test_c1fBDZcNaDnv5cqg1WNBXNCDmlUwwLBP59mIYRwRB1OUAEYocADHCi5EOH", + "invoice": null, + "invoice_creation": null, + "livemode": false, + "locale": null, + "metadata": { + "type": "card_update", + "user_id": "10" + }, + "mode": "setup", + "object": "checkout.session", + "payment_intent": null, + "payment_link": null, + "payment_method_collection": "always", + "payment_method_configuration_details": null, + "payment_method_options": {}, + "payment_method_types": [ + "card" + ], + "payment_status": "no_payment_required", + "phone_number_collection": { + "enabled": false + }, + "recovered_from": null, + "setup_intent": "seti_1OGirHDEQaroqDjsWRgeKxys", + "shipping": null, + "shipping_address_collection": null, + "shipping_options": [], + "shipping_rate": null, + "status": "open", + "submit_type": null, + "subscription": null, + "success_url": "http://zulip.testserver/billing/event_status?stripe_session_id={CHECKOUT_SESSION_ID}", + "total_details": null, + "ui_mode": "hosted", + "url": "https://checkout.stripe.com/c/pay/cs_test_c1fBDZcNaDnv5cqg1WNBXNCDmlUwwLBP59mIYRwRB1OUAEYocADHCi5EOH#fidkdWxOYHwnPyd1blpxYHZxWl1UZjFOczZJXUE2PUpzUWNPV2ZpdlFzUCcpJ2N3amhWYHdzYHcnP3F3cGApJ2lkfGpwcVF8dWAnPyd2bGtiaWBaZmppcGhrJyknYGtkZ2lgVWlkZmBtamlhYHd2Jz9xd3BgeCUl" +} diff --git a/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--checkout.Session.list.1.json b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--checkout.Session.list.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_annual_to_monthly--checkout.Session.list.1.json @@ -0,0 +1,80 @@ +{ + "data": [ + { + "after_expiration": null, + "allow_promotion_codes": null, + "amount_subtotal": null, + "amount_total": null, + "automatic_tax": { + "enabled": false, + "status": null + }, + "billing_address_collection": null, + "cancel_url": "http://zulip.testserver/upgrade/", + "client_reference_id": null, + "client_secret": null, + "consent": null, + "consent_collection": null, + "created": 1701007131, + "currency": null, + "currency_conversion": null, + "custom_fields": [], + "custom_text": { + "shipping_address": null, + "submit": null, + "terms_of_service_acceptance": null + }, + "customer": "cus_P4scN21egyF63j", + "customer_creation": null, + "customer_details": { + "address": null, + "email": "[email protected]", + "name": null, + "phone": null, + "tax_exempt": null, + "tax_ids": null + }, + "customer_email": null, + "expires_at": 1701093531, + "id": "cs_test_c1fBDZcNaDnv5cqg1WNBXNCDmlUwwLBP59mIYRwRB1OUAEYocADHCi5EOH", + "invoice": null, + "invoice_creation": null, + "livemode": false, + "locale": null, + "metadata": { + "type": "card_update", + "user_id": "10" + }, + "mode": "setup", + "object": "checkout.session", + "payment_intent": null, + "payment_link": null, + "payment_method_collection": "always", + "payment_method_configuration_details": null, + "payment_method_options": {}, + "payment_method_types": [ + "card" + ], + "payment_status": "no_payment_required", + "phone_number_collection": { + "enabled": false + }, + "recovered_from": null, + "setup_intent": "seti_1OGirHDEQaroqDjsWRgeKxys", + "shipping": null, + "shipping_address_collection": null, + "shipping_options": [], + "shipping_rate": null, + "status": "open", + "submit_type": null, + "subscription": null, + "success_url": "http://zulip.testserver/billing/event_status?stripe_session_id={CHECKOUT_SESSION_ID}", + "total_details": null, + "ui_mode": "hosted", + "url": "https://checkout.stripe.com/c/pay/cs_test_c1fBDZcNaDnv5cqg1WNBXNCDmlUwwLBP59mIYRwRB1OUAEYocADHCi5EOH#fidkdWxOYHwnPyd1blpxYHZxWl1UZjFOczZJXUE2PUpzUWNPV2ZpdlFzUCcpJ2N3amhWYHdzYHcnP3F3cGApJ2lkfGpwcVF8dWAnPyd2bGtiaWBaZmppcGhrJyknYGtkZ2lgVWlkZmBtamlhYHd2Jz9xd3BgeCUl" + } + ], + "has_more": true, + "object": "list", + "url": "/v1/checkout/sessions" +} diff --git a/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--Customer.create.1.json b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--Customer.create.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--Customer.create.1.json @@ -0,0 +1,33 @@ +{ + "address": null, + "balance": 0, + "created": 1000000000, + "currency": null, + "default_currency": null, + "default_source": null, + "delinquent": false, + "description": "zulip (Zulip Dev)", + "discount": null, + "email": "[email protected]", + "id": "cus_NORMALIZED0001", + "invoice_prefix": "NORMA01", + "invoice_settings": { + "custom_fields": null, + "default_payment_method": null, + "footer": null, + "rendering_options": null + }, + "livemode": false, + "metadata": { + "realm_id": "1", + "realm_str": "zulip" + }, + "name": null, + "next_invoice_sequence": 1, + "object": "customer", + "phone": null, + "preferred_locales": [], + "shipping": null, + "tax_exempt": "none", + "test_clock": null +} diff --git a/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--Customer.modify.1.json b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--Customer.modify.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--Customer.modify.1.json @@ -0,0 +1,33 @@ +{ + "address": null, + "balance": 0, + "created": 1000000000, + "currency": null, + "default_currency": null, + "default_source": null, + "delinquent": false, + "description": "zulip (Zulip Dev)", + "discount": null, + "email": "[email protected]", + "id": "cus_NORMALIZED0001", + "invoice_prefix": "NORMA01", + "invoice_settings": { + "custom_fields": null, + "default_payment_method": "pm_1OGjOiDEQaroqDjs1saPoOzz", + "footer": null, + "rendering_options": null + }, + "livemode": false, + "metadata": { + "realm_id": "1", + "realm_str": "zulip" + }, + "name": null, + "next_invoice_sequence": 1, + "object": "customer", + "phone": null, + "preferred_locales": [], + "shipping": null, + "tax_exempt": "none", + "test_clock": null +} diff --git a/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--Customer.retrieve.1.json b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--Customer.retrieve.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--Customer.retrieve.1.json @@ -0,0 +1,79 @@ +{ + "address": null, + "balance": 0, + "created": 1000000000, + "currency": null, + "default_currency": null, + "default_source": null, + "delinquent": false, + "description": "zulip (Zulip Dev)", + "discount": null, + "email": "[email protected]", + "id": "cus_NORMALIZED0001", + "invoice_prefix": "NORMA01", + "invoice_settings": { + "custom_fields": null, + "default_payment_method": { + "billing_details": { + "address": { + "city": null, + "country": null, + "line1": null, + "line2": null, + "postal_code": null, + "state": null + }, + "email": null, + "name": null, + "phone": null + }, + "card": { + "brand": "visa", + "checks": { + "address_line1_check": null, + "address_postal_code_check": null, + "cvc_check": "pass" + }, + "country": "US", + "exp_month": 11, + "exp_year": 2024, + "fingerprint": "NORMALIZED000001", + "funding": "credit", + "generated_from": null, + "last4": "4242", + "networks": { + "available": [ + "visa" + ], + "preferred": null + }, + "three_d_secure_usage": { + "supported": true + }, + "wallet": null + }, + "created": 1000000000, + "customer": "cus_NORMALIZED0001", + "id": "pm_1OGjOiDEQaroqDjs1saPoOzz", + "livemode": false, + "metadata": {}, + "object": "payment_method", + "type": "card" + }, + "footer": null, + "rendering_options": null + }, + "livemode": false, + "metadata": { + "realm_id": "1", + "realm_str": "zulip" + }, + "name": null, + "next_invoice_sequence": 1, + "object": "customer", + "phone": null, + "preferred_locales": [], + "shipping": null, + "tax_exempt": "none", + "test_clock": null +} diff --git a/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--Customer.retrieve.2.json b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--Customer.retrieve.2.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--Customer.retrieve.2.json @@ -0,0 +1,79 @@ +{ + "address": null, + "balance": 0, + "created": 1000000000, + "currency": null, + "default_currency": null, + "default_source": null, + "delinquent": false, + "description": "zulip (Zulip Dev)", + "discount": null, + "email": "[email protected]", + "id": "cus_NORMALIZED0001", + "invoice_prefix": "NORMA01", + "invoice_settings": { + "custom_fields": null, + "default_payment_method": { + "billing_details": { + "address": { + "city": null, + "country": null, + "line1": null, + "line2": null, + "postal_code": null, + "state": null + }, + "email": null, + "name": null, + "phone": null + }, + "card": { + "brand": "visa", + "checks": { + "address_line1_check": null, + "address_postal_code_check": null, + "cvc_check": "pass" + }, + "country": "US", + "exp_month": 11, + "exp_year": 2024, + "fingerprint": "NORMALIZED000001", + "funding": "credit", + "generated_from": null, + "last4": "4242", + "networks": { + "available": [ + "visa" + ], + "preferred": null + }, + "three_d_secure_usage": { + "supported": true + }, + "wallet": null + }, + "created": 1000000000, + "customer": "cus_NORMALIZED0001", + "id": "pm_1OGjOiDEQaroqDjs1saPoOzz", + "livemode": false, + "metadata": {}, + "object": "payment_method", + "type": "card" + }, + "footer": null, + "rendering_options": null + }, + "livemode": false, + "metadata": { + "realm_id": "1", + "realm_str": "zulip" + }, + "name": null, + "next_invoice_sequence": 1, + "object": "customer", + "phone": null, + "preferred_locales": [], + "shipping": null, + "tax_exempt": "none", + "test_clock": null +} diff --git a/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--Customer.retrieve.3.json b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--Customer.retrieve.3.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--Customer.retrieve.3.json @@ -0,0 +1,79 @@ +{ + "address": null, + "balance": 0, + "created": 1000000000, + "currency": null, + "default_currency": null, + "default_source": null, + "delinquent": false, + "description": "zulip (Zulip Dev)", + "discount": null, + "email": "[email protected]", + "id": "cus_NORMALIZED0001", + "invoice_prefix": "NORMA01", + "invoice_settings": { + "custom_fields": null, + "default_payment_method": { + "billing_details": { + "address": { + "city": null, + "country": null, + "line1": null, + "line2": null, + "postal_code": null, + "state": null + }, + "email": null, + "name": null, + "phone": null + }, + "card": { + "brand": "visa", + "checks": { + "address_line1_check": null, + "address_postal_code_check": null, + "cvc_check": "pass" + }, + "country": "US", + "exp_month": 11, + "exp_year": 2024, + "fingerprint": "NORMALIZED000001", + "funding": "credit", + "generated_from": null, + "last4": "4242", + "networks": { + "available": [ + "visa" + ], + "preferred": null + }, + "three_d_secure_usage": { + "supported": true + }, + "wallet": null + }, + "created": 1000000000, + "customer": "cus_NORMALIZED0001", + "id": "pm_1OGjOiDEQaroqDjs1saPoOzz", + "livemode": false, + "metadata": {}, + "object": "payment_method", + "type": "card" + }, + "footer": null, + "rendering_options": null + }, + "livemode": false, + "metadata": { + "realm_id": "1", + "realm_str": "zulip" + }, + "name": null, + "next_invoice_sequence": 1, + "object": "customer", + "phone": null, + "preferred_locales": [], + "shipping": null, + "tax_exempt": "none", + "test_clock": null +} diff --git a/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--Customer.retrieve.4.json b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--Customer.retrieve.4.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--Customer.retrieve.4.json @@ -0,0 +1,79 @@ +{ + "address": null, + "balance": 0, + "created": 1000000000, + "currency": null, + "default_currency": null, + "default_source": null, + "delinquent": false, + "description": "zulip (Zulip Dev)", + "discount": null, + "email": "[email protected]", + "id": "cus_NORMALIZED0001", + "invoice_prefix": "NORMA01", + "invoice_settings": { + "custom_fields": null, + "default_payment_method": { + "billing_details": { + "address": { + "city": null, + "country": null, + "line1": null, + "line2": null, + "postal_code": null, + "state": null + }, + "email": null, + "name": null, + "phone": null + }, + "card": { + "brand": "visa", + "checks": { + "address_line1_check": null, + "address_postal_code_check": null, + "cvc_check": "pass" + }, + "country": "US", + "exp_month": 11, + "exp_year": 2024, + "fingerprint": "NORMALIZED000001", + "funding": "credit", + "generated_from": null, + "last4": "4242", + "networks": { + "available": [ + "visa" + ], + "preferred": null + }, + "three_d_secure_usage": { + "supported": true + }, + "wallet": null + }, + "created": 1000000000, + "customer": "cus_NORMALIZED0001", + "id": "pm_1OGjOiDEQaroqDjs1saPoOzz", + "livemode": false, + "metadata": {}, + "object": "payment_method", + "type": "card" + }, + "footer": null, + "rendering_options": null + }, + "livemode": false, + "metadata": { + "realm_id": "1", + "realm_str": "zulip" + }, + "name": null, + "next_invoice_sequence": 1, + "object": "customer", + "phone": null, + "preferred_locales": [], + "shipping": null, + "tax_exempt": "none", + "test_clock": null +} diff --git a/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--Event.list.1.json b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--Event.list.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--Event.list.1.json @@ -0,0 +1,60 @@ +{ + "data": [ + { + "api_version": "2020-08-27", + "created": 1000000000, + "data": { + "object": { + "address": null, + "balance": 0, + "created": 1000000000, + "currency": null, + "default_currency": null, + "default_source": null, + "delinquent": false, + "description": "zulip (Zulip Dev)", + "discount": null, + "email": "[email protected]", + "id": "cus_NORMALIZED0001", + "invoice_prefix": "NORMA01", + "invoice_settings": { + "custom_fields": null, + "default_payment_method": "pm_1OGjOiDEQaroqDjs1saPoOzz", + "footer": null, + "rendering_options": null + }, + "livemode": false, + "metadata": { + "realm_id": "1", + "realm_str": "zulip" + }, + "name": null, + "next_invoice_sequence": 1, + "object": "customer", + "phone": null, + "preferred_locales": [], + "shipping": null, + "tax_exempt": "none", + "test_clock": null + }, + "previous_attributes": { + "invoice_settings": { + "default_payment_method": null + } + } + }, + "id": "evt_1OGjOjDEQaroqDjsgh56akwA", + "livemode": false, + "object": "event", + "pending_webhooks": 0, + "request": { + "id": "req_NORMALIZED0001", + "idempotency_key": "82ec0759-4649-4aa5-ab13-f80c5b6300cc" + }, + "type": "customer.updated" + } + ], + "has_more": true, + "object": "list", + "url": "/v1/events" +} diff --git a/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--Invoice.list.1.json b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--Invoice.list.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--Invoice.list.1.json @@ -0,0 +1,6 @@ +{ + "data": [], + "has_more": false, + "object": "list", + "url": "/v1/invoices" +} diff --git a/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--SetupIntent.create.1.json b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--SetupIntent.create.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--SetupIntent.create.1.json @@ -0,0 +1,34 @@ +{ + "application": null, + "automatic_payment_methods": null, + "cancellation_reason": null, + "client_secret": "seti_1OGjOiDEQaroqDjs0mczPK5Q_secret_P4tBceetMSlLfbfrbp4RXKdBjnNp4In", + "created": 1000000000, + "customer": "cus_NORMALIZED0001", + "description": null, + "flow_directions": null, + "id": "seti_1OGjOiDEQaroqDjs0mczPK5Q", + "last_setup_error": null, + "latest_attempt": "setatt_1OGjOiDEQaroqDjsZve6lwXi", + "livemode": false, + "mandate": null, + "metadata": {}, + "next_action": null, + "object": "setup_intent", + "on_behalf_of": null, + "payment_method": "pm_1OGjOiDEQaroqDjs1saPoOzz", + "payment_method_configuration_details": null, + "payment_method_options": { + "card": { + "mandate_options": null, + "network": null, + "request_three_d_secure": "automatic" + } + }, + "payment_method_types": [ + "card" + ], + "single_use_mandate": null, + "status": "succeeded", + "usage": "off_session" +} diff --git a/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--SetupIntent.list.1.json b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--SetupIntent.list.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--SetupIntent.list.1.json @@ -0,0 +1,41 @@ +{ + "data": [ + { + "application": null, + "automatic_payment_methods": null, + "cancellation_reason": null, + "client_secret": "seti_1OGjOgDEQaroqDjsnqXN4MEe_secret_P4tBu0OljOeHnxDc1xFcHJLxe3YbMFs", + "created": 1000000000, + "customer": "cus_NORMALIZED0001", + "description": null, + "flow_directions": null, + "id": "seti_1OGjOgDEQaroqDjsnqXN4MEe", + "last_setup_error": null, + "latest_attempt": null, + "livemode": false, + "mandate": null, + "metadata": {}, + "next_action": null, + "object": "setup_intent", + "on_behalf_of": null, + "payment_method": null, + "payment_method_configuration_details": null, + "payment_method_options": { + "card": { + "mandate_options": null, + "network": null, + "request_three_d_secure": "automatic" + } + }, + "payment_method_types": [ + "card" + ], + "single_use_mandate": null, + "status": "requires_payment_method", + "usage": "off_session" + } + ], + "has_more": true, + "object": "list", + "url": "/v1/setup_intents" +} diff --git a/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--SetupIntent.retrieve.1.json b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--SetupIntent.retrieve.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--SetupIntent.retrieve.1.json @@ -0,0 +1,34 @@ +{ + "application": null, + "automatic_payment_methods": null, + "cancellation_reason": null, + "client_secret": "seti_1OGjOiDEQaroqDjs0mczPK5Q_secret_P4tBceetMSlLfbfrbp4RXKdBjnNp4In", + "created": 1000000000, + "customer": "cus_NORMALIZED0001", + "description": null, + "flow_directions": null, + "id": "seti_1OGjOiDEQaroqDjs0mczPK5Q", + "last_setup_error": null, + "latest_attempt": "setatt_1OGjOiDEQaroqDjsZve6lwXi", + "livemode": false, + "mandate": null, + "metadata": {}, + "next_action": null, + "object": "setup_intent", + "on_behalf_of": null, + "payment_method": "pm_1OGjOiDEQaroqDjs1saPoOzz", + "payment_method_configuration_details": null, + "payment_method_options": { + "card": { + "mandate_options": null, + "network": null, + "request_three_d_secure": "automatic" + } + }, + "payment_method_types": [ + "card" + ], + "single_use_mandate": null, + "status": "succeeded", + "usage": "off_session" +} diff --git a/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--checkout.Session.create.1.json b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--checkout.Session.create.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--checkout.Session.create.1.json @@ -0,0 +1,73 @@ +{ + "after_expiration": null, + "allow_promotion_codes": null, + "amount_subtotal": null, + "amount_total": null, + "automatic_tax": { + "enabled": false, + "status": null + }, + "billing_address_collection": null, + "cancel_url": "http://zulip.testserver/upgrade/", + "client_reference_id": null, + "client_secret": null, + "consent": null, + "consent_collection": null, + "created": 1000000000, + "currency": null, + "currency_conversion": null, + "custom_fields": [], + "custom_text": { + "shipping_address": null, + "submit": null, + "terms_of_service_acceptance": null + }, + "customer": "cus_NORMALIZED0001", + "customer_creation": null, + "customer_details": { + "address": null, + "email": "[email protected]", + "name": null, + "phone": null, + "tax_exempt": null, + "tax_ids": null + }, + "customer_email": null, + "expires_at": 1000000000, + "id": "cs_test_NORMALIZED01X2pCpFwoBMHMedIXu5mI7Xubvoh8wc4oenhkdkooMUfP5a", + "invoice": null, + "invoice_creation": null, + "livemode": false, + "locale": null, + "metadata": { + "type": "card_update", + "user_id": "10" + }, + "mode": "setup", + "object": "checkout.session", + "payment_intent": null, + "payment_link": null, + "payment_method_collection": "always", + "payment_method_configuration_details": null, + "payment_method_options": {}, + "payment_method_types": [ + "card" + ], + "payment_status": "no_payment_required", + "phone_number_collection": { + "enabled": false + }, + "recovered_from": null, + "setup_intent": "seti_1OGjOgDEQaroqDjsnqXN4MEe", + "shipping": null, + "shipping_address_collection": null, + "shipping_options": [], + "shipping_rate": null, + "status": "open", + "submit_type": null, + "subscription": null, + "success_url": "http://zulip.testserver/billing/event_status?stripe_session_id={CHECKOUT_SESSION_ID}", + "total_details": null, + "ui_mode": "hosted", + "url": "https://checkout.stripe.com/c/pay/cs_test_NORMALIZED01X2pCpFwoBMHMedIXu5mI7Xubvoh8wc4oenhkdkooMUfP5a#fidkdWxOYHwnPyd1blpxYHZxWl1UZjFOczZJXUE2PUpzUWNPV2ZpdlFzUCcpJ2N3amhWYHdzYHcnP3F3cGApJ2lkfGpwcVF8dWAnPyd2bGtiaWBaZmppcGhrJyknYGtkZ2lgVWlkZmBtamlhYHd2Jz9xd3BgeCUl" +} diff --git a/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--checkout.Session.list.1.json b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--checkout.Session.list.1.json new file mode 100644 --- /dev/null +++ b/corporate/tests/stripe_fixtures/switch_now_free_trial_from_monthly_to_annual--checkout.Session.list.1.json @@ -0,0 +1,80 @@ +{ + "data": [ + { + "after_expiration": null, + "allow_promotion_codes": null, + "amount_subtotal": null, + "amount_total": null, + "automatic_tax": { + "enabled": false, + "status": null + }, + "billing_address_collection": null, + "cancel_url": "http://zulip.testserver/upgrade/", + "client_reference_id": null, + "client_secret": null, + "consent": null, + "consent_collection": null, + "created": 1000000000, + "currency": null, + "currency_conversion": null, + "custom_fields": [], + "custom_text": { + "shipping_address": null, + "submit": null, + "terms_of_service_acceptance": null + }, + "customer": "cus_NORMALIZED0001", + "customer_creation": null, + "customer_details": { + "address": null, + "email": "[email protected]", + "name": null, + "phone": null, + "tax_exempt": null, + "tax_ids": null + }, + "customer_email": null, + "expires_at": 1000000000, + "id": "cs_test_NORMALIZED01X2pCpFwoBMHMedIXu5mI7Xubvoh8wc4oenhkdkooMUfP5a", + "invoice": null, + "invoice_creation": null, + "livemode": false, + "locale": null, + "metadata": { + "type": "card_update", + "user_id": "10" + }, + "mode": "setup", + "object": "checkout.session", + "payment_intent": null, + "payment_link": null, + "payment_method_collection": "always", + "payment_method_configuration_details": null, + "payment_method_options": {}, + "payment_method_types": [ + "card" + ], + "payment_status": "no_payment_required", + "phone_number_collection": { + "enabled": false + }, + "recovered_from": null, + "setup_intent": "seti_1OGjOgDEQaroqDjsnqXN4MEe", + "shipping": null, + "shipping_address_collection": null, + "shipping_options": [], + "shipping_rate": null, + "status": "open", + "submit_type": null, + "subscription": null, + "success_url": "http://zulip.testserver/billing/event_status?stripe_session_id={CHECKOUT_SESSION_ID}", + "total_details": null, + "ui_mode": "hosted", + "url": "https://checkout.stripe.com/c/pay/cs_test_NORMALIZED01X2pCpFwoBMHMedIXu5mI7Xubvoh8wc4oenhkdkooMUfP5a#fidkdWxOYHwnPyd1blpxYHZxWl1UZjFOczZJXUE2PUpzUWNPV2ZpdlFzUCcpJ2N3amhWYHdzYHcnP3F3cGApJ2lkfGpwcVF8dWAnPyd2bGtiaWBaZmppcGhrJyknYGtkZ2lgVWlkZmBtamlhYHd2Jz9xd3BgeCUl" + } + ], + "has_more": true, + "object": "list", + "url": "/v1/checkout/sessions" +} diff --git a/corporate/tests/test_stripe.py b/corporate/tests/test_stripe.py --- a/corporate/tests/test_stripe.py +++ b/corporate/tests/test_stripe.py @@ -1031,7 +1031,7 @@ def test_free_trial_upgrade_by_card(self, *mocks: Mock) -> None: free_trial_end_date = self.now + timedelta(days=60) self.assert_in_success_response( - ["You won't be charged", "Free Trial", "60 day"], response + ["You card will not be charged", "free trial", "60-day"], response ) self.assertNotEqual(user.realm.plan_type, Realm.PLAN_TYPE_STANDARD) self.assertFalse(Customer.objects.filter(realm=user.realm).exists()) @@ -1249,7 +1249,7 @@ def test_free_trial_upgrade_by_invoice(self, *mocks: Mock) -> None: response = self.client_get("/upgrade/") self.assert_in_success_response( - ["You won't be charged", "Free Trial", "60 day"], response + ["You card will not be charged", "free trial", "60-day"], response ) self.assertNotEqual(user.realm.plan_type, Realm.PLAN_TYPE_STANDARD) self.assertFalse(Customer.objects.filter(realm=user.realm).exists()) @@ -2839,7 +2839,116 @@ def test_downgrade_during_invoicing(self, *mocks: Mock) -> None: self.assertIsNone(plan.next_invoice_date) self.assertEqual(plan.status, CustomerPlan.ENDED) - def test_downgrade_free_trial(self) -> None: + @mock_stripe() + def test_switch_now_free_trial_from_monthly_to_annual(self, *mocks: Mock) -> None: + user = self.example_user("hamlet") + self.login_user(user) + + free_trial_end_date = self.now + timedelta(days=60) + with self.settings(FREE_TRIAL_DAYS=60): + with patch("corporate.lib.stripe.timezone_now", return_value=self.now): + self.add_card_and_upgrade(user, schedule="monthly") + plan = CustomerPlan.objects.get() + self.assertEqual(plan.next_invoice_date, free_trial_end_date) + self.assertEqual(get_realm("zulip").plan_type, Realm.PLAN_TYPE_STANDARD) + self.assertEqual(plan.status, CustomerPlan.FREE_TRIAL) + + customer = get_customer_by_realm(user.realm) + assert customer is not None + result = self.client_patch( + "/json/billing/plan", + { + "status": CustomerPlan.FREE_TRIAL, + "schedule": CustomerPlan.ANNUAL, + }, + ) + self.assert_json_success(result) + + plan.refresh_from_db() + self.assertEqual(plan.status, CustomerPlan.ENDED) + + plan = CustomerPlan.objects.get( + customer=customer, + automanage_licenses=True, + price_per_license=8000, + fixed_price=None, + discount=None, + billing_cycle_anchor=self.now, + billing_schedule=CustomerPlan.ANNUAL, + invoiced_through=None, + next_invoice_date=free_trial_end_date, + tier=CustomerPlan.STANDARD, + status=CustomerPlan.FREE_TRIAL, + charge_automatically=True, + ) + LicenseLedger.objects.get( + plan=plan, + is_renewal=True, + event_time=self.now, + licenses=self.seat_count, + licenses_at_next_renewal=self.seat_count, + ) + + realm_audit_log = RealmAuditLog.objects.filter( + event_type=RealmAuditLog.CUSTOMER_SWITCHED_FROM_MONTHLY_TO_ANNUAL_PLAN + ).last() + assert realm_audit_log is not None + + @mock_stripe() + def test_switch_now_free_trial_from_annual_to_monthly(self, *mocks: Mock) -> None: + user = self.example_user("hamlet") + self.login_user(user) + + free_trial_end_date = self.now + timedelta(days=60) + with self.settings(FREE_TRIAL_DAYS=60): + with patch("corporate.lib.stripe.timezone_now", return_value=self.now): + self.add_card_and_upgrade(user, schedule="annual") + plan = CustomerPlan.objects.get() + self.assertEqual(plan.next_invoice_date, free_trial_end_date) + self.assertEqual(get_realm("zulip").plan_type, Realm.PLAN_TYPE_STANDARD) + self.assertEqual(plan.status, CustomerPlan.FREE_TRIAL) + + customer = get_customer_by_realm(user.realm) + assert customer is not None + result = self.client_patch( + "/json/billing/plan", + { + "status": CustomerPlan.FREE_TRIAL, + "schedule": CustomerPlan.MONTHLY, + }, + ) + self.assert_json_success(result) + plan.refresh_from_db() + self.assertEqual(plan.status, CustomerPlan.ENDED) + + plan = CustomerPlan.objects.get( + customer=customer, + automanage_licenses=True, + price_per_license=800, + fixed_price=None, + discount=None, + billing_cycle_anchor=self.now, + billing_schedule=CustomerPlan.MONTHLY, + invoiced_through=None, + next_invoice_date=free_trial_end_date, + tier=CustomerPlan.STANDARD, + status=CustomerPlan.FREE_TRIAL, + charge_automatically=True, + ) + LicenseLedger.objects.get( + plan=plan, + is_renewal=True, + event_time=self.now, + licenses=self.seat_count, + licenses_at_next_renewal=self.seat_count, + ) + + realm_audit_log = RealmAuditLog.objects.filter( + event_type=RealmAuditLog.CUSTOMER_SWITCHED_FROM_ANNUAL_TO_MONTHLY_PLAN + ).last() + assert realm_audit_log is not None + + def test_end_free_trial(self) -> None: user = self.example_user("hamlet") free_trial_end_date = self.now + timedelta(days=60) @@ -2887,6 +2996,172 @@ def test_downgrade_free_trial(self) -> None: invoice_plans_as_needed(self.next_year) mocked.assert_not_called() + def test_downgrade_at_end_of_free_trial(self) -> None: + user = self.example_user("hamlet") + self.login_user(user) + + free_trial_end_date = self.now + timedelta(days=60) + with self.settings(FREE_TRIAL_DAYS=60): + with patch("corporate.lib.stripe.timezone_now", return_value=self.now): + self.local_upgrade(self.seat_count, True, CustomerPlan.ANNUAL, False, True) + plan = get_current_plan_by_realm(user.realm) + assert plan is not None + self.assertEqual(plan.next_invoice_date, free_trial_end_date) + self.assertEqual(get_realm("zulip").plan_type, Realm.PLAN_TYPE_STANDARD) + self.assertEqual(plan.status, CustomerPlan.FREE_TRIAL) + self.assertEqual(plan.licenses(), self.seat_count) + self.assertEqual(plan.licenses_at_next_renewal(), self.seat_count) + + # Schedule downgrade + with self.assertLogs("corporate.stripe", "INFO") as m: + with patch("corporate.lib.stripe.timezone_now", return_value=self.now): + response = self.client_patch( + "/json/billing/plan", + {"status": CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL}, + ) + stripe_customer_id = Customer.objects.get(realm=user.realm).id + new_plan = get_current_plan_by_realm(user.realm) + assert new_plan is not None + expected_log = f"INFO:corporate.stripe:Change plan status: Customer.id: {stripe_customer_id}, CustomerPlan.id: {new_plan.id}, status: {CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL}" + self.assertEqual(m.output[0], expected_log) + self.assert_json_success(response) + plan.refresh_from_db() + self.assertEqual(plan.next_invoice_date, free_trial_end_date) + self.assertEqual(get_realm("zulip").plan_type, Realm.PLAN_TYPE_STANDARD) + self.assertEqual(plan.status, CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL) + self.assertEqual(plan.licenses(), self.seat_count) + self.assertEqual(plan.licenses_at_next_renewal(), None) + + with patch("corporate.lib.stripe.timezone_now", return_value=self.now): + mock_customer = Mock(email=user.delivery_email) + mock_customer.invoice_settings.default_payment_method = Mock( + spec=stripe.PaymentMethod, type=Mock() + ) + with patch("corporate.lib.stripe.stripe_get_customer", return_value=mock_customer): + response = self.client_get("/billing/") + self.assert_in_success_response( + [ + "Your organization will be downgraded to <strong>Zulip Cloud Free</strong> at the end of the free trial", + "<strong>March 2, 2012</strong>", + ], + response, + ) + + # Verify that we still write LicenseLedger rows during the remaining + # part of the cycle + with patch("corporate.lib.stripe.get_latest_seat_count", return_value=20): + update_license_ledger_if_needed(user.realm, self.now) + self.assertEqual( + LicenseLedger.objects.order_by("-id") + .values_list("licenses", "licenses_at_next_renewal") + .first(), + (20, 20), + ) + + # Verify that we don't invoice them for the additional users during free trial. + from stripe import Invoice + + Invoice.create = lambda **args: None # type: ignore[assignment] # cleaner than mocking + Invoice.finalize_invoice = lambda *args: None # type: ignore[assignment] # cleaner than mocking + with patch("stripe.InvoiceItem.create") as mocked: + invoice_plans_as_needed(self.next_month) + mocked.assert_not_called() + + # Check that we downgrade properly if the cycle is over + with patch("corporate.lib.stripe.get_latest_seat_count", return_value=30): + update_license_ledger_if_needed(user.realm, free_trial_end_date) + plan = CustomerPlan.objects.first() + assert plan is not None + self.assertIsNone(plan.next_invoice_date) + self.assertEqual(plan.status, CustomerPlan.ENDED) + self.assertEqual(get_realm("zulip").plan_type, Realm.PLAN_TYPE_LIMITED) + self.assertEqual( + LicenseLedger.objects.order_by("-id") + .values_list("licenses", "licenses_at_next_renewal") + .first(), + (20, 20), + ) + + # Verify that we don't write LicenseLedger rows once we've downgraded + with patch("corporate.lib.stripe.get_latest_seat_count", return_value=40): + update_license_ledger_if_needed(user.realm, self.next_year) + self.assertEqual( + LicenseLedger.objects.order_by("-id") + .values_list("licenses", "licenses_at_next_renewal") + .first(), + (20, 20), + ) + + self.login_user(user) + response = self.client_get("/billing/") + self.assertEqual(response.status_code, 302) + self.assertEqual("/plans/", response["Location"]) + + # The extra users added in the final month are not charged + with patch("corporate.lib.stripe.invoice_plan") as mocked: + invoice_plans_as_needed(self.next_month) + mocked.assert_not_called() + + # The plan is not renewed after an year + with patch("corporate.lib.stripe.invoice_plan") as mocked: + invoice_plans_as_needed(self.next_year) + mocked.assert_not_called() + + def test_cancel_downgrade_at_end_of_free_trial(self) -> None: + user = self.example_user("hamlet") + self.login_user(user) + + free_trial_end_date = self.now + timedelta(days=60) + with self.settings(FREE_TRIAL_DAYS=60): + with patch("corporate.lib.stripe.timezone_now", return_value=self.now): + self.local_upgrade(self.seat_count, True, CustomerPlan.ANNUAL, False, True) + plan = get_current_plan_by_realm(user.realm) + assert plan is not None + self.assertEqual(plan.next_invoice_date, free_trial_end_date) + self.assertEqual(get_realm("zulip").plan_type, Realm.PLAN_TYPE_STANDARD) + self.assertEqual(plan.status, CustomerPlan.FREE_TRIAL) + self.assertEqual(plan.licenses(), self.seat_count) + self.assertEqual(plan.licenses_at_next_renewal(), self.seat_count) + + # Schedule downgrade + with self.assertLogs("corporate.stripe", "INFO") as m: + with patch("corporate.lib.stripe.timezone_now", return_value=self.now): + response = self.client_patch( + "/json/billing/plan", + {"status": CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL}, + ) + stripe_customer_id = Customer.objects.get(realm=user.realm).id + new_plan = get_current_plan_by_realm(user.realm) + assert new_plan is not None + expected_log = f"INFO:corporate.stripe:Change plan status: Customer.id: {stripe_customer_id}, CustomerPlan.id: {new_plan.id}, status: {CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL}" + self.assertEqual(m.output[0], expected_log) + self.assert_json_success(response) + plan.refresh_from_db() + self.assertEqual(plan.next_invoice_date, free_trial_end_date) + self.assertEqual(get_realm("zulip").plan_type, Realm.PLAN_TYPE_STANDARD) + self.assertEqual(plan.status, CustomerPlan.DOWNGRADE_AT_END_OF_FREE_TRIAL) + self.assertEqual(plan.licenses(), self.seat_count) + self.assertEqual(plan.licenses_at_next_renewal(), None) + + # Cancel downgrade + with self.assertLogs("corporate.stripe", "INFO") as m: + with patch("corporate.lib.stripe.timezone_now", return_value=self.now): + response = self.client_patch( + "/json/billing/plan", {"status": CustomerPlan.FREE_TRIAL} + ) + stripe_customer_id = Customer.objects.get(realm=user.realm).id + new_plan = get_current_plan_by_realm(user.realm) + assert new_plan is not None + expected_log = f"INFO:corporate.stripe:Change plan status: Customer.id: {stripe_customer_id}, CustomerPlan.id: {new_plan.id}, status: {CustomerPlan.FREE_TRIAL}" + self.assertEqual(m.output[0], expected_log) + self.assert_json_success(response) + plan.refresh_from_db() + self.assertEqual(plan.next_invoice_date, free_trial_end_date) + self.assertEqual(get_realm("zulip").plan_type, Realm.PLAN_TYPE_STANDARD) + self.assertEqual(plan.status, CustomerPlan.FREE_TRIAL) + self.assertEqual(plan.licenses(), self.seat_count) + self.assertEqual(plan.licenses_at_next_renewal(), self.seat_count) + def test_reupgrade_by_billing_admin_after_downgrade(self) -> None: user = self.example_user("hamlet") diff --git a/zerver/tests/test_signup.py b/zerver/tests/test_signup.py --- a/zerver/tests/test_signup.py +++ b/zerver/tests/test_signup.py @@ -1792,7 +1792,7 @@ def test_create_realm_during_free_trial(self) -> None: self.assertEqual(result["Location"], "http://custom-test.testserver/upgrade/") result = self.client_get(result["Location"], subdomain=string_id) - self.assert_in_success_response(["You won't be charged during the free trial."], result) + self.assert_in_success_response(["You card will not be charged", "free trial"], result) realm = get_realm(string_id) self.assertEqual(realm.string_id, string_id)
Add billing frequency dropdown on free trial page billing page. This will immediately change the biling frequency rather than waiting for the next billing cycle.
2023-11-27T19:45:06
zulip/zulip
27,940
zulip__zulip-27940
[ "25899" ]
150c64ddd0cea245e70f3117cc69460f66a06321
diff --git a/zerver/views/registration.py b/zerver/views/registration.py --- a/zerver/views/registration.py +++ b/zerver/views/registration.py @@ -767,8 +767,17 @@ def send_confirm_registration_email( activation_url: str, *, realm: Optional[Realm] = None, + realm_subdomain: Optional[str] = None, + realm_type: Optional[int] = None, request: Optional[HttpRequest] = None, ) -> None: + org_url = "" + org_type = "" + if realm is None: + assert realm_subdomain is not None + org_url = f"{realm_subdomain}.{settings.EXTERNAL_HOST}" + assert realm_type is not None + org_type = get_org_type_display_name(realm_type) send_email( "zerver/emails/confirm_registration", to_emails=[email], @@ -778,6 +787,8 @@ def send_confirm_registration_email( "create_realm": realm is None, "activate_url": activation_url, "corporate_enabled": settings.CORPORATE_ENABLED, + "organization_url": org_url, + "organization_type": org_type, }, realm=realm, request=request, @@ -845,7 +856,13 @@ def create_realm(request: HttpRequest, creation_key: Optional[str] = None) -> Ht return HttpResponseRedirect(activation_url) try: - send_confirm_registration_email(email, activation_url, request=request) + send_confirm_registration_email( + email, + activation_url, + realm_subdomain=realm_subdomain, + realm_type=realm_type, + request=request, + ) except EmailNotDeliveredError: logging.exception("Failed to deliver email during realm creation") if settings.CORPORATE_ENABLED:
diff --git a/zerver/tests/test_signup.py b/zerver/tests/test_signup.py --- a/zerver/tests/test_signup.py +++ b/zerver/tests/test_signup.py @@ -1406,7 +1406,9 @@ def test_create_realm_with_subdomain(self) -> None: self.assert_in_response("check your email", result) # Visit the confirmation link. - confirmation_url = self.get_confirmation_url_from_outbox(email) + confirmation_url = self.get_confirmation_url_from_outbox( + email, email_body_contains="Organization URL" + ) result = self.client_get(confirmation_url) self.assertEqual(result.status_code, 200) @@ -1779,7 +1781,9 @@ def test_create_realm_during_free_trial(self) -> None: result = self.client_get(result["Location"]) self.assert_in_response("check your email", result) - confirmation_url = self.get_confirmation_url_from_outbox(email) + confirmation_url = self.get_confirmation_url_from_outbox( + email, email_body_contains="Organization URL" + ) result = self.client_get(confirmation_url) self.assertEqual(result.status_code, 200) @@ -1832,7 +1836,9 @@ def test_create_two_realms(self) -> None: ) result = self.client_get(result["Location"]) self.assert_in_response("check your email", result) - first_confirmation_url = self.get_confirmation_url_from_outbox(email) + first_confirmation_url = self.get_confirmation_url_from_outbox( + email, email_body_contains="Organization URL" + ) self.assertEqual(PreregistrationRealm.objects.filter(email=email, status=0).count(), 1) result = self.submit_realm_creation_form( @@ -1846,7 +1852,9 @@ def test_create_two_realms(self) -> None: ) result = self.client_get(result["Location"]) self.assert_in_response("check your email", result) - second_confirmation_url = self.get_confirmation_url_from_outbox(email) + second_confirmation_url = self.get_confirmation_url_from_outbox( + email, email_body_contains="Organization URL" + ) self.assertNotEqual(first_confirmation_url, second_confirmation_url) self.assertEqual(PreregistrationRealm.objects.filter(email=email, status=0).count(), 2) @@ -2119,7 +2127,9 @@ def verify_signup( self.assert_in_response("check your email", result) # Visit the confirmation link. - confirmation_url = self.get_confirmation_url_from_outbox(email) + confirmation_url = self.get_confirmation_url_from_outbox( + email, email_body_contains="You recently signed up for Zulip. Awesome!" + ) result = self.client_get(confirmation_url, **client_kwargs) self.assertEqual(result.status_code, 200)
Add organization details to new organization sign-up confirmation email Following up on https://github.com/zulip/zulip/issues/24307 / https://github.com/zulip/zulip/pull/24689, we should add organization information to the `confirm_registration` email. Current text: {{ _('You have requested a new Zulip organization. Awesome!') }} {{ _('Click the button below to create the organization and register your account.') }} Updated text (with appropriate translation tags): --- You have requested a new Zulip organization: - Organization URL: - Organization type: Click the button below to create the organization and register your account. You'll be able to update the information above if you like. ---- - No changes to the button or "contact us" line. - Leaving out the organization name to minimize the risk that these emails would be used to send spam.
Hello @zulip/server-development, @zulip/server-onboarding members, this issue was labeled with the "area: onboarding", "area: emails" labels, so you may want to check it out! <!-- areaLabelAddition --> @laurynmm Could you please add this one to your todo list? Hello @pydeveloperashish! Thanks for your interest in Zulip! You have attempted to claim an issue without the label "help wanted". You can only claim and submit pull requests for issues with the [help wanted](https://github.com/zulip/zulip/issues?q=is%3Aopen+is%3Aissue+no%3Aassignee+label%3A%22help+wanted%22) label. If this is your first time here, we recommend reading our [guide for new contributors](https://zulip.readthedocs.io/en/latest/overview/contributing.html) before getting started. Question about the issue description above. When you say organization URL, what we want to send is what was input in the new organization form, correct? E.g. the subdomain with the host information appended like `lauryn.zulipchat.com` for a Zulip Cloud organization. And it wouldn't be a link at this point since the organization doesn't yet exist, correct? Yes, that sounds right -- good thought!
2023-11-28T16:22:45
zulip/zulip
27,957
zulip__zulip-27957
[ "27946" ]
fd57a9033b3488d96845b0e84fe481778a401788
diff --git a/zerver/lib/markdown/help_relative_links.py b/zerver/lib/markdown/help_relative_links.py --- a/zerver/lib/markdown/help_relative_links.py +++ b/zerver/lib/markdown/help_relative_links.py @@ -28,13 +28,13 @@ "integrations": ['<i class="fa fa-github"></i> Integrations', "/integrations/"], "stats": ['<i class="fa fa-bar-chart"></i> Usage statistics', "/stats"], "plans": ['<i class="fa fa-rocket"></i> Plans and pricing', "/plans/"], - "billing": ['<i class="fa fa-credit-card"></i> Billing', "/billing/"], + "billing": ['<i class="zulip-icon zulip-icon-credit-card"></i> Billing', "/billing/"], "about-zulip": ["About Zulip", "/#about-zulip"], } gear_instructions = """ -1. Click on the **gear** (<i class="fa fa-cog"></i>) icon in the upper - right corner of the web or desktop app. +1. Click on the **gear** (<i class="zulip-icon zulip-icon-gear"></i>) icon in + the upper right corner of the web or desktop app. 1. Select {item}. """ diff --git a/zerver/lib/markdown/tabbed_sections.py b/zerver/lib/markdown/tabbed_sections.py --- a/zerver/lib/markdown/tabbed_sections.py +++ b/zerver/lib/markdown/tabbed_sections.py @@ -86,6 +86,10 @@ "via-stream-settings": "Via stream settings", "default-subdomain": "Default subdomain", "custom-subdomain": "Custom subdomain", + "zulip-cloud-standard": "Zulip Cloud Standard", + "zulip-cloud-plus": "Zulip Cloud Plus", + "request-sponsorship": "Request sponsorship", + "request-education-pricing": "Request education pricing", "zulip-cloud": "Zulip Cloud", "self-hosting": "Self hosting", "okta": "Okta",
Document billing management, upgrade flow, and sponsorship requests We have recently redesigned the billing management, upgrade flow, and sponsorship requests pages. We should document: - How to upgrade to a paid plan. (starting point: Plans and pricing option in gear menu) - How to manage billing (starting point: Billing option in the gear menu) - How to apply for sponsorship (starting point: Option at the top of the gear menu. The sponsorship form can be accessed form /plans if it's not in the menu, but that should be considered a secondary way to do it.) This documentation can be added to https://zulip.com/help/zulip-cloud-billing. Note that the options are conditional on the org's status (whether or not it's on a paid plan), and type (for whether to show the sponsorship request link in the menu; there is also special wording for education orgs). You can use `./manage.py populate_billing_realms` in the `dev` environment to create orgs with a bunch of different billing states for testing.
@drrosa It would be great if you could pick this one up as your top priority. Hello @zulip/server-user-docs members, this issue was labeled with the "area: documentation (user)" label, so you may want to check it out! <!-- areaLabelAddition -->
2023-11-29T07:42:15
zulip/zulip
27,960
zulip__zulip-27960
[ "27886" ]
32c730e5308095ce86eb60dd034fe35ac869504f
diff --git a/tools/lib/capitalization.py b/tools/lib/capitalization.py --- a/tools/lib/capitalization.py +++ b/tools/lib/capitalization.py @@ -26,6 +26,7 @@ r"IP", r"JSON", r"Kerberos", + r"LinkedIn", r"LDAP", r"Markdown", r"OTP",
Social links in website footer Discussed here https://chat.zulip.org/#narrow/stream/107-kandra/topic/website.20footer <img width="182" alt="image" src="https://github.com/zulip/zulip/assets/1903309/37ad6196-e5a3-499f-b65c-e035e4901596"> Working demo is on https://terpimost.github.io/zulip-plans/ ```html <div class="footer-social-links"> <a class="social-icon social-icon-mastodon" title="Mastodon" href="https://fosstodon.org/@zulip"></a> <a class="social-icon social-icon-x" title="X (Twitter)" href="https://twitter.com/zulip"></a> <a class="social-icon social-icon-linkedin" title="LinkedIn" href="https://www.linkedin.com/company/zulip-by-kandra-labs/"></a> </div> ``` ```css .footer-social-links{ margin-top: 12px; display: flex; gap: 8px; } .social-icon{ width: 28px; height: 28px; display: inline-block; flex-shrink: 0; background-color: #A3A5F8; mask-position: center; -webkit-mask-position: center; mask-repeat: no-repeat; -webkit-mask-repeat: no-repeat; mask-image: var(--icon); -webkit-mask-image: var(--icon); transition: all 150ms ease-out; } .social-icon:hover{ background-color: #D0D1FB; } .social-icon:active{ background-color: #F1F1FE; } .social-icon-mastodon{ --icon: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='28' height='28' fill='none' viewBox='0 0 28 28'%3e%3cg fill='%23A3A5F8'%3e%3cpath d='M18.42 16.43h2.38v-6.02c0-1.23-.3-2.2-.94-2.93a3.27 3.27 0 0 0-2.55-1.1c-1.22 0-2.15.47-2.76 1.41l-.6 1-.58-1a3.07 3.07 0 0 0-2.76-1.4c-1.05 0-1.9.37-2.55 1.1a4.3 4.3 0 0 0-.94 2.92v6.02H9.5v-5.84c0-1.23.52-1.86 1.55-1.86 1.15 0 1.72.74 1.72 2.2v3.2h2.38v-3.2c0-1.46.57-2.2 1.71-2.2 1.04 0 1.56.63 1.56 1.86v5.84Z'/%3e%3cpath fill-rule='evenodd' d='M3 0a3 3 0 0 0-3 3v22a3 3 0 0 0 3 3h22a3 3 0 0 0 3-3V3a3 3 0 0 0-3-3H3Zm18.39 3.6s3.26 1.45 3.26 6.43c0 0 .04 3.66-.46 6.2-.31 1.63-2.81 3.4-5.69 3.74-1.5.18-2.97.34-4.54.27-2.57-.12-4.6-.62-4.6-.62 0 .24.02.48.05.72.33 2.53 2.51 2.68 4.58 2.76 2.09.07 3.94-.52 3.94-.52l.09 1.89s-1.46.78-4.06.92c-1.43.08-3.21-.03-5.28-.58-4.5-1.19-5.27-5.98-5.39-10.84a100.6 100.6 0 0 1-.02-3v-.94c0-4.97 3.27-6.43 3.27-6.43 1.64-.76 4.46-1.07 7.39-1.1H14c2.93.03 5.75.34 7.39 1.1Z' clip-rule='evenodd'/%3e%3c/g%3e%3c/svg%3e"); } .social-icon-x{ --icon: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='28' height='28' fill='none' viewBox='0 0 28 28'%3e%3cg fill='%23A3A5F8' clip-path='url(%23a)'%3e%3cpath d='M18.87 23.69h2.71L9.11 5.36H6.4L18.87 23.7Z'/%3e%3cpath fill-rule='evenodd' d='M3.04.04a3 3 0 0 0-3 3v22a3 3 0 0 0 3 3h22a3 3 0 0 0 3-3v-22a3 3 0 0 0-3-3h-22ZM23.34 4l-7.44 8.89 8.1 12.1h-5.96l-5.45-8.15-6.83 8.15H4l7.8-9.32L4 4h5.96l5.16 7.72L21.58 4h1.77Z' clip-rule='evenodd'/%3e%3c/g%3e%3cdefs%3e%3cclipPath id='a'%3e%3crect width='28' height='28' fill='white' rx='3'/%3e%3c/clipPath%3e%3c/defs%3e%3c/svg%3e"); } .social-icon-linkedin{ --icon: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='28' height='28' fill='none' viewBox='0 0 28 28'%3e%3cg clip-path='url(%23a)'%3e%3cpath fill='%23A3A5F8' d='M28 3a3 3 0 0 0-3-3H3a3 3 0 0 0-3 3v22a3 3 0 0 0 3 3h22a3 3 0 0 0 3-3V3ZM8.27 23.9H4.19V10.5h4.18v13.4h-.1ZM6.17 8.7A2.42 2.42 0 0 1 3.8 6.3c0-1.3 1.1-2.4 2.39-2.4 1.3 0 2.39 1.1 2.39 2.4 0 1.3-1 2.4-2.4 2.4Zm17.65 15.2h-4.09v-6.5c0-1.5 0-3.5-2.2-3.5-2.18 0-2.48 1.7-2.48 3.4v6.6h-4.09V10.5h3.99v1.8h.1c.6-1 1.89-2.2 3.88-2.2 4.19 0 4.98 2.8 4.98 6.4v7.4h-.1Z'/%3e%3c/g%3e%3cdefs%3e%3cclipPath id='a'%3e%3cpath fill='white' d='M0 0h28v28H0z'/%3e%3c/clipPath%3e%3c/defs%3e%3c/svg%3e"); } ```
Hello @zulip/server-misc members, this issue was labeled with the "area: portico" label, so you may want to check it out! <!-- areaLabelAddition --> @terpimost i would like to contribute , Please let me know the details about the issue @zulipbot claim Hello @HimanshuUpreti02! Thanks for your interest in Zulip! You have attempted to claim an issue without the label "help wanted". You can only claim and submit pull requests for issues with the [help wanted](https://github.com/zulip/zulip/issues?q=is%3Aopen+is%3Aissue+no%3Aassignee+label%3A%22help+wanted%22) label. If this is your first time here, we recommend reading our [guide for new contributors](https://zulip.readthedocs.io/en/latest/overview/contributing.html) before getting started. @zulipbot claim Hello @parthksingh1! Thanks for your interest in Zulip! You have attempted to claim an issue without the label "help wanted". You can only claim and submit pull requests for issues with the [help wanted](https://github.com/zulip/zulip/issues?q=is%3Aopen+is%3Aissue+no%3Aassignee+label%3A%22help+wanted%22) label. If this is your first time here, we recommend reading our [guide for new contributors](https://zulip.readthedocs.io/en/latest/overview/contributing.html) before getting started. This is a project for a core team member; assigned to @amanagr.
2023-11-29T13:21:11
zulip/zulip
28,016
zulip__zulip-28016
[ "27878" ]
d631c76747a22aca81cc8056d903de8b5da2ed6b
diff --git a/zerver/lib/hotspots.py b/zerver/lib/hotspots.py --- a/zerver/lib/hotspots.py +++ b/zerver/lib/hotspots.py @@ -46,6 +46,9 @@ def to_dict(self, delay: float = 0) -> Dict[str, Union[str, float, bool]]: ), ), Hotspot( + # In theory, this should be renamed to intro_personal, since + # it's no longer attached to the gear menu, but renaming these + # requires a migration that is not worth doing at this time. name="intro_gear", title=gettext_lazy("Settings"), description=gettext_lazy("Go to Settings to configure your notifications and preferences."),
Onboarding hotspots are misplaced I think our grid rewrites of the sidebars have resulted in the onboarding hotspots being somewhat misplaced: ![image](https://github.com/zulip/zulip/assets/2746074/2392e57c-63c1-4cc9-a032-1d9e3bcd10d5) (The `offset_x` and `offset_y` values may need updating). I'm not entirely sure where the best place for these are. The main one that seems very wrong is the compose box one. That said, we should aim to spend pretty minimal time on this system because we plan to rip it out in favor of a totally different onboarding system. See https://zulip.readthedocs.io/en/latest/subsystems/hotspots.html for notes on how to test using the `ALWAYS_SEND_ALL_HOTSPOTS` setting as shown in this screenshot. (Usually, they're shown only one at a time in sequence). @sayamsamal can you pick this one up?
Hello @zulip/server-onboarding members, this issue was labeled with the "area: onboarding" label, so you may want to check it out! <!-- areaLabelAddition --> Surely, thanks! @zulipbot claim Hello @aarishshahmohsin! Thanks for your interest in Zulip! You have attempted to claim an issue without the label "help wanted". You can only claim and submit pull requests for issues with the [help wanted](https://github.com/zulip/zulip/issues?q=is%3Aopen+is%3Aissue+no%3Aassignee+label%3A%22help+wanted%22) label. If this is your first time here, we recommend reading our [guide for new contributors](https://zulip.readthedocs.io/en/latest/overview/contributing.html) before getting started.
2023-12-02T01:58:54
zulip/zulip
28,068
zulip__zulip-28068
[ "28012" ]
bbfcb2dcb3bbc05ee04707f892520be1b05c7451
diff --git a/zerver/lib/markdown/help_relative_links.py b/zerver/lib/markdown/help_relative_links.py --- a/zerver/lib/markdown/help_relative_links.py +++ b/zerver/lib/markdown/help_relative_links.py @@ -25,6 +25,10 @@ '<i class="fa fa-bolt"></i> Organization settings', "/#organization/organization-profile", ], + "group-settings": [ + '<i class="zulip-icon zulip-icon-user-cog"></i> Group settings', + "/#groups/your", + ], "integrations": ['<i class="fa fa-github"></i> Integrations', "/integrations/"], "stats": ['<i class="fa fa-bar-chart"></i> Usage statistics', "/stats"], "plans": ['<i class="fa fa-rocket"></i> Plans and pricing', "/plans/"], @@ -104,6 +108,27 @@ def stream_handle_match(key: str) -> str: return stream_instructions_no_link +group_info = { + "all": ["All groups", "/#groups/all"], + "subscribed": ["Your groups", "/#groups/your"], +} + +group_instructions_no_link = """ +1. Click on the **gear** (<i class="fa fa-cog"></i>) icon in the upper + right corner of the web or desktop app. + +1. Click **Group settings**. +""" + + +def group_handle_match(key: str) -> str: + if relative_help_links: + return f"1. Go to [{group_info[key][0]}]({group_info[key][1]})." + if key == "all": + return group_instructions_no_link + "\n\n1. Click **All groups** in the upper left." + return group_instructions_no_link + + draft_instructions = """ 1. Click on <i class="fa fa-pencil"></i> **Drafts** in the left sidebar. """ @@ -163,6 +188,7 @@ def message_handle_match(key: str) -> str: "stream": stream_handle_match, "message": message_handle_match, "help": help_handle_match, + "group": group_handle_match, } diff --git a/zerver/lib/markdown/help_settings_links.py b/zerver/lib/markdown/help_settings_links.py --- a/zerver/lib/markdown/help_settings_links.py +++ b/zerver/lib/markdown/help_settings_links.py @@ -58,11 +58,6 @@ "Authentication methods", "/#organization/auth-methods", ], - "user-groups-admin": [ - "Organization settings", - "User groups", - "/#organization/user-groups-admin", - ], "user-list-admin": ["Organization settings", "Users", "/#organization/user-list-admin"], "deactivated-users-admin": [ "Organization settings",
diff --git a/web/tests/dispatch.test.js b/web/tests/dispatch.test.js --- a/web/tests/dispatch.test.js +++ b/web/tests/dispatch.test.js @@ -63,7 +63,6 @@ const settings_realm_user_settings_defaults = mock_esm( ); const settings_realm_domains = mock_esm("../src/settings_realm_domains"); const settings_streams = mock_esm("../src/settings_streams"); -const settings_user_groups_legacy = mock_esm("../src/settings_user_groups_legacy"); const settings_users = mock_esm("../src/settings_users"); const sidebar_ui = mock_esm("../src/sidebar_ui"); const stream_data = mock_esm("../src/stream_data"); @@ -171,7 +170,6 @@ run_test("attachments", ({override}) => { run_test("user groups", ({override}) => { let event = event_fixtures.user_group__add; - override(settings_user_groups_legacy, "reload", noop); { const stub = make_stub(); const user_group_settings_ui_stub = make_stub(); @@ -1165,7 +1163,7 @@ run_test("realm_export", ({override}) => { assert.equal(args.exports, event.exports); }); -run_test("server_event_dispatch_op_errors", ({override}) => { +run_test("server_event_dispatch_op_errors", () => { blueslip.expect("error", "Unexpected event type subscription/other"); server_events_dispatch.dispatch_normal_event({type: "subscription", op: "other"}); blueslip.expect("error", "Unexpected event type reaction/other"); @@ -1190,7 +1188,6 @@ run_test("server_event_dispatch_op_errors", ({override}) => { sender: {user_id: 5}, op: "other", }); - override(settings_user_groups_legacy, "reload", noop); blueslip.expect("error", "Unexpected event type user_group/other"); server_events_dispatch.dispatch_normal_event({type: "user_group", op: "other"}); }); diff --git a/web/tests/pill_typeahead.test.js b/web/tests/pill_typeahead.test.js --- a/web/tests/pill_typeahead.test.js +++ b/web/tests/pill_typeahead.test.js @@ -124,6 +124,11 @@ run_test("set_up", ({mock_template}) => { get_text_from_item: noop, }); + let update_func_called = false; + function update_func() { + update_func_called = true; + } + let opts = {}; $fake_input.typeahead = (config) => { assert.equal(config.items, 5); @@ -297,6 +302,8 @@ run_test("set_up", ({mock_template}) => { assert.equal(number_of_pills(), 2); config.updater.call(fake_group_this, testers); assert.equal(number_of_pills(), 3); + + assert.ok(update_func_called); } })(); @@ -324,7 +331,7 @@ run_test("set_up", ({mock_template}) => { {user_group: true, stream: true}, {user_group: true, user: true}, {user: true, stream: true}, - {user_group: true, stream: true, user: true}, + {user_group: true, stream: true, user: true, update_func}, ]; for (const config of all_possible_opts) { diff --git a/web/tests/settings_user_groups_legacy.test.js b/web/tests/settings_user_groups_legacy.test.js deleted file mode 100644 --- a/web/tests/settings_user_groups_legacy.test.js +++ /dev/null @@ -1,854 +0,0 @@ -"use strict"; - -const {strict: assert} = require("assert"); - -const {$t} = require("./lib/i18n"); -const {mock_esm, set_global, zrequire} = require("./lib/namespace"); -const {run_test} = require("./lib/test"); -const blueslip = require("./lib/zblueslip"); -const $ = require("./lib/zjquery"); -const {page_params} = require("./lib/zpage_params"); - -const noop = () => {}; - -const pills = { - pill: {}, -}; - -let create_item_handler; - -const channel = mock_esm("../src/channel"); -const confirm_dialog = mock_esm("../src/confirm_dialog"); -const dialog_widget = mock_esm("../src/dialog_widget"); -const input_pill = mock_esm("../src/input_pill"); -const settings_data = mock_esm("../src/settings_data"); -const typeahead_helper = mock_esm("../src/typeahead_helper"); -const user_groups = mock_esm("../src/user_groups", { - get_user_group_from_id: noop, - remove: noop, - add: noop, -}); -const ui_report = mock_esm("../src/ui_report"); - -const people = zrequire("people"); -const settings_user_groups_legacy = zrequire("settings_user_groups_legacy"); -const user_pill = zrequire("user_pill"); - -function reset_test_setup($pill_container_stub) { - function input_pill_stub(opts) { - assert.equal(opts.$container, $pill_container_stub); - create_item_handler = opts.create_item_from_text; - assert.ok(create_item_handler); - return pills; - } - input_pill.create = input_pill_stub; -} - -function test_ui(label, f) { - // The sloppy_$ flag lets us reuse setup from prior tests. - run_test(label, f, {sloppy_$: true}); -} - -test_ui("can_edit", ({override}) => { - override(settings_data, "user_can_edit_user_groups", () => false); - assert.ok(!settings_user_groups_legacy.can_edit(1)); - - override(settings_data, "user_can_edit_user_groups", () => true); - user_groups.is_direct_member_of = (user_id, group_id) => { - assert.equal(group_id, 1); - assert.equal(user_id, undefined); - return false; - }; - assert.ok(!settings_user_groups_legacy.can_edit(1)); - - page_params.is_admin = true; - assert.ok(settings_user_groups_legacy.can_edit(1)); - - page_params.is_admin = false; - page_params.is_moderator = true; - assert.ok(settings_user_groups_legacy.can_edit(1)); - - page_params.is_admin = false; - page_params.is_moderator = false; - user_groups.is_direct_member_of = (user_id, group_id) => { - assert.equal(group_id, 1); - assert.equal(user_id, undefined); - return true; - }; - assert.ok(settings_user_groups_legacy.can_edit(1)); -}); - -const user_group_selector = `#user-groups #${CSS.escape(1)}`; -const cancel_selector = `#user-groups #${CSS.escape(1)} .save-status.btn-danger`; -const saved_selector = `#user-groups #${CSS.escape(1)} .save-status.sea-green`; -const name_selector = `#user-groups #${CSS.escape(1)} .name`; -const description_selector = `#user-groups #${CSS.escape(1)} .description`; -const instructions_selector = `#user-groups #${CSS.escape(1)} .save-instructions`; - -test_ui("populate_user_groups", ({mock_template, override, override_rewire}) => { - override(settings_data, "user_can_edit_user_groups", () => true); - - const realm_user_group = { - id: 1, - name: "Mobile", - description: "All mobile people", - members: new Set([2, 4]), - }; - const iago = { - email: "[email protected]", - user_id: 2, - full_name: "Iago", - }; - const alice = { - email: "[email protected]", - user_id: 31, - full_name: "Alice", - }; - const bob = { - email: "[email protected]", - user_id: 32, - full_name: "Bob", - }; - - people.add_active_user(iago); - people.add_active_user(alice); - people.add_active_user(bob); - - override_rewire(people, "get_realm_users", () => [iago, alice, bob]); - - user_groups.get_realm_user_groups = () => [realm_user_group]; - - let templates_render_called = false; - const $fake_rendered_temp = $.create("fake_admin_user_group_list_template_rendered"); - mock_template("settings/admin_user_group_list.hbs", false, (args) => { - assert.equal(args.user_group.id, 1); - assert.equal(args.user_group.name, "Mobile"); - assert.equal(args.user_group.description, "All mobile people"); - templates_render_called = true; - return $fake_rendered_temp; - }); - - let user_groups_list_append_called = false; - $("#user-groups").append = (rendered_temp) => { - assert.equal(rendered_temp, $fake_rendered_temp); - user_groups_list_append_called = true; - }; - - let get_by_user_id_called = false; - override_rewire(people, "get_by_user_id", (user_id) => { - if (user_id === iago.user_id) { - return iago; - } - assert.equal(user_id, 4); - blueslip.expect("warn", "Undefined user in function append_user"); - get_by_user_id_called = true; - return undefined; - }); - override_rewire( - people, - "is_known_user", - () => people.get_by_user_id !== undefined && people.get_by_user_id !== noop, - ); - - page_params.is_admin = true; - - const all_pills = new Map(); - - const $pill_container_stub = $(`.pill-container[data-group-pills="${CSS.escape(1)}"]`); - pills.appendValidatedData = (item) => { - const id = item.user_id; - assert.ok(!all_pills.has(id)); - all_pills.set(id, item); - }; - pills.items = () => [...all_pills.values()]; - - let text_cleared; - pills.clear_text = () => { - text_cleared = true; - }; - - const $input_field_stub = $.create("fake-input-field"); - $pill_container_stub.children = () => $input_field_stub; - - let input_typeahead_called = false; - $input_field_stub.typeahead = (config) => { - assert.equal(config.items, 5); - assert.ok(config.fixed); - assert.ok(config.dropup); - assert.ok(config.stopAdvance); - assert.equal(typeof config.source, "function"); - assert.equal(typeof config.highlighter, "function"); - assert.equal(typeof config.matcher, "function"); - assert.equal(typeof config.sorter, "function"); - assert.equal(typeof config.updater, "function"); - - (function test_highlighter() { - const $fake_person = $.create("fake-person"); - typeahead_helper.render_person = () => $fake_person; - assert.equal(config.highlighter(), $fake_person); - })(); - - const fake_context = { - query: "ali", - }; - - const fake_context_for_email = { - query: "am", - }; - - (function test_source() { - const result = config.source.call(fake_context, iago); - const emails = result.map((user) => user.email).sort(); - assert.deepEqual(emails, [alice.email, bob.email]); - })(); - - (function test_matcher() { - /* Here the query doesn't begin with an '@' because typeahead is triggered - by the '@' sign and thus removed in the query. */ - let result = config.matcher.call(fake_context, iago); - assert.ok(!result); - - result = config.matcher.call(fake_context, alice); - assert.ok(result); - - bob.delivery_email = null; - result = config.matcher.call(fake_context_for_email, bob); - assert.ok(!result); - - bob.delivery_email = "[email protected]"; - result = config.matcher.call(fake_context_for_email, bob); - assert.ok(result); - })(); - - (function test_sorter() { - let sort_recipients_typeahead_called = false; - typeahead_helper.sort_recipients = function () { - sort_recipients_typeahead_called = true; - }; - config.sorter.call(fake_context, []); - assert.ok(sort_recipients_typeahead_called); - })(); - - (function test_updater() { - $input_field_stub.text("@ali"); - user_groups.get_user_group_from_id = () => realm_user_group; - - let saved_fade_out_called = false; - let cancel_fade_to_called = false; - let instructions_fade_to_called = false; - $(saved_selector).fadeOut = () => { - saved_fade_out_called = true; - }; - $(cancel_selector).css = (data) => { - assert.equal(typeof data, "object"); - assert.equal(data.display, "inline-block"); - assert.equal(data.opacity, "0"); - return $(cancel_selector); - }; - $(cancel_selector).fadeTo = () => { - cancel_fade_to_called = true; - }; - $(instructions_selector).css = (data) => { - assert.equal(typeof data, "object"); - assert.equal(data.display, "block"); - assert.equal(data.opacity, "0"); - return $(instructions_selector); - }; - $(instructions_selector).fadeTo = () => { - instructions_fade_to_called = true; - }; - - text_cleared = false; - config.updater(alice); - // update_cancel_button is called. - assert.ok(saved_fade_out_called); - assert.ok(cancel_fade_to_called); - assert.ok(instructions_fade_to_called); - assert.equal(text_cleared, true); - })(); - input_typeahead_called = true; - }; - - let get_by_email_called = false; - override_rewire(people, "get_by_email", (user_email) => { - get_by_email_called = true; - switch (user_email) { - case iago.email: - return iago; - case bob.email: - return bob; - /* istanbul ignore next */ - default: - throw new Error("Expected user email to be of Iago or Bob here."); - } - }); - - function test_create_item(handler) { - (function test_rejection_path() { - const item = handler(iago.email, pills.items()); - assert.ok(get_by_email_called); - assert.equal(item, undefined); - })(); - - (function test_success_path() { - get_by_email_called = false; - const res = handler(bob.email, pills.items()); - assert.ok(get_by_email_called); - assert.equal(typeof res, "object"); - assert.equal(res.user_id, bob.user_id); - assert.equal(res.display_value, bob.full_name); - })(); - - (function test_deactivated_pill() { - people.deactivate(bob); - get_by_email_called = false; - const res = handler(bob.email, pills.items()); - assert.ok(get_by_email_called); - assert.equal(typeof res, "object"); - assert.equal(res.user_id, bob.user_id); - assert.equal(res.display_value, bob.full_name); - assert.ok(res.deactivated); - people.add_active_user(bob); - })(); - } - - pills.onPillRemove = (handler) => { - set_global("setTimeout", (func) => { - func(); - }); - realm_user_group.members = new Set([2, 31]); - handler(); - }; - - reset_test_setup($pill_container_stub); - settings_user_groups_legacy.set_up(); - assert.ok(templates_render_called); - assert.ok(user_groups_list_append_called); - assert.ok(get_by_user_id_called); - assert.ok(input_typeahead_called); - test_create_item(create_item_handler); - - // Tests for settings_user_groups_legacy.set_up workflow. - assert.equal(typeof $("#user-groups").get_on_handler("click", ".delete"), "function"); - assert.equal( - typeof $("#user-groups").get_on_handler("keypress", ".user-group h4 > span"), - "function", - ); -}); -test_ui("with_external_user", ({disallow_rewire, override_rewire, mock_template}) => { - const realm_user_group = { - id: 1, - name: "Mobile", - description: "All mobile people", - members: new Set([2, 4]), - }; - - user_groups.get_realm_user_groups = () => [realm_user_group]; - - // These are already tested, so we skip them - disallow_rewire(people, "get_realm_users"); - - mock_template( - "settings/admin_user_group_list.hbs", - false, - () => "settings/admin_user_group_list.hbs", - ); - - override_rewire(people, "get_by_user_id", () => "user stub"); - - override_rewire(user_pill, "append_person", noop); - - let can_edit_called = 0; - override_rewire(settings_user_groups_legacy, "can_edit", () => { - can_edit_called += 1; - return false; - }); - - // Reset zjquery to test stuff with user who cannot edit - $.clear_all_elements(); - - let user_group_find_called = 0; - const $user_group_stub = $(`div.user-group[id="${CSS.escape(1)}"]`); - const $name_field_stub = $.create("fake-name-field"); - const $description_field_stub = $.create("fake-description-field"); - const $input_stub = $.create("fake-input"); - $user_group_stub.find = (elem) => { - user_group_find_called += 1; - switch (elem) { - case ".name": - return $name_field_stub; - case ".description": - return $description_field_stub; - /* istanbul ignore next */ - default: - throw new Error(`Unknown element ${elem}`); - } - }; - - const $pill_container_stub = $(`.pill-container[data-group-pills="${CSS.escape(1)}"]`); - const $pill_stub = $.create("fake-pill"); - let pill_container_find_called = 0; - $pill_container_stub.find = (elem) => { - pill_container_find_called += 1; - switch (elem) { - case ".input": - return $input_stub; - case ".pill": - return $pill_stub; - /* istanbul ignore next */ - default: - throw new Error(`Unknown element ${elem}`); - } - }; - - $input_stub.css = (property, val) => { - assert.equal(property, "display"); - assert.equal(val, "none"); - }; - - // Test the 'off' handlers on the pill-container - const turned_off = {}; - $pill_container_stub.off = (event_name, sel = "whole") => { - turned_off[event_name + "/" + sel] = true; - }; - - const $exit_button = $.create("fake-pill-exit"); - $pill_stub.set_find_results(".exit", $exit_button); - let exit_button_called = false; - $exit_button.css = (property, value) => { - exit_button_called = true; - assert.equal(property, "opacity"); - assert.equal(value, "0.5"); - }; - - // We return [] because these are already tested, so we skip them - $pill_container_stub.children = () => []; - - $("#user-groups").append = noop; - - reset_test_setup($pill_container_stub); - - settings_user_groups_legacy.set_up(); - - let set_parents_result_called = 0; - let set_attributes_called = 0; - - // Test different handlers with an external user - const delete_handler = $("#user-groups").get_on_handler("click", ".delete"); - const $fake_delete = $.create("fk-#user-groups.delete_btn"); - $fake_delete.set_parents_result(".user-group", $(".user-group")); - set_parents_result_called += 1; - $(".user-group").attr("id", "1"); - set_attributes_called += 1; - - const name_update_handler = $(user_group_selector).get_on_handler("input", ".name"); - - const des_update_handler = $(user_group_selector).get_on_handler("input", ".description"); - - const member_change_handler = $(user_group_selector).get_on_handler("blur", ".input"); - - const name_change_handler = $(user_group_selector).get_on_handler("blur", ".name"); - - const des_change_handler = $(user_group_selector).get_on_handler("blur", ".description"); - - const event = { - stopPropagation: noop, - }; - const pill_mouseenter_handler = $pill_stub.get_on_handler("mouseenter"); - const pill_click_handler = $pill_container_stub.get_on_handler("click"); - pill_mouseenter_handler(event); - pill_click_handler(event); - assert.equal(delete_handler.call($fake_delete), undefined); - assert.equal(name_update_handler(), undefined); - assert.equal(des_update_handler(), undefined); - assert.equal(member_change_handler(), undefined); - assert.equal(name_change_handler(), undefined); - assert.equal(des_change_handler(), undefined); - assert.equal(set_parents_result_called, 1); - assert.equal(set_attributes_called, 1); - assert.equal(can_edit_called, 9); - assert.ok(exit_button_called); - assert.equal(user_group_find_called, 2); - assert.equal(pill_container_find_called, 4); - assert.equal(turned_off["keydown/.pill"], true); - assert.equal(turned_off["keydown/.input"], true); - assert.equal(turned_off["click/whole"], true); -}); - -test_ui("reload", ({override_rewire}) => { - $("#user-groups").html("Some text"); - let populate_user_groups_called = false; - override_rewire(settings_user_groups_legacy, "populate_user_groups", () => { - populate_user_groups_called = true; - }); - settings_user_groups_legacy.reload(); - assert.ok(populate_user_groups_called); - assert.equal($("#user-groups").html(), ""); -}); - -test_ui("reset", () => { - settings_user_groups_legacy.reset(); - const result = settings_user_groups_legacy.reload(); - assert.equal(result, undefined); -}); - -test_ui("on_events", ({mock_template, override, override_rewire}) => { - override(settings_data, "user_can_edit_user_groups", () => true); - mock_template("confirm_dialog/confirm_delete_user.hbs", false, (data) => { - assert.deepEqual(data, { - group_name: "Mobile", - }); - return "stub"; - }); - - page_params.is_admin = true; - - (function test_admin_user_group_form_submit_triggered() { - const handler = settings_user_groups_legacy.add_user_group; - const event = { - stopPropagation: noop, - preventDefault: noop, - }; - const $fake_this = $.create("#add-user-group-form"); - const fake_object_array = [ - { - name: "fake-name", - value: "", - }, - { - name: "fake-name", - value: "fake-value", - }, - ]; - $fake_this.serializeArray = () => fake_object_array; - channel.post = (opts) => { - const data = { - members: "[null]", - }; - data[fake_object_array[1].name] = fake_object_array[1].value; - assert.equal(opts.url, "/json/user_groups/create"); - assert.deepEqual(opts.data, data); - - (function test_post_success() { - $("#dialog_error").show(); - $("#add-user-group-form input[type='text']").val("fake-content"); - ui_report.success = (text, ele) => { - assert.equal(text, "translated HTML: User group added!"); - assert.equal(ele, $("#dialog_error")); - }; - dialog_widget.close = () => {}; - - opts.success(); - - assert.ok(!$("#dialog_error").visible()); - })(); - (function test_post_error() { - $("#dialog_error").show(); - ui_report.error = (error_msg, error_obj, ele) => { - assert.equal(error_msg, "translated HTML: Failed"); - assert.deepEqual(error_obj, {responseJson: {msg: "fake-msg"}}); - assert.equal(ele, $("#dialog_error")); - }; - opts.error({responseJson: {msg: "fake-msg"}}); - - assert.ok(!$("#dialog_error").visible()); - })(); - }; - - handler(event); - })(); - - (function test_user_groups_delete_click_triggered() { - const handler = $("#user-groups").get_on_handler("click", ".delete"); - const $fake_this = $.create("fake-#user-groups.delete_btn"); - $fake_this.set_parents_result(".user-group", $(".user-group")); - $(".user-group").attr("id", "1"); - - channel.del = (opts) => { - const data = { - id: 1, - }; - assert.equal(opts.url, "/json/user_groups/1"); - assert.deepEqual(opts.data, data); - - $fake_this.text($t({defaultMessage: "fake-text"})); - opts.error(); - assert.equal($fake_this.text(), "translated: Failed!"); - }; - - confirm_dialog.launch = (conf) => { - conf.on_click(); - }; - - handler.call($fake_this); - })(); - - (function test_user_groups_keypress_enter_triggered() { - const handler = $("#user-groups").get_on_handler("keypress", ".user-group h4 > span"); - let default_action_for_enter_stopped = false; - const event = { - key: "Enter", - preventDefault() { - default_action_for_enter_stopped = true; - }, - }; - handler(event); - assert.ok(default_action_for_enter_stopped); - })(); - - (function test_do_not_blur() { - const blur_event_classes = [".name", ".description", ".input"]; - let api_endpoint_called = false; - /* istanbul ignore next */ - channel.post = () => { - api_endpoint_called = true; - }; - channel.patch = noop; - const $fake_this = $.create("fake-#user-groups_do_not_blur"); - const event = { - // FIXME: event.relatedTarget should not be a jQuery object - relatedTarget: $fake_this, - }; - - // Any of the blur_exceptions trigger blur event. - for (const class_name of blur_event_classes) { - const handler = $(user_group_selector).get_on_handler("blur", class_name); - - for (const blur_exception of [ - ".pill-container", - ".name", - ".description", - ".input", - ".delete", - ]) { - if (blur_exception === class_name) { - continue; - } - api_endpoint_called = false; - $fake_this.closest = (class_name) => { - if (class_name === blur_exception || class_name === user_group_selector) { - return [1]; - } - return []; - }; - handler.call($fake_this, event); - assert.ok(!api_endpoint_called); - } - - api_endpoint_called = false; - $fake_this.closest = (class_name) => { - assert.equal(class_name, ".typeahead"); - return [1]; - }; - handler.call($fake_this, event); - assert.ok(!api_endpoint_called); - - // Cancel button triggers blur event. - let settings_user_groups_legacy_reload_called = false; - override_rewire(settings_user_groups_legacy, "reload", () => { - settings_user_groups_legacy_reload_called = true; - }); - api_endpoint_called = false; - $fake_this.closest = (class_name) => { - if ( - class_name === ".save-status.btn-danger" || - class_name === user_group_selector - ) { - return [1]; - } - return []; - }; - handler.call($fake_this, event); - assert.ok(!api_endpoint_called); - assert.ok(settings_user_groups_legacy_reload_called); - } - })(); - - (function test_update_cancel_button() { - const handler_name = $(user_group_selector).get_on_handler("input", ".name"); - const handler_desc = $(user_group_selector).get_on_handler("input", ".description"); - const $sib_des = $(description_selector); - const $sib_name = $(name_selector); - $sib_name.text($t({defaultMessage: "mobile"})); - $sib_des.text($t({defaultMessage: "All mobile members"})); - - const group_data = { - name: "translated: mobile", - description: "translated: All mobile members", - members: new Set([2, 31]), - }; - user_groups.get_user_group_from_id = () => group_data; - - let cancel_fade_out_called = false; - let instructions_fade_out_called = false; - $(cancel_selector).show(); - $(cancel_selector).fadeOut = () => { - cancel_fade_out_called = true; - }; - $(instructions_selector).fadeOut = () => { - instructions_fade_out_called = true; - }; - - // Cancel button removed if user group if user group has no changes. - const $fake_this = $.create("fake-#update_cancel_button"); - handler_name.call($fake_this); - assert.ok(cancel_fade_out_called); - assert.ok(instructions_fade_out_called); - - // Check if cancel button removed if user group error is showing. - $(user_group_selector + " .user-group-status").show(); - cancel_fade_out_called = false; - instructions_fade_out_called = false; - handler_name.call($fake_this); - assert.ok(cancel_fade_out_called); - assert.ok(instructions_fade_out_called); - - // Check for handler_desc to achieve 100% coverage. - cancel_fade_out_called = false; - instructions_fade_out_called = false; - handler_desc.call($fake_this); - assert.ok(cancel_fade_out_called); - assert.ok(instructions_fade_out_called); - })(); - - (function test_user_groups_save_group_changes_triggered() { - const handler_name = $(user_group_selector).get_on_handler("blur", ".name"); - const handler_desc = $(user_group_selector).get_on_handler("blur", ".description"); - const $sib_des = $(description_selector); - const $sib_name = $(name_selector); - $sib_name.text($t({defaultMessage: "mobile"})); - $sib_des.text($t({defaultMessage: "All mobile members"})); - - const group_data = {members: new Set([2, 31])}; - user_groups.get_user_group_from_id = () => group_data; - let api_endpoint_called = false; - let cancel_fade_out_called = false; - let saved_fade_to_called = false; - let instructions_fade_out_called = false; - $(instructions_selector).fadeOut = () => { - instructions_fade_out_called = true; - }; - $(cancel_selector).fadeOut = () => { - cancel_fade_out_called = true; - }; - $(saved_selector).css = (data) => { - assert.equal(typeof data, "object"); - assert.equal(data.display, "inline-block"); - assert.equal(data.opacity, "0"); - return $(saved_selector); - }; - $(saved_selector).fadeTo = () => { - saved_fade_to_called = true; - return $(saved_selector); - }; - - channel.patch = (opts) => { - assert.equal(opts.url, "/json/user_groups/1"); - assert.equal(opts.data.name, "translated: mobile"); - assert.equal(opts.data.description, "translated: All mobile members"); - api_endpoint_called = true; - (function test_post_success() { - set_global("setTimeout", (func) => { - func(); - }); - opts.success(); - assert.ok(cancel_fade_out_called); - assert.ok(instructions_fade_out_called); - assert.ok(saved_fade_to_called); - })(); - (function test_post_error() { - const $user_group_error = $(user_group_selector + " .user-group-status"); - $user_group_error.show(); - ui_report.error = (error_msg, error_obj, ele) => { - assert.equal(error_msg, "translated HTML: Failed"); - assert.deepEqual(error_obj, {responseJson: {msg: "fake-msg"}}); - assert.equal(ele, $user_group_error); - }; - opts.error({responseJson: {msg: "fake-msg"}}); - - assert.ok($user_group_error.visible()); - })(); - }; - - const $fake_this = $.create("fake-#user-groups_blur_name"); - $fake_this.closest = () => []; - $fake_this.set_parents_result(user_group_selector, $(user_group_selector)); - const event = { - // FIXME: event.relatedTarget should not be a jQuery object - relatedTarget: $fake_this, - }; - - api_endpoint_called = false; - handler_name.call($fake_this, event); - assert.ok(api_endpoint_called); - - // Check API endpoint isn't called if name and desc haven't changed. - group_data.name = "translated: mobile"; - group_data.description = "translated: All mobile members"; - api_endpoint_called = false; - handler_name.call($fake_this, event); - assert.ok(!api_endpoint_called); - - // Check for handler_desc to achieve 100% coverage. - api_endpoint_called = false; - handler_desc.call($fake_this, event); - assert.ok(!api_endpoint_called); - })(); - - (function test_user_groups_save_member_changes_triggered() { - const handler = $(user_group_selector).get_on_handler("blur", ".input"); - const realm_user_group = { - id: 1, - name: "Mobile", - description: "All mobile people", - members: new Set([2, 4]), - }; - - user_groups.get_user_group_from_id = (id) => { - assert.equal(id, 1); - return realm_user_group; - }; - - let cancel_fade_out_called = false; - let saved_fade_to_called = false; - let instructions_fade_out_called = false; - $(instructions_selector).fadeOut = () => { - instructions_fade_out_called = true; - }; - $(cancel_selector).fadeOut = () => { - cancel_fade_out_called = true; - }; - $(saved_selector).css = () => $(saved_selector); - $(saved_selector).fadeTo = () => { - saved_fade_to_called = true; - return $(saved_selector); - }; - - let api_endpoint_called = false; - channel.post = (opts) => { - assert.equal(opts.url, "/json/user_groups/1/members"); - assert.equal(opts.data.add, "[31]"); - assert.equal(opts.data.delete, "[4]"); - api_endpoint_called = true; - - (function test_post_success() { - opts.success(); - assert.ok(cancel_fade_out_called); - assert.ok(instructions_fade_out_called); - assert.ok(saved_fade_to_called); - })(); - }; - - const $fake_this = $.create("fake-#user-groups_blur_input"); - $fake_this.set_parents_result(user_group_selector, $(user_group_selector)); - $fake_this.closest = () => []; - const event = { - // FIXME: event.relatedTarget should not be a jQuery object - relatedTarget: $fake_this, - }; - - api_endpoint_called = false; - handler.call($fake_this, event); - assert.ok(api_endpoint_called); - })(); -}); diff --git a/web/tests/user_pill.test.js b/web/tests/user_pill.test.js --- a/web/tests/user_pill.test.js +++ b/web/tests/user_pill.test.js @@ -4,6 +4,7 @@ const {strict: assert} = require("assert"); const {zrequire} = require("./lib/namespace"); const {run_test} = require("./lib/test"); +const blueslip = require("./lib/zblueslip"); const {page_params} = require("./lib/zpage_params"); const people = zrequire("people"); @@ -102,6 +103,9 @@ test("append", () => { assert.ok(appended); assert.ok(cleared); + + blueslip.expect("warn", "Undefined user in function append_user"); + user_pill.append_user(undefined, pill_widget); }); test("get_items", () => {
Switch to new groups UI <!-- Issue description --> Now that #27912 has been merged, we are ready to: - [ ] Remove the old user groups management panel from Organization settings. > [#19526](https://github.com/zulip/zulip/issues/19526): Once the above are done, we can delete the settings_user_groups.js UI and cutover the UI, perhaps after a bit more work - [ ] Make the gear menu options (in order): Stream settings Organization settings Group settings Personal settings Icon: https://lucide.dev/icons/user-cog @_**Vlad Korobov|22433** [said](https://chat.zulip.org/#narrow/stream/101-design/topic/settings.20order/near/1692676): ``` <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 16 16"><path fill="#000" d="M2.668 4.668a3.332 3.332 0 1 1 6.664 0 3.332 3.332 0 0 1-6.664 0ZM6 2.666a2.002 2.002 0 1 0 0 4.003 2.002 2.002 0 0 0 0-4.003Zm8.102 5.696.118-.047a.665.665 0 0 1 .494 1.235l-.082.033a2.682 2.682 0 0 1 .017.71l.028.01a.665.665 0 1 1-.42 1.261l-.08-.026a2.68 2.68 0 0 1-.54.566l.047.116a.665.665 0 1 1-1.235.494l-.032-.08a2.692 2.692 0 0 1-.71.016l-.01.027a.665.665 0 1 1-1.261-.42l.026-.08a2.682 2.682 0 0 1-.565-.54l-.117.047a.665.665 0 1 1-.494-1.235l.081-.032a2.684 2.684 0 0 1-.016-.71l-.028-.009a.665.665 0 0 1 .42-1.261l.08.026c.152-.214.334-.404.54-.565l-.047-.119a.665.665 0 0 1 1.235-.494l.033.083a2.686 2.686 0 0 1 .709-.016l.01-.03a.665.665 0 0 1 1.261.42l-.027.082c.214.15.404.332.565.538Zm-2.785.492a1.334 1.334 0 0 0-.595 1.533.664.664 0 0 1 .134.302 1.334 1.334 0 0 0 1.53.59.664.664 0 0 1 .304-.135 1.334 1.334 0 0 0 .587-1.534.668.668 0 0 1-.132-.296 1.334 1.334 0 0 0-1.537-.59.665.665 0 0 1-.291.13ZM4 9.336a3.332 3.332 0 0 0-3.332 3.332V14a.665.665 0 1 0 1.33 0v-1.333A2.002 2.002 0 0 1 4 10.666h2.667a.665.665 0 1 0 0-1.33H4Z"/></svg> ``` - [ ] Update the help center pages/macros for user groups. Can be an immediate follow-up, but I think it shouldn't be too hard, and then we can check it off. <!-- Link to a message in the chat.zulip.org discussion. Message links will still work even if the topic is renamed or resolved. Link back to this issue from the chat.zulip.org thread. --> [CZO thread](https://chat.zulip.org/#narrow/stream/101-design/topic/settings.20order/near/1692676)
2023-12-06T17:43:18
zulip/zulip
28,085
zulip__zulip-28085
[ "28075" ]
d29d132e8ae1261b368447ba1f1367e640a11aa3
diff --git a/version.py b/version.py --- a/version.py +++ b/version.py @@ -33,7 +33,7 @@ # Changes should be accompanied by documentation explaining what the # new level means in api_docs/changelog.md, as well as "**Changes**" # entries in the endpoint's documentation in `zulip.yaml`. -API_FEATURE_LEVEL = 233 +API_FEATURE_LEVEL = 234 # Bump the minor PROVISION_VERSION to indicate that folks should provision # only when going from an old version of the code to a newer version. Bump diff --git a/zerver/lib/push_notifications.py b/zerver/lib/push_notifications.py --- a/zerver/lib/push_notifications.py +++ b/zerver/lib/push_notifications.py @@ -908,6 +908,7 @@ def get_base_payload(user_profile: UserProfile) -> Dict[str, Any]: data["server"] = settings.EXTERNAL_HOST data["realm_id"] = user_profile.realm.id data["realm_uri"] = user_profile.realm.uri + data["realm_name"] = user_profile.realm.name data["user_id"] = user_profile.id return data @@ -1398,7 +1399,7 @@ def send_test_push_notification_directly_to_devices( remote: Optional["RemoteZulipServer"] = None, ) -> None: payload = copy.deepcopy(base_payload) - payload["event"] = "test-by-device-token" + payload["event"] = "test" apple_devices = [device for device in devices if device.kind == PushDeviceToken.APNS] android_devices = [device for device in devices if device.kind == PushDeviceToken.GCM] @@ -1408,10 +1409,13 @@ def send_test_push_notification_directly_to_devices( android_payload = copy.deepcopy(payload) realm_uri = base_payload["realm_uri"] + realm_name = base_payload["realm_name"] apns_data = { "alert": { "title": _("Test notification"), - "body": _("This is a test notification from {realm_uri}.").format(realm_uri=realm_uri), + "body": _("This is a test notification from {realm_name} ({realm_uri}).").format( + realm_name=realm_name, realm_uri=realm_uri + ), }, "sound": "default", "custom": {"zulip": apple_payload},
diff --git a/zerver/tests/test_push_notifications.py b/zerver/tests/test_push_notifications.py --- a/zerver/tests/test_push_notifications.py +++ b/zerver/tests/test_push_notifications.py @@ -196,9 +196,10 @@ def test_send_test_push_notification_api_no_bouncer_config(self) -> None: expected_android_payload = { "server": "testserver", "realm_id": user.realm_id, + "realm_name": "Zulip Dev", "realm_uri": "http://zulip.testserver", "user_id": user.id, - "event": "test-by-device-token", + "event": "test", "time": datetime_to_timestamp(time_now), } expected_gcm_options = {"priority": "high"} @@ -219,16 +220,17 @@ def test_send_test_push_notification_api_no_bouncer_config(self) -> None: expected_apple_payload = { "alert": { "title": "Test notification", - "body": "This is a test notification from http://zulip.testserver.", + "body": "This is a test notification from Zulip Dev (http://zulip.testserver).", }, "sound": "default", "custom": { "zulip": { "server": "testserver", "realm_id": user.realm_id, + "realm_name": "Zulip Dev", "realm_uri": "http://zulip.testserver", "user_id": user.id, - "event": "test-by-device-token", + "event": "test", } }, } @@ -301,9 +303,10 @@ def test_send_test_push_notification_api_with_bouncer_config(self) -> None: expected_payload = { "server": "testserver", "realm_id": user.realm_id, + "realm_name": "Zulip Dev", "realm_uri": "http://zulip.testserver", "user_id": user.id, - "event": "test-by-device-token", + "event": "test", "time": datetime_to_timestamp(time_now), } expected_gcm_options = {"priority": "high"} @@ -2389,6 +2392,7 @@ def test_send_remove_notifications_to_bouncer(self) -> None: "zulip": { "server": "testserver", "realm_id": self.sender.realm.id, + "realm_name": self.sender.realm.name, "realm_uri": "http://zulip.testserver", "user_id": self.user_profile.id, "event": "remove", @@ -2399,6 +2403,7 @@ def test_send_remove_notifications_to_bouncer(self) -> None: { "server": "testserver", "realm_id": self.sender.realm.id, + "realm_name": self.sender.realm.name, "realm_uri": "http://zulip.testserver", "user_id": self.user_profile.id, "event": "remove", @@ -2452,6 +2457,7 @@ def test_non_bouncer_push_remove(self) -> None: { "server": "testserver", "realm_id": self.sender.realm.id, + "realm_name": self.sender.realm.name, "realm_uri": "http://zulip.testserver", "user_id": self.user_profile.id, "event": "remove", @@ -2469,6 +2475,7 @@ def test_non_bouncer_push_remove(self) -> None: "zulip": { "server": "testserver", "realm_id": self.sender.realm.id, + "realm_name": self.sender.realm.name, "realm_uri": "http://zulip.testserver", "user_id": self.user_profile.id, "event": "remove", @@ -2948,6 +2955,7 @@ def test_get_message_payload_apns_personal_message(self) -> None: "sender_id": self.sender.id, "server": settings.EXTERNAL_HOST, "realm_id": self.sender.realm.id, + "realm_name": self.sender.realm.name, "realm_uri": self.sender.realm.uri, "user_id": user_profile.id, "time": datetime_to_timestamp(message.date_sent), @@ -2991,6 +2999,7 @@ def test_get_message_payload_apns_huddle_message( "sender_id": self.sender.id, "server": settings.EXTERNAL_HOST, "realm_id": self.sender.realm.id, + "realm_name": self.sender.realm.name, "realm_uri": self.sender.realm.uri, "user_id": user_profile.id, "time": datetime_to_timestamp(message.date_sent), @@ -3023,6 +3032,7 @@ def _test_get_message_payload_apns_stream_message(self, trigger: str) -> None: "topic": message.topic_name(), "server": settings.EXTERNAL_HOST, "realm_id": self.sender.realm.id, + "realm_name": self.sender.realm.name, "realm_uri": self.sender.realm.uri, "user_id": self.sender.id, "time": datetime_to_timestamp(message.date_sent), @@ -3061,6 +3071,7 @@ def test_get_message_payload_apns_stream_mention(self) -> None: "topic": message.topic_name(), "server": settings.EXTERNAL_HOST, "realm_id": self.sender.realm.id, + "realm_name": self.sender.realm.name, "realm_uri": self.sender.realm.uri, "user_id": user_profile.id, "time": datetime_to_timestamp(message.date_sent), @@ -3098,6 +3109,7 @@ def test_get_message_payload_apns_user_group_mention(self) -> None: "topic": message.topic_name(), "server": settings.EXTERNAL_HOST, "realm_id": self.sender.realm.id, + "realm_name": self.sender.realm.name, "realm_uri": self.sender.realm.uri, "user_id": user_profile.id, "mentioned_user_group_id": user_group.id, @@ -3136,6 +3148,7 @@ def _test_get_message_payload_apns_wildcard_mention(self, trigger: str) -> None: "topic": message.topic_name(), "server": settings.EXTERNAL_HOST, "realm_id": self.sender.realm.id, + "realm_name": self.sender.realm.name, "realm_uri": self.sender.realm.uri, "user_id": user_profile.id, "time": datetime_to_timestamp(message.date_sent), @@ -3197,6 +3210,7 @@ def test_get_message_payload_apns_redacted_content(self) -> None: "sender_id": self.sender.id, "server": settings.EXTERNAL_HOST, "realm_id": self.sender.realm.id, + "realm_name": self.sender.realm.name, "realm_uri": self.sender.realm.uri, "user_id": user_profile.id, "time": datetime_to_timestamp(message.date_sent), @@ -3246,6 +3260,7 @@ def test_get_message_payload_apns_stream_message_from_inaccessible_user(self) -> "topic": message.topic_name(), "server": settings.EXTERNAL_HOST, "realm_id": hamlet.realm.id, + "realm_name": hamlet.realm.name, "realm_uri": hamlet.realm.uri, "user_id": polonius.id, "time": datetime_to_timestamp(message.date_sent), @@ -3284,6 +3299,7 @@ def _test_get_message_payload_gcm_stream_message( "content_truncated": truncate_content, "server": settings.EXTERNAL_HOST, "realm_id": hamlet.realm.id, + "realm_name": hamlet.realm.name, "realm_uri": hamlet.realm.uri, "sender_id": hamlet.id, "sender_email": hamlet.email, @@ -3342,6 +3358,7 @@ def test_get_message_payload_gcm_direct_message(self) -> None: "content_truncated": False, "server": settings.EXTERNAL_HOST, "realm_id": hamlet.realm.id, + "realm_name": hamlet.realm.name, "realm_uri": hamlet.realm.uri, "sender_id": hamlet.id, "sender_email": hamlet.email, @@ -3374,6 +3391,7 @@ def test_get_message_payload_gcm_redacted_content(self) -> None: "content_truncated": False, "server": settings.EXTERNAL_HOST, "realm_id": hamlet.realm.id, + "realm_name": hamlet.realm.name, "realm_uri": hamlet.realm.uri, "sender_id": hamlet.id, "sender_email": hamlet.email, @@ -3423,6 +3441,7 @@ def test_get_message_payload_gcm_stream_message_from_inaccessible_user(self) -> "content_truncated": False, "server": settings.EXTERNAL_HOST, "realm_id": hamlet.realm.id, + "realm_name": hamlet.realm.name, "realm_uri": hamlet.realm.uri, "sender_id": hamlet.id, "sender_email": f"user{hamlet.id}@zulip.testserver",
Adjust API endpoint for sending test notifications. As noted in https://chat.zulip.org/#narrow/stream/378-api-design/topic/.2323997.20Endpoint.20for.20test.20notification/near/1696957: > To summarize from [this message](https://chat.zulip.org/#narrow/stream/378-api-design/topic/.2323997.20Endpoint.20for.20test.20notification/near/1690721) on 2023-11-28 and following, there are two changes we want to include in the 8.0 release if possible: > - Change the notification payload's "event" field from "test-by-device-token" to just "test". (More on this [here](https://chat.zulip.org/#narrow/stream/378-api-design/topic/.2323997.20Endpoint.20for.20test.20notification/near/1690777).) > - Add a "realm_name" field to the payload, with the realm's name.
2023-12-07T18:10:59
zulip/zulip
28,119
zulip__zulip-28119
[ "28108" ]
367afbb5beb25f1b8c2a4207fc2a8ed2e770d324
diff --git a/zerver/views/realm.py b/zerver/views/realm.py --- a/zerver/views/realm.py +++ b/zerver/views/realm.py @@ -1,6 +1,5 @@ from typing import Any, Dict, Mapping, Optional, Union -from django.conf import settings from django.core.exceptions import ValidationError from django.http import HttpRequest, HttpResponse from django.shortcuts import render @@ -236,9 +235,6 @@ def update_realm( realm.ensure_not_on_limited_plan() if can_access_all_users_group_id is not None: - # Remove this when the feature is ready for production. - assert settings.DEVELOPMENT - realm.can_enable_restricted_user_access_for_guests() data: Dict[str, Any] = {}
diff --git a/web/tests/user_groups.test.js b/web/tests/user_groups.test.js --- a/web/tests/user_groups.test.js +++ b/web/tests/user_groups.test.js @@ -79,7 +79,7 @@ run_test("user_groups", () => { }); assert.equal(user_groups.get_user_group_from_name(all.name), undefined); - assert.equal(user_groups.get_user_group_from_name(admins.name).id, 1); + assert.equal(user_groups.get_user_group_from_name("new admins").id, 1); user_groups.add(all); const user_groups_array = user_groups.get_realm_user_groups(); diff --git a/zerver/tests/test_realm.py b/zerver/tests/test_realm.py --- a/zerver/tests/test_realm.py +++ b/zerver/tests/test_realm.py @@ -1386,30 +1386,6 @@ def test_update_realm_properties(self) -> None: with self.subTest(property=prop): self.do_test_realm_permission_group_setting_update_api(prop) - def test_update_can_access_all_users_group_setting(self) -> None: - realm = get_realm("zulip") - self.login("iago") - members_group = UserGroup.objects.get(realm=realm, name=SystemGroups.MEMBERS) - - with self.settings(DEVELOPMENT=False): - with self.assertRaises(AssertionError), self.assertLogs( - "django.request", "ERROR" - ) as error_log: - self.client_patch("/json/realm", {"can_access_all_users_group": members_group.id}) - - self.assertTrue( - "ERROR:django.request:Internal Server Error: /json/realm" in error_log.output[0] - ) - self.assertTrue("AssertionError" in error_log.output[0]) - - with self.settings(DEVELOPMENT=True): - result = self.client_patch( - "/json/realm", {"can_access_all_users_group": members_group.id} - ) - self.assert_json_success(result) - realm = get_realm("zulip") - self.assertEqual(realm.can_access_all_users_group_id, members_group.id) - # Not in Realm.property_types because org_type has # a unique RealmAuditLog event_type. def test_update_realm_org_type(self) -> None:
Can't reuse group name after it's renamed (until refresh) 1. Make a group named **foo** 2. Rename it to **bar** 3. Try to make a new group named **foo**, or rename another existing group to **foo**. Expected: It should work. Actual: <img width="633" alt="Screenshot 2023-12-08 at 9 20 52 PM" src="https://github.com/zulip/zulip/assets/2090066/c708f5a8-c9bb-4b6a-bbfb-3af252f596c9"> Refreshing the browser fixes this.
2023-12-10T08:24:01
zulip/zulip
28,192
zulip__zulip-28192
[ "28163" ]
27d236fb523ae33663a1ada123d3f831bad60a05
diff --git a/zerver/lib/markdown/help_relative_links.py b/zerver/lib/markdown/help_relative_links.py --- a/zerver/lib/markdown/help_relative_links.py +++ b/zerver/lib/markdown/help_relative_links.py @@ -37,7 +37,7 @@ ], "stats": ['<i class="zulip-icon zulip-icon-bar-chart"></i> Usage statistics', "/stats"], "integrations": ['<i class="zulip-icon-git-pull-request"></i> Integrations', "/integrations/"], - "plans": ['<i class="fa fa-rocket"></i> Plans and pricing', "/plans/"], + "plans": ['<i class="zulip-icon zulip-icon-rocket"></i> Plans and pricing', "/plans/"], "billing": ['<i class="zulip-icon zulip-icon-credit-card"></i> Billing', "/billing/"], "about-zulip": ["About Zulip", "/#about-zulip"], }
Update Plans and pricing icon We should update the rocket icon everywhere it shows up in the gear menu (Plans and pricing, Plan management) to: <img width="128" alt="rocket" src="https://github.com/zulip/zulip/assets/2090066/a951bc3b-1d95-4ec5-b5a2-3cf9d1ba88f4"> ![rocket](https://github.com/zulip/zulip/assets/2090066/883735c4-9a2f-49e2-a629-ba8b43d80974) source: https://lucide.dev/icons/rocket
@sayamsamal Would you be available to take care of this one today? @alya Surely, thanks!
2023-12-13T09:15:30
zulip/zulip
28,236
zulip__zulip-28236
[ "28227" ]
11dff6b4d8df76b07932f0556146001b0c7db315
diff --git a/zerver/management/commands/change_user_role.py b/zerver/management/commands/change_user_role.py --- a/zerver/management/commands/change_user_role.py +++ b/zerver/management/commands/change_user_role.py @@ -13,6 +13,17 @@ from zerver.lib.management import ZulipBaseCommand from zerver.models import UserProfile +ROLE_CHOICES = [ + "owner", + "admin", + "moderator", + "member", + "guest", + "can_forge_sender", + "can_create_users", + "is_billing_admin", +] + class Command(ZulipBaseCommand): help = """Change role of an existing user in their (own) Realm. @@ -26,17 +37,8 @@ def add_arguments(self, parser: ArgumentParser) -> None: parser.add_argument( "new_role", metavar="<new_role>", - choices=[ - "owner", - "admin", - "moderator", - "member", - "guest", - "can_forge_sender", - "can_create_users", - "is_billing_admin", - ], - help="new role of the user", + choices=ROLE_CHOICES, + help="new role of the user; choose from " + ", ".join(ROLE_CHOICES), ) parser.add_argument( "--revoke",
`manage.py change_user_role --help` should self-document the set of roles it supports Right now, the only way it self-documents this is when you try an invalid role: ``` manage.py change_user_role: error: argument <new_role>: invalid choice: 'is_billing_administrator' (choose from 'owner', 'admin', 'moderator', 'member', 'guest', 'can_forge_sender', 'can_create_users', 'is_billing_admin') ```
2023-12-14T22:41:16
zulip/zulip
28,267
zulip__zulip-28267
[ "18320" ]
94558478dff538affbb5f4b22ca2e1d6dc184e8b
diff --git a/zerver/lib/integrations.py b/zerver/lib/integrations.py --- a/zerver/lib/integrations.py +++ b/zerver/lib/integrations.py @@ -197,6 +197,7 @@ def __init__( stream_name: Optional[str] = None, legacy: bool = False, config_options: Sequence[Tuple[str, str, OptionValidator]] = [], + dir_name: Optional[str] = None, ) -> None: if client_name is None: client_name = self.DEFAULT_CLIENT_NAME.format(name=name.title()) @@ -229,9 +230,12 @@ def __init__( if doc is None: doc = self.DEFAULT_DOC_PATH.format(name=name, ext="md") - self.doc = doc + if dir_name is None: + dir_name = self.name + self.dir_name = dir_name + @property def url_object(self) -> URLResolver: assert self.function is not None @@ -266,7 +270,7 @@ def get_fixture_and_image_paths( integration: Integration, screenshot_config: BaseScreenshotConfig ) -> Tuple[str, str]: if isinstance(integration, WebhookIntegration): - fixture_dir = os.path.join("zerver", "webhooks", integration.name, "fixtures") + fixture_dir = os.path.join("zerver", "webhooks", integration.dir_name, "fixtures") else: fixture_dir = os.path.join("zerver", "integration_fixtures", integration.name) fixture_path = os.path.join(fixture_dir, screenshot_config.fixture_name) @@ -401,6 +405,16 @@ def __init__(self, name: str, *args: Any, **kwargs: Any) -> None: function="zerver.webhooks.github.view.api_github_webhook", stream_name="github", ), + WebhookIntegration( + "githubsponsors", + ["financial"], + display_name="GitHub Sponsors", + logo="images/integrations/logos/github.svg", + dir_name="github", + function="zerver.webhooks.github.view.api_github_webhook", + doc="github/githubsponsors.md", + stream_name="github", + ), WebhookIntegration("gitlab", ["version-control"], display_name="GitLab"), WebhookIntegration("gocd", ["continuous-integration"], display_name="GoCD"), WebhookIntegration("gogs", ["version-control"], stream_name="commits"), @@ -739,6 +753,7 @@ def __init__(self, name: str, *args: Any, **kwargs: Any) -> None: "gci": [ScreenshotConfig("task_abandoned_by_student.json")], "gitea": [ScreenshotConfig("pull_request__merged.json")], "github": [ScreenshotConfig("push__1_commit.json")], + "githubsponsors": [ScreenshotConfig("created.json")], "gitlab": [ScreenshotConfig("push_hook__push_local_branch_without_commits.json")], "gocd": [ScreenshotConfig("pipeline.json")], "gogs": [ScreenshotConfig("pull_request__opened.json")], @@ -836,8 +851,9 @@ def __init__(self, name: str, *args: Any, **kwargs: Any) -> None: def get_all_event_types_for_integration(integration: Integration) -> Optional[List[str]]: integration = INTEGRATIONS[integration.name] - if isinstance(integration, WebhookIntegration) and hasattr( - integration.function, "_all_event_types" - ): - return integration.function._all_event_types + if isinstance(integration, WebhookIntegration): + if integration.name == "githubsponsors": + return import_string("zerver.webhooks.github.view.SPONSORS_EVENT_TYPES") + if hasattr(integration.function, "_all_event_types"): + return integration.function._all_event_types return None diff --git a/zerver/webhooks/github/view.py b/zerver/webhooks/github/view.py --- a/zerver/webhooks/github/view.py +++ b/zerver/webhooks/github/view.py @@ -1,4 +1,5 @@ import re +from datetime import datetime, timezone from typing import Callable, Dict, Optional from django.http import HttpRequest, HttpResponse @@ -637,6 +638,82 @@ def get_ping_body(helper: Helper) -> str: return get_setup_webhook_message("GitHub", get_sender_name(payload)) +def get_cancelled_body(helper: Helper) -> str: + payload = helper.payload + template = "{user_name} cancelled their {subscription} subscription." + return template.format( + user_name=get_sender_name(payload), + subscription=get_subscription(payload), + ).rstrip() + + +def get_created_body(helper: Helper) -> str: + payload = helper.payload + template = "{user_name} subscribed for {subscription}." + return template.format( + user_name=get_sender_name(payload), + subscription=get_subscription(payload), + ).rstrip() + + +def get_edited_body(helper: Helper) -> str: + payload = helper.payload + template = "{user_name} changed who can see their sponsorship from {prior_privacy_level} to {privacy_level}." + return template.format( + user_name=get_sender_name(payload), + prior_privacy_level=payload["changes"]["privacy_level"]["from"].tame(check_string), + privacy_level=payload["sponsorship"]["privacy_level"].tame(check_string), + ).rstrip() + + +def get_pending_cancellation_body(helper: Helper) -> str: + payload = helper.payload + template = "{user_name}'s {subscription} subscription will be cancelled on {effective_date}." + return template.format( + user_name=get_sender_name(payload), + subscription=get_subscription(payload), + effective_date=get_effective_date(payload), + ).rstrip() + + +def get_pending_tier_change_body(helper: Helper) -> str: + payload = helper.payload + template = "{user_name}'s subscription will change from {prior_subscription} to {subscription} on {effective_date}." + return template.format( + user_name=get_sender_name(payload), + prior_subscription=get_prior_subscription(payload), + subscription=get_subscription(payload), + effective_date=get_effective_date(payload), + ).rstrip() + + +def get_tier_changed_body(helper: Helper) -> str: + payload = helper.payload + template = "{user_name} changed their subscription from {prior_subscription} to {subscription}." + return template.format( + user_name=get_sender_name(payload), + prior_subscription=get_prior_subscription(payload), + subscription=get_subscription(payload), + ).rstrip() + + +def get_subscription(payload: WildValue) -> str: + return payload["sponsorship"]["tier"]["name"].tame(check_string) + + +def get_effective_date(payload: WildValue) -> str: + effective_date = payload["effective_date"].tame(check_string)[:10] + return ( + datetime.strptime(effective_date, "%Y-%m-%d") + .replace(tzinfo=timezone.utc) + .strftime("%B %d, %Y") + ) + + +def get_prior_subscription(payload: WildValue) -> str: + return payload["changes"]["tier"]["from"]["name"].tame(check_string) + + def get_repository_name(payload: WildValue) -> str: return payload["repository"]["name"].tame(check_string) @@ -728,6 +805,8 @@ def get_topic_based_on_type(payload: WildValue, event: str) -> str: number=payload["discussion"]["number"].tame(check_int), title=payload["discussion"]["title"].tame(check_string), ) + elif event in SPONSORS_EVENT_TYPES: + return "sponsors" return get_repository_name(payload) @@ -770,8 +849,23 @@ def get_topic_based_on_type(payload: WildValue, event: str) -> str: "team": get_team_body, "team_add": get_add_team_body, "watch": get_watch_body, + "cancelled": get_cancelled_body, + "created": get_created_body, + "edited": get_edited_body, + "pending_cancellation": get_pending_cancellation_body, + "pending_tier_change": get_pending_tier_change_body, + "tier_changed": get_tier_changed_body, } +SPONSORS_EVENT_TYPES = [ + "cancelled", + "created", + "edited", + "pending_cancellation", + "pending_tier_change", + "tier_changed", +] + IGNORED_EVENTS = [ "check_suite", "label",
diff --git a/zerver/webhooks/github/tests.py b/zerver/webhooks/github/tests.py --- a/zerver/webhooks/github/tests.py +++ b/zerver/webhooks/github/tests.py @@ -13,6 +13,7 @@ TOPIC_BRANCH = "public-repo / changes" TOPIC_WIKI = "public-repo / wiki pages" TOPIC_DISCUSSION = "testing-gh discussion #20: Lets discuss" +TOPIC_SPONSORS = "sponsors" class GitHubWebhookTest(WebhookTestCase): @@ -591,3 +592,59 @@ def test_discussion_comment_msg_with_custom_topic_in_url(self) -> None: def test_discussion_comment_edited_msg(self) -> None: expected_message = "sbansal1999 edited a [comment](https://github.com/sbansal1999/testing-gh/discussions/20#discussioncomment-6332416) on [discussion #20](https://github.com/sbansal1999/testing-gh/discussions/20):\n\n~~~ quote\nsome random comment edited\n~~~" self.check_webhook("discussion_comment__edited", TOPIC_DISCUSSION, expected_message) + + +class GitHubSponsorsHookTests(WebhookTestCase): + STREAM_NAME = "github" + URL_TEMPLATE = "/api/v1/external/githubsponsors?stream={stream}&api_key={api_key}" + WEBHOOK_DIR_NAME = "github" + + def test_cancelled_message(self) -> None: + expected_message = "monalisa cancelled their $5 a month subscription." + self.check_webhook( + "cancelled", + TOPIC_SPONSORS, + expected_message, + ) + + def test_created_message(self) -> None: + expected_message = "monalisa subscribed for $5 a month." + self.check_webhook( + "created", + TOPIC_SPONSORS, + expected_message, + ) + + def test_pending_cancellation_message(self) -> None: + expected_message = ( + "monalisa's $5 a month subscription will be cancelled on January 05, 2020." + ) + self.check_webhook( + "pending_cancellation", + TOPIC_SPONSORS, + expected_message, + ) + + def test_pending_tier_change_message(self) -> None: + expected_message = "monalisa's subscription will change from $10 a month to $5 a month on December 30, 2019." + self.check_webhook( + "pending_tier_change", + TOPIC_SPONSORS, + expected_message, + ) + + def test_tier_changed_message(self) -> None: + expected_message = "monalisa changed their subscription from $10 a month to $5 a month." + self.check_webhook( + "tier_changed", + TOPIC_SPONSORS, + expected_message, + ) + + def test_edited_message(self) -> None: + expected_message = "monalisa changed who can see their sponsorship from public to private." + self.check_webhook( + "edited", + TOPIC_SPONSORS, + expected_message, + )
Create incoming webhook integration for Github Sponsors Create an [incoming webhook](https://zulip.com/api/incoming-webhooks-overview) integration for Github Sponsors. The main use case is getting notifications when new sponsors sign up. Github Sponsors webhooks documentation: https://docs.github.com/en/sponsors/integrating-with-github-sponsors/configuring-webhooks-for-events-in-your-sponsored-account Now that [Zulip has a Github Sponsors page](https://github.com/sponsors/zulip), it would be great to be able to monitor new sign-ups!
Hello @zulip/server-integrations members, this issue was labeled with the "area: integrations" label, so you may want to check it out! <!-- areaLabelAddition --> @zulipbot claim Welcome to Zulip, @akshat1499! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: * Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. * [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @akshat1499 can I take this issue. yes please @ritikchauhan-01 @zulipbot claim Welcome to Zulip, @Avi-sa! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: * Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. * [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @zulipbot abandon @zulipbot claim Welcome to Zulip, @SirAzako! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: * Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. * [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! Hello @siddhant141, you have been unassigned from this issue because you have not updated this issue or any referenced pull requests for over 14 days. You can reclaim this issue or claim any other issue by commenting `@zulipbot claim` on that issue. Thanks for your contributions, and hope to see you again soon! @zulipbot claim @zulipbot claim @timabbott @alya I'm getting this error and I don't know how to resolve this. ERROR: Some URLs are untested! Here's the list of untested URLs: api/v1/external/githubsponsors Error: Process completed with exit code 1. I ran the following command : ./tools/create-test-api-docs This hasn't resolved the error. @zulipbot claim @zulipbot claim Welcome to Zulip, @siddhant141! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @zulipbot claim Hello @profgrammer, you have been unassigned from this issue because you have not updated this issue or any referenced pull requests for over 14 days. You can reclaim this issue or claim any other issue by commenting `@zulipbot claim` on that issue. Thanks for your contributions, and hope to see you again soon! @zulipbot claim Welcome to Zulip, @iamu985! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! Hello @iamu985, you have been unassigned from this issue because you have not updated this issue or any referenced pull requests for over 14 days. You can reclaim this issue or claim any other issue by commenting `@zulipbot claim` on that issue. Thanks for your contributions, and hope to see you again soon! @zulipbot claim Hi @iamu985 , are you still working on this pr? If not can you please close it? I'd like to work on this one. @akshi2000 There is no need to close existing PRs. (CC @iamu985) As noted in the [contributor guide](https://zulip.readthedocs.io/en/latest/overview/contributing.html#common-questions): > What if there is already a pull request for the issue I want to work on? Start by reviewing the existing work. If you agree with the approach, you can use the existing pull request (PR) as a starting point for your contribution. If you think a different approach is needed, you can post a new PR, with a comment that clearly explains why you decided to start from scratch. Okay, Thank you @alya, I'll take a look at the existing PR and see what can be done. Hi @alya, I have submitted a PR. Some feedback on it would be really helpful. Can you please have a look at it? Thank you! Hello @akshi2000, you have been unassigned from this issue because you have not updated this issue or any referenced pull requests for over 14 days. You can reclaim this issue or claim any other issue by commenting `@zulipbot claim` on that issue. Thanks for your contributions, and hope to see you again soon! Hello @alya , Is this issue still been worked upon or it's done. If an issue is open, then it's not done. However, note the [comment](https://github.com/zulip/zulip/issues/18320#issuecomment-1016765667) above about how to approach an issue with open PRs. @zulipbot claim Hello @B1TSH3LL, it looks like you've currently claimed 1 issue in this repository. We encourage new contributors to focus their efforts on at most 1 issue at a time, so please complete your work on your other claimed issues before trying to claim this issue again. We look forward to your valuable contributions! @zulipbot claim Welcome to Zulip, @qiqistyle! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @zulipbot claim @qiqistyle You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! @zulipbot claim Welcome to Zulip, @Fahdmoh01! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @zulipbot abandon @zulipbot claim Welcome to Zulip, @jo-reko! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @jo-reko You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! @zulipbot claim @drrosa You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! @zulipbot claim @drrosa You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! @zulipbot claim
2023-12-16T07:59:48
zulip/zulip
28,327
zulip__zulip-28327
[ "25626" ]
c58c12911c55a7a310fc92b4d683a928228c46df
diff --git a/zerver/decorator.py b/zerver/decorator.py --- a/zerver/decorator.py +++ b/zerver/decorator.py @@ -123,7 +123,7 @@ def wrapper( return json_method_not_allowed(["POST"]) else: return TemplateResponse( - request, "404.html", context={"status_code": 405}, status=405 + request, "4xx.html", context={"status_code": 405}, status=405 ) return func(request, *args, **kwargs) diff --git a/zerver/middleware.py b/zerver/middleware.py --- a/zerver/middleware.py +++ b/zerver/middleware.py @@ -19,7 +19,6 @@ from django.utils.deprecation import MiddlewareMixin from django.utils.log import log_response from django.utils.translation import gettext as _ -from django.views.csrf import csrf_failure as html_csrf_failure from django_scim.middleware import SCIMAuthCheckMiddleware from django_scim.settings import scim_settings from sentry_sdk import set_tag @@ -454,7 +453,7 @@ def csrf_failure(request: HttpRequest, reason: str = "") -> HttpResponse: if RequestNotes.get_notes(request).error_format == "JSON": return json_response_from_error(CsrfFailureError(reason)) else: - return html_csrf_failure(request, reason) + return render(request, "4xx.html", context={"csrf_failure": True}, status=403) class LocaleMiddleware(DjangoLocaleMiddleware):
Customize CSRF error page We should customize the error page shown to users when CSRF validation fails. Currently, it looks like the default: <img width="281" alt="django-csrf-failed" src="https://github.com/zulip/zulip/assets/28347/3253f653-08de-40e0-bc15-f0598aead89f"> We should [customize it](https://docs.djangoproject.com/en/dev/ref/settings/#csrf-failure-view) to: - Use the Zulip standard error template - Remove mention of `DEBUG=True` - Suggest that if they are using Safari private browsing mode or some other privacy-blocking extension, they may need to disable it.
Hello @zulip/server-misc members, this issue was labeled with the "area: misc" label, so you may want to check it out! <!-- areaLabelAddition --> @mateuszmandera You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! @zulipbot claim Welcome to Zulip, @joanasouza! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @joanasouza You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! @zulipbot claim Welcome to Zulip, @ntwari-bruce! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @ntwari-bruce You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! @alexmv By 'Zulip standard error template' you mean the 404.html template? We should add 403 status code in html file and use it for CSRF validation fail error? @zulipbot claim
2023-12-22T18:26:42
zulip/zulip
28,384
zulip__zulip-28384
[ "18321" ]
26536a20ed828f2b20a8d43d6fae769d8b7bee9d
diff --git a/zerver/lib/integrations.py b/zerver/lib/integrations.py --- a/zerver/lib/integrations.py +++ b/zerver/lib/integrations.py @@ -441,6 +441,7 @@ def __init__(self, name: str, *args: Any, **kwargs: Any) -> None: WebhookIntegration("opsgenie", ["meta-integration", "monitoring"]), WebhookIntegration("pagerduty", ["monitoring"], display_name="PagerDuty"), WebhookIntegration("papertrail", ["monitoring"]), + WebhookIntegration("patreon", ["financial"], display_name="Patreon"), WebhookIntegration("pingdom", ["monitoring"]), WebhookIntegration("pivotal", ["project-management"], display_name="Pivotal Tracker"), WebhookIntegration("radarr", ["entertainment"], display_name="Radarr"), @@ -777,6 +778,7 @@ def __init__(self, name: str, *args: Any, **kwargs: Any) -> None: "opsgenie": [ScreenshotConfig("addrecipient.json", image_name="000.png")], "pagerduty": [ScreenshotConfig("trigger_v2.json")], "papertrail": [ScreenshotConfig("short_post.json", payload_as_query_param=True)], + "patreon": [ScreenshotConfig("members_pledge_create.json")], "pingdom": [ScreenshotConfig("http_up_to_down.json", image_name="002.png")], "pivotal": [ScreenshotConfig("v5_type_changed.json")], "radarr": [ScreenshotConfig("radarr_movie_grabbed.json")], diff --git a/zerver/webhooks/patreon/__init__.py b/zerver/webhooks/patreon/__init__.py new file mode 100644 diff --git a/zerver/webhooks/patreon/view.py b/zerver/webhooks/patreon/view.py new file mode 100644 --- /dev/null +++ b/zerver/webhooks/patreon/view.py @@ -0,0 +1,190 @@ +from typing import Callable, Dict, Optional + +from django.http import HttpRequest, HttpResponse + +from zerver.decorator import webhook_view +from zerver.lib.exceptions import UnsupportedWebhookEventTypeError +from zerver.lib.response import json_success +from zerver.lib.typed_endpoint import JsonBodyPayload, typed_endpoint +from zerver.lib.validator import WildValue, check_int, check_none_or, check_string +from zerver.lib.webhooks.common import ( + check_send_webhook_message, + validate_extract_webhook_http_header, +) +from zerver.models import UserProfile + + +# The events for this integration contain the ":" character, which is not appropriate in a +# filename and requires us to deviate from the common `get_http_headers_from_filename` method +# from zerver.lib.webhooks.common. +def get_custom_http_headers_from_filename(http_header_key: str) -> Callable[[str], Dict[str, str]]: + def fixture_to_headers(filename: str) -> Dict[str, str]: + event_type = filename.replace("_", ":") + return {http_header_key: event_type} + + return fixture_to_headers + + +fixture_to_headers = get_custom_http_headers_from_filename("HTTP_X_PATREON_EVENT") + + +def get_members_create_body(payload: WildValue) -> Optional[str]: + last_charge_status = get_last_charge_status(payload) + patron_status = get_patron_status(payload) + # null values indicate the member has never pledged + if last_charge_status is None and patron_status is None: + template = "{user_name} has joined as a member!" + return template.format( + user_name=get_user_name(payload), + ).rstrip() + return None + + +def get_members_update_body(payload: WildValue) -> Optional[str]: + last_charge_status = get_last_charge_status(payload) + patron_status = get_patron_status(payload) + if last_charge_status in ("Paid", None) and patron_status in ("active_patron", "former_patron"): + template = "{user_name}'s membership has been updated to {patron_status}." + return template.format( + user_name=get_user_name(payload), + patron_status=str(patron_status).replace("_", " "), + ).rstrip() + return None + + +def get_members_delete_body(payload: WildValue) -> Optional[str]: + last_charge_status = get_last_charge_status(payload) + patron_status = get_patron_status(payload) + # null value indicates the member has never pledged + if last_charge_status in ("Paid", None) and patron_status != "declined_patron": + template = "{user_name}'s membership has ended." + return template.format( + user_name=get_user_name(payload), + ).rstrip() + return None + + +def get_members_pledge_create_body(payload: WildValue) -> Optional[str]: + last_charge_status = get_last_charge_status(payload) + pledge_amount = get_pledge_amount(payload) + # The only successful charge status is "Paid". null if not yet charged. + if last_charge_status in ("Paid", None) and pledge_amount > 0: + template = "{user_name} has pledged ${pledge_amount:.2f} per {pay_per_name}. :tada:\nTotal number of patrons: {patron_count}" + return template.format( + user_name=get_user_name(payload), + pledge_amount=pledge_amount, + pay_per_name=get_pay_per_name(payload), + patron_count=get_patron_count(payload), + ).rstrip() + return None + + +def get_members_pledge_update_body(payload: WildValue) -> Optional[str]: + last_charge_status = get_last_charge_status(payload) + pledge_amount = get_pledge_amount(payload) + # The only successful charge status is "Paid". null if not yet charged. + if last_charge_status in ("Paid", None) and pledge_amount > 0: + template = "{user_name} has updated their pledge to ${pledge_amount:.2f} per {pay_per_name}. :gear:" + return template.format( + user_name=get_user_name(payload), + pledge_amount=pledge_amount, + pay_per_name=get_pay_per_name(payload), + ).rstrip() + return None + + +def get_members_pledge_delete_body(payload: WildValue) -> Optional[str]: + last_charge_status = get_last_charge_status(payload) + if last_charge_status in ("Paid", "Deleted", None): + template = "{user_name}'s pledge has been cancelled. :cross_mark:\nTotal number of patrons: {patron_count}" + return template.format( + user_name=get_user_name(payload), + patron_count=get_patron_count(payload), + ).rstrip() + return None + + +def get_last_charge_status(payload: WildValue) -> Optional[str]: + return payload["data"]["attributes"]["last_charge_status"].tame(check_none_or(check_string)) + + +def get_patron_status(payload: WildValue) -> Optional[str]: + return payload["data"]["attributes"]["patron_status"].tame(check_none_or(check_string)) + + +def get_user_name(payload: WildValue) -> str: + return payload["data"]["attributes"]["full_name"].tame(check_string) + + +def get_pledge_amount(payload: WildValue) -> float: + return payload["data"]["attributes"]["currently_entitled_amount_cents"].tame(check_int) / 100 + + +def get_patron_count(payload: WildValue) -> int: + return payload["included"][0]["attributes"]["patron_count"].tame(check_int) + + +def get_pay_per_name(payload: WildValue) -> str: + return payload["included"][0]["attributes"]["pay_per_name"].tame(check_string) + + +EVENT_FUNCTION_MAPPER: Dict[str, Callable[[WildValue], Optional[str]]] = { + "members:create": get_members_create_body, + "members:update": get_members_update_body, + "members:delete": get_members_delete_body, + "members:pledge:create": get_members_pledge_create_body, + "members:pledge:update": get_members_pledge_update_body, + "members:pledge:delete": get_members_pledge_delete_body, +} + +# deprecated events +IGNORED_EVENTS = [ + "pledges:create", + "pledges:update", + "pledges:delete", +] + +ALL_EVENT_TYPES = list(EVENT_FUNCTION_MAPPER.keys()) + + +@webhook_view("Patreon", all_event_types=ALL_EVENT_TYPES) +@typed_endpoint +def api_patreon_webhook( + request: HttpRequest, + user_profile: UserProfile, + *, + payload: JsonBodyPayload[WildValue], +) -> HttpResponse: + header_event = validate_extract_webhook_http_header(request, "X-Patreon-Event", "Patreon") + + event_name = get_zulip_event_name(header_event, payload) + if event_name is None: + # See IGNORED_EVENTS. + return json_success(request) + topic = "membership notifications" + + body_function = EVENT_FUNCTION_MAPPER[event_name] + body = body_function(payload) + + if body is None: + # None for payloads that are valid, + # but where we intentionally do not send a message. + return json_success(request) + + check_send_webhook_message(request, user_profile, topic, body, event_name) + return json_success(request) + + +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 header_event + elif header_event in IGNORED_EVENTS: + return None + raise UnsupportedWebhookEventTypeError(header_event)
diff --git a/zerver/webhooks/patreon/tests.py b/zerver/webhooks/patreon/tests.py new file mode 100644 --- /dev/null +++ b/zerver/webhooks/patreon/tests.py @@ -0,0 +1,105 @@ +from unittest.mock import patch + +import orjson + +from zerver.lib.test_classes import WebhookTestCase + +EXPECTED_TOPIC = "membership notifications" +IGNORED_EVENTS = [ + "pledges:create", + "pledges:update", + "pledges:delete", +] + + +class PatreonHookTests(WebhookTestCase): + STREAM_NAME = "Patreon" + URL_TEMPLATE = "/api/v1/external/patreon?&api_key={api_key}&stream={stream}" + WEBHOOK_DIR_NAME = "patreon" + + def test_patreon_members_create(self) -> None: + expected_message = "Kopi has joined as a member!" + self.check_webhook( + "members_create", + EXPECTED_TOPIC, + expected_message, + ) + + def test_patreon_members_update(self) -> None: + expected_message = "Kopi's membership has been updated to active patron." + self.check_webhook( + "members_update", + EXPECTED_TOPIC, + expected_message, + ) + + def test_patreon_members_delete(self) -> None: + expected_message = "Kopi's membership has ended." + self.check_webhook( + "members_delete", + EXPECTED_TOPIC, + expected_message, + ) + + def test_patreon_members_pledge_create(self) -> None: + expected_message = "Kopi has pledged $5.00 per month. :tada:\nTotal number of patrons: 5" + self.check_webhook( + "members_pledge_create", + EXPECTED_TOPIC, + expected_message, + ) + + def test_patreon_members_pledge_update(self) -> None: + expected_message = "Kopi has updated their pledge to $10.00 per month. :gear:" + self.check_webhook( + "members_pledge_update", + EXPECTED_TOPIC, + expected_message, + ) + + def test_patreon_members_pledge_delete(self) -> None: + expected_message = ( + "Kopi's pledge has been cancelled. :cross_mark:\nTotal number of patrons: 4" + ) + self.check_webhook( + "members_pledge_delete", + EXPECTED_TOPIC, + expected_message, + ) + + def test_ignored_events(self) -> None: + # The payload for these events never gets looked at in the + # webhook itself; it only needs to be valid JSON. + payload = "{}" + + for event in IGNORED_EVENTS: + self.verify_post_is_ignored(payload, event) + + def test_ignored_payloads(self) -> None: + payload = orjson.loads(self.get_body("members_create")) + payload["data"]["attributes"]["last_charge_status"] = "Declined" + payload["data"]["attributes"]["patron_status"] = "declined_patron" + + event_types = [ + "members:create", + "members:update", + "members:delete", + "members:pledge:create", + "members:pledge:update", + "members:pledge:delete", + ] + + for event in event_types: + self.verify_post_is_ignored(orjson.dumps(payload).decode(), event) + + def verify_post_is_ignored(self, payload: str, http_x_patreon_event: str) -> None: + with patch("zerver.webhooks.patreon.view.check_send_webhook_message") as m: + result = self.client_post( + self.url, + payload, + HTTP_X_PATREON_EVENT=http_x_patreon_event, + content_type="application/json", + ) + if http_x_patreon_event in IGNORED_EVENTS: + self.assertFalse(m.called) + self.assert_json_success(result)
Create incoming webhook integration for Patreon Create an [incoming webhook](https://zulip.com/api/incoming-webhooks-overview) integration for Patreon. The main use case is getting notifications when new patrons sign up. Patreon webhook documentation: https://docs.patreon.com/#webhooks Now that [Zulip has a Patreon page](https://www.patreon.com/zulip), it would be great to be able to monitor new sign-ups!
Hello @zulip/server-integrations members, this issue was labeled with the "area: integrations" label, so you may want to check it out! <!-- areaLabelAddition --> i would be willing to work on this would this feature be used for internal use? @Sick-codes It will be used as an integration on all Zulip services. @zulipbot claim @drrosa You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! you can use this [link](https://www.patreon.com/portal/registration/register-webhooks) to create webhook on patreon when you have created your account. (someone who has a patreon account should handle the issue. ) You will need to `@zulipbot abandon` so somebody else can claim it. @ritikchauhan-01 @zulipbot abandon I have been following the repository for some time now, and feel like this would be a good first issue. Would it be possible for me to work on this without properly claiming it? I wouldn't want to discourage anyone else from fixing it if it could be done faster. I would just like to throw my hat in the ring. I tried setting up a basic [JSON integration](https://zulip.com/integrations/doc/json) to get sample data for this issue, and it seems that the Patreon outgoing webhook setup has a problem. In particular, it convert the URL to all-caps, which breaks it for us. I think the next step is probably to contact Patreon support about this, which I can do and post an update here once I hear back. Support request submitted. In the meantime, I sent sample data from all the non-deprecated event types here: https://webhook.site/#!/a6ed673f-a5c6-4c64-b292-13c71d0523f0/8f5f510b-a1f2-4145-a44b-037ceb15b2c3/1 @zulipbot claim Welcome to Zulip, @sudipto! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: * Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. * [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! I have created the webhook integration for Patreon using the webhook.site data posted here by @alya . Please check it once here: https://imgur.com/a/oHVDP8V I am open to suggestions if any. Also I haven't tested this with Patreon website. I don't have a patreon so if anyone can help me test that out. @sudipto have you created a PR for this? @adambirds not yet. I am new to opensource so a little hesitant in creating the PR. @sudipto in case you haven't found it yet, https://zulip.readthedocs.io/en/latest/git/using.html is a helpful reference. Patreon's support response on the URL capitalization issue (after a clarification): > I understand your report here and will share it with our engineers. Hello, I'm new to open source and i'm interested in solving this issue. Is this issue still open? @prah23 please let us know if you plan on finishing this so if not @akshatakulkarni25 can pick the work up instead. @adambirds @akshatakulkarni25 this is blocked on clarification from Patreon. The current actual webhook payload's structure is not reflected on the test webhook payloads they provide. I would be updating #22561 as clarification is provided. CZO discussion: https://chat.zulip.org/#narrow/stream/127-integrations/topic/Patreon.20Integration. Hello @alya , can I contribute to this issue, Is it open for me to work upon @zulipbot claim Welcome to Zulip, @komala777! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! Is this issue still open ? If an issue is open, its still open. @zulipbot claim Welcome to Zulip, @sachinsingh3107! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @zulipbot abandon @zulipbot claim **ERROR:** Unexpected response from GitHub API. @zulipbot claim **ERROR:** Unexpected response from GitHub API. I would like to work on this issue On Wed, Sep 27, 2023 at 8:41 PM zulipbot ***@***.***> wrote: > *ERROR:* Unexpected response from GitHub API. > > — > Reply to this email directly, view it on GitHub > <https://github.com/zulip/zulip/issues/18321#issuecomment-1737974053>, or > unsubscribe > <https://github.com/notifications/unsubscribe-auth/AIFAQETJ6CYCOWO2Y36ETWDX4R6NVANCNFSM4326YI7A> > . > You are receiving this because you commented.Message ID: > ***@***.***> > not interested. been assigned to a different one On Wed, Sep 27, 2023 at 8:42 PM Fahd Agodzo ***@***.***> wrote: > I would like to work on this issue > > On Wed, Sep 27, 2023 at 8:41 PM zulipbot ***@***.***> wrote: > >> *ERROR:* Unexpected response from GitHub API. >> >> — >> Reply to this email directly, view it on GitHub >> <https://github.com/zulip/zulip/issues/18321#issuecomment-1737974053>, >> or unsubscribe >> <https://github.com/notifications/unsubscribe-auth/AIFAQETJ6CYCOWO2Y36ETWDX4R6NVANCNFSM4326YI7A> >> . >> You are receiving this because you commented.Message ID: >> ***@***.***> >> > @zulipbot claim @zulipbot claim
2023-12-30T05:09:41
zulip/zulip
28,419
zulip__zulip-28419
[ "27796" ]
fe2d7a92b29b9d588b4ea54e58bd61bf891a740e
diff --git a/zerver/views/user_topics.py b/zerver/views/user_topics.py --- a/zerver/views/user_topics.py +++ b/zerver/views/user_topics.py @@ -15,8 +15,9 @@ access_stream_to_remove_visibility_policy_by_name, check_for_exactly_one_stream_arg, ) -from zerver.lib.validator import check_int, check_int_in, check_string_in +from zerver.lib.validator import check_capped_string, check_int, check_int_in, check_string_in from zerver.models import UserProfile, UserTopic +from zerver.models.constants import MAX_TOPIC_NAME_LENGTH def mute_topic( @@ -66,7 +67,7 @@ def update_muted_topic( user_profile: UserProfile, stream_id: Optional[int] = REQ(json_validator=check_int, default=None), stream: Optional[str] = REQ(default=None), - topic: str = REQ(), + topic: str = REQ(str_validator=check_capped_string(MAX_TOPIC_NAME_LENGTH)), op: str = REQ(str_validator=check_string_in(["add", "remove"])), ) -> HttpResponse: check_for_exactly_one_stream_arg(stream_id=stream_id, stream=stream) @@ -94,7 +95,7 @@ def update_user_topic( request: HttpRequest, user_profile: UserProfile, stream_id: int = REQ(json_validator=check_int), - topic: str = REQ(), + topic: str = REQ(str_validator=check_capped_string(MAX_TOPIC_NAME_LENGTH)), visibility_policy: int = REQ(json_validator=check_int_in(UserTopic.VisibilityPolicy.values)), ) -> HttpResponse: if visibility_policy == UserTopic.VisibilityPolicy.INHERIT:
diff --git a/zerver/tests/test_user_topics.py b/zerver/tests/test_user_topics.py --- a/zerver/tests/test_user_topics.py +++ b/zerver/tests/test_user_topics.py @@ -13,6 +13,7 @@ from zerver.lib.test_helpers import get_subscription from zerver.lib.user_topics import get_topic_mutes, topic_has_visibility_policy from zerver.models import UserProfile, UserTopic +from zerver.models.constants import MAX_TOPIC_NAME_LENGTH from zerver.models.streams import get_stream @@ -199,6 +200,12 @@ def test_muted_topic_add_invalid(self) -> None: result = self.api_patch(user, url, data) self.assert_json_error(result, "Please choose one: 'stream' or 'stream_id'.") + data = {"stream_id": stream.id, "topic": "a" * (MAX_TOPIC_NAME_LENGTH + 1), "op": "add"} + result = self.api_patch(user, url, data) + self.assert_json_error( + result, f"topic is too long (limit: {MAX_TOPIC_NAME_LENGTH} characters)" + ) + def test_muted_topic_remove_invalid(self) -> None: user = self.example_user("hamlet") realm = user.realm @@ -233,6 +240,12 @@ def test_muted_topic_remove_invalid(self) -> None: result = self.api_patch(user, url, data) self.assert_json_error(result, "Please choose one: 'stream' or 'stream_id'.") + data = {"stream_id": stream.id, "topic": "a" * (MAX_TOPIC_NAME_LENGTH + 1), "op": "remove"} + result = self.api_patch(user, url, data) + self.assert_json_error( + result, f"topic is too long (limit: {MAX_TOPIC_NAME_LENGTH} characters)" + ) + class MutedTopicsTests(ZulipTestCase): def test_get_deactivated_muted_topic(self) -> None: @@ -436,6 +449,17 @@ def test_muted_topic_add_invalid(self) -> None: result = self.api_post(user, url, data) self.assert_json_error(result, "Invalid stream ID") + stream = get_stream("Verona", user.realm) + data = { + "stream_id": stream.id, + "topic": "a" * (MAX_TOPIC_NAME_LENGTH + 1), + "visibility_policy": UserTopic.VisibilityPolicy.MUTED, + } + result = self.api_post(user, url, data) + self.assert_json_error( + result, f"topic is too long (limit: {MAX_TOPIC_NAME_LENGTH} characters)" + ) + def test_muted_topic_remove_invalid(self) -> None: user = self.example_user("hamlet") self.login_user(user) @@ -450,6 +474,17 @@ def test_muted_topic_remove_invalid(self) -> None: result = self.api_post(user, url, data) self.assert_json_error(result, "Invalid stream ID") + stream = get_stream("Verona", user.realm) + data = { + "stream_id": stream.id, + "topic": "a" * (MAX_TOPIC_NAME_LENGTH + 1), + "visibility_policy": UserTopic.VisibilityPolicy.INHERIT, + } + result = self.api_post(user, url, data) + self.assert_json_error( + result, f"topic is too long (limit: {MAX_TOPIC_NAME_LENGTH} characters)" + ) + class UnmutedTopicsTests(ZulipTestCase): def test_user_ids_unmuting_topic(self) -> None:
Topic length too long error in `bulk_set_user_topic_visibility_policy_in_database`. We received the following error log via sentry: > New exception: DataError: value too long for type character varying(60) > filename: zerver/lib/user_topics.py ```py Traceback: rows.filter(user_profile__in=user_profiles_seeking_visibility_policy_update).update( visibility_policy=visibility_policy, last_updated=last_updated ) if user_profiles_without_visibility_policy: ---> UserTopic.objects.bulk_create( UserTopic( user_profile=user_profile, stream_id=stream_id, recipient_id=recipient_id, topic_name=topic_name, ``` Update: To be explicit -- Ideally we'd have validated the topic length before getting here. We should debug which codepath is not validating and truncating topic name, hence resulted in this error.
## Issue: >The error log from Sentry indicates a DataError due to a value being too long for the 'topic_name' field, which is limited to 60 characters in the 'UserTopic' model. ## Solution: >It seems the 'topic_name' being set exceeds the character limit defined in the database schema. To address this, consider truncating or ensuring that the 'topic_name' input does not exceed 60 characters before creating the UserTopic objects. One possible approach: - Before creating UserTopic objects using bulk_create, truncate the 'topic_name' field to fit within the 60-character limit. - Example code snippet (assuming 'topic_name' needs truncation): ```python # Truncate 'topic_name' if it exceeds 60 characters topic_name = topic_name[:60] # Create UserTopic objects after truncation UserTopic.objects.bulk_create( UserTopic( user_profile=user_profile, stream_id=stream_id, recipient_id=recipient_id, topic_name=topic_name, # Additional fields if applicable ) @prakhar1144 You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! Hello @zulip/server-misc members, this issue was labeled with the "area: topics" label, so you may want to check it out! <!-- areaLabelAddition --> @zulipbot claim Hello @khanumar03! Thanks for your interest in Zulip! You have attempted to claim an issue without the label "help wanted". You can only claim and submit pull requests for issues with the [help wanted](https://github.com/zulip/zulip/issues?q=is%3Aopen+is%3Aissue+no%3Aassignee+label%3A%22help+wanted%22) label. If this is your first time here, we recommend reading our [guide for new contributors](https://zulip.readthedocs.io/en/latest/overview/contributing.html) before getting started. hi @CODEWITHRIZA I fixed this by using the textwrap module to truncate the topic name to 60 characters here is an example truncate_topic_name = textwrap.shorten(topic_name,width=60, placeholder="") is that all we have to do ? @zulipbot claim Hello @charu1603! Thanks for your interest in Zulip! You have attempted to claim an issue without the label "help wanted". You can only claim and submit pull requests for issues with the [help wanted](https://github.com/zulip/zulip/issues?q=is%3Aopen+is%3Aissue+no%3Aassignee+label%3A%22help+wanted%22) label. If this is your first time here, we recommend reading our [guide for new contributors](https://zulip.readthedocs.io/en/latest/overview/contributing.html) before getting started. hello @prakhar1144 @timabbott I am interested in solving this issue Can you please assign this issue to me ? Thank You : ) @Kota-Karthik This issue doesn't have a "help-wanted" label, so please consider working on other such issues. Thanks @prakhar1144 I am interested in working on this issue can you please assign me this? Thank You : )
2024-01-03T11:17:46
zulip/zulip
28,477
zulip__zulip-28477
[ "28412" ]
9c77300c5a0a6d7c03b1c08e870345f08436e117
diff --git a/zerver/actions/message_send.py b/zerver/actions/message_send.py --- a/zerver/actions/message_send.py +++ b/zerver/actions/message_send.py @@ -1530,8 +1530,10 @@ def check_private_message_policy( realm: Realm, sender: UserProfile, user_profiles: Sequence[UserProfile] ) -> None: if realm.private_message_policy == Realm.PRIVATE_MESSAGE_POLICY_DISABLED: - if sender.is_bot or (len(user_profiles) == 1 and user_profiles[0].is_bot): - # We allow direct messages only between users and bots, + if sender.is_bot or ( + len(user_profiles) == 1 and (user_profiles[0].is_bot or user_profiles[0] == sender) + ): + # We allow direct messages only between users and bots or to oneself, # to avoid breaking the tutorial as well as automated # notifications from system bots to users. return
diff --git a/zerver/tests/test_message_send.py b/zerver/tests/test_message_send.py --- a/zerver/tests/test_message_send.py +++ b/zerver/tests/test_message_send.py @@ -2613,6 +2613,73 @@ def test_ensure_stream_gets_called(self) -> None: # wasn't automatically created. Stream.objects.get(name=stream_name, realm_id=realm.id) + def test_direct_message_to_self_and_bot_in_dm_disabled_org(self) -> None: + """ + Test that a user can send a direct message to themselves and to a bot in a DM disabled organization + """ + sender = self.example_user("hamlet") + sender.realm.private_message_policy = Realm.PRIVATE_MESSAGE_POLICY_DISABLED + sender.realm.save() + + # Create a non-bot user + recipient_user = self.example_user("othello") + recipient_user.realm = sender.realm + + # Create a new bot user + bot = do_create_user( + email="[email protected]", + password="", + realm=sender.realm, + full_name="Test Bot", + bot_type=UserProfile.DEFAULT_BOT, + bot_owner=sender, + acting_user=None, + ) + + # Test sending a message to self + result = self.api_post( + sender, + "/api/v1/messages", + { + "type": "private", + "to": orjson.dumps([sender.id]).decode(), + "content": "Test message to self", + }, + ) + self.assert_json_success(result) + + msg = self.get_last_message() + expected = "Test message to self" + self.assertEqual(msg.content, expected) + + # Test sending a message to non-bot user + result = self.api_post( + sender, + "/api/v1/messages", + { + "type": "private", + "to": orjson.dumps([recipient_user.id]).decode(), + "content": "Test message", + }, + ) + self.assert_json_error(result, "Direct messages are disabled in this organization.") + + # Test sending a message to the bot + result = self.api_post( + sender, + "/api/v1/messages", + { + "type": "private", + "to": orjson.dumps([bot.id]).decode(), + "content": "Test message to bot", + }, + ) + self.assert_json_success(result) + + msg = self.get_last_message() + expected = "Test message to bot" + self.assertEqual(msg.content, expected) + class TestCrossRealmPMs(ZulipTestCase): def make_realm(self, domain: str) -> Realm:
Make it possible to send a DM to bots and to yourself when DMs are disabled <!-- Issue description --> Even when DMs are disabled, you should still be able to send a DM to bots and to yourself. We broke something about this at some point, though. Currently, with a bot: - Replying to a message works fine. - Starting a new conversation looks like it won't work, but you can actually do it if you send with the keyboard (the button is disabled). The tooltip on the disabled "Send" button also looks broken specifically when you're composing to a bot, probably because that button is actually supposed to be enabled, and we're in some weird intermediate state: <img width="888" alt="Screenshot-2023-12-18-at-1 35 05AM" src="https://github.com/zulip/zulip/assets/2090066/1469d6fe-9b1f-4c7f-9e72-fe621cf40715"> This bug is mainly because of the placement of ```check_posting_policy_for_compose_box``` method inside ```on_compose_select_recipient_update``` rather than ```update_on_recipient_change```, which is causing it to update the posting policy of compose only when you change the things in recipient dropdown, and not when you update the sender. <!-- Link to a message in the chat.zulip.org discussion. Message links will still work even if the topic is renamed or resolved. Link back to this issue from the chat.zulip.org thread. --> [CZO thread](https://chat.zulip.org/#narrow/stream/9-issues/topic/compose.20box.20tooltips.20lag.20.2327158/near/1705825)
@zulipbot claim
2024-01-07T06:17:08
zulip/zulip
28,556
zulip__zulip-28556
[ "28508" ]
a53aee714d5652c21afb059acda3362b1416d5ce
diff --git a/tools/linter_lib/custom_check.py b/tools/linter_lib/custom_check.py --- a/tools/linter_lib/custom_check.py +++ b/tools/linter_lib/custom_check.py @@ -879,7 +879,7 @@ "pattern": "[a-z][.][A-Z]", "description": "Likely missing space after end of sentence", "include_only": {"help/"}, - "exclude_pattern": "Rocket.Chat", + "exclude_pattern": "Rocket.Chat|org.zulip.Zulip", }, { "pattern": r"\b[rR]ealm[s]?\b",
Document flathub option for Zulip desktop apps on Linux See https://chat.zulip.org/#narrow/stream/19-documentation/topic/Linux.20Desktop.20App.20install.20options/near/1707537.
Hello @zulip/server-misc, @zulip/server-user-docs members, this issue was labeled with the "area: documentation (user)", "area: portico" labels, so you may want to check it out! <!-- areaLabelAddition --> @zulipbot claim
2024-01-12T17:05:37
zulip/zulip
28,558
zulip__zulip-28558
[ "28511" ]
c0a0c0e834bfa5934a1f0cce725ed8f002794f3c
diff --git a/zerver/migrations/0417_alter_customprofilefield_field_type.py b/zerver/migrations/0417_alter_customprofilefield_field_type.py --- a/zerver/migrations/0417_alter_customprofilefield_field_type.py +++ b/zerver/migrations/0417_alter_customprofilefield_field_type.py @@ -14,14 +14,14 @@ class Migration(migrations.Migration): name="field_type", field=models.PositiveSmallIntegerField( choices=[ - (1, "Short text"), - (2, "Long text"), - (4, "Date picker"), - (5, "Link"), + (4, "Date"), (7, "External account"), - (8, "Pronouns"), + (5, "Link"), (3, "List of options"), - (6, "Person picker"), + (8, "Pronouns"), + (2, "Text (long)"), + (1, "Text (short)"), + (6, "Users"), ], default=1, ), diff --git a/zerver/models/custom_profile_fields.py b/zerver/models/custom_profile_fields.py --- a/zerver/models/custom_profile_fields.py +++ b/zerver/models/custom_profile_fields.py @@ -94,7 +94,7 @@ class CustomProfileField(models.Model): (SELECT, gettext_lazy("List of options"), validate_select_field, str, "SELECT"), ] USER_FIELD_TYPE_DATA: List[UserFieldElement] = [ - (USER, gettext_lazy("Person picker"), check_valid_user_ids, orjson.loads, "USER"), + (USER, gettext_lazy("Users"), check_valid_user_ids, orjson.loads, "USER"), ] SELECT_FIELD_VALIDATORS: Dict[int, ExtendedValidator] = { @@ -106,9 +106,9 @@ class CustomProfileField(models.Model): FIELD_TYPE_DATA: List[FieldElement] = [ # Type, display name, validator, converter, keyword - (SHORT_TEXT, gettext_lazy("Short text"), check_short_string, str, "SHORT_TEXT"), - (LONG_TEXT, gettext_lazy("Long text"), check_long_string, str, "LONG_TEXT"), - (DATE, gettext_lazy("Date picker"), check_date, str, "DATE"), + (SHORT_TEXT, gettext_lazy("Text (short)"), check_short_string, str, "SHORT_TEXT"), + (LONG_TEXT, gettext_lazy("Text (long)"), check_long_string, str, "LONG_TEXT"), + (DATE, gettext_lazy("Date"), check_date, str, "DATE"), (URL, gettext_lazy("Link"), check_url, str, "URL"), ( EXTERNAL_ACCOUNT, @@ -120,7 +120,9 @@ class CustomProfileField(models.Model): (PRONOUNS, gettext_lazy("Pronouns"), check_short_string, str, "PRONOUNS"), ] - ALL_FIELD_TYPES = [*FIELD_TYPE_DATA, *SELECT_FIELD_TYPE_DATA, *USER_FIELD_TYPE_DATA] + ALL_FIELD_TYPES = sorted( + [*FIELD_TYPE_DATA, *SELECT_FIELD_TYPE_DATA, *USER_FIELD_TYPE_DATA], key=lambda x: x[1] + ) FIELD_VALIDATORS: Dict[int, Validator[ProfileDataElementValue]] = { item[0]: item[2] for item in FIELD_TYPE_DATA
diff --git a/web/e2e-tests/custom-profile.test.ts b/web/e2e-tests/custom-profile.test.ts --- a/web/e2e-tests/custom-profile.test.ts +++ b/web/e2e-tests/custom-profile.test.ts @@ -31,7 +31,7 @@ async function test_add_new_profile_field(page: Page): Promise<void> { ); assert.strictEqual( await common.get_text_from_selector(page, `${profile_field_row} span.profile_field_type`), - "Short text", + "Text (short)", ); } @@ -57,7 +57,7 @@ async function test_edit_profile_field(page: Page): Promise<void> { ); assert.strictEqual( await common.get_text_from_selector(page, `${profile_field_row} span.profile_field_type`), - "Short text", + "Text (short)", ); }
Rename and reorder custom profile field types <!-- Issue description --> In the custom profile field type dropdown, we should: 1. Make the following naming changes: * Short text -> Text (short) * Long text -> Text (long) * Date picker -> Date * Person picker -> Users 2. Order the fields alphabetically. Current menu: ![Screenshot 2024-01-09 at 3 12 38 PM](https://github.com/zulip/zulip/assets/2090066/e378f417-bd7c-49a3-abf0-833e1861fc5c) <!-- Link to a message in the chat.zulip.org discussion. Message links will still work even if the topic is renamed or resolved. Link back to this issue from the chat.zulip.org thread. --> [CZO thread](https://chat.zulip.org/#narrow/stream/137-feedback/topic/Improvements.20for.20Custom.20profile.20fields/near/1712583)
Hello @zulip/server-settings members, this issue was labeled with the "area: settings UI" label, so you may want to check it out! <!-- areaLabelAddition --> @zulipbot claim Hello @Pratik2026, it looks like you've currently claimed 1 issue in this repository. We encourage new contributors to focus their efforts on at most 1 issue at a time, so please complete your work on your other claimed issues before trying to claim this issue again. We look forward to your valuable contributions! @zulipbot claim Welcome to Zulip, @Kushdapush! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! Hi @Kushdapush , I think I have a solution if you end up not working on this, just let me know as I don't want to steal your issue
2024-01-13T01:22:48
zulip/zulip
28,647
zulip__zulip-28647
[ "23022" ]
4a2a9176c2787c1a5a1bb861e812faeddab30833
diff --git a/version.py b/version.py --- a/version.py +++ b/version.py @@ -33,7 +33,7 @@ # Changes should be accompanied by documentation explaining what the # new level means in api_docs/changelog.md, as well as "**Changes**" # entries in the endpoint's documentation in `zulip.yaml`. -API_FEATURE_LEVEL = 251 +API_FEATURE_LEVEL = 252 # Bump the minor PROVISION_VERSION to indicate that folks should provision # only when going from an old version of the code to a newer version. Bump diff --git a/zerver/actions/custom_profile_fields.py b/zerver/actions/custom_profile_fields.py --- a/zerver/actions/custom_profile_fields.py +++ b/zerver/actions/custom_profile_fields.py @@ -101,21 +101,34 @@ def remove_custom_profile_field_value_if_required( def try_update_realm_custom_profile_field( realm: Realm, field: CustomProfileField, - name: str, - hint: str = "", + name: Optional[str] = None, + hint: Optional[str] = None, field_data: Optional[ProfileFieldData] = None, - display_in_profile_summary: bool = False, - required: bool = False, + display_in_profile_summary: Optional[bool] = None, + required: Optional[bool] = None, ) -> None: - field.name = name - field.hint = hint - field.display_in_profile_summary = display_in_profile_summary - field.required = required - if field.field_type in (CustomProfileField.SELECT, CustomProfileField.EXTERNAL_ACCOUNT): - if field.field_type == CustomProfileField.SELECT: - assert field_data is not None + if name is not None: + field.name = name + if hint is not None: + field.hint = hint + if required is not None: + field.required = required + if display_in_profile_summary is not None: + field.display_in_profile_summary = display_in_profile_summary + + if field.field_type in ( + CustomProfileField.SELECT, + CustomProfileField.EXTERNAL_ACCOUNT, + ): + # If field_data is None, field_data is unchanged and there is no need for + # comparing field_data values. + if field_data is not None and field.field_type == CustomProfileField.SELECT: remove_custom_profile_field_value_if_required(field, field_data) - field.field_data = orjson.dumps(field_data or {}).decode() + + # If field.field_data is the default empty string, we will set field_data + # to an empty dict. + if field_data is not None or field.field_data == "": + field.field_data = orjson.dumps(field_data or {}).decode() field.save() notify_realm_custom_profile_fields(realm) diff --git a/zerver/views/custom_profile_fields.py b/zerver/views/custom_profile_fields.py --- a/zerver/views/custom_profile_fields.py +++ b/zerver/views/custom_profile_fields.py @@ -116,21 +116,55 @@ def validate_custom_profile_field( validate_display_in_profile_summary_field(field_type, display_in_profile_summary) +def validate_custom_profile_field_update( + field: CustomProfileField, + display_in_profile_summary: Optional[bool] = None, + field_data: Optional[ProfileFieldData] = None, + name: Optional[str] = None, + hint: Optional[str] = None, +) -> None: + if name is None: + name = field.name + if hint is None: + hint = field.hint + if field_data is None: + if field.field_data == "": + # We're passing this just for validation, sinec the function won't + # accept a string. This won't change the actual value. + field_data = {} + else: + field_data = orjson.loads(field.field_data) + if display_in_profile_summary is None: + display_in_profile_summary = field.display_in_profile_summary + + assert field_data is not None + validate_custom_profile_field( + name, + hint, + field.field_type, + field_data, + display_in_profile_summary, + ) + + check_profile_field_data: Validator[ProfileFieldData] = check_dict( value_validator=check_union([check_dict(value_validator=check_string), check_string]) ) def update_only_display_in_profile_summary( - requested_name: str, - requested_hint: str, - requested_field_data: ProfileFieldData, existing_field: CustomProfileField, + requested_field_data: Optional[ProfileFieldData] = None, + requested_name: Optional[str] = None, + requested_hint: Optional[str] = None, ) -> bool: if ( - requested_name != existing_field.name - or requested_hint != existing_field.hint - or requested_field_data != orjson.loads(existing_field.field_data) + (requested_name is not None and requested_name != existing_field.name) + or (requested_hint is not None and requested_hint != existing_field.hint) + or ( + requested_field_data is not None + and requested_field_data != orjson.loads(existing_field.field_data) + ) ): return False return True @@ -208,11 +242,13 @@ def update_realm_custom_profile_field( request: HttpRequest, user_profile: UserProfile, field_id: int, - name: str = REQ(default="", converter=lambda var_name, x: x.strip()), - hint: str = REQ(default=""), - field_data: ProfileFieldData = REQ(default={}, json_validator=check_profile_field_data), - display_in_profile_summary: bool = REQ(default=False, json_validator=check_bool), - required: bool = REQ(default=False, json_validator=check_bool), + name: Optional[str] = REQ(default=None, converter=lambda var_name, x: x.strip()), + hint: Optional[str] = REQ(default=None), + field_data: Optional[ProfileFieldData] = REQ( + default=None, json_validator=check_profile_field_data + ), + required: Optional[bool] = REQ(default=None, json_validator=check_bool), + display_in_profile_summary: Optional[bool] = REQ(default=None, json_validator=check_bool), ) -> HttpResponse: realm = user_profile.realm try: @@ -233,20 +269,21 @@ def update_realm_custom_profile_field( # of default external account types, but not any others. # # TODO: Make the name/hint/field_data parameters optional, and - # just require that None was passed for all of them for this case. + # explicitly require that the client passes None for all of them for this case. + # Right now, for name/hint/field_data we allow the client to send the existing + # values for the respective fields. After this TODO is done, we will only allow + # the client to pass None values if the field is unchanged. and is_default_external_field(field.field_type, orjson.loads(field.field_data)) - and not update_only_display_in_profile_summary(name, hint, field_data, field) + and not update_only_display_in_profile_summary(field, field_data, name, hint) ): raise JsonableError(_("Default custom field cannot be updated.")) - validate_custom_profile_field( - name, hint, field.field_type, field_data, display_in_profile_summary - ) + validate_custom_profile_field_update(field, display_in_profile_summary, field_data, name, hint) try: try_update_realm_custom_profile_field( - realm, - field, - name, + realm=realm, + field=field, + name=name, hint=hint, field_data=field_data, display_in_profile_summary=display_in_profile_summary,
diff --git a/zerver/tests/test_custom_profile_data.py b/zerver/tests/test_custom_profile_data.py --- a/zerver/tests/test_custom_profile_data.py +++ b/zerver/tests/test_custom_profile_data.py @@ -494,7 +494,6 @@ def test_update(self) -> None: result = self.client_patch( f"/json/realm/profile_fields/{field.id}", info={ - "name": "New phone number", "hint": "*" * 81, }, ) @@ -504,8 +503,6 @@ def test_update(self) -> None: result = self.client_patch( f"/json/realm/profile_fields/{field.id}", info={ - "name": "New phone number", - "hint": "New contact number", "display_in_profile_summary": "invalid value", }, ) @@ -515,8 +512,6 @@ def test_update(self) -> None: result = self.client_patch( f"/json/realm/profile_fields/{field.id}", info={ - "name": "New phone number", - "hint": "New contact number", "required": "invalid value", }, ) @@ -533,8 +528,7 @@ def test_update(self) -> None: }, ) self.assert_json_success(result) - - field = CustomProfileField.objects.get(id=field.id, realm=realm) + field.refresh_from_db() self.assertEqual(CustomProfileField.objects.count(), self.original_count) self.assertEqual(field.name, "New phone number") self.assertEqual(field.hint, "New contact number") @@ -542,6 +536,18 @@ def test_update(self) -> None: self.assertEqual(field.display_in_profile_summary, True) self.assertEqual(field.required, True) + # Not sending required should not set it to false. + result = self.client_patch( + f"/json/realm/profile_fields/{field.id}", + info={ + "hint": "New hint", + }, + ) + self.assert_json_success(result) + field.refresh_from_db() + self.assertEqual(field.hint, "New hint") + self.assertEqual(field.required, True) + result = self.client_patch( f"/json/realm/profile_fields/{field.id}", info={"name": "Name ", "display_in_profile_summary": "true"}, @@ -554,7 +560,7 @@ def test_update(self) -> None: field = CustomProfileField.objects.get(name="Favorite editor", realm=realm) result = self.client_patch( f"/json/realm/profile_fields/{field.id}", - info={"name": "Favorite editor", "field_data": "invalid"}, + info={"field_data": "invalid"}, ) self.assert_json_error(result, 'Argument "field_data" is not valid JSON.') @@ -566,7 +572,7 @@ def test_update(self) -> None: ).decode() result = self.client_patch( f"/json/realm/profile_fields/{field.id}", - info={"name": "Favorite editor", "field_data": field_data}, + info={"field_data": field_data}, ) self.assert_json_error(result, "field_data is not a dict") @@ -580,19 +586,28 @@ def test_update(self) -> None: result = self.client_patch( f"/json/realm/profile_fields/{field.id}", info={ - "name": "Favorite editor", "field_data": field_data, "display_in_profile_summary": "true", }, ) self.assert_json_success(result) + # Not sending display_in_profile_summary should not set it to false. + result = self.client_patch( + f"/json/realm/profile_fields/{field.id}", + info={ + "hint": "Fav editor", + }, + ) + field.refresh_from_db() + self.assertEqual(field.hint, "Fav editor") + self.assertEqual(field.display_in_profile_summary, True) + self.assert_json_success(result) + field = CustomProfileField.objects.get(name="Birthday", realm=realm) result = self.client_patch( f"/json/realm/profile_fields/{field.id}", info={ - "name": field.name, - "hint": field.hint, "display_in_profile_summary": "true", }, ) @@ -600,6 +615,26 @@ def test_update(self) -> None: result, "Only 2 custom profile fields can be displayed in the profile summary." ) + # Empty string for hint should set it to an empty string + result = self.client_patch( + f"/json/realm/profile_fields/{field.id}", + info={"hint": ""}, + ) + self.assert_json_success(result) + field.refresh_from_db() + self.assertEqual(field.hint, "") + + field = CustomProfileField.objects.get(name="Favorite editor", realm=realm) + + # Empty field_data should not be allowed + result = self.client_patch( + f"/json/realm/profile_fields/{field.id}", + info={ + "field_data": {}, + }, + ) + self.assert_json_error(result, "Field must have at least one choice.") + def test_update_is_aware_of_uniqueness(self) -> None: self.login("iago") realm = get_realm("zulip") diff --git a/zerver/tests/test_events.py b/zerver/tests/test_events.py --- a/zerver/tests/test_events.py +++ b/zerver/tests/test_events.py @@ -1390,7 +1390,11 @@ def test_custom_profile_fields_events(self) -> None: events = self.verify_action( lambda: try_update_realm_custom_profile_field( - realm, field, name, hint=hint, display_in_profile_summary=display_in_profile_summary + realm=realm, + field=field, + name=name, + hint=hint, + display_in_profile_summary=display_in_profile_summary, ) ) check_custom_profile_fields("events[0]", events[0]) @@ -1416,7 +1420,9 @@ def test_pronouns_type_support_in_custom_profile_fields_events(self) -> None: hint = "What pronouns should people use to refer you?" events = self.verify_action( - lambda: try_update_realm_custom_profile_field(realm, field, name, hint=hint), + lambda: try_update_realm_custom_profile_field( + realm=realm, field=field, name=name, hint=hint + ), pronouns_field_type_supported=False, ) check_custom_profile_fields("events[0]", events[0])
Change the API endpoint of custom profile fields to not have the name/hint/etc. Change the API endpoint of custom profile fields to not have the name/hint/etc. to be passed in a request as mandatory, instead of supporting passing them as optional. _Originally posted by @timabbott in https://github.com/zulip/zulip/issues/21588#issuecomment-1253017422_
@zulipbot claim Hello @otemitay! Thanks for your interest in Zulip! You have attempted to claim an issue without the label "help wanted". You can only claim and submit pull requests for issues with the [help wanted](https://github.com/zulip/zulip/issues?q=is%3Aopen+is%3Aissue+no%3Aassignee+label%3A%22help+wanted%22) label. If this is your first time here, we recommend reading our [guide for new contributors](https://zulip.readthedocs.io/en/latest/overview/contributing.html) before getting started. Hello @zulip/server-api members, this issue was labeled with the "area: api" label, so you may want to check it out! <!-- areaLabelAddition --> @zulipbot claim Welcome to Zulip, @gopivaibhav! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @gopivaibhav You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! @zulipbot claim Welcome to Zulip, @dhruv-goyal-10! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @dhruv-goyal-10 You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! @yogesh-sirsat @timabbott Can I request more context on this issue? Why do we want to make this change and what is the expected end result. (Note: I wasn't able to find the convo related this on CZO that the other PR mentions, so asking here) For the `PATCH /realm/profile_fields/{field.id}` endpoint, it is required to pass `name` and `hint` fields in the request data even if we want to change some other field like `display_in_profile_summary`. I have not tested the behavior on not passing these fields - but from reading the code I think the behavior is - 1) If we do not pass `name` in request data, an error will be raised because we do not allow empty names. 2) If we do not pass `hint` in request data, the `hint` field for the custom profile field becomes empty string. Instead the API should behave that if any of the fields is not present in the request data, then they should remain same as before like what we do for most of the other endpoints, like `PATCH /realm` endpoint for updating realm settings. Thanks Sahil ! @zulipbot claim @shubham-padia You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks!
2024-01-20T06:19:52
zulip/zulip
28,775
zulip__zulip-28775
[ "28758" ]
0e6f013e03a2033d0660b841e1050f6f7fe9be3d
diff --git a/zerver/lib/url_redirects.py b/zerver/lib/url_redirects.py --- a/zerver/lib/url_redirects.py +++ b/zerver/lib/url_redirects.py @@ -81,6 +81,7 @@ class URLRedirect: URLRedirect("/help/reading-topics", "/help/reading-conversations"), URLRedirect("/help/finding-a-topic-to-read", "/help/finding-a-conversation-to-read"), URLRedirect("/help/view-and-browse-images", "/help/view-images-and-videos"), + URLRedirect("/help/bots-and-integrations", "/help/bots-overview"), ] LANDING_PAGE_REDIRECTS = [
Improve integrations documentation in help center We should: - Rename /help/bots-and-integrations to "Bots overview" everywhere (sidebar, page title, page URL). - Add a copy of https://zulip.com/api/integrations-overview as the second page in the Bots & integrations section, titled "Integration overview" - Cross-link as appropriate, both in related articles and in the content of the pages.
Hello @zulip/server-api, @zulip/server-user-docs members, this issue was labeled with the "area: documentation (user)", "area: documentation (api and integrations)" labels, so you may want to check it out! <!-- areaLabelAddition --> @drrosa Are you up for taking care of this one? There are probably other improvements we could do, but this seems like a nice easy one.
2024-01-31T22:31:31
zulip/zulip
28,937
zulip__zulip-28937
[ "27601" ]
80a6b12690fc664a724d0a8ced3960431f3ccabb
diff --git a/zerver/webhooks/slack/view.py b/zerver/webhooks/slack/view.py --- a/zerver/webhooks/slack/view.py +++ b/zerver/webhooks/slack/view.py @@ -1,13 +1,14 @@ +from typing import Optional + from django.http import HttpRequest from django.http.response import HttpResponse from django.utils.translation import gettext as _ -from zerver.actions.message_send import check_send_stream_message from zerver.decorator import webhook_view from zerver.lib.exceptions import JsonableError -from zerver.lib.request import RequestNotes from zerver.lib.response import json_success from zerver.lib.typed_endpoint import typed_endpoint +from zerver.lib.webhooks.common import check_send_webhook_message from zerver.models import UserProfile ZULIP_MESSAGE_TEMPLATE = "**{message_sender}**: {text}" @@ -23,20 +24,39 @@ def api_slack_webhook( user_name: str, text: str, channel_name: str, - stream: str = "slack", - channels_map_to_topics: str = "1", + channels_map_to_topics: Optional[str] = None, ) -> HttpResponse: - if channels_map_to_topics not in VALID_OPTIONS.values(): - raise JsonableError(_("Error: channels_map_to_topics parameter other than 0 or 1")) + content = ZULIP_MESSAGE_TEMPLATE.format(message_sender=user_name, text=text) + topic_name = "Message from Slack" - if channels_map_to_topics == VALID_OPTIONS["SHOULD_BE_MAPPED"]: + if channels_map_to_topics is None: + check_send_webhook_message( + request, + user_profile, + topic_name, + content, + ) + elif channels_map_to_topics == VALID_OPTIONS["SHOULD_BE_MAPPED"]: + # If the webhook URL has a user_specified_topic, + # then this topic-channel mapping will not be used. topic_name = f"channel: {channel_name}" + check_send_webhook_message( + request, + user_profile, + topic_name, + content, + ) + elif channels_map_to_topics == VALID_OPTIONS["SHOULD_NOT_BE_MAPPED"]: + # This stream-channel mapping will be used even if + # there is a stream specified in the webhook URL. + check_send_webhook_message( + request, + user_profile, + topic_name, + content, + stream=channel_name, + ) else: - stream = channel_name - topic_name = _("Message from Slack") + raise JsonableError(_("Error: channels_map_to_topics parameter other than 0 or 1")) - content = ZULIP_MESSAGE_TEMPLATE.format(message_sender=user_name, text=text) - client = RequestNotes.get_notes(request).client - assert client is not None - check_send_stream_message(user_profile, client, stream, topic_name, content) return json_success(request)
diff --git a/zerver/webhooks/slack/tests.py b/zerver/webhooks/slack/tests.py --- a/zerver/webhooks/slack/tests.py +++ b/zerver/webhooks/slack/tests.py @@ -2,31 +2,71 @@ from zerver.lib.test_classes import WebhookTestCase +EXPECTED_TOPIC = "Message from Slack" +EXPECTED_MESSAGE = "**slack_user**: test" + class SlackWebhookTests(WebhookTestCase): STREAM_NAME = "slack" URL_TEMPLATE = "/api/v1/external/slack?stream={stream}&api_key={api_key}" WEBHOOK_DIR_NAME = "slack" - def test_slack_channel_to_topic(self) -> None: + def test_slack_only_stream_parameter(self) -> None: + self.check_webhook( + "message_info", + EXPECTED_TOPIC, + EXPECTED_MESSAGE, + content_type="application/x-www-form-urlencoded", + ) + + def test_slack_with_user_specified_topic(self) -> None: + self.url = self.build_webhook_url(topic="test") + expected_topic_name = "test" + self.check_webhook( + "message_info", + expected_topic_name, + EXPECTED_MESSAGE, + content_type="application/x-www-form-urlencoded", + ) + + def test_slack_channels_map_to_topics_true(self) -> None: + self.url = self.build_webhook_url(channels_map_to_topics="1") expected_topic_name = "channel: general" - expected_message = "**slack_user**: test" self.check_webhook( "message_info", expected_topic_name, - expected_message, + EXPECTED_MESSAGE, + content_type="application/x-www-form-urlencoded", + ) + + def test_slack_channels_map_to_topics_true_and_user_specified_topic(self) -> None: + self.url = self.build_webhook_url(topic="test", channels_map_to_topics="1") + expected_topic_name = "test" + self.check_webhook( + "message_info", + expected_topic_name, + EXPECTED_MESSAGE, + content_type="application/x-www-form-urlencoded", + ) + + def test_slack_channels_map_to_topics_false(self) -> None: + self.STREAM_NAME = "general" + self.url = self.build_webhook_url(channels_map_to_topics="0") + self.check_webhook( + "message_info", + EXPECTED_TOPIC, + EXPECTED_MESSAGE, content_type="application/x-www-form-urlencoded", ) - def test_slack_channel_to_stream(self) -> None: + def test_slack_channels_map_to_topics_false_and_user_specified_topic(self) -> None: self.STREAM_NAME = "general" - self.url = "{}{}".format(self.url, "&channels_map_to_topics=0") - expected_topic_name = "Message from Slack" - expected_message = "**slack_user**: test" + self.url = self.build_webhook_url(topic="test", channels_map_to_topics="0") + expected_topic_name = "test" self.check_webhook( "message_info", expected_topic_name, - expected_message, + EXPECTED_MESSAGE, content_type="application/x-www-form-urlencoded", ) @@ -50,7 +90,7 @@ def test_missing_data_text(self) -> None: def test_invalid_channels_map_to_topics(self) -> None: payload = self.get_body("message_info") - url = "{}{}".format(self.url, "&channels_map_to_topics=abc") + url = self.build_webhook_url(channels_map_to_topics="abc") result = self.client_post(url, payload, content_type="application/x-www-form-urlencoded") self.assert_json_error(result, "Error: channels_map_to_topics parameter other than 0 or 1")
Update Slack integration to use `check_send_webhook_message`. The current Slack integration documented at https://zulip.com/integrations/doc/slack was never updated to use `check_send_webhook_message` as part of its implementation (see [`zerver/webhooks/slack/view.py`](https://github.com/zulip/zulip/blob/main/zerver/webhooks/slack/view.py)). How to handle the `channels_map_to_topics` parameter implemented in this Slack webhook probably merits a discussion in the [# integrations](https://chat.zulip.org/#narrow/stream/127-integrations) stream on chat.zulip.org. CZO thread: https://chat.zulip.org/#narrow/stream/9-issues/topic/slack.20webhook.20bug/near/1655623
Hello @zulip/server-integrations members, this issue was labeled with the "area: integrations" label, so you may want to check it out! <!-- areaLabelAddition --> @zulipbot claim Hello @Rahulr2101, it looks like you've currently claimed 1 issue in this repository. We encourage new contributors to focus their efforts on at most 1 issue at a time, so please complete your work on your other claimed issues before trying to claim this issue again. We look forward to your valuable contributions! @zulipbot claim Welcome to Zulip, @AlexiusTatius! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! Hey @laurynmm, I've been working on the code changes for the assigned Slack integration issue and have been using the [commit](https://github.com/zulip/zulip/commit/a4979410f983e7aaa10f4833a9c302110bea685c) as a reference for making the necessary changes. However, before proceeding with the changes, I wanted to test the existing behavior on my local server. I successfully spun up the Zulip server locally using this [guide]( https://zulip.readthedocs.io/en/latest/development/setup-recommended.html#windows-10-or-11 ), but when I attempt to introduce an "outgoing webhook" for my Zulip app from Slack, the local Zulip app is not receiving any messages from Slack. On the other hand, when I set up an outgoing hook from Slack to the actual Zulip server (chat.zulip.org), the webhook functions as expected. For your reference, here is the outgoing hook API key configuration I have set up for my local Zulip instance: ![outgoing_Webhooks](https://github.com/zulip/zulip/assets/96935985/134bc335-bb9a-4f86-bf43-573ea438a62c) The above configuration is expected to publish the message to the Zulip server hosted on localhost at port 9991 in the test channel. However, it's not working as expected. Could you please suggest a possible way to test the changes locally? Your assistance would greatly help in progressing with the issue. Additionally, I attempted to refer to the documentation for Zulip-Slack integration at this [link](https://zulip.com/integrations/doc/slack). Unfortunately, no text is getting rendered on this link now, whereas I distinctly remember it was rendering properly two days ago. Can you help me with this as well. Thank you for your attention to these matters. Looking forward to your guidance and support. @AlexiusTatius I recommend asking for help in the [Zulip development community](https://zulip.com/development-community/), where more people will see your question. Sure, I'll reach out in the zulip community Thank you! @AlexiusTatius - Just checking in to see if you'd made progress on this issue and will be putting up a PR soon as this is one of the issues being tracked for the upcoming 8.0 release. @laurynmm - Yes I've been working on the issue and will soon put up the PR. Could you please provide information on the expected release date for the 8.0 version? You can follow the [# release management stream](https://chat.zulip.org/#narrow/stream/438-release-management) on chat.zulip.org for up-to-date information. Hey @laurynmm, Apologies for my delayed response—I've been swamped with semester exams at university. Regarding the migration of Slack from `check_send_stream_message` to `check_send_webhook_message` in the Integrations Developer Panel, I've run into an issue during testing. The error "missing ‘user_name’ argument" is coming up. You can check out the screenshot of the error here. ![Integration Testing](https://github.com/zulip/zulip/assets/96935985/e2c14000-bd1f-44e7-81e5-e714ec816525) I suspect there's an issue with the fixture body, seemingly created for a Slack team associated with gsoc 2017. I also tried creating a new webhook without specifying a URL. Should I define the URL where the outgoing webhook should send the data? ![outgoing_webhook_without_url](https://github.com/zulip/zulip/assets/96935985/02faf4d5-3bda-4dfa-9adc-122d8cbe8ae2) Even after creating my fixture using the token from the outgoing webhook (g5uxoQHojGenqdJVlJ54xLBL), some terms like team_id=T0001, team_domain=example, user_name=steve seem to default. I've figured out my channel_id and user_id, but I'm unsure about channel_name, user_name, text, team_id. Any suggestions? ![outgoing_webhook_config](https://github.com/zulip/zulip/assets/96935985/02a7eda3-d8cb-4f5c-8150-5d67d305cd00) I went through the CZO thread https://chat.zulip.org/#narrow/stream/9-issues/topic/slack.20webhook.20bug/near/1655623 and have a basic grasp of the highlighted issue. Could you suggest some ideas on managing the `channels_map_to_topics` variable to prevent the creation of a new topic if the "topic" variable is mentioned in the URL? Thanks for your help! Mehtab @AlexiusTatius You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! Yes, I've been working on the issue. Very sorry for the delay because my semester exams were holding me back. @zulipbot claim @laurynmm I have solved the issue I migrated the slack webhook from `check_send_stream_message ` to `check_send_webhook_message`. I checked it on integration dev panel, now whenever the client mentions a new topic, the message gets delivered to that particular topic. For example, if I now mention the `topic name` as `topic_1` then zulip would display it as: ![1_solved_topic](https://github.com/zulip/zulip/assets/96935985/352c8ac6-7c9c-4c5b-aa57-f8028ba97b6f) If we don’t specify the specify the topic then zulip would simply pick up the channel name of the slack. ![2_solved_topic](https://github.com/zulip/zulip/assets/96935985/253123ec-fa44-46f5-b010-075ed9ec8efc) But there is only one thing that I wanted to ask, that was: When I was testing the changes on the integration developer panel, the query parameters which I added in the URL of the API endpoint, were added manually. What I mean is, when I specify the `Bot`, the `Integration`, the `Fixture`, the `stream` and the `Topic` I get the following `URL` generated: ![3_solved_topic](https://github.com/zulip/zulip/assets/96935985/cf79fe00-dbad-4fd4-992f-918734e2acc8) I added the following query parameters manually `&user_name=mehtabsinghcse&text=web_bruh+1st+Text+sent&channel_name=zulip_web_local_host` Only then the slack webhook works properly, else it shows error of `Result: (400) Missing ‘user_name’ argument` One thing to note is that, when I send a message to the `test here` stream of `chat.zulip.org`. from slack using the outgoing webhook the message gets sent successfully. ![4_solved_topic](https://github.com/zulip/zulip/assets/96935985/b1d4703c-27b2-4d74-8786-899993f68c68) The above screenshot is from `chat.zulip.org` I believe that the changes I made would work for the production as well (as evident by the above screenshot), so there would be no need to alter the query parameters for the production. I wanted to ask whether I should fix the query parameters for the integration testing as well or shall I raise the pull request? @AlexiusTatius - I feel like you should open a pull request with your changes as it's hard to understand what the issue you're still running into at this point from the information above. Looking at https://github.com/zulip/zulip/blob/main/zerver/webhooks/slack/view.py, the `user_name` and `text` parameters are used to construct the message content and are likely expected in the payload from Slack. @laurynmm I've raised the pull request > Hey @laurynmm, I've been working on the code changes for the assigned Slack integration issue and have been using the [commit](https://github.com/zulip/zulip/commit/a4979410f983e7aaa10f4833a9c302110bea685c) as a reference for making the necessary changes. However, before proceeding with the changes, I wanted to test the existing behavior on my local server. I successfully spun up the Zulip server locally using this [guide](https://zulip.readthedocs.io/en/latest/development/setup-recommended.html#windows-10-or-11), but when I attempt to introduce an "outgoing webhook" for my Zulip app from Slack, the local Zulip app is not receiving any messages from Slack. On the other hand, when I set up an outgoing hook from Slack to the actual Zulip server (chat.zulip.org), the webhook functions as expected. For your reference, here is the outgoing hook API key configuration I have set up for my local Zulip instance: ![outgoing_Webhooks](https://private-user-images.githubusercontent.com/96935985/282293760-134bc335-bb9a-4f86-bf43-573ea438a62c.png?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTEiLCJleHAiOjE3MDM0Mjk5OTksIm5iZiI6MTcwMzQyOTY5OSwicGF0aCI6Ii85NjkzNTk4NS8yODIyOTM3NjAtMTM0YmMzMzUtYmI5YS00Zjg2LWJmNDMtNTczZWE0MzhhNjJjLnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFJV05KWUFYNENTVkVINTNBJTJGMjAyMzEyMjQlMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjMxMjI0VDE0NTQ1OVomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPTg2NTQ3ZGM4YzBjNjJlZDRjYzE3ZjFiMGIwOTA2NWFlOWNiMDIzOGEzNzQ0MjVjMTRhNjAyZjA5YTc3ZjU1ZDAmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0JmFjdG9yX2lkPTAma2V5X2lkPTAmcmVwb19pZD0wIn0.8cA0XFvN3aTBZekvjfKeK26f6UWSaq81Glpzl6zqUjY) > > The above configuration is expected to publish the message to the Zulip server hosted on localhost at port 9991 in the test channel. However, it's not working as expected. Could you please suggest a possible way to test the changes locally? Your assistance would greatly help in progressing with the issue. Additionally, I attempted to refer to the documentation for Zulip-Slack integration at this [link](https://zulip.com/integrations/doc/slack). Unfortunately, no text is getting rendered on this link now, whereas I distinctly remember it was rendering properly two days ago. Can you help me with this as well. Thank you for your attention to these matters. Looking forward to your guidance and support. Hello @AlexiusTatius , I have been facing the same issue while working on some other issues for quite a while. It would be really great if you could tell me how did you resolve this issue. Thanks. @shashank-23002 Yeah sure! Basically, the slack outgoing webhook cannot be given a local address, "localhost:9991", because `localhost:9991` is a URL that is only going to resolve to computer on your computer, and on Slack's computer, it resolves to their own server's port 9991. So, if your issue is related testing webhooks by capturing payloads, you should use the `integration dev panel` of zulip. When you host your website you shall get this below link: http://localhost:9991/devtools/integrations/ for testing the webhook integrations. https://zulip.com/api/incoming-webhooks-overview Checkout the above link and related documentation for how to test webhooks by capturing payloads. @zulipbot abandon @zulipbot claim Welcome to Zulip, @Sadaf-A! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @Sadaf-A Thank you for finding this issue. But I've already, solved and raised a pull request for this issue and it is waiting to get reviewed. Can you look for another issue? You can review my pull request and suggest changes too. Thanks :) > @Sadaf-A Thank you for finding this issue. But I've already, solved and raised a pull request for this issue and it is waiting to get reviewed. Can you look for another issue? > You can review my pull request and suggest changes too. Thanks :) I'm sorry you abandoned it so I thought it's up for contribution @zulipbot abandon > > @Sadaf-A Thank you for finding this issue. But I've already, solved and raised a pull request for this issue and it is waiting to get reviewed. Can you look for another issue? > > You can review my pull request and suggest changes too. Thanks :) > > I'm sorry you abandoned it so I thought it's up for contribution No problem :)
2024-02-15T14:53:16
zulip/zulip
28,952
zulip__zulip-28952
[ "28881" ]
e4e65074dfbb782be88164bc40388cdf7c6b818c
diff --git a/zerver/lib/markdown/tabbed_sections.py b/zerver/lib/markdown/tabbed_sections.py --- a/zerver/lib/markdown/tabbed_sections.py +++ b/zerver/lib/markdown/tabbed_sections.py @@ -112,6 +112,8 @@ "v6": "Zulip Server 6.0+", "v4": "Zulip Server 4.0+", "all-versions": "All versions", + "for-a-bot": "For a bot", + "for-yourself": "For yourself", }
Add instructions to download .zuliprc file https://zulip.com/api/configuring-python-bindings describes .zuliprc files, but does not give instructions for where download them. We should fix this. - [ ] Add instructions for downloading a bot's .zuliprc file and your .zuliprc file to https://zulip.com/api/configuring-python-bindings. We'll might want to add some section headings to this page as part of this change. The instructions should have tabs for downloading the file for a bot vs. for yourself. - [ ] Your own .zuliprc file is downloaded via the "Show/change your API key" on SETTINGS / ACCOUNT & PRIVACY. While we're here, let's rename that button to "Manage your API key".
Hello @zulip/server-api members, this issue was labeled with the "area: documentation (api and integrations)" label, so you may want to check it out! <!-- areaLabelAddition --> @drrosa Another API documentation tweak. :)
2024-02-16T00:45:47
zulip/zulip
29,008
zulip__zulip-29008
[ "28885" ]
ac47f85a34a1abb79d361678992eefcb51d4d3be
diff --git a/zerver/lib/markdown/tabbed_sections.py b/zerver/lib/markdown/tabbed_sections.py --- a/zerver/lib/markdown/tabbed_sections.py +++ b/zerver/lib/markdown/tabbed_sections.py @@ -46,6 +46,8 @@ "mac": "macOS", "windows": "Windows", "linux": "Linux", + "most-systems": "Most systems", + "linux-with-apt": "Linux with APT", "python": "Python", "js": "JavaScript", "curl": "curl",
Clean up beta app installation instructions Following up on #28884, we should convert the beta app installation instructions into our standard tabbed instructions format. I'm not sure about the best tab labels. Perhaps something like this? - Most systems - Linux with APT
Hello @zulip/server-user-docs members, this issue was labeled with the "area: documentation (user)" label, so you may want to check it out! <!-- areaLabelAddition --> We should also probably just say "Debian" rather than "Debian 8+", given that Debian 7 is old enough to not be relevant anymore. @drrosa We noticed that you have not made any updates to this issue or linked PRs for 10 days. Please comment here if you are still actively working on it. Otherwise, we'd appreciate a quick `@zulipbot abandon` comment so that someone else can claim this issue and continue from where you left off. If we don't hear back, you will be automatically unassigned in 4 days. Thanks! <!-- inactiveWarning -->
2024-02-21T02:29:04
zulip/zulip
29,029
zulip__zulip-29029
[ "26969" ]
9a12d1798ea84d1663507272b48a37e4d9f18cf8
diff --git a/version.py b/version.py --- a/version.py +++ b/version.py @@ -48,4 +48,4 @@ # historical commits sharing the same major version, in which case a # minor version bump suffices. -PROVISION_VERSION = (261, 0) +PROVISION_VERSION = (262, 2)
`:flag scotland:` shows Seychelles flag **Describe the bug** The `:flag scotland:` emoji seems to show the flag of Seychelles instead of that of Scotland. **To Reproduce** Type `:flag scotland:` in the Zulip desktop client - this also occurs when reading messages. **Expected behavior** The Scottish flag (white X on blue background) should show. **Screenshots** ![image](https://github.com/zulip/zulip-desktop/assets/57840981/ca55e8e8-f726-4051-9c19-06e06595fed3) - Operating System: Reproduced on Arch Linux 6.5.4, Manjaro, Windows 10 and MacOS (all different machines) so does not seem to be OS specific! Fine on mobile though - Zulip Desktop Version: Reproduced on 5.10.2 and 5.10.3
Hello @zulip/server-emoji members, this issue was labeled with the "area: emoji" label, so you may want to check it out! <!-- areaLabelAddition --> This is a bug in the [emoji-datasource](https://www.npmjs.com/package/emoji-datasource) library. It can also be seen at https://projects.iamcal.com/emoji-data/table.htm (warning: very big page, may slow down your browser). Opened - iamcal/emoji-data#231. Amazing, thanks for debugging so quickly @andersk!!
2024-02-22T20:06:51
zulip/zulip
29,140
zulip__zulip-29140
[ "28928" ]
b4f95a54e1175341bf8afd6be3c74d9204fc8b8f
diff --git a/analytics/lib/counts.py b/analytics/lib/counts.py --- a/analytics/lib/counts.py +++ b/analytics/lib/counts.py @@ -797,6 +797,7 @@ def get_count_stats(realm: Optional[Realm] = None) -> Dict[str, CountStat]: # In RealmCount, 'active_users_audit:is_bot:day' should be the partial # sum sequence of 'active_users_log:is_bot:day', for any realm that # started after the latter stat was introduced. + # Included in LOGGING_COUNT_STAT_PROPERTIES_NOT_SENT_TO_BOUNCER. LoggingCountStat("active_users_log:is_bot:day", RealmCount, CountStat.DAY), # Another sanity check on 'active_users_audit:is_bot:day'. Is only an # approximation, e.g. if a user is deactivated between the end of the @@ -843,13 +844,15 @@ def get_count_stats(realm: Optional[Realm] = None) -> Dict[str, CountStat]: "minutes_active::day", DataCollector(UserCount, do_pull_minutes_active), CountStat.DAY ), # Tracks the number of push notifications requested by the server. + # Included in LOGGING_COUNT_STAT_PROPERTIES_NOT_SENT_TO_BOUNCER. LoggingCountStat( "mobile_pushes_sent::day", RealmCount, CountStat.DAY, ), # Rate limiting stats - # Used to limit the number of invitation emails sent by a realm + # Used to limit the number of invitation emails sent by a realm. + # Included in LOGGING_COUNT_STAT_PROPERTIES_NOT_SENT_TO_BOUNCER. LoggingCountStat("invites_sent::day", RealmCount, CountStat.DAY), # Dependent stats # Must come after their dependencies. @@ -890,6 +893,19 @@ def get_count_stats(realm: Optional[Realm] = None) -> Dict[str, CountStat]: "mobile_pushes_forwarded::day", ] +# LoggingCountStats with a daily duration and that are directly stored on +# the RealmCount table (instead of via aggregation in process_count_stat), +# can be in a state, after the hourly cron job to update analytics counts, +# where the logged value will be live-updated later (as the end time for +# the stat is still in the future). As these logging counts are designed +# to be used on the self-hosted installation for either debugging or rate +# limiting, sending these incomplete counts to the bouncer has low value. +LOGGING_COUNT_STAT_PROPERTIES_NOT_SENT_TO_BOUNCER = [ + "invites_sent::day", + "mobile_pushes_sent::day", + "active_users_log:is_bot:day", +] + # To avoid refactoring for now COUNT_STATS can be used as before COUNT_STATS = get_count_stats() diff --git a/zerver/lib/remote_server.py b/zerver/lib/remote_server.py --- a/zerver/lib/remote_server.py +++ b/zerver/lib/remote_server.py @@ -9,6 +9,7 @@ from django.utils.translation import gettext as _ from pydantic import UUID4, BaseModel, ConfigDict, Field, Json, field_validator +from analytics.lib.counts import LOGGING_COUNT_STAT_PROPERTIES_NOT_SENT_TO_BOUNCER from analytics.models import InstallationCount, RealmCount from version import API_FEATURE_LEVEL, ZULIP_VERSION from zerver.actions.realm_settings import ( @@ -364,8 +365,10 @@ def send_server_data_to_push_bouncer(consider_usage_statistics: bool = True) -> # uploading such statistics enabled. installation_count_query = InstallationCount.objects.filter( id__gt=last_acked_installation_count_id + ).exclude(property__in=LOGGING_COUNT_STAT_PROPERTIES_NOT_SENT_TO_BOUNCER) + realm_count_query = RealmCount.objects.filter(id__gt=last_acked_realm_count_id).exclude( + property__in=LOGGING_COUNT_STAT_PROPERTIES_NOT_SENT_TO_BOUNCER ) - realm_count_query = RealmCount.objects.filter(id__gt=last_acked_realm_count_id) else: installation_count_query = InstallationCount.objects.none() realm_count_query = RealmCount.objects.none() diff --git a/zerver/management/commands/export_search.py b/zerver/management/commands/export_search.py --- a/zerver/management/commands/export_search.py +++ b/zerver/management/commands/export_search.py @@ -17,6 +17,7 @@ from zerver.lib.soft_deactivation import reactivate_user_if_soft_deactivated from zerver.lib.upload import save_attachment_contents from zerver.models import Attachment, Message, Recipient, Stream, UserProfile +from zerver.models.recipients import get_or_create_huddle from zerver.models.users import get_user_by_delivery_email @@ -89,6 +90,12 @@ def add_arguments(self, parser: ArgumentParser) -> None: metavar="<email>", help="Limit to messages received by users with any of these emails (may be specified more than once). This is a superset of --sender, since senders receive every message they send.", ) + users.add_argument( + "--dm", + action="append", + metavar="<email>", + help="Limit to messages in a DM between all of the users provided. This option must be given two or more times.", + ) @override def handle(self, *args: Any, **options: Any) -> None: @@ -104,6 +111,7 @@ def handle(self, *args: Any, **options: Any) -> None: and not options["after"] and not options["sender"] and not options["recipient"] + and not options["dm"] ): raise CommandError("One or more limits are required!") @@ -153,6 +161,18 @@ def handle(self, *args: Any, **options: Any) -> None: or_, [Q(sender__delivery_email__iexact=e) for e in options["sender"]], ) + elif options["dm"]: + if len(options["dm"]) == 1: + raise CommandError("Must pass two or more --dm arguments, not just one") + user_profiles = [get_user_by_delivery_email(e, realm) for e in options["dm"]] + if len(user_profiles) == 2: + user_a, user_b = user_profiles + limits &= Q(recipient=user_a.recipient, sender=user_b) | Q( + recipient=user_b.recipient, sender=user_a + ) + else: + huddle = get_or_create_huddle([user.id for user in user_profiles]) + limits &= Q(recipient=huddle.recipient) attachments_written: Set[str] = set() messages_query = Message.objects.filter(limits, realm=realm).order_by("date_sent")
diff --git a/zerver/tests/test_push_notifications.py b/zerver/tests/test_push_notifications.py --- a/zerver/tests/test_push_notifications.py +++ b/zerver/tests/test_push_notifications.py @@ -23,7 +23,7 @@ from typing_extensions import override from analytics.lib.counts import CountStat, LoggingCountStat -from analytics.models import InstallationCount, RealmCount +from analytics.models import InstallationCount, RealmCount, UserCount from corporate.models import CustomerPlan from version import ZULIP_VERSION from zerver.actions.message_delete import do_delete_messages @@ -1478,17 +1478,35 @@ def check_counts( ) # Create some rows we'll send to remote server - realm_stat = LoggingCountStat("invites_sent::day", RealmCount, CountStat.DAY) + # LoggingCountStat that should be included; + # i.e. not in LOGGING_COUNT_STAT_PROPERTIES_NOT_SENT_TO_BOUNCER + messages_read_logging_stat = LoggingCountStat( + "messages_read::hour", UserCount, CountStat.HOUR + ) RealmCount.objects.create( - realm=user.realm, property=realm_stat.property, end_time=end_time, value=5 + realm=user.realm, + property=messages_read_logging_stat.property, + end_time=end_time, + value=5, + ) + InstallationCount.objects.create( + property=messages_read_logging_stat.property, + end_time=end_time, + value=5, + ) + # LoggingCountStat that should not be included; + # i.e. in LOGGING_COUNT_STAT_PROPERTIES_NOT_SENT_TO_BOUNCER + invites_sent_logging_stat = LoggingCountStat("invites_sent::day", RealmCount, CountStat.DAY) + RealmCount.objects.create( + realm=user.realm, + property=invites_sent_logging_stat.property, + end_time=end_time, + value=5, ) InstallationCount.objects.create( - property=realm_stat.property, + property=invites_sent_logging_stat.property, end_time=end_time, value=5, - # We set a subgroup here to work around: - # https://github.com/zulip/zulip/issues/12362 - subgroup="test_subgroup", ) # Event type in SYNCED_BILLING_EVENTS -- should be included RealmAuditLog.objects.create( @@ -1510,8 +1528,8 @@ def check_counts( event_time=end_time, extra_data=orjson.dumps({"foo": "bar"}).decode(), ) - self.assertEqual(RealmCount.objects.count(), 1) - self.assertEqual(InstallationCount.objects.count(), 1) + self.assertEqual(RealmCount.objects.count(), 2) + self.assertEqual(InstallationCount.objects.count(), 2) self.assertEqual(RealmAuditLog.objects.filter(id__gt=audit_log_max_id).count(), 2) with self.settings(SUBMIT_USAGE_STATISTICS=False): @@ -1686,13 +1704,13 @@ def check_counts( # Test only having new RealmCount rows RealmCount.objects.create( realm=user.realm, - property=realm_stat.property, + property=messages_read_logging_stat.property, end_time=end_time + timedelta(days=1), value=6, ) RealmCount.objects.create( realm=user.realm, - property=realm_stat.property, + property=messages_read_logging_stat.property, end_time=end_time + timedelta(days=2), value=9, ) @@ -1701,7 +1719,9 @@ def check_counts( # Test only having new InstallationCount rows InstallationCount.objects.create( - property=realm_stat.property, end_time=end_time + timedelta(days=1), value=6 + property=messages_read_logging_stat.property, + end_time=end_time + timedelta(days=1), + value=6, ) send_server_data_to_push_bouncer() check_counts(8, 8, 3, 2, 7) @@ -1820,12 +1840,17 @@ def test_analytics_api_foreign_keys_to_remote_realm(self) -> None: end_time = self.TIME_ZERO # Create some rows we'll send to remote server - realm_stat = LoggingCountStat("invites_sent::day", RealmCount, CountStat.DAY) + messages_read_logging_stat = LoggingCountStat( + "messages_read::hour", UserCount, CountStat.HOUR + ) realm_count = RealmCount.objects.create( - realm=user.realm, property=realm_stat.property, end_time=end_time, value=5 + realm=user.realm, + property=messages_read_logging_stat.property, + end_time=end_time, + value=5, ) installation_count = InstallationCount.objects.create( - property=realm_stat.property, + property=messages_read_logging_stat.property, end_time=end_time, value=5, ) @@ -1917,12 +1942,14 @@ def test_analytics_api_foreign_keys_to_remote_realm(self) -> None: # set as it should. RealmCount.objects.create( realm=user.realm, - property=realm_stat.property, + property=messages_read_logging_stat.property, end_time=end_time + timedelta(days=1), value=6, ) InstallationCount.objects.create( - property=realm_stat.property, end_time=end_time + timedelta(days=1), value=6 + property=messages_read_logging_stat.property, + end_time=end_time + timedelta(days=1), + value=6, ) RealmAuditLog.objects.create( realm=user.realm,
Split /production/deployment.html into multiple pages To make https://zulip.readthedocs.io/en/stable/production/deployment.html easier to navigate, we should split two sections out into dedicated pages: - https://zulip.readthedocs.io/en/stable/production/deployment.html#putting-the-zulip-application-behind-a-reverse-proxy section, to be labeled "Reverse proxies", placed right after Deployment options in the left sidebar. - https://zulip.readthedocs.io/en/stable/production/deployment.html#system-and-deployment-configuration, to be labeled "System configuration", and placed after "Server configuration" in the left sidebar. [CZO discussion](https://chat.zulip.org/#narrow/stream/19-documentation/topic/splitting.20.2Fproduction.2Fdeployment.2Ehtml.20.2328928/near/1737746)
Hello @zulip/server-production members, this issue was labeled with the "area: documentation (production)" label, so you may want to check it out! <!-- areaLabelAddition --> @drrosa Would you be up for taking care of this one in the next few days?
2024-03-01T01:47:50
zulip/zulip
29,188
zulip__zulip-29188
[ "28887" ]
fb7d77545f6bf742b2929e2344ccc35441553bce
diff --git a/zerver/lib/markdown/tabbed_sections.py b/zerver/lib/markdown/tabbed_sections.py --- a/zerver/lib/markdown/tabbed_sections.py +++ b/zerver/lib/markdown/tabbed_sections.py @@ -77,6 +77,7 @@ "via-recent-conversations": "Via recent conversations", "via-inbox-view": "Via inbox view", "via-left-sidebar": "Via left sidebar", + "via-right-sidebar": "Via right sidebar", "instructions-for-all-platforms": "Instructions for all platforms", "public-streams": "Public streams", "private-streams": "Private streams",
Add "View stream subscribers" page We should add a "View stream subscribers" page (below "Create a stream" under Streams & topics). It should document the right sidebar UI in #26717 (currently test-deployed on CZO), as well as how to see subscribers via settings.
Hello @zulip/server-user-docs members, this issue was labeled with the "area: documentation (user)" label, so you may want to check it out! <!-- areaLabelAddition --> @drrosa Getting this merged will be blocked on https://github.com/zulip/zulip/pull/26717, but I think the UI is sufficiently settled that we can start working on this. @drrosa You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! @zulipbot claim
2024-03-05T06:52:25
zulip/zulip
29,192
zulip__zulip-29192
[ "29073" ]
a33c68026c9b0853c441d7aeff3195594e5d2c0d
diff --git a/tools/lib/capitalization.py b/tools/lib/capitalization.py --- a/tools/lib/capitalization.py +++ b/tools/lib/capitalization.py @@ -16,6 +16,7 @@ r"Cookie Bot", r"DevAuthBackend", r"DSN", + r"Esc", r"GCM", r"GitHub", r"Gravatar", @@ -23,6 +24,7 @@ r"HTTP", r"ID", r"IDs", + r"Inbox", r"IP", r"JSON", r"Kerberos", @@ -31,6 +33,7 @@ r"Markdown", r"OTP", r"Pivotal", + r"Recent conversations", r"DM", r"DMs", r"Slack", diff --git a/zerver/lib/hotspots.py b/zerver/lib/hotspots.py --- a/zerver/lib/hotspots.py +++ b/zerver/lib/hotspots.py @@ -83,6 +83,12 @@ def to_dict(self) -> Dict[str, str]: OneTimeNotice( name="visibility_policy_banner", ), + OneTimeNotice( + name="intro_inbox_view_modal", + ), + OneTimeNotice( + name="intro_recent_view_modal", + ), ] # We would most likely implement new hotspots in the future that aren't diff --git a/zerver/migrations/0501_mark_introduce_zulip_view_modals_as_read.py b/zerver/migrations/0501_mark_introduce_zulip_view_modals_as_read.py new file mode 100644 --- /dev/null +++ b/zerver/migrations/0501_mark_introduce_zulip_view_modals_as_read.py @@ -0,0 +1,75 @@ +# Generated by Django 4.2.10 on 2024-03-11 04:43 + +from django.db import connection, migrations +from django.db.backends.base.schema import BaseDatabaseSchemaEditor +from django.db.migrations.state import StateApps +from django.db.models import Q +from django.utils.timezone import now as timezone_now +from psycopg2.sql import SQL + + +def mark_introduce_zulip_view_modals_as_read( + apps: StateApps, schema_editor: BaseDatabaseSchemaEditor +) -> None: + with connection.cursor() as cursor: + cursor.execute( + SQL( + "SELECT MAX(id) FROM zerver_userprofile WHERE is_bot = False AND is_mirror_dummy = False;" + ) + ) + (max_id,) = cursor.fetchone() + + if max_id is None: + return + + BATCH_SIZE = 10000 + lower_id_bound = 0 + timestamp_value = timezone_now() + while lower_id_bound < max_id: + upper_id_bound = min(lower_id_bound + BATCH_SIZE, max_id) + with connection.cursor() as cursor: + query = SQL(""" + INSERT INTO zerver_onboardingstep (user_id, onboarding_step, timestamp) + SELECT id, step, %(timestamp_value)s + FROM zerver_userprofile + CROSS JOIN UNNEST(%(step_names)s) step + WHERE is_bot = False + AND is_mirror_dummy = False + AND id > %(lower_id_bound)s AND id <= %(upper_id_bound)s; + """) + cursor.execute( + query, + { + "timestamp_value": timestamp_value, + "step_names": ["intro_inbox_view_modal", "intro_recent_view_modal"], + "lower_id_bound": lower_id_bound, + "upper_id_bound": upper_id_bound, + }, + ) + + print(f"Processed {upper_id_bound} / {max_id}") + lower_id_bound = lower_id_bound + BATCH_SIZE + + +def mark_introduce_zulip_view_modals_as_unread( + apps: StateApps, schema_editor: BaseDatabaseSchemaEditor +) -> None: + OnboardingStep = apps.get_model("zerver", "OnboardingStep") + + OnboardingStep.objects.filter( + Q(onboarding_step="intro_inbox_view_modal") | Q(onboarding_step="intro_recent_view_modal") + ).delete() + + +class Migration(migrations.Migration): + atomic = False + dependencies = [ + ("zerver", "0500_realm_zulip_update_announcements_stream"), + ] + + operations = [ + migrations.RunPython( + mark_introduce_zulip_view_modals_as_read, + reverse_code=mark_introduce_zulip_view_modals_as_unread, + ), + ]
diff --git a/zerver/tests/test_hotspots.py b/zerver/tests/test_hotspots.py --- a/zerver/tests/test_hotspots.py +++ b/zerver/tests/test_hotspots.py @@ -39,9 +39,11 @@ def test_some_done_some_not(self) -> None: do_mark_onboarding_step_as_read(self.user, "intro_streams") do_mark_onboarding_step_as_read(self.user, "intro_compose") onboarding_steps = get_next_onboarding_steps(self.user) - self.assert_length(onboarding_steps, 2) + self.assert_length(onboarding_steps, 4) self.assertEqual(onboarding_steps[0]["name"], "visibility_policy_banner") - self.assertEqual(onboarding_steps[1]["name"], "intro_topics") + self.assertEqual(onboarding_steps[1]["name"], "intro_inbox_view_modal") + self.assertEqual(onboarding_steps[2]["name"], "intro_recent_view_modal") + self.assertEqual(onboarding_steps[3]["name"], "intro_topics") def test_all_onboarding_steps_done(self) -> None: with self.settings(TUTORIAL_ENABLED=True):
Add modals to introduce views We should add one-time modals to explain some Zulip views the first time that a user enters the view. ## Inbox Text to use (no header): > The **Inbox** view provides an overview of your conversations with unread messages. In Zulip, a conversation is either a [direct message](https://zulip.com/help/direct-messages) thread (one-on-one or with a group), or a [topic in a stream](https://zulip.com/help/streams-and-topics). The colored bars show where each conversation took place. > Click on a conversation you're interested in to view it. You can return to your **Inbox** when done to select the next conversation. > Tip: **Inbox** is your home view, so use `Esc` to come back any time. [if home view and Esc navigation to home view is enabled] [Continue] <- action button; dismisses modal ## Recent conversations > The **Recent conversations** view provides an overview of all the ongoing conversations. In Zulip, a conversation is a [direct message](https://zulip.com/help/direct-messages) thread (one-on-one or with a group), or a [topic in a stream](https://zulip.com/help/streams-and-topics). > Click on a conversation you're interested in to view it. You can return to your **Recent conversations** when done to select the next conversation. > Tip: **Recent conversations** is your home view, so use `Esc` to come back any time. [if home view and Esc navigation to home view is enabled] [Continue] <- action button; dismisses modal
Hello @zulip/server-onboarding members, this issue was labeled with the "area: onboarding" label, so you may want to check it out! <!-- areaLabelAddition --> @alya can u explain more about the purpose of this modal ?
2024-03-05T13:01:44
zulip/zulip
29,385
zulip__zulip-29385
[ "29152", "29152" ]
a5cf0ec526bd9155e971969069137d5feb3c473c
diff --git a/zerver/lib/push_notifications.py b/zerver/lib/push_notifications.py --- a/zerver/lib/push_notifications.py +++ b/zerver/lib/push_notifications.py @@ -922,13 +922,7 @@ def process(elem: lxml.html.HtmlElement) -> str: return plain_text if settings.PUSH_NOTIFICATION_REDACT_CONTENT: - return ( - "*" - + _( - "This organization has disabled including message content in mobile push notifications" - ) - + "*" - ) + return _("New message") elem = lxml.html.fragment_fromstring(rendered_content, create_parent=True) change_katex_to_raw_latex(elem)
diff --git a/zerver/tests/test_push_notifications.py b/zerver/tests/test_push_notifications.py --- a/zerver/tests/test_push_notifications.py +++ b/zerver/tests/test_push_notifications.py @@ -4109,7 +4109,7 @@ def test_get_message_payload_apns_redacted_content(self) -> None: "alert": { "title": "Cordelia, Lear's daughter, King Hamlet, Othello, the Moor of Venice", "subtitle": "King Hamlet:", - "body": "*This organization has disabled including message content in mobile push notifications*", + "body": "New message", }, "sound": "default", "badge": 0, @@ -4305,7 +4305,7 @@ def test_get_message_payload_gcm_redacted_content(self) -> None: "event": "message", "zulip_message_id": message.id, "time": datetime_to_timestamp(message.date_sent), - "content": "*This organization has disabled including message content in mobile push notifications*", + "content": "New message", "content_truncated": False, "server": settings.EXTERNAL_HOST, "realm_id": hamlet.realm.id,
Use shorter message when sending notifications without content <!-- Issue description --> At present, we send a long placeholder message when an organization disables message content in push notifications. We should change it to just "_New message_" (formatted with italics, if possible), or else `*New message*` if it can't be formatted. <!-- Link to a message in the chat.zulip.org discussion. Message links will still work even if the topic is renamed or resolved. Link back to this issue from the chat.zulip.org thread. --> [CZO thread ](https://chat.zulip.org/#narrow/stream/137-feedback/topic/Disabled.20content.20in.20push.20notifications.20has.20bad.20error.20message/near/1747141) Use shorter message when sending notifications without content <!-- Issue description --> At present, we send a long placeholder message when an organization disables message content in push notifications. We should change it to just "_New message_" (formatted with italics, if possible), or else `*New message*` if it can't be formatted. <!-- Link to a message in the chat.zulip.org discussion. Message links will still work even if the topic is renamed or resolved. Link back to this issue from the chat.zulip.org thread. --> [CZO thread ](https://chat.zulip.org/#narrow/stream/137-feedback/topic/Disabled.20content.20in.20push.20notifications.20has.20bad.20error.20message/near/1747141)
@zulipbot claim Welcome to Zulip, @ShristiSharan! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @ShristiSharan You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! working on it, got stuck somewhere but got it resolved now. @zulipbot claim Welcome to Zulip, @AdityaB4! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @zulipbot claim Welcome to Zulip, @ShristiSharan! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @ShristiSharan You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! working on it, got stuck somewhere but got it resolved now. @zulipbot claim Welcome to Zulip, @AdityaB4! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)!
2024-03-21T03:45:21
zulip/zulip
29,386
zulip__zulip-29386
[ "27511" ]
bd00337776acb5bf4246cfa3c0cb923d44656941
diff --git a/tools/lib/capitalization.py b/tools/lib/capitalization.py --- a/tools/lib/capitalization.py +++ b/tools/lib/capitalization.py @@ -27,6 +27,7 @@ r"Inbox", r"IP", r"JSON", + r"Jitsi", r"Kerberos", r"LinkedIn", r"LDAP",
Add clarification tooltip when settings can't be saved due to invalid Jitsi URL In SETTINGS / ORGANIZATION SETTINGS > Other settings, we disable the "Save changes" button when the custom Jitsi URL is invalid. We should add a tooltip do the disabled button to explain why it is disabled: "Cannot save invalid Jitsi server URL." <img width="809" alt="Screenshot 2023-11-02 at 10 31 14 PM" src="https://github.com/zulip/zulip/assets/2090066/b6bbb302-8b01-41ae-be98-1181497ecbf5">
Hello @zulip/server-settings members, this issue was labeled with the "area: settings UI" label, so you may want to check it out! <!-- areaLabelAddition --> @alya I am interested in doing this issue Please assign me this so that i could work on this Thank You : ) @zulipbot claim @zulipbot claim I understood the task. ETA: EOD @VirtualDharm This issue cannot be claimed, as someone else is already working on it. Please see our [contributor guide](https://zulip.readthedocs.io/en/latest/overview/contributing.html#your-first-codebase-contribution) for advice on finding an issue to work on. Thanks! @SiddheshKotwal This issue cannot be claimed, as someone else is already working on it. Please see our [contributor guide](https://zulip.readthedocs.io/en/latest/overview/contributing.html#your-first-codebase-contribution) for advice on finding an issue to work on. Thanks! can i contribute to this issue? @peterssonlinn You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! @zulipbot the PR has been updated several times and is in progress. hello @zulipbot can i work on this issue? @zulipbot clain @zulipbot claim @pankaj87072 This issue cannot be claimed, as someone else is already working on it. Please see our [contributor guide](https://zulip.readthedocs.io/en/latest/overview/contributing.html#your-first-codebase-contribution) for advice on finding an issue to work on. Thanks! @peterssonlinn You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! claim @zulipbot claim Welcome to Zulip, @ankitsuryawanshi9892! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @ankitsuryawanshi9892 You have been unassigned from this issue because you have not made any updates for over 14 days. Please feel free to reclaim the issue if you decide to pick up again. Thanks! @zulipbot claim Welcome to Zulip, @sandesh31122000! We just sent you an invite to collaborate on this repository at https://github.com/zulip/zulip/invitations. Please accept this invite in order to claim this issue and begin a fun, rewarding experience contributing to Zulip! Here's some tips to get you off to a good start: - Join me on the [Zulip developers' server](https://chat.zulip.org), to get help, chat about this issue, and meet the other developers. - [Unwatch this repository](https://help.github.com/articles/unwatching-repositories/), so that you don't get 100 emails a day. As you work on this issue, you'll also want to refer to the [Zulip code contribution guide](https://zulip.readthedocs.io/en/latest/contributing/index.html), as well as the rest of the developer documentation on that site. See you on the other side (that is, the pull request side)! @zulipbot claim @utkarsh-shrivastav77 This issue cannot be claimed, as someone else is already working on it. Please see our [contributor guide](https://zulip.readthedocs.io/en/latest/overview/contributing.html#your-first-codebase-contribution) for advice on finding an issue to work on. Thanks! Hi @sandesh31122000 are you working on it
2024-03-21T04:07:58
zulip/zulip
29,412
zulip__zulip-29412
[ "29375" ]
bd00337776acb5bf4246cfa3c0cb923d44656941
diff --git a/zerver/lib/hotspots.py b/zerver/lib/hotspots.py --- a/zerver/lib/hotspots.py +++ b/zerver/lib/hotspots.py @@ -89,6 +89,9 @@ def to_dict(self) -> Dict[str, str]: OneTimeNotice( name="intro_recent_view_modal", ), + OneTimeNotice( + name="first_stream_created_banner", + ), ] # We would most likely implement new hotspots in the future that aren't
diff --git a/web/e2e-tests/stream_create.test.ts b/web/e2e-tests/stream_create.test.ts --- a/web/e2e-tests/stream_create.test.ts +++ b/web/e2e-tests/stream_create.test.ts @@ -81,6 +81,13 @@ async function create_stream(page: Page): Promise<void> { stream_description: "Everything Puppeteer", }); await page.click("form#stream_creation_form .finalize_create_stream"); + // an explanatory modal is shown for the first stream created + await common.wait_for_micromodal_to_open(page); + await page.click(".dialog_submit_button"); + await common.wait_for_micromodal_to_close(page); + await page.waitForSelector(".message-header-stream-settings-button"); + await page.click(".message-header-stream-settings-button"); + await page.waitForSelector(".stream_section"); await page.waitForSelector( `xpath///*[${common.has_class_x("stream-name")} and text()="Puppeteer"]`, ); diff --git a/zerver/tests/test_hotspots.py b/zerver/tests/test_hotspots.py --- a/zerver/tests/test_hotspots.py +++ b/zerver/tests/test_hotspots.py @@ -39,11 +39,12 @@ def test_some_done_some_not(self) -> None: do_mark_onboarding_step_as_read(self.user, "intro_streams") do_mark_onboarding_step_as_read(self.user, "intro_compose") onboarding_steps = get_next_onboarding_steps(self.user) - self.assert_length(onboarding_steps, 4) + self.assert_length(onboarding_steps, 5) self.assertEqual(onboarding_steps[0]["name"], "visibility_policy_banner") self.assertEqual(onboarding_steps[1]["name"], "intro_inbox_view_modal") self.assertEqual(onboarding_steps[2]["name"], "intro_recent_view_modal") - self.assertEqual(onboarding_steps[3]["name"], "intro_topics") + self.assertEqual(onboarding_steps[3]["name"], "first_stream_created_banner") + self.assertEqual(onboarding_steps[4]["name"], "intro_topics") def test_all_onboarding_steps_done(self) -> None: with self.settings(TUTORIAL_ENABLED=True):
Go to newly created stream (with first-time modal) Even after #29154, users find it hard to navigate to a newly created stream. To address this, we should: 1. Take the user directly to the stream they just created. To avoid a potentially confusing interleaved view, we should go to the most recent topic in the stream (currently "stream events", but might be "general chat" in the future). 2. The first time that a user creates a stream, show an explanatory modal (wording to be finalized when working on the PR): ---- ## Stream **#{stream name}** created! You will now see the stream you created. If you'd like to go back to stream settings, click on the name of the stream at the top of your Zulip window, or use the **back** button in your browser or desktop app. [Continue] --- Since we are changing the behavior, it's fine to show this once to existing users. [CZO thread](https://chat.zulip.org/#narrow/stream/137-feedback/topic/user.20research.3A.20going.20to.20a.20new.20stream/near/1744305)
Hello @zulip/server-onboarding, @zulip/server-streams members, this issue was labeled with the "area: onboarding", "area: stream settings" labels, so you may want to check it out! <!-- areaLabelAddition --> @alya Can I work on this issue? @kuv2707 You can give this a try if you think you'll be able to get a PR up this week. Sure!
2024-03-22T13:03:47