Commit Graph

3990 Commits

Author SHA1 Message Date
Steve Howell 3091412806 refactor: Use messages in gather_hot_conversations().
We rename stream_messages -> stream_ums, and then we get
messages at the top for the loop that only cares about
messages.
2018-11-14 23:24:06 -08:00
Steve Howell f961408782 digest: Reduce queries using select_related().
We use the message a lot for the query modified
here, so I think it's worth taking the up-front
hit of getting bulkier objects to avoid O(N)
hops back to the database.
2018-11-14 23:24:06 -08:00
Steve Howell 27d79352da topic -> subject: Extract get_topic_from_message_info().
This changes files where it's safe to just assume caller
may use either "topic" or "subject", and we prefer "topic"
but support "subject".
2018-11-14 23:24:06 -08:00
Steve Howell aa4e9cec2d minor: Add a code comment and move two constants. 2018-11-14 23:24:06 -08:00
Steve Howell b666a6bd6c subject -> topic: Fix most of api_test_helpers.
We don't want to change anything that can end
up in docs yet, but for test setup, we can switch
to topic_name.
2018-11-14 23:24:06 -08:00
Eeshan Garg d9958610a4 webhook_decorator: Support notifying bot owner on invalid JSON.
Our webhook-errors.log file is riddled with exceptions that are
logged when a webhook is incorrectly configured to send data in
a non-JSON format. To avoid this, api_key_only_webhook_view
now supports an additional argument, notify_bot_owner_on_invalid_json.
This argument, when True, will send a PM notification to the bot's
owner notifying them of the configuration issue.
2018-11-14 22:35:56 -08:00
Tim Abbott 67c3593b39 sessions: Add coverage exception for now. 2018-11-14 15:28:35 -08:00
Eeshan Garg 41c0e9ba47 webhooks: Add ReviewBoard integration. 2018-11-12 16:11:32 -08:00
Steve Howell d86dd165da gitter/slack/hipchat: Remove "subject" from conversions.
We (lexically) remove "subject" from the conversion code.  The
`build_message` helper calls `set_topic_name` under the hood,
so things still have "subject" in the JSON.

There was good code coverage on `build_message`.
2018-11-12 15:47:11 -08:00
Steve Howell ea98a44db3 webhooks: Replace SUBJECT_WITH_* with TOPIC_WITH_*. 2018-11-12 15:47:11 -08:00
Steve Howell e55fc144b9 Add alias support to REQ helpers for subject/topic.
The alias support is generic here, and we use it for
migrating subject -> topic in REQ_topic().
2018-11-12 15:47:11 -08:00
Steve Howell de6c08a842 Extract messages_for_topic(). 2018-11-12 15:47:11 -08:00
Steve Howell 754795c0b7 Extract REQ_topic() helper.
For now we use it only in the send path, not the update
path.
2018-11-12 15:47:11 -08:00
Steve Howell 0a171bf9bf Fix "prev_subject" with LEGACY_PREV_TOPIC.
I added `LEGACY_` prefix to the var, because
otherwise you'd have really confusing code
where you change the key from `PREV_TOPIC`
to "prev_topic".
2018-11-12 15:47:11 -08:00
Steve Howell a49ba8c577 Extract user_message_exists_for_topic(). 2018-11-12 15:47:11 -08:00
Steve Howell 39e5c61d4a Extact MATCH_TOPIC constant. 2018-11-12 15:47:11 -08:00
Steve Howell 8981b65bbc Extract topic_column_sa(). 2018-11-12 15:47:11 -08:00
Steve Howell bb959acbaf Use modern huddle URLs in digest emails. 2018-11-12 12:01:09 -08:00
Steve Howell e79e0018f7 Use modern PM URLs in digest emails. 2018-11-12 12:01:09 -08:00
Roman Godov aa3682f9fc api: Add GET /user_groups documentation.
This documents our GET endpoint for interacting with Zulip's user
groups feature.

Fixes #10298.
2018-11-08 22:19:30 -08:00
Tim Abbott 17be6e9165 confirmation: Move one_click_unsubscribe_link out of notifications.py.
This helps prevent a problematic import sequence when we start using
it from signals.py.
2018-11-08 14:39:33 -08:00
Steve Howell cd4d447d90 Minor: change message.subject -> message.topic_name().
This also allows us to lock down
push_notifications.py from using "subject"
in the future.
2018-11-08 16:34:30 +00:00
Steve Howell ff9a6c5ced minor: Rename subject -> topic_name in bugdown. 2018-11-08 16:21:14 +00:00
Steve Howell e802be0fde Remove "subject" in notifications.py.
These last few are all pretty safe.
2018-11-08 15:12:10 +00:00
Steve Howell 39dc5f2691 Rename recipient_subject to bucket.
The various vars here that had recipient_subject
in the name now have either bucket or bucket_tup
there.

The shorter names are a bit easier to read, and the
original names were misleading for the PM case.

This was basically two search/replaces, and we have
good test coverage here, so it's pretty low risk
despite the messy diff.
2018-11-08 14:59:09 +00:00
Steve Howell 226a2826b5 Remove "subject" from zerver/lib/message.py.
We also lock this down file in the linter, so
that you can no longer introduce "subject"
to `message.py`.
2018-11-08 14:45:16 +00:00
Steve Howell 592dd290b2 Avoid "subject" in MessageDict. 2018-11-08 14:33:44 +00:00
Steve Howell 881e046c37 minor: Use TOPIC_NAME constant for "subject" event. 2018-11-08 14:01:45 +00:00
Steve Howell d05f731c1c Eliminate the use of arguments.db_data.
We now attach zulip_db_data to the markdown engines
for classes that need it.  This was the last remaining
global we had, so we remove `arguments.py` here.
2018-11-07 10:44:49 -08:00
Steve Howell b66304e167 refactor: Pass db_data down to helpers.
This mostly preps for the next commit.
2018-11-07 10:44:49 -08:00
Steve Howell fa6f642c9c refactor: Remove global argument.current_realm. 2018-11-07 10:44:48 -08:00
Steve Howell e1113c7011 refactor: Remove the global arguments.current_message.
The Markdown processor makes it fairly simple for
the helper classes to access the `md` engine.  We
now write `_md_engine.zulip_message` to avoid having
the current message in the global namespace.

Note that we do reuse engines for multiple messages,
but each engine is specific to a realm.  And we therefore
avoid even the theoretical possibility of leaking message
data between realms.
2018-11-07 10:44:48 -08:00
Steve Howell ab24cc2535 minor: Pass in arguments.current_message to helpers. 2018-11-07 10:44:48 -08:00
Steve Howell c26768ea63 bugdown: Import nl2br and tables extensions "normally".
This makes us consistent with how we import codehilite.

Using Python's normal import mechanism avoids some overhead
with Markdown having to parse dotted notation.

These modules are tiny, so they shouldn't impact startup
too much.  Also, by explicitly importing them, we avoid
the pitfall of having a sucessful startup and a broken
renderer.
2018-11-07 10:44:48 -08:00
Steve Howell c8a2081526 bugdown: Break out helper functions for extending bugdown.
These will make profiling a lot easier, and you
can also quickly disable features.  The overhead
of these function calls is dwarfed by other concerns.
2018-11-07 10:44:47 -08:00
Steve Howell ffa4daf936 bugdown: Reduce overhead of building link regexes.
We were building the same link regex every time
we build a Markdown engine, which happens twice
per realm.  It's an expensive operation due to
the complexity of the regex and us reading a file.
2018-11-07 10:33:11 -08:00
Steve Howell 18a76c54de bugdown: Extract build_engine.
This separates out the main job of building
an instance of Markdown from the fairly orthogonal
task of maintaining a list of engines.
2018-11-07 10:33:11 -08:00
Steve Howell eb2269c614 fenced_code: Refactor to avoid nested classes.
Nested classes are kind of expensive in Python,
particularly when you throw in mypy annotations.

Also, flatter is arguably better, although it is
kind of a pain here not to have closures.
2018-11-07 10:33:11 -08:00
Steve Howell dfadbcd3bc bugdown: Avoid ORM when there are no group names.
This change avoids hitting the Django ORM when
we don't find any possible group mentions in
the message content.

Django doesn't necessarily actually hit the database,
but it's still slow and shows up in profiles.
2018-11-07 10:33:11 -08:00
Steve Howell 88f50b97fd import: Render content before inserting messages.
By rendering content before bulk importing messages,
we avoid O(N) database hops.
2018-11-07 10:33:11 -08:00
Steve Howell bf3f7d93d0 Simplify params for fix_message_rendered_content. 2018-11-07 10:33:11 -08:00
Steve Howell 0878d86706 import: Avoid unnecessary Message lookups.
We now no longer go the DB to get a Message object
during render.
2018-11-07 10:33:11 -08:00
Steve Howell 1e12b13a56 import: Avoid unnecessary sender lookups.
This commit speeds up the import by avoiding
sender lookups and instead using the data
for users that we already have in memory.

This avoids a few DB hops, many hops to memcached,
plus some object construction.

We now call do_render_markdown() directly.  This
also makes it more explicit that the import has
never rendered alert words.
2018-11-07 10:33:10 -08:00
Steve Howell 06f8d0af7e refactor: Extract do_render_markdown().
For the import-data codepath, we will call
the extracted function directly in a
subsequent commit.

The do_render_markdown() function has more
required parameters, which allows for more
explicit code and also allows us to flatten
out some logic related to alert words.  (We
just pass in empty sets/dicts as needed).
2018-11-07 10:20:14 -08:00
Steve Howell 35e9e5928f render: Upstream calculation of translate_emoticons. 2018-11-07 10:20:14 -08:00
Steve Howell 82b808e620 bugdown: Avoid zephyr-related queries in rendering.
We can rely on `message_realm` being the same
as `message.sender.realm`, which allows us to
skip two queries to the database for the rare
Zephyr mirroring case.
2018-11-07 10:11:06 -08:00
Steve Howell 659c9dde00 bugdown: Avoid unnecessary realm queries.
We now keep realm in the arguments variable,
which avoids some lookups.

We also test settings before even trying to
get realms.
2018-11-07 10:08:46 -08:00
Steve Howell f9a7451167 import: Pass in realm to render codepath.
We avoid querying the same realm multiple times.
2018-11-07 10:08:46 -08:00
Steve Howell 92a7f04149 import: Inline save_message_rendered_content().
This function requires a message object, whereas
we want to work with JSON data to avoid necessary
queries when we import data.  Inlining the function
sets us up for a subsequent refactoring.

We change the way we deal with theoretical return
values of `None` to use an assertion; otherwise,
we would have to loosen up a bunch of mypy types
from `str` to `Optional[str]`.  It's not clear `None`
is even possible--we've moved toward throwing exceptions
there instead of silently failing.
2018-11-07 10:08:45 -08:00
Steve Howell 6b6001c46c Remove "subject" from test_classes.py.
We now use "topic" lingo.
2018-11-07 10:03:53 -08:00
Steve Howell ff60055fa4 Use topic_match_sa() for topic searches.
Note this introduce literal(), which makes the way
we handle topic mutes more consistent with general
topic searches.
2018-11-07 10:03:53 -08:00
Steve Howell 79d5e36ca3 Extract topic_match_sa() helper.
We'll also use this in zerver/views/messages.py, but
that's a bigger change.
2018-11-07 10:03:53 -08:00
Steve Howell af1acf9239 Rename constant to MAX_TOPIC_NAME_LENGTH. 2018-11-07 10:03:53 -08:00
Steve Howell 2cf46f0122 Extract save_message_for_edit_use_case().
This is mostly extracted to help clean out
all "subject" references from actions.py.
2018-11-07 10:03:53 -08:00
Steve Howell 0cf4cddc5b Extract update_messages_for_topic_edit().
This is somewhat hairy logic, so it's nice
to extract it and not worry about variable leaks.

Also, this moves some legacy "subject" references out
of actions.py.
2018-11-07 10:03:53 -08:00
Steve Howell 32232377f7 Rename bugdown.subject_links -> topic_links. 2018-11-07 10:03:53 -08:00
Steve Howell 0e854288ee Add some string constants to topic.py.
The goal here is to make it easy to
forbid "subject" in actions.py.
2018-11-07 10:03:53 -08:00
Steve Howell 7252861785 Extract filter_by_topic_name_via_message. 2018-11-07 10:03:53 -08:00
Steve Howell 2fd0cfe708 Use topic_name() helper in more places. 2018-11-07 10:03:53 -08:00
Steve Howell 55afadc286 Introduce Message.set_topic_name(). 2018-11-07 10:03:53 -08:00
Steve Howell dc8f893494 Extract filter_by_exact_message_topic(). 2018-11-07 10:03:53 -08:00
Steve Howell 56ecd227ff Add topic-related helpers for ScheduledMessage. 2018-11-07 10:03:53 -08:00
Steve Howell 50e3f85557 Extract topic.py library.
We start by including functions that do custom
queries for topic history.

The goal of this library is partly to quarantine
the legacy "subject" column on Message.
2018-11-07 10:03:53 -08:00
Rohitt Vashishtha 652477daea bugdown: Refactor name to mention_text in mention.py.
This commit renames some variables to make it clear that a mention's
text is not only the name of the user in all cases.
2018-11-07 10:02:53 -08:00
Tim Abbott e14a35b490 import: Don't assume a last_modified key is present.
This fixes an exception when importing uploaded file data from
Slack/HipChat.
2018-11-07 09:52:35 -08:00
Eeshan Garg 006e47198c webhooks/jira: Decode stream name on our end.
Recently, one of our users reported that a JIRA webhook was not
able to send messages to a stream with a space character in its
name. Turns out that JIRA does something weird with webhook URLs,
such that escaped space characters (%20) are escaped again, so
that when the request gets to Zulip, the double escaped %20 is
evaluated as the literal characters `%20`, and not as a space.

We fix this by unescaping the stream name on our end before
sending the message forward!
2018-11-06 15:57:04 -08:00
Tim Abbott 1bf385e35f import: Avoid sending a content-type of None to S3.
The previous logic was incorrect, in that if `content_type` was set to
None (which happens with Slack/HipChat export, among other things),
then we wouldn't run the `guess_type` logic to auto-detect the
Content-Type to send to S3.
2018-11-06 13:03:14 -08:00
Steve Howell a092bee6b3 import: Reduce memory usage for UserMessage ids.
The UserMessage table can be huge, so creating a
bunch of entries in `ID_MAP` can overflow memory.

We don't have any tables that depend on `UserMessage`,
and we don't send the 'id' fields from `zerver_usermessage`
to the database, so re-mapping them was just busy-work.
2018-11-05 10:18:01 -08:00
Jack Zhang 5902a573be push_notifications: Play 'default' sound for iOS notifications.
Fixes zulip/zulip-mobile#2651.

This was tested on an iPhone 7 running iOS 12.
2018-11-02 17:01:50 -07:00
Tim Abbott ea1ec68899 events: Pass a realm object into send_event.
This is a preparator refactor for supporting hosting different Tornado
processes on different servers; to look up which Tornado server we
should be sending the event to, we'll need the realm object.
2018-11-02 16:47:39 -07:00
Tim Abbott ff2b496067 error_notify: Stringify QUERY_STRING values directly.
Apparently, the QUERY_STRING property of the report object wasn't
actually a string; since we only care about its string representation,
we should just stringify it.
2018-10-31 16:30:38 -07:00
Yashashvi Dave 4ceb4b607f zerver/lib/users.py: Extract func `validate_user_custom_profile_data`.
Extract function `validate_user_custom_profile_data` to validate
user's custom profile field values according to field type.
2018-10-31 15:36:44 -07:00
Jack Zhang 3d6a745047 notifications: Show stream names for private stream messages.
Fixes #10745.

Use get_display_recipient to get stream names, and remove the
references to message.stream_name in push_notifications.py which were
added in 97571a203, as the actual stream names were being retrived
only for Message objects associated with public streams.
2018-10-30 20:03:48 -07:00
Steve Howell e90f47a530 minor: Remove unused param for get_message_url(). 2018-10-29 12:57:15 -07:00
Steve Howell fd62e71737 Clean up URLs sent by outgoing webhooks.
When you send a message to a bot that wants
to talk via an outgoing webhook, and there's
an error (e.g. server is down), we send a
message to the bot's owner that links to the
message that triggered the error.

The code to produce those links was out of
date.

Now we move the important code to the
`url_encoding.py` library and fix the PM
links to use the more modern style (user_ids
instead of emails).  We also replace "subject"
with "topic" in the stream urls.
2018-10-29 12:57:15 -07:00
Pragati Agrawal d5df0377cc settings_users: Support guest user in admin-user-table.
This supports guest user in the user-info-form-modal as well as in the
role section of the admin-user-table.

With some fixes by Tim Abbott and Shubham Dhama.
2018-10-29 12:33:35 -07:00
Vishnu Ks cc8dd0e971 billing: Set message_visibility_limit to 10000 for Limited. 2018-10-26 17:10:38 -07:00
Aditya Bansal 86eeae6faa bugdown: Rename use_thumbnails to already_thumbnailed for clarity. 2018-10-26 16:51:54 -07:00
Aditya Bansal 7dc1b591cb camo: Extract generate_camo_url out from get_camo_url.
This will help us eliminate camo from our production installs.
Basically it helps us de duplicate some code from upcoming code
which will help us check validity of a camo url.
2018-10-26 16:51:54 -07:00
Jack Zhang f116aba490 push notifications: Reword APNs payload alert titles.
Also, rename get_alert_from_message to get_gcm_alert.

With the implementation of the and get_apns_alert_title and
get_apns_alert_subtitle, the logic within get_alert_from_message
is only relevant to the GCM payload, so we adjust the name
accordingly.

Progresses #9949.
Resolves https://github.com/zulip/zulip-mobile/issues/1316.
2018-10-26 16:02:04 -07:00
Jack Zhang 92a100798c push notifications: Remove tests for get_alert_from_message.
The string that is returned from get_alert_from_message is
dependent upon the same message that is passed into get_apns_payload
and get_gcm_payload. The contents of those payloads that are tested via
TestGetAPNsPayload and TestGetGCMPayload, which makes the tests for
get_alert_from_message redundant.

Also, simplify the logic by removing the last elif conditional.
2018-10-26 15:55:26 -07:00
Steve Howell e2ee455314 outgoing webhooks: Support widget content.
If we use an outgoing webhook and the web server
responds with `widget_content` in the payload, we
include that in what we send through the send-message
codepath.

This makes outgoing webhook bots more consistent with
generic bots.
2018-10-26 12:08:05 -07:00
Tim Abbott 462b9c80c0 bots: Add basic documentation for duplicate bot names feature. 2018-10-24 17:01:34 -07:00
Steve Howell 551fc7f165 bots: Prevent bots from having duplicate full names.
Bots are not allowed to use the same name as
other users in the realm (either bot or human).

This is kind of a big commit, but I wanted to
combine the post/patch (aka add/edit) checks
into one commit, since it's a change in policy
that affects both codepaths.

A lot of the noise is in tests.  We had good
coverage on the previous code, including some places
like event testing where we were expediently
not bothering to use different names for
different bots in some longer tests.  And then
of course I test some new scenarios that are relevant
with the new policy.

There are two new functions:

    check_bot_name_available:
        very simple Django query

    check_change_bot_full_name:
        this diverges from the 3-line
        check_change_full_name, where the latter
        is still used for the "humans" use case

And then we just call those in appropriate places.

Note that there is still a loophole here
where you can get two bots with the same
name if you reactivate a bot named Fred
that was inactive when the second bot named
Fred was created.  Also, we don't attempt
to fix historical data.  So this commit
shouldn't be considered any kind of lockdown,
it's just meant to help people from
inadvertently creating two bots of the same
name where they don't intend to.  For more
context, we are continuing to allow two
human users in the same realm to have the
same full name, and our code should generally
be tolerant of that possibility.  (A good
example is our new mention syntax, which disambiguates
same-named people using ids.)

It's also worth noting that our web app client
doesn't try to scrub full_name from its payload in
situations where the user has actually only modified other
fields in the "Edit bot" UI.  Starting here
we just handle this on the server, since it's
easy to fix there, and even if we fixed it in the web
app, there's no guarantee that other clients won't be
just as brute force.  It wasn't exactly broken before,
but we'd needlessly write rows to audit tables.

Fixes #10509
2018-10-24 16:59:57 -07:00
Rishi Gupta 458169928c billing: Rename Zulip Premium to Zulip Standard. 2018-10-24 10:42:16 -07:00
Steve Howell 53436b4b41 import: Rename id_maps -> ID_MAP. 2018-10-23 17:27:37 -05:00
Steve Howell bd9e4ef0c8 import: Use pub_date to sort message ids.
When we create new ids for message rows, we
now sort the new ids by their corresponding
pub_date values in the rows.

This takes a sizable chunk of memory.

This feature only gets turned on if you
set sort_by_date to True in realm.json.
2018-10-23 17:27:37 -05:00
Rishi Gupta fbd884f934 billing: Rename MAX_INVITES_PREMIUM.
Largely to have parallel structure with INVITES_DEFAULT_REALM_DAILY_MAX.
2018-10-23 14:47:00 -07:00
Rishi Gupta a7fe6b1c34 billing: Fix max_invites for PREMIUM_FREE.
We could migrate all the current PREMIUM_FREE organizations to have more
invites, but this setting mainly affects orgs right as they are starting, so
it's probably fine.
2018-10-23 14:47:00 -07:00
Rishi Gupta 1c264dedc5 api docs: Change Shakespeare quote.
The previous quote doesn't come off well if you don't know the reference
(which the majority of our users will not).
2018-10-22 15:44:36 -07:00
Aditya Bansal a16bf34c7f thumbnailing: Fix oversharpening of thumbnails.
We seemed to have been doing too much of sharpening on the thumbnails.
The purpose of sharpening here was to just counter the softening
effects of a resize on an image but overdoing it is bad.

Value sharpen(0.5,0.2,true) seems to look good for achieving the
best results here on different displays as revealed in the manual
hit and trial based testing.

Thanks to @borisyankov for pointing out the issue and suggesting
the values.
2018-10-22 22:28:04 +05:30
Tim Abbott 39ea471cf1 error reports: Ensure we filter API keys from query strings.
For some webhook endpoints where the third-party API requires us to do
this, the user's API key might appear in error emails through
appearing in the `QUERY_STRING` parameter.  Fix that by filtering any
actual content from those; what we usually need for debugging is just
what set of parameters were provided.
2018-10-19 15:03:14 -07:00
Rishi Gupta aad5c3df48 user docs: Fix typo causing broken gear icon. 2018-10-18 16:30:42 -07:00
Tim Abbott 695d8d0bd1 get_apns_payload: Require a UserProfile object for the recipient.
This is preparatory work for being able to display an unread count
badge on iOS, in which case we need to know who the current user is.
2018-10-18 15:09:18 -07:00
Tim Abbott 2eebacf2dc push_notifications: Lazily import APNS libraries.
The APNS client libraries (especially the hyper.http20 one) were
determined via profiling to take significant time during the import
process, so we move them to be lazily imported in order to optimize
the overall Zulip import process.  This save up to about 100ms in
import time.

These libraries are only used in certain Django processes inside
zulipchat.com, and so are unnecessary both in development as well as
for self-hosted Zulip servers.
2018-10-17 11:59:33 -07:00
Tim Abbott 704967faa4 email_mirror: Don't import talon unless we're using it.
Talon is an expensive import; on my system, deferring this import
saves 28ms on the import time for Zulip.
2018-10-17 11:25:38 -07:00
Aditya Bansal 8324e2c976 thumbnails: Return original path if url is not supposed to be thumbnailed. 2018-10-16 16:00:47 -07:00
Aditya Bansal 5d68bd92ad thumbnails: Extract user_uploads_or_external as a function.
This is a prepartory commit for the upcoming changes. It was meaningful
to extract this one out because this function is essentially a condition
check on whether a given url is one of the user_uploads or an external
one. Based on its value we decide whether a url must be thumbnailed or
not and thus this function will also be used in an upcoming commit
patching lib/thumbnail.py to do the same check before thumbnail url
generation.
2018-10-16 16:00:47 -07:00
Aditya Bansal 9a411a5765 thumbnails: Stop thumbnailing urls other than external or user_uploads.
We are basically adding a check for url's to be external (belonging
to some 3rd party web site hosting the image) or be one of the
user uploaded files. User uploaded files are served by a separate
endpoint which is /user_uploads/. Any other local url such as
/user_avatars/ or /static/ should never be sent to thumbor for
thumbnailing.
Not sending /user_avatars/ to thumbor for thumbnailing makes sense
because they are already properly thumbnailed and stored properly.
/static/ urls host very few images we use for demo and can be safely
be excluded from thumbnailing.
2018-10-16 16:00:47 -07:00
Yago González 3eeec94d03 api docs: Document the POST /users/me/subscriptions/properties endpoint. 2018-10-16 12:38:27 -07:00
Tim Abbott 8481a2fd2d api docs: Fix confusing discussion of "dev server".
The Zulip API is to be used on both development and production
servers, and really we just need to talk about zuliprc files.

There's a similar issue for the JS docs, but we need to fix the
copy/paste issues with those as well.
2018-10-16 12:23:23 -07:00
Yago González 3d2b3f8fa4 api docs: Document the POST /messages/flags endpoint. 2018-10-16 12:19:24 -07:00
Yago González 7a4103eee6 api docs: Document POST /mark_(all|stream|topic)_as_read. 2018-10-16 12:12:05 -07:00
Yago González 3bdc8f9946 api: Document the GET /realm/emoji endpoint. 2018-10-16 11:51:48 -07:00
Yago González 7a7b507e86 api docs: Document DELETE /realm/filters/<filter_id>. 2018-10-16 11:51:48 -07:00
Yago González a7c48acc8e api docs: Document GET /realm/filters. 2018-10-16 11:51:48 -07:00
Vishnu Ks 57e0a24020 management: Scrub delivery email as well while running scrub_realm. 2018-10-16 11:16:46 -07:00
Steve Howell 2d4b09f59d utils: Add process_list_in_batches(). 2018-10-15 10:54:23 -07:00
Steve Howell 76deb30312 preview: Hash cache keys for preview urls.
We don't want really long urls to lead to truncated
keys, or we could theoretically have two different
urls get mixed up previews.

Also, this suppresses warnings about exceeding the
250 char limit.

Finally, this gives the key a proper prefix.
2018-10-14 09:28:57 -07:00
Steve Howell 493aae2958 imports: Make loading UserMessage faster and more robust.
We use UserMessageLite to avoid Django overhead, and we
do updates in chunks of 10000.  (The export may be broken
into several files already, but a reasonable chunking at
import time is good defense against running out of memory.)
2018-10-13 16:43:28 -07:00
Tim Abbott 68ab71eb8b push: Fix exceptions when removing push notifications.
Now that we allow multiple users to have registered the same token, we
need to configure calls to unregister tokens to only query the
targeted user_id.

We conveniently were already passing the `user_id` into the push
notification bouncer for the remove API, so no migration for older
Zulip servers is required.
2018-10-12 11:19:23 -07:00
Steve Howell 0f7628280f narrow: Handle spurious emails in pm-with searches.
If cordelia searches on pm-with:iago@zulip.com,cordelia@zulip.com,
we now properly treat that the same way as pm-with:iago@zulip.com.

Before this fix, the query would initially go through the
huddle code path.  The symptom wasn't completely obvious, as
eventually a deeper function would return a recipient id
corresponding to a single PM with @iago@zulip.com, but we would
only get messages where iago was the recipient, and not any
messages where he was the sender to cordelia.

I put the helper function for this in zerver/lib/addressee, which
is somewhat speculative.  Eventually, we'll want pm-with queries
to allow for user ids, and I imagine there will be some shared
logic with other Addressee code in terms of how we handle these
strings.  The way we deal with lists of emails/users for various
endpoints is kind of haphazard in the current code, although
granted it's mostly just repeating the same simple patterns.  It
would be nice for some of this code to converge a bit.  This
affects new messages, typing indicators, search filters, etc.,
and some endpoints have strange legacy stuff like supporting
JSON-encoded lists, so it's not trivial to clean this up.

Tweaked by tabbott to add some additional tests.
2018-10-12 10:18:30 -07:00
Steve Howell 8379aeee15 outgoing bots: Fix header for generic servers.
For our bots that use GenericOutgoingWebhookService
(which are basically Zulip style bots), we now
include a "content-type" header of "application/json".

We accomplish this by having the service classes
implement their own custom method called
`send_data_to_server`. For the Slack-related
code, we just extracted code from `do_rest_call`,
and then for the Zulip-related code, we added
a `headers` parameter.
2018-10-11 16:12:07 -07:00
Steve Howell 8f74d99b6c Remove stubs in OutgoingWebhookServiceInterface.
If we omit methods in subclasses, they're likely to
be caught by linters or unit tests, and even if they
aren't, raising NotImplementedError doesn't actually
prevent user problems.

I've been fighting these in refactoring, and it's
just been a bunch of busy work, plus comments are
highly likely to bitrot.
2018-10-11 16:12:07 -07:00
Steve Howell 31597cf33e Remove timeout parameter in do_rest_call().
Nobody was setting it.
2018-10-11 16:12:07 -07:00
Steve Howell 69ee84bb14 refactor: Extract build_bot_request().
This fixes a couple things:

    * process_event() is a pretty vague name
    * returning tuples should generally be avoided
    * we were producing the same REST parameters in both
      subclasses
    * relative_url_path was always blank
    * request_kwargs was always empty

Now process_event() is called build_bot_request(),
and it only returns request data,
not a tuple of `rest_operation` and `request_data`.

By no longer returning `rest_operation`, there are
fewer moving parts.  We just have `do_rest_call` make
a POST call.
2018-10-11 16:12:07 -07:00
Steve Howell 16eff75e49 refactor: Simplify how we use base_url.
Before this change, we instantiated base_url into a superclass
of subclasses that returned base_url into a dictionary that
gets returned to our caller.

Now we just pull base_url out of service when we need to make
the REST call.
2018-10-11 16:12:07 -07:00
Steve Howell b89a94f730 Improve errors when we can't connect to a bot server.
We don't overwhelm people with error info when bots
fail to connect or time out.
2018-10-11 16:12:07 -07:00
Steve Howell 3790c469e9 outgoing bots: Report JSON errors to users.
We should arguably report these to bot owners
as well, but this is at least an improvement
over having the server crash.
2018-10-11 16:12:07 -07:00
Steve Howell df4b665658 refactor: Parse JSON from bots in one place.
We move the JSON parsing step into the
higher level function: process_success_response().

In the unlikely event that we'll start integrating
with a solution that doesn't use JSON, we can deal
with that, and for now doing the parsing in one
place will help us make error reporting more
consistent.

In a subsequent commit we'll introduce better
error handling for malformed JSON.
2018-10-11 16:12:07 -07:00
Steve Howell 229dd5d861 outgoing webhooks: Get rid of "Success!" prefix.
The earlier code here, if it got a payload with
"response_string" as a key, would prefix the
corresponding value with "Success!".  We just
want the bot to set its own content.

The code is reorganized here so that process_success()
always produces a value keyed by "content" from
incoming data, and then process_success_response()
doesn't do any fancy munging of the data.
2018-10-11 16:12:07 -07:00
Tim Abbott 0a751567a3 upload: Fix missing mypy return type annotation. 2018-10-11 16:11:20 -07:00
Aditya Bansal 6893f52ad9 thumbnails: Instruct thumbor to sharpen thumbnailed images.
Fixes: #10218.
2018-10-11 15:44:47 -07:00
Vishnu Ks 962d72b58b retention: move_messages_to_archive should accept multiple message ids.
This will speed up the scrub realm management command. Calling the
function with a single message_id in a loop was extremely inefficient.
2018-10-11 15:31:12 -07:00
Vishnu Ks 6972de21be management: Add command to scrub a realm of personal data. 2018-10-11 15:30:26 -07:00
Vishnu Ks 2f5a5c2c49 test_classes: Create lear_user helper function. 2018-10-11 15:30:26 -07:00
Vishnu Ks 5bdadc8061 upload: Create function to delete avatar image. 2018-10-11 15:30:26 -07:00
Vishnu Ks 1d94fc7dbb upload: Extract function to delete file. 2018-10-11 15:30:26 -07:00
Tim Abbott c57c4cf703 notifications: Fix push notifications with multiple realms.
Previously, Zulip did not correctly handle the case of a mobile device
being registered with a push device token being registered for
multiple accounts on the same server (which is a common case on
zulipchat.com).  This was because our database `unique` and
`unique_together` indexes incorrectly enforced the token being unique
on a given server, rather than unique for a given user_id.

We fix this gap, and at the same time remove unnecessary (and
incorrectly racey) logic deleting and recreating the tokens in the
appropriate tables.

There's still an open mobile app bug causing repeated re-registrations
in a loop, but this should fix the fact that the relevant mobile bug
causes the server to 500.

Follow-up work that may be of value includes:
* Removing `ios_app_id`, which may not have much purpose.
* Renaming `last_updated` to `data_created`, since that's what it is now.

But none of those are critical to solving the actual bug here.

Fixes #8841.
2018-10-10 16:15:52 -07:00
Steve Howell c0df049a18 Allow "content" from outgoing webhooks.
We now allow outgoing webhooks to provide us a
"content" field, which is probably a more guessable
name than "response_string", particularly for folks
that use our other bot-related APIs.  And we don't
modify content as we do response_string, i.e. no
"Success!" prefix.

If we're not too concerned about backward compatibility,
we can do a subsequent commit that makes "content"
and "response_string" true synonyms and get rid of
the "Success!" prefix, which was probably accidental
to begin with.
2018-10-09 15:56:24 -07:00
Steve Howell 6c4343c86d refactor: Clean up send_response_message().
This commit starts by changing the third
argument of send_response_message to be a Dict
instead of a string, so that the data can be more
structured going forward.

That change makes the 2nd/3rd parameters both be
dicts, so to be defensive, I now have all the callers
pass in explicit keyword names.  And then I rename
message to message_info, so that the callers have
more clear code.

And that changes the implementation inside of
send_response_message() a bit.

Sorry this commit is a bit coarse, but the intermediate
commits would have been kind of ugly, too.

At the end of the day, it's pretty simple:

    bot_id: never changed
    message_info: just renamed from message
    response_data: is a Dict with the key of "content"

And the innards of send_response_message() are basically
simply dictionary lookups and function calls.
2018-10-09 15:56:24 -07:00
Steve Howell 4956107c53 refactor: Simplify return type for process_success().
There's no reason to return a failure message in
process_success(), since it's implied to be part of
the success codepath.  I didn't look at the full history
of how the strange API evolved, but the second element
of the tuple was clearly noise by the time I got here.
Neither of the subclasses ever set it, and none of the
consumers used it.
2018-10-09 15:56:24 -07:00
Steve Howell f2dd218331 refactor: Inline succeed_with_message().
This two-line function wasn't really carrying its
weight, and it just made it harder to refactor the
overall codepath.

Eliminating the function forces us to mock at a slightly
deeper level, which is probably a good thing for what
the test intends to do.  The deeper mock still verifies that
we're sending the message (good) without digging into
all the details of how we send it (good).

Note that we will still keep around the similarly named
`fail_with_message` helper, which is a lot more useful.
(The succeed/fail scenarios aren't really symmetric here.
For success, there are fewer codepaths that do more complex
things, whereas we have lots and lots of failure codepaths
that all do the same simple thing of replying with a canned
message.)
2018-10-09 15:56:24 -07:00
Steve Howell fa505a1af1 refactor: Have process_success return structured data.
Before this change subclasses of OutgoingWebhookServiceInterface
would return a raw string as the first element of its return
tuple in process_success().  This is not a very flexible
design, as it prevents the bot from passing extra data like
`widget_content`.

It's also possible in the future that we'll want to let outgoing
bots reply directly to senders who mention them on streams, and
again the original design was overly constrained for that.

This commit does not actually change any functionality yet.
2018-10-09 15:56:24 -07:00
Steve Howell 3bb8cbe0c7 minor: Dedup check_send_message() call. 2018-10-09 15:56:24 -07:00
Steve Howell e641036911 minor: Rename var to message_type. 2018-10-09 15:56:24 -07:00
Steve Howell b61612d50b minor: De-duplicate code for client. 2018-10-09 15:56:24 -07:00
Rishi Gupta 7956c57448 user docs: Add import-from-hipchat. 2018-10-09 15:23:07 -07:00
Lyla Fischer 3c51328763 user docs: Remove icon-vector for font-awesome. 2018-10-09 14:16:16 -07:00
Pragati Agrawal 749e034863 org settings: Rename "Filter settings" to "Linkifiers".
Fixes: #10551
2018-10-09 08:50:45 -07:00
Lenny Jagielski 4fa4ca53c2 webhooks: Add Netlify integration.
Fixes: #10169.
2018-10-05 17:04:40 -07:00
Steve Howell 329154da32 import: Speed up create_subscription_events().
The code was needlessly querying the DB to get full
objects for entities where we only needed user_id,
realm_id, and stream_id.

With my test data of ~1000 records this sped up the
function from ~8s to ~0.5s.  The speedup would probably
be even more for larger data sets.
2018-10-02 16:55:16 -07:00
Adam Birds 18a4239d7e integration: Add AppVeyor webhook. 2018-09-21 17:51:34 -07:00
Shubham Padia 6bfa29b8e6 notifications: Fix soft-deactivated users don't get push notifications.
Fixes the urgent part of #10397.

It was discovered that soft-deactivated users don't get mobile push
notifications for messages on private streams that they have configured
to send push notifications.

Reason: `handle_push_notification` calls `access_message`, and that
logic assumes that a user who is a recipient of a message has an
associated UserMessage row. Those UserMessage rows are created
lazily for soft-deactivated users, so they might not exist (yet)
until the user comes back.

Solution: Ensure that userMessage row is created for
stream_push_user_ids and stream_email_user_ids in create_user_messages.
2018-09-21 12:06:18 -07:00
Adam Birds bd6a5ed7af integrations: Add Ansible Tower Webhook. 2018-09-21 11:05:36 -07:00
Tim Abbott a0451b692f import: Move zerver_client import before realm import.
This table is independent of the realm/stream table dance, and moving
it here helps makes the flow read more clearly.
2018-09-21 10:58:24 -07:00
Rishi Gupta b470cef864 import: Set Realm.plan_type to SELF_HOSTED on import.
Tweaked by tabbott to avoid an unnecessary .save().
2018-09-21 10:57:22 -07:00
Tim Abbott 75376a3fc5 email_mirror: Limit message length using defined constants.
Previously, we had the somewhat arbitrary limit of 2K characters
(which some users complained about), as well as the constant 60 for
the topic.
2018-09-21 10:39:57 -07:00
Tim Abbott feee76eb23 export: Fix exporting files with S3 upload backend.
At some point as part of the process of supporting renumbering data,
we changed the structure of our file uploads to expect `path` to match
`s3_path`, with both having the relative path within the overall
hierarchy (including the realm ID).  This change updates the more
rarely-used S3 export code path to use that model, fixing a crash when
messages reference an Attachment object with a rewritten path_id.
2018-09-20 20:14:19 -07:00
Tim Abbott e2bd03365e import: Fix handling of recipient IDs for welcome bot.
If any user had sent the reply to the welcome bot recommended by our
tutorial, then the Zulip export/import process didn't work properly,
because we weren't including (and then remapping) the recipient ID for
sending PMs to the cross-realm bots.  This commit fixes that gap, by
recording the necessary data on the export side, and doing the
appropriate remapping on the import side.
2018-09-20 17:55:17 -07:00
Tim Abbott c9189439de import: Handle signup_notifications_stream_id.
Previously, our realm import logic only did the special remapping
logic for the original notifications_stream_id; when we added the new
signup_notifications_stream_id field, we neglected to handle it in the
same way.
2018-09-20 17:41:55 -07:00
Eeshan Garg 0817905480 api docs: Use Markdown extension for tabbed sections. 2018-09-18 13:49:34 -07:00
Eeshan Garg 2443919a7e user docs: Use tabbed instructions on desktop-app-install-guide.
Note that the correct tab is automatically activated depending on
the user's OS.
2018-09-18 13:49:34 -07:00
Eeshan Garg ecd4f821be user docs: Automatically activate correct tab for OS-specific instructions. 2018-09-18 13:49:34 -07:00
Eeshan Garg 4f366daec0 markdown: Add extension for creating tabbed sections on /help and /api. 2018-09-18 13:49:34 -07:00
Rishi Gupta bad4a2e8ca user docs: Update invite-a-friend-to-zulip. 2018-09-16 08:24:28 -07:00
Rishi Gupta c050593752 user docs: Add stream relative links. 2018-09-15 23:57:22 -07:00
Rishi Gupta a87ed67695 user docs: Add relative links for gear menu items. 2018-09-15 23:47:45 -07:00
Steve Howell 67e2fd5900 Minimize race conditions for reading zulip.yaml.
In the event that two processes are racing to be the
first to load data from zulip.yaml, we now make the
race scenario be duplicated effort instead of having
the second racer get an attribute error on `data`.

We do this by declaring victory only after setting
`data`.  "Declaring victory" in this case is a matter
of setting `last_update`.

We are still possibly vulnerable to corrupted data
here, so we should investigate a mutex, or just
read the data on every call (but it's strangely
expensive, almost 3.5s on my instance), or converting
the YAML to code before launching the server.
2018-09-12 11:07:20 -07:00
Rishi Gupta 31ed4492ce billing: Add backend for downgrading. 2018-08-31 17:49:34 -07:00
Yago González ea10f5eb2c api docs: Document GET /users/<email>/presence.
Tweaked by tabbott to describe more clearly what this is for.
2018-08-31 15:15:54 -07:00
Rohitt Vashishtha 2864ce552b bugdown: Add @user|id syntax to support users with same name. 2018-08-31 14:16:47 -07:00
Rohitt Vashishtha bc37800ad5 bugdown: Store users with same full_names in mention_data.
We start by stripping the ids in front of the name before the database
lookup. This has the advantage of not mentioning anyone if an incorrect
user id and full name combination is specified, as well as not having
the query the database twice, once by fullname and next by id.

Previously, we were storing only the most recent person with the same
full name as others; this commit adds new keys to the dict such that
simply looking by name would get you the newest user with this name,
and the get_user_by_id function can index the remaining users.
2018-08-31 14:16:47 -07:00
Yago González 78f85ef960 api docs: Document the GET /messages/<message_id>/history endpoint. 2018-08-28 17:33:02 -07:00
Yago González 5c6f381f32 api docs: Document the DELETE /messages/<message_id> endpoint. 2018-08-28 17:26:49 -07:00
Yago González 9575f1b51f api docs: Document the GET /messages/<message_id> endpoint. 2018-08-28 17:22:28 -07:00
Yago González ab164ba740 api docs: Document the GET /messages endpoint. 2018-08-28 17:17:46 -07:00
Vishnu Ks 7b307fa58f billing: Set max_invites to 3000 for Premium organizations.
This is meant to be effectively infinite for legitimate use.
2018-08-28 16:03:34 -07:00
Tim Abbott 54e90deda8 notifications: Handle APNS "Unregistered" errors properly.
Apparently, the APNS library we're using is inconsistent about the
format of its result entries; some are strings while others are
tuples.
2018-08-28 12:12:46 -07:00
Yago González c36cf95dc8 api docs: Document GET /server_settings. 2018-08-27 17:45:50 -07:00
Yago González 54464feda7 api docs: Document the PATCH /users/me/subscriptions/muted_topics endpoint. 2018-08-26 23:10:21 -07:00
Steve Howell 9e8930f6de tests: Test get_widget_data() helper.
We also remove some unreachable code.  Calling
split() always returns at least one token, even
if it's just the empty string.  This is tested
directly on this commit, plus messages with
empty content get rejected pretty early in
the execution path.
2018-08-24 10:00:25 -07:00
Tim Abbott c313a939f7 custom profile fields: Cleanup event generation logic.
In my opinion, this makes the code somewhat more readable.
2018-08-22 22:45:08 -07:00
Yashashvi Dave d5153bd136 events: Convert custom user field value to json object on update event.
In user type custom field, field value is list of user ids. We weren't
converting list to json object in update event payload. This throws
error in frontend, cause we store stringify representation of custom
field value. Therefore, after update event is recieved field-value-
type gets updated to array from string which throws json parsing error.
2018-08-22 22:45:08 -07:00
Shubham Dhama e784c95d97 guests: Prevent guests from sending to unsubscribed public streams.
This matches the overall security model of these users only having
access to streams they are subscribed to.
2018-08-22 17:53:42 -07:00
Yago González e7c7b19507 api docs: Document POST /realm/filters. 2018-08-22 17:42:14 -07:00
Yago González df7234f3a6 api docs: Escape HTML in the examples.
Having HTML (or HTML-like) content in the examples was making parts of
the content invisible, since the browser identified them as HTML tags
rather than verbose text.
2018-08-22 17:19:09 -07:00
Yago González c70d051031 test-api: Add function for server & realm tests.
There are some endpoints that don't fall into the currently available
categories, so this new function will be used for calling the tests for
server and realm-related endpoints.
2018-08-22 17:19:09 -07:00
Steve Howell fe6680c316 refactor: Flatten code in check_invite_limit().
Using early-exit here allows us to more easily
comment why there are certain exemptions to
this logic.

We also only require callers to pass in realm,
not the whole user object.
2018-08-22 16:52:30 -07:00
Steve Howell 4318f75718 Remove `code` from JsonableError.__init__.
Since this class was built, folks have always chosen
to subclass JsonableError for situations where
the default of ErrorCode.BAD_REQUEST is insufficient.

So now we simplify the use cases, which also gets
us 100% coverage on this core module.
2018-08-22 16:51:40 -07:00
Tim Abbott 2e6aaf3215 actions: Use better query for active_mobile_push_notification. 2018-08-21 15:28:05 -07:00
Tim Abbott 887d20795f message flags: Add where_starred helper and use it.
The previous query ended up doing a scan of all a user's UserMessage
rows, not just the ones tracked in the `starred` index.
2018-08-21 15:28:04 -07:00
Joshua Pan 83d8d662dc events: Query starred message ids in fetch_initial_state_data. 2018-08-21 13:01:41 -07:00
Vishnu Ks 9bb338be11 models: Add plan_type to Realm. 2018-08-21 12:39:06 -07:00
Yashashvi Dave 6e65235a6d zerver/lib/events.py: Add FIELD_TYPE_CHOICES_DICT to page_params.
This commit add FIELD_TYPE_CHOICES_DICT to page_params and replace
FIELD_TYPE_CHOICES.

FIELD_TYPE_CHOICES_DICT includes all field types with keyword, id
and display name. Using this field-type-dict, we can access field
type information by it's keyword, and remove all static use of
field-type'a name or id in frontend.
This commit also modifies functions in js where this page_params
field-types is used.
2018-08-21 11:37:51 -07:00
Yashashvi Dave 621a5cdc35 zerver/models.py: Modify FIELD_TYPE_DATA, add keyword for field type.
This commit modifies FIELD_TYPE_DATA dict in `CustomProfileField`
model to store keyword of field types. And create new dict
FIELD_TYPE_CHOICES_DICT to store all field type information
by field type keyword, i.e. id, name.

This is preparatory commit to remove all static use of field
types in frontend and access field type with keyword instead
of display name.
2018-08-21 11:37:51 -07:00
Steve Howell a6bc3886e6 refactor: Extract send_peer_remove_event().
This prevents leaking some variables into an already
cluttered function.

We also add test coverage for what's now an
early-exit condition in the new function--we exempt
public MIT streams from these events.
2018-08-21 11:23:40 -07:00
Steve Howell 79fb36c599 refactor: Extract maybe_add_event() function.
This change was partially driven by a quirk in Python
where peephole optimizations make `continue` lines
appear not to be covered.

I also think it's generally a good idiom to extract
functions for loop bodies when they don't actually
accumulate values or maintain other state.  With this
commit we now prevent potential bugs for vars like
`is_stream` leaking between loop iterations.
2018-08-21 11:23:40 -07:00
Steve Howell e99c0929f0 tests: Test race handling for creating mirror users.
We simulate a race condition by mocking create_user
to actually create a user, but then raise an
IntegrityError (as if another process had actually
created the user, not our test).

I also changed the real code to use explicitly
named parameters.
2018-08-21 11:23:40 -07:00
Tim Abbott 0068a5ccd6 events: Fix can_subscribe_other_users not being set properly.
I don't understand why this didn't cause test failures in CI; this
change was clearly required and test_change_realm_property was failing
consistently for me locally.
2018-08-21 11:20:59 -07:00
Rishi Gupta 99b55b712b user docs: Shorten instructions when using relative settings links. 2018-08-20 21:26:01 -07:00
Abhilash Verma 0e2322a322 logging: Show timestamp in UTC in non-django production scripts.
Done in pair programming with @aero31aero.

Fixes #9678.
2018-08-20 12:52:40 -07:00
Rohitt Vashishtha 920ef2b7f7 bugdown: Add mention_data.get_user_by_id().
This will allow us to do the lookups required to support the upcoming
`@**name|id**` syntax.
2018-08-20 12:46:46 -07:00
Yago González aa5185fdf8 api docs: Document POST /typing. 2018-08-17 12:57:40 -07:00
Akash Nimare dab75e4990 help: Fix styling of emoticons on help pages. 2018-08-17 11:37:29 -07:00
Rishi Gupta c3a912f8b6 management commands: Add sleep_forever to lib/management. 2018-08-17 09:20:51 -07:00
Steve Howell 0e56fecbd9 peformance: Avoid broad StreamCount queries.
Our get_streams_traffic function used to query
all streams in the StreamCount table if you
passed in `None` for `streams`.

Now we require that you pass in a list of
stream_ids.

I don't know how much work this will save
the database, since probably the bulk of
the work is aggregating.  If we need to fine
tune DB performance, we could possibly add
`realm` as an argument and add it to the filter.

What we'll immediately get, for large multi-realm
installations, is less data over the wire and
less work for the ORM.
2018-08-17 08:14:42 -07:00
Steve Howell 040dafbfc5 refactor: Streamline subscribed_to_stream().
The prior code uses an awkward idiom that
pre-dates the `exists()` function, and it
had an unreachable line of code.

The new version should be faster, since we
don't create a throwaway heavy Django object
or send needless data over the wire.
2018-08-17 08:14:42 -07:00
Steve Howell c41377aaab Remove _default_stream_permision_check.
This functions appears to be redundant to
`access_stream_by_name`.  The only
meaningful line of code in the function that we're
removing, the code that raises an error,
appears to be unreachable, despite reasonably
extensive tests.

The only thing the function was restricting
was that the case where the bot's owner was
unsubscribed to a private stream, which
is already locked down in
`access_stream_by_name` calls inside of
`patch_bot_backend`.

This commit increases test coverage
by removing unreachable code.

It's possible this function had
some theoretical value before we
introduced the `require_non_guest_human_user`
decorator to the `patch_bot_backend`
view, since in theory the bot itself
could have subscribed to a stream that
the owner didn't subscribe to.  Even
then it's not clear that allowing the
bot to set that as a default stream
would have been harmful, since they
can already access it.
2018-08-17 08:14:42 -07:00
Steve Howell 93e8798ac7 Extract get_last_message_id().
We want our methodology for extracting the last message
id to be consistent, particularly in terms of how we
handle edge cases.  (I'll concede that the
`bulk_remove_subscriptions` codepath never hits that
corner case in practice, but it's harmless to handle
the theoretical case.)

It may also be nice to have this function show up
clearly in profiling.

This also adds some direct testing to the function.

It's not clear to me why we don't use `latest('id')`
in the implementation, but that's outside the scope
of this commit.
2018-08-17 08:14:42 -07:00