Commit Graph

649 Commits

Author SHA1 Message Date
Anders Kaseorg 31d0141a30 python: Close opened files.
Fixes various instances of ‘ResourceWarning: unclosed file’ with
python -Wd.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2020-10-26 12:31:30 -07:00
Anders Kaseorg 72d6ff3c3b docs: Fix more capitalization issues.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2020-10-23 11:46:55 -07:00
Steve Howell 9df9934ed6 refactor: Pass realm to bulk_add_subscriptions.
I think it's important that the callers understand
that bulk_add_subscriptions assumes all streams
are being created within a single realm, so I make
it an explicit parameter.

This may be overkill--I would also be happy if we
just included the assertions from this commit.
2020-10-13 11:28:17 -07:00
Alex Vandiver d47637fa40 queue: Set a max consume timeout with SIGALRM.
SIGALRM is the simplest way to set a specific maximum duration that
queue workers can take to handle a specific message.  This only works
in non-threaded environments, however, as signal handlers are
per-process, not per-thread.

The MAX_CONSUME_SECONDS is set quite high, at 10s -- the longest
average worker consume time is embed_links, which hovers near 1s.
Since just knowing the recent mean does not give much information[1],
it is difficult to know how much variance is expected.  As such, we
set the threshold to be such that only events which are significant
outliers will be timed out.  This can be tuned downwards as more
statistics are gathered on the runtime of the workers.

The exception to this is DeferredWorker, which deals with quite-long
requests, and thus has no enforceable SLO.

[1] https://www.autodesk.com/research/publications/same-stats-different-graphs
2020-10-06 17:26:14 -07:00
Alex Vandiver 8cf37a0d4b queue: Add a tool to profile no-op enqueue and dequeue actions. 2020-10-06 17:26:14 -07:00
sahil839 2e58e27926 populate_db: Set wildcard_mention_policy to show warning in test_suite.
We set wildcard_mention_policy in the test database so that we can
avoid future changes in mention puppeteer tests, as the default
membership of streams in the Zulip development organization is large
enough to prevent random users from using wildcard mentions.
2020-10-01 12:20:41 -07:00
sahil839 6c473ed75f message: Call build_message_send_dict from check_message.
We call build_message_send_dict from check_message instead of
do_send_messages.

This is a prep commit for adding a new setting for handling
wildcard mentions in large streams.
2020-09-29 17:18:04 -07:00
Wes Galbraith 9645959ac4 populate_db: Add emoji reactions to development environment database.
This change adds automated generated emoji reactions to the data in
the development environment's database.

Fixes part of #14991.
2020-09-23 16:10:37 -07:00
Anders Kaseorg 0228acf0f5 rest: Add rest_path shortcut for path with rest_dispatch.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2020-09-22 10:51:00 -07:00
Anders Kaseorg 5297e4a30a urls: Use unqualified imports.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2020-09-22 10:51:00 -07:00
Anders Kaseorg e70f2ae58d rest: Specify rest_dispatch handlers by function, not by string.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2020-09-22 10:46:28 -07:00
Alex Vandiver e5f62d083e tornado: Merge the TORNADO_SERVER and TORNADO_PORTS configs.
Having both of these is confusing; TORNADO_SERVER is used only when
there is one TORNADO_PORT.  Its primary use is actually to be _unset_,
and signal that in-process handling is to be done.

Rename to USING_TORNADO, to parallel the existing USING_RABBITMQ, and
switch the places that used it for its contents to using
TORNADO_PORTS.
2020-09-21 15:36:16 -07:00
Anders Kaseorg a50fae89e2 python: Elide type=str from argparse arguments.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2020-09-03 16:17:14 -07:00
Anders Kaseorg 1f2ac1962f python: Elide default=None for argparse arguments.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2020-09-03 16:17:14 -07:00
Anders Kaseorg b4597a8ca8 python: Elide default for store_{true,false} argparse arguments.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2020-09-03 16:17:14 -07:00
Anders Kaseorg a276eefcfe python: Rewrite dict() as {}.
Suggested by the flake8-comprehensions plugin.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2020-09-02 11:15:41 -07:00
Anders Kaseorg a5dbab8fb0 python: Remove redundant dest for argparse arguments.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2020-09-02 11:04:10 -07:00
Hashir Sarwar b885678881 push_notifications: Simplify `if device exists` checks. 2020-08-31 17:31:41 -07:00
Anders Kaseorg 61d0417e75 python: Replace ujson with orjson.
Fixes #6507.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2020-08-11 10:55:12 -07:00
Anders Kaseorg dbdf67301b memcached: Switch from pylibmc to python-binary-memcached.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2020-08-06 12:51:14 -07:00
Steve Howell c44500175d database: Remove short_name from UserProfile.
A few major themes here:

    - We remove short_name from UserProfile
      and add the appropriate migration.

    - We remove short_name from various
      cache-related lists of fields.

    - We allow import tools to continue to
      write short_name to their export files,
      and then we simply ignore the field
      at import time.

    - We change functions like do_create_user,
      create_user_profile, etc.

    - We keep short_name in the /json/bots
      API.  (It actually gets turned into
      an email.)

    - We don't modify our LDAP code much
      here.
2020-07-17 11:15:15 -07:00
Steve Howell 7c0fa3aefc populate_db: Add alert words for Zulip users. 2020-07-15 12:33:08 -07:00
Steve Howell 5c544da843 populate_db: Extract/fix mark_all_messages_as_read.
The prior version clobbered all flags, which means
we had unrealistic values for is_private.

Now we only touch the unread flag, which
also means when we go next to create alert words,
those will now work.
2020-07-15 12:33:08 -07:00
arpit551 e0c9b0fdff audit_log: Log RealmAuditLog when Stream is created.
Added new Event Type in AbstractRealmAuditLog STREAM_CREATED.
Since we finally create streams in create_stream_if_needed function
in zerver/lib/streams.py so logged realm_audit there.
Passed acting_user when create_stream_if_needed or ensure_stream
function  is called.
Added tests in test_audit_log.
2020-07-06 17:32:11 -07:00
arpit551 87aaa84b42 audit_log: Log acting_user in do_change_user_role. 2020-07-06 17:32:11 -07:00
arpit551 01f12b9fc2 audit_log: Log acting_user in user creation and user activation. 2020-07-06 17:32:09 -07:00
arpit551 653928bdfe audit_log: Log acting_user in do_change_avatar_fields. 2020-07-06 17:24:18 -07:00
Aman Agrawal a7eef1ed35 mark_all_messages_unread: Remove reset of depricated pointer. 2020-07-06 15:47:27 -07:00
Anders Kaseorg 6c9c12ee2d add_new_realm: Fix strict_optional errors.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2020-07-06 11:25:48 -07:00
Tim Abbott 866965f162 views: Rename messages.py to message_fetch.py.
This completes to effort to split zerver.views.messages into smaller
modules focused on the different core type of work.
2020-06-22 15:08:34 -07:00
Anders Kaseorg f364d06fb5 python: Convert percent formatting to .format for translated strings.
Signed-off-by: Anders Kaseorg <anders@zulip.com>
2020-06-15 16:24:46 -07:00
Anders Kaseorg 74c17bf94a python: Convert more percent formatting to Python 3.6 f-strings.
Generated by pyupgrade --py36-plus.

Now including %d, %i, %u, and multi-line strings.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2020-06-14 23:27:22 -07:00
Anders Kaseorg 365fe0b3d5 python: Sort imports with isort.
Fixes #2665.

Regenerated by tabbott with `lint --fix` after a rebase and change in
parameters.

Note from tabbott: In a few cases, this converts technical debt in the
form of unsorted imports into different technical debt in the form of
our largest files having very long, ugly import sequences at the
start.  I expect this change will increase pressure for us to split
those files, which isn't a bad thing.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2020-06-11 16:45:32 -07:00
Anders Kaseorg 69730a78cc python: Use trailing commas consistently.
Automatically generated by the following script, based on the output
of lint with flake8-comma:

import re
import sys

last_filename = None
last_row = None
lines = []

for msg in sys.stdin:
    m = re.match(
        r"\x1b\[35mflake8    \|\x1b\[0m \x1b\[1;31m(.+):(\d+):(\d+): (\w+)", msg
    )
    if m:
        filename, row_str, col_str, err = m.groups()
        row, col = int(row_str), int(col_str)

        if filename == last_filename:
            assert last_row != row
        else:
            if last_filename is not None:
                with open(last_filename, "w") as f:
                    f.writelines(lines)

            with open(filename) as f:
                lines = f.readlines()
            last_filename = filename
        last_row = row

        line = lines[row - 1]
        if err in ["C812", "C815"]:
            lines[row - 1] = line[: col - 1] + "," + line[col - 1 :]
        elif err in ["C819"]:
            assert line[col - 2] == ","
            lines[row - 1] = line[: col - 2] + line[col - 1 :].lstrip(" ")

if last_filename is not None:
    with open(last_filename, "w") as f:
        f.writelines(lines)

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-06-11 16:04:12 -07:00
Anders Kaseorg 67e7a3631d python: Convert percent formatting to Python 3.6 f-strings.
Generated by pyupgrade --py36-plus.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2020-06-10 15:02:09 -07:00
Anders Kaseorg 8dd83228e7 python: Convert "".format to Python 3.6 f-strings.
Generated by pyupgrade --py36-plus --keep-percent-format, but with the
NamedTuple changes reverted (see commit
ba7906a3c6, #15132).

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2020-06-08 15:31:20 -07:00
Anders Kaseorg 1f565a9f41 timezone: Use standard library datetime.timezone.utc consistently.
datetime.timezone is available in Python ≥ 3.2.  This also lets us
remove a pytz dependency from the PostgreSQL scripts.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2020-06-05 09:34:17 -07:00
Sahil Batra 77d4be56a4
users: Modify do_create_user and create_user to accept role.
We change do_create_user and create_user to accept
role as a parameter instead of 'is_realm_admin' and 'is_guest'.
These changes are done to minimize data conversions between
role and boolean fields.
2020-06-02 16:11:36 -07:00
sahil839 2fe8971204 populate_db: Change role of 'desdemona' to realm owner.
Modified by tabbott to update PROVISION_VERSION.
2020-06-01 15:22:27 -07:00
anshgit101 d0cfaebb15 populate_db: Reduce 'boring users' threshold. 2020-05-30 10:26:56 -04:00
sahil839 1aebf3cab9 actions: Merge do_change_is_admin and do_change_is_guest.
This commit merges do_change_is_admin and do_change_is_guest to a
single function do_change_user_role which will be used for changing
role of users.

do_change_is_api_super_user is added as a separate function for
changing is_api_super_user field of UserProfile.
2020-05-25 16:17:10 -07:00
sahil839 9b78a73e36 populate_db: Add new admin user as 'Desdemona'.
This commit adds a second admin user named 'Desdemona' to dev and
test database.
2020-05-19 11:42:27 -07:00
wowol 049288eaeb urls: Migrate zilencer urls to use modern django pattern. 2020-05-07 16:28:58 -07:00
Aman Agrawal a4495dbc6b populate_db: Generate topics using config fixture.
Instread of using stream_name + Intergers as topics, we now
generate topics using pos in `config.generate_data.json`.

This helps us create and test more realistic topics.
2020-05-05 16:11:09 -07:00
Aman Agrawal 8e0f0d2096 populate_db: Evenly distribute messages across all streams.
Populate db with messages after non-Shakespeare streams
are created so that we can distribute messages across them too.
2020-05-04 09:41:31 -07:00
Aman Agrawal b25f2ed5b3 populate_db: Add option to specify max no of topics to create.
This will help us create more topics per stream than we currently do
by default.
2020-05-04 09:41:31 -07:00
Anders Kaseorg bdc365d0fe logging: Pass format arguments to logging.
https://docs.python.org/3/howto/logging.html#optimization

Signed-off-by: Anders Kaseorg <anders@zulip.com>
2020-05-02 10:18:02 -07:00
Anders Kaseorg fead14951c python: Convert assignment type annotations to Python 3.6 style.
This commit was split by tabbott; this piece covers the vast majority
of files in Zulip, but excludes scripts/, tools/, and puppet/ to help
ensure we at least show the right error messages for Xenial systems.

We can likely further refine the remaining pieces with some testing.

Generated by com2ann, with whitespace fixes and various manual fixes
for runtime issues:

-    invoiced_through: Optional[LicenseLedger] = models.ForeignKey(
+    invoiced_through: Optional["LicenseLedger"] = models.ForeignKey(

-_apns_client: Optional[APNsClient] = None
+_apns_client: Optional["APNsClient"] = None

-    notifications_stream: Optional[Stream] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE)
-    signup_notifications_stream: Optional[Stream] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE)
+    notifications_stream: Optional["Stream"] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE)
+    signup_notifications_stream: Optional["Stream"] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE)

-    author: Optional[UserProfile] = models.ForeignKey('UserProfile', blank=True, null=True, on_delete=CASCADE)
+    author: Optional["UserProfile"] = models.ForeignKey('UserProfile', blank=True, null=True, on_delete=CASCADE)

-    bot_owner: Optional[UserProfile] = models.ForeignKey('self', null=True, on_delete=models.SET_NULL)
+    bot_owner: Optional["UserProfile"] = models.ForeignKey('self', null=True, on_delete=models.SET_NULL)

-    default_sending_stream: Optional[Stream] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE)
-    default_events_register_stream: Optional[Stream] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE)
+    default_sending_stream: Optional["Stream"] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE)
+    default_events_register_stream: Optional["Stream"] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE)

-descriptors_by_handler_id: Dict[int, ClientDescriptor] = {}
+descriptors_by_handler_id: Dict[int, "ClientDescriptor"] = {}

-worker_classes: Dict[str, Type[QueueProcessingWorker]] = {}
-queues: Dict[str, Dict[str, Type[QueueProcessingWorker]]] = {}
+worker_classes: Dict[str, Type["QueueProcessingWorker"]] = {}
+queues: Dict[str, Dict[str, Type["QueueProcessingWorker"]]] = {}

-AUTH_LDAP_REVERSE_EMAIL_SEARCH: Optional[LDAPSearch] = None
+AUTH_LDAP_REVERSE_EMAIL_SEARCH: Optional["LDAPSearch"] = None

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-22 11:02:32 -07:00
Anders Kaseorg c734bbd95d python: Modernize legacy Python 2 syntax with pyupgrade.
Generated by `pyupgrade --py3-plus --keep-percent-format` on all our
Python code except `zthumbor` and `zulip-ec2-configure-interfaces`,
followed by manual indentation fixes.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-09 16:43:22 -07:00
Steve Howell eb9a252ec9 populate_db, tests: Restrict emails in zulip realm.
We now restrict emails on the zulip realm, and now
`email` and `delivery_email` will be different for
users.

This change should make it more likely to catch
errors where we leak delivery emails or use the
wrong field for lookups.
2020-03-19 16:21:31 -07:00
Mateusz Mandera 89394fc1eb middleware: Use request.user for logging when possible.
Instead of trying to set the _requestor_for_logs attribute in all the
relevant places, we try to use request.user when possible (that will be
when it's a UserProfile or RemoteZulipServer as of now). In other
places, we set _requestor_for_logs to avoid manually editing the
request.user attribute, as it should mostly be left for Django to manage
it.
In places where we remove the "request._requestor_for_logs = ..." line,
it is clearly implied by the previous code (or the current surrounding
code) that request.user is of the correct type.
2020-03-09 13:54:58 -07:00
Mateusz Mandera fe0f381914 populate_db: Don't restrict email domains by default in tests and dev.
The email domain restriction to @zulip.com is annoying in development
environment when trying to test sign up. For consistency, it's best to
have tests use the same default, and the tests that require domain
restriction can be adjusted to set that configuration up for themselves
explicitly.
2020-03-07 18:38:59 -08:00
Steve Howell c4e3cfebb0 presence: Add realm_id to UserPresence.
This index is intended to optimize the performance of the very
frequently run query of "what is the presence status of all users in a
realm?".

Main changes:
    - add realm_id to UserPresence
    - add index for realm_id
    - backfill realm_id for old rows
    - change all writes to UserPresence to include
      realm_id

The index is of this form:

    "zerver_userpresence_realm_id_5c4ef5a9" btree (realm_id)

We will create an index on (realm_id, timestamp) in a
future commit, but I think it's a bit faster if you do
the backfill before the index.

There's also a minor tweak to the populate_db script.
2020-02-10 17:21:45 -08:00
Steve Howell 1f62b5e671 populate_db: Remove create_user_presenses() helper.
The last caller to this function was removed in
64230b3bd5

So it's been dead code for a while.
2020-02-10 17:20:44 -08:00
Ryan Rehman 174b2abcfd settings: Migrate to stream_post_policy structure.
This commit includes a new `stream_post_policy` setting,
by replacing the `is_announcement_only` field from the Stream model,
which is done by mirroring the structure of the existing
`create_stream_policy`.

It includes the necessary schema and database migrations to migrate
the is_announcement_only boolean field to stream_post_policy,
a smallPositiveInteger field similar to many other settings.

This change is done to allow organization administrators to restrict
new members from creating and posting to a stream. However, this does
not affect admins who are new members.

With many tweaks by tabbott to documentation under /help, etc.

Fixes #13616.
2020-02-04 17:08:08 -08:00
Mateusz Mandera d24936cbe3 server_initialization: Use tos_version argument in create_users. 2020-01-29 17:26:45 -08:00
Mateusz Mandera 261da5999d populate_db: Extract default client creation to server_initialization. 2020-01-29 17:26:45 -08:00
Mateusz Mandera a25f00a69c populate_db: Extract some functions to server_initialization.py. 2020-01-29 17:26:45 -08:00
Vishnu KS 05b4610381 bots: Remove feedback cross realm bot.
This completes the remaining pieces of removing this missed in
d70e799466 (mostly in tests).
2020-01-25 22:54:44 -08:00
Anders Kaseorg cdda983e90 settings: Support optional memcached authentication.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-01-15 17:35:15 -08:00
Tim Abbott 8e7ce7cc79 python: Sort migrations/management command imports with isort.
This is a preparatory commit for using isort for sorting all of our
imports, merging changes to files where we can easily review the
changes as something we're happy with.

These are also files with relatively little active development, which
means we don't expect much merge conflict risk from these changes.
2020-01-14 13:07:47 -08:00
Tim Abbott 0dc7542363 populate_db: Fix cache flushing when rebuilding test database.
This fixes a similar problem to the last commit; we don't use
memcached with the test database, so we don't need to flush memcached
when rebuilding it.

(And if we try, we'll get exceptions trying to access the relevant
settings).
2020-01-13 18:22:55 -08:00
Tim Abbott 571ce2f5cb populate_db: Fix handling of memcached flushing.
Our recent fixes to using the system's configured memcached settings
broke populate_db, because its hacky clear_database helper is called
with a hacked-up settings module.

We fix this by first moving this out-of-place code from models.py into
populate_db, and then saving the settings required to access memcached
so that we can use them in clear_database.

We also fix a mypy erorr in flush-memcached that matches the same
issue fixed in clear_database.
2020-01-13 18:05:21 -08:00
Steve Howell 6a9eaebff2 populate_db: Make num_recips calculation more clear.
Extracting this calculation makes it easier to hack
it when you're trying to load lots of users.

We probably want a slightly more realistic calculation
here for stress testing.  And also fewer rows.  But
at least now it's a little more clear what it's doing.
2019-12-28 10:56:03 -08:00
Steve Howell 4a8c70593f populate_db: Add random names for large user batches.
If extra_users > 1000, add some names that are more
interesing than Extra111 User.
2019-12-28 10:56:03 -08:00
Tim Abbott 6407d0b1f9 push_notifications: Clear PushDeviceToken on API key change.
This includes adding a new endpoint to the push notification bouncer
interface, and code to call it appropriately after resetting a user's
personal API key.

When we add support for a user having multiple API keys, we may need
to add an additional key here to support removing keys associated with
just one client.
2019-11-19 15:37:43 -08:00
Anders Kaseorg cafac83676 request: Tighten type checking on REQ.
Then, find and fix a predictable number of previous misuses.

With a small change by tabbott to preserve backwards compatibility for
sending `yes` for the `forged` field.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2019-11-13 12:35:55 -08:00
Anders Kaseorg b0a7b33f9b push_notifications: Declare token of type str, not bytes.
Declaring a CharField of type bytes made no sense.

Signed-off-by: Anders Kaseorg <andersk@zulipchat.com>
2019-11-12 23:21:20 -08:00
Rishi Gupta 360cd7f147 remote data: Send RealmAuditLog data. 2019-10-08 17:27:29 -07:00
Rishi Gupta 48dc1d1128 remote data: Refactor remote_server_post_analytics to be more generic.
One small change in behavior is that this creates an array with all the
row_objects at once, rather than creating them 1000 at a time.

That should be fine, given that the client batches these in units of
10000 anyway, and so we're just creating 10K rows of a relatively
small data structure in Python code here.
2019-10-06 16:55:41 -07:00
Rishi Gupta e10361a832 models: Replace is_guest and is_realm_admin with UserProfile.role.
This new data model will be more extensible for future work on
features like a primary administrator.
2019-10-06 16:24:37 -07:00
Mateusz Mandera dbe508bb91 models: Migration of Message.pub_date to date_sent, part 2.
Fixes #1727.

With the server down, apply migrations 0245 and 0246. 0246 will remove
the pub_date column, so it's essential that the previous migrations
ran correctly to copy data before running this.
2019-10-05 19:01:34 -07:00
Mateusz Mandera 4166c901ef do_update_user_custom_profile_data: Rename to ..._if_changed.
This adds clarity to the fact that the function no longer does
anything if the field values haven't changed.
2019-10-01 13:52:43 -07:00
Yashashvi Dave e05429b6a9 custom fields: Add default external account custom fields. 2019-08-28 15:35:53 -07:00
Mateusz Mandera 16479fa606 populate_db: Extract internal realm creation into a function. 2019-08-23 12:57:24 -07:00
Gloria Elston 092662d83e api: Use new endpoint for handling reactions. 2019-08-16 14:36:15 -07:00
Anders Kaseorg 5d063910ff zilencer: Clean up type ignores.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2019-08-09 17:42:33 -07:00
Anders Kaseorg becef760bf cleanup: Delete leading newlines.
Previous cleanups (mostly the removals of Python __future__ imports)
were done in a way that introduced leading newlines.  Delete leading
newlines from all files, except static/assets/zulip-emoji/NOTICE,
which is a verbatim copy of the Apache 2.0 license.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2019-08-06 23:29:11 -07:00
Mateusz Mandera 8e0b6fa6cf populate_db: Use separate realm for system bots, like in production.
This commit alone breaks things, needs to be merged with the follow-up
ones.

welcome-bot is removed from the explicit list, because it already is in
settings.INTERNAL_BOTS.
2019-07-31 15:58:39 -07:00
Anders Kaseorg fd7803e7f4 settings: Unset STATIC_ROOT in development.
Django’s default FileSystemFinder disallows STATICFILES_DIRS from
containing STATIC_ROOT (by raising an ImproperlyConfigured exception),
because STATIC_ROOT is supposed to be the result of collecting all the
static files in the project, not one of the potentially many sources
of static files.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2019-07-24 17:40:31 -07:00
Mateusz Mandera 34b9a7bcad populate_db: Refactor and rename send_messages().
We rename the send_messages function to generate_and_messages, and
factor out the actual sending part of it into a separate function, which
now gets the name send_messages().
2019-07-22 15:56:17 -07:00
Mateusz Mandera e5138c38b2 populate_db: Add a batching option. 2019-07-22 15:55:28 -07:00
Mateusz Mandera d1bab42da6 populate_db: Send generated messages in one do_send_messages call.
Sending messages one-by-one is significantly slower compared to taking
advantage of the batch-handling code in do_send_messages, so we pass all
the messages to the function in one go. This is memory-hungry if there's
a lot of messages, so we will allow splitting into smaller batches in
the next commit.
2019-07-22 15:55:28 -07:00
Mateusz Mandera a50524762c populate_db: Refactor message.pub_date generating code.
The code generating pub_dates for messages would fail to distribute them
across days if tot_messages was too large.
We refactor this code as a separate function (for clarity and to unit
test for the bug we're fixing), and change the structure and naming to a
form that more clearly describes what's happening. We also shift away
from the approach of all the float-to-int conversions as this is in
general tricky and bug prone - django's timedelta() handles floats as
arguments, so we take advantage of that.
2019-07-22 15:55:28 -07:00
Wyatt Hoodes 9b69c1f7fe Merge pull request #12833 from whoodes/clean-up-new-user-bot
bots: Replace remnants of new-user-bot with default-bot@zulip.com.
2019-07-20 14:38:05 -07:00
Mateusz Mandera c1a8ba2974 populate_db: Use do_change_is_admin for setting api_super_user. 2019-07-15 12:32:29 -07:00
Yashashvi Dave d7ee2aced1 models: Add `external_account` in custom profile field types.
Add new custom profile field type, External account.
External account field links user's social media
profile with account. e.g. GitHub, Twitter, etc.

Fixes part of #12302
2019-07-09 17:21:54 -07:00
Yashashvi Dave f813fdcd5e populate_db: Rename URL type custom profile field.
Rename URL type custom profile field in populate db to avoid confusion
with the "GitHub profile" custom external account profile field we'll
be adding shortly.
2019-07-09 17:21:39 -07:00
Vaibhav fa85b92eda populate_db: Add MD content to stream descriptions and user bio.
This adds a 'bold' element to `all` stream and 'code' element to
`test` stream in populate_db. Also changes the bio for Hamlet to
include a list.
2019-06-24 22:10:24 -07:00
Wyatt Hoodes fb58b54293 test-backend: Move `test_messages.json` to `var/<uuid>/test-backend`. 2019-06-24 12:23:09 -07:00
Tim Abbott bcc6949461 zilencer: Add better error handling for IntegrityError.
This provides a clean warning and 40x error, rather than a 500, for
this corner case which is very likely user error.

The test here is awkward because we have to work around
https://github.com/zulip/zulip/issues/12362.
2019-05-20 17:53:43 -07:00
neiljp (Neil Pilgrim) f3ef2a186c mypy: Enable strict-optional for calculate_first_visible_message_id. 2019-05-01 10:49:24 -07:00
Vishnu Ks ecdd3bea43 billing: Add cron job to run invoice_plans once a day.
Fixes #11960
2019-04-29 11:23:17 -07:00
Anders Kaseorg 9a9de156c3 lint: Fix calls to _() on computed strings.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2019-04-23 15:23:03 -07:00
Anders Kaseorg 643bd18b9f lint: Fix code that evaded our lint checks for string % non-tuple.
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2019-04-23 15:21:37 -07:00
Tim Abbott cfd5054f2d zilencer: Add indexes for remotecount models.
These new indexes improve the performance of checking whether our
Remote*Count models are up to date by a factor of ~1000.
2019-04-23 13:52:02 -07:00
Rishi Gupta e8741c448d refactoring: Move set_default_streams into do_create_realm.
After the commits leading up to this, the only meaningful use of this
function was in the realm creation process.
2019-03-21 12:33:19 -07:00
Rishi Gupta e71a1a2b4e onboarding: Remove initial streams other than general and core team.
The hope is that by having a shorter list of initial streams, it'll
avoid some potential confusion confusion about the value of topics.
At the very least, having 5 streams each with 1 topic was not a good
way to introduce Zulip.

This commit minimizes changes to the message content in
`send_initial_realm_messages` to keep the diff readable. Future commits will
reshape the content.
2019-03-21 12:30:14 -07:00
Tim Abbott 12756b48a0 populate_db: Fix help text for --test-suite. 2019-02-20 17:42:30 -08:00
Eeshan Garg 179b747769 streams: Refactor multi-option helpers into separate functions.
For internal stream messages, most of the time, we have access to
a Stream object. For the few corner cases where we don't, it is a
much cleaner approach to have a separate function that accepts a
stream name than having one multi-option helper that accepts both
names and objects.
2019-02-12 11:10:26 -08:00
Greg Price 49fd2e65de push notif: Add GCM options to bouncer API; empty for now.
The first use case for this will be setting `priority`,
coming up shortly.
2019-02-08 09:40:43 -08:00
Eeshan Garg c240008edb internal_prep_stream_message: Support accepting a Stream object.
If the caller has access to a Stream object, it is wasteful to
query a database for a stream by ID or name. In addition, not
having to go through stream names eliminates various classes of
possible bugs involved with getting a Stream object back.
2019-02-08 08:53:16 -08:00
Anders Kaseorg f5197518a9 analytics/zilencer/zproject: Remove unused imports.
Signed-off-by: Anders Kaseorg <andersk@mit.edu>
2019-02-02 17:31:45 -08:00
Anders Kaseorg 4e21cc0152 views: Remove unused imports.
Signed-off-by: Anders Kaseorg <andersk@mit.edu>
2019-02-02 17:23:43 -08:00
Tim Abbott 55ead5b77f zilencer: Fix buggy validation of installation_counts upload.
This was a simple copy-paste error.  It's probably worth a bit more
work on code duplication in this code path.
2019-02-02 11:51:22 -08:00
Tim Abbott 022c8beaf5 analytics: Add APIs for submitting analytics to another server.
This adds a new API for sending basic analytics data (number of users,
number of messages sent) from a Zulip server to the Zulip Cloud
central analytics database, which will make it possible for servers to
elect to have their usage numbers counted in published stats on the
size of the Zulip ecosystem.
2019-02-01 22:03:52 -08:00
Anders Kaseorg 79d888223f profiling: Use mkstemp for profile.data filename.
Signed-off-by: Anders Kaseorg <andersk@mit.edu>
2019-01-15 16:08:48 -08:00
Tim Abbott 3c70a61132 models: Deduplicate definitions of push tokens.
Since c57c4cf703, these are no longer
different implementations, so we can deduplicate them.  Because Django
is smart, no migration is required.
2018-12-18 13:05:23 -08:00
Tim Abbott e603237010 email: Convert accounts code to use delivery_email.
A key part of this is the new helper, get_user_by_delivery_email.  Its
verbose name is important for clarity; it should help avoid blind
copy-pasting of get_user (which we'll also want to rename).
Unfortunately, it requires detailed understanding of the context to
figure out which one to use; each is used in about half of call sites.

Another important note is that this PR doesn't migrate get_user calls
in the tests except where not doing so would cause the tests to fail.
This probably deserves a follow-up refactor to avoid bugs here.
2018-12-06 16:21:38 -08:00
Vishnu Ks 2889de6d90 populate_db: Extract subscribe_users_to_streams function. 2018-11-29 12:15:58 -08:00
Tim Abbott 9c224ccdd3 populate_db: Suppress logging output for push notifications.
This fixes a lot of spammy output of the form:

2018-11-27 17:46:48.279 INFO [zerver.lib.push_notifications] Sending push notification to user 46

when running populate_db, which is both confusing (since we're not
actually sending push notifications here) and spammy.
2018-11-27 09:50:17 -08:00
Tim Abbott e8290ccd6d add_new_user: Fix mention of running "python manage.py".
This won't work on Python 3.
2018-11-06 13:28:18 -08: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
Vishnu Ks d8c19cb003 models: Move billing models from zilencer to corporate. 2018-10-11 14:54:29 -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
Vishnu Ks 59865797ac billing: Move billing tests from zilencer to corporate. 2018-10-01 15:44:02 -07:00
Vishnu Ks c01ebaa8d8 billing: Move billing management commands from zilencer to corporate. 2018-10-01 15:43:55 -07:00
Vishnu Ks 93b398bc0a billing: Move zilencer/lib/stripe to corporate. 2018-10-01 15:43:44 -07:00
Vishnu Ks 6914ee126c billing: Move billing-related views and urls to corporate. 2018-10-01 15:43:21 -07:00
Vishnu Ks 5a6b2ebb1f billing: Add ability for users to change their card. 2018-09-24 19:25:26 -07:00
Vishnu Ks 3e86fa84ea billing: Rename RealmAuditLog.STRIPE_CARD_ADDED to STRIPE_CARD_CHANGED. 2018-09-11 00:08:38 -07:00
Rishi Gupta 18b86a9499 billing: Fix RealmAuditLog accounting for downgrade. 2018-09-01 09:42:10 -07:00
Rishi Gupta 31ed4492ce billing: Add backend for downgrading. 2018-08-31 17:49:34 -07:00
Rishi Gupta b7c326a161 billing: Include account balance in prorated credits calculation. 2018-08-31 17:49:34 -07:00
Rishi Gupta bebd93b571 billing: Fix idempotency bug in setup_stripe management command. 2018-08-31 17:49:34 -07:00
Rishi Gupta 24b22e7e75 billing: Guard billing by BILLING_ENABLED rather than DEVELOPMENT. 2018-08-31 17:49:34 -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
Vishnu Ks 98dac0f0a9 billing: Remove Customer.billing_user. 2018-08-27 12:35:46 -07:00
Vishnu Ks dcb7b15069 billing: Use UserProfile.is_billing_admin instead of Customer.billing_user. 2018-08-27 12:35:46 -07:00
Rishi Gupta eec07072ee billing: Add coupons. 2018-08-24 17:27:26 -07:00
Rishi Gupta d229948a43 billing: Make source optional when creating stripe customer. 2018-08-24 16:40:34 -07:00
Rishi Gupta 4ad8f20c28 billing: Add comment explaining race condition in customer creation. 2018-08-24 16:40:34 -07:00
Rishi Gupta 90407537a0 billing: Add comment explaining race conditions in initial subscription. 2018-08-22 21:30:48 -07:00
Rishi Gupta 16a5540e58 billing: Add comment to downgrading section in views.billing_home. 2018-08-22 19:20:06 -07:00
Rishi Gupta d081cf7b78 billing: Add transaction.atomic() for Customer creation and logging. 2018-08-22 19:20:06 -07:00
Rishi Gupta 3cf9cd00d6 billing: Remove idempotency key from upgrade process.
This would be relevant if we retried on network failure, but we don't.
2018-08-22 19:18:32 -07:00
Vishnu Ks 9bb338be11 models: Add plan_type to Realm. 2018-08-21 12:39:06 -07:00
Rishi Gupta c3a912f8b6 management commands: Add sleep_forever to lib/management. 2018-08-17 09:20:51 -07:00
Rishi Gupta 4181d575b1 billing: Move Stripe call to end in do_subscribe_customer_to_plan.
In general, everything that could throw an error and that could come before
the Stripe call should do so.
2018-08-13 20:24:08 -07:00
Rishi Gupta 56d4034db4 billing: Require successful charge to establish billing relationship.
There are several situations in which we want to create a Customer and
stripe.Customer object before we really have a billing relationship with a
customer. The main one is giving non-profit or educational discounts.
2018-08-13 20:24:08 -07:00
Rishi Gupta 27d4b1a5f0 billing: Add RealmAuditLogProcessor. 2018-08-13 17:12:50 -07:00
Rishi Gupta e804c563a8 billing: Update stripe error handling code. 2018-08-13 17:12:50 -07:00
Rishi Gupta d0e377428a billing: Fix typo in CONTACT_SUPPORT error message. 2018-08-10 22:48:10 -07:00
Rishi Gupta 2855864f54 billing: Rename RealmAuditLog.REALM_PLAN_QUANTITY_RESET. 2018-08-10 15:54:31 -07:00
Rishi Gupta abc044e869 billing: Rename RealmAuditLog.REALM_PLAN_STARTED. 2018-08-10 15:54:31 -07:00
Rishi Gupta d33d7e1c28 billing: Rename RealmAuditLog.REALM_CARD_ADDED. 2018-08-10 15:54:30 -07:00
Rishi Gupta bdb6d8213f billing: Rename RealmAuditLog.REALM_STRIPE_INITIALIZED. 2018-08-10 15:46:55 -07:00
Vishnu Ks 0c84260faa billing: Enforce full coverage in zilencer/tests. 2018-08-10 13:52:35 -07:00
Vishnu Ks 4895637a5a billing: Fix the BillingError description check in test.
The self.assertEqual statement won't get executed because
BillingError would be raised and the execution would exit
with block.
2018-08-10 13:52:35 -07:00
Vishnu Ks d32051b106 billing: Test that salt and seat_count are set correctly in /upgrade. 2018-08-10 13:52:35 -07:00
Vishnu Ks 132480c031 billing: Pass email to stripe.Customer.create. 2018-08-10 13:52:35 -07:00
Vishnu Ks d64ba5d2be billing: Update the charged amount when user changes plan in upgrade page. 2018-08-10 13:52:35 -07:00
Yago González 6a192ac84c utils: Move random API key generator as generate_api_key.
random_api_key, the function we use to generate random tokens for API
keys, has been moved to zerver/lib/utils.py because it's used in more
parts of the codebase (apart from user creation), and having it in
zerver/lib/create_user.py was prone to cyclic dependencies.

The function has also been renamed to generate_api_key to have an
imperative name, that makes clearer what it does.
2018-08-08 16:45:25 -07:00
Yago González f6219745de users: Get all API keys via wrapper method.
Now reading API keys from a user is done with the get_api_key wrapper
method, rather than directly fetching it from the user object.

Also, every place where an action should be done for each API key is now
using get_all_api_keys. This method returns for the moment a single-item
list, containing the specified user's API key.

This commit is the first step towards allowing users have multiple API
keys.
2018-08-08 16:35:17 -07:00
Rishi Gupta 2cdcf4b88f billing: Rename get_upcoming_invoice. 2018-08-06 16:24:09 -04:00
Rishi Gupta 89ca1d0d97 billing: Rename get_stripe_customer. 2018-08-06 16:24:09 -04:00
Rishi Gupta 086b7d76e5 billing: Rename customer_with_active_subscription in fixture generation.
Fixes regression introduced in 79dddd5.
2018-08-06 16:24:09 -04:00
Rishi Gupta 9f2b8a4a11 billing: Move checks from process_initial_upgrade into separate function. 2018-08-06 11:05:33 -04:00
Rishi Gupta 5719633992 billing: Update and unify billing error handling. 2018-08-06 11:05:33 -04:00
Rishi Gupta 79dddd5b80 billing: Rename customer_with_active_subscriptiion. 2018-08-06 11:05:33 -04:00
Vishnu Ks 18a9e4fc9c billing: Call mock directly in test_subscribe_customer_to_second_plan. 2018-08-06 11:05:33 -04:00
Vishnu Ks e06957bef5 billing: Raise exceptions instead of returning errors in upgrade flow. 2018-08-06 11:05:33 -04:00
Vishnu Ks 8643c681f0 billing: Separate initial upgrade logic to another function. 2018-08-06 11:05:33 -04:00
Vishnu Ks fa7b98030b billing: Add mock for cancel at period end subscriptions. 2018-08-04 19:17:34 -04:00
Vishnu Ks d89e07b8a7 billing: Add mock and test for extracting canceled subscription. 2018-08-04 19:17:34 -04:00
Vishnu Ks 84b148728f billing: Don't mock functions in test_extract_current_subscription. 2018-08-04 19:17:34 -04:00
Vishnu Ks c2023eaaa8 billing: Mention the exact type of stripe.Customers subscriptions attribute. 2018-08-04 19:17:34 -04:00
Vishnu Ks 036ad03b3a billing: Mention the exact return type for mock functions. 2018-08-04 19:17:34 -04:00
Vishnu Ks 8bcd4131fe billing: Rename retrieve_customer fixture. 2018-08-04 19:17:34 -04:00
Vishnu Ks b7d3a1a0f3 billing: Don't check for stripe key and plan objects in tests.
Stripe already returns an appropriate error in prod, and these checks are
just a hassle in tests.

Also fixes an error where the check for Plan.objects.exists() was missing
a "not".
2018-08-04 19:17:34 -04:00
Roman Godov c0806917ec models: Rename Realm.restricted_to_domain field.
This renames Realm.restricted_to_domain field to
emails_restricted_to_domains, for greater clarity as to what it does
just from seeing the setting name, without having to look it up.

Fixes part of #10042.
2018-07-31 09:28:33 -07:00
Rishi Gupta 4554b564f7 billing: Rename RealmAuditLog.REALM_PLAN_QUANTITY_UPDATED. 2018-07-31 10:56:31 -04:00
Vishnu Ks abf485bfcb billing: Add mypy stubs to stripe imports.
Tweaked by tabbott to add an extra type: ignore.
2018-07-26 16:31:32 -07:00
Vishnu Ks d7b7430af0 billing: Add test for subscribing customer to second plan. 2018-07-25 23:03:55 -07:00
Vishnu Ks ba7db968d8 billing: Don't check for stripe config while running tests. 2018-07-25 23:03:55 -07:00
Vishnu Ks 51c82b6d4f models: Rename PLAN_QUANITY_UPDATED event type. 2018-07-25 23:03:55 -07:00
Vishnu Ks 975969aa89 stripe: Check for the existence of Pan objects in dev environment. 2018-07-25 23:03:55 -07:00
Vishnu Ks d6ed2c69be billing: Don't use self.realm and self.user in tests. 2018-07-25 23:03:55 -07:00
Vishnu Ks f98a86cdc2 billing: Don't show initial upgrade page in production for now. 2018-07-25 23:03:55 -07:00
Vishnu Ks b88613fd0b billing: Expand default_source object when retrieving customer. 2018-07-24 10:20:23 -07:00
Vishnu Ks 1225bfd6ee billing: Don't use data attribute for iterating through subscriptions.
Iterating through data attribute is same as iterating through
subscriptions.
2018-07-24 10:20:23 -07:00
Vishnu Ks 0bcc0ca0d8 stripe: Fix type of stripe_customer_id. 2018-07-24 10:20:23 -07:00
Vishnu Ks 15eff517f4 billing: Verify that plan names are not tampered. 2018-07-24 08:04:00 -07:00
Vishnu Ks 82fc82b7e2 billing: Sign and verify the seat count during upgrade. 2018-07-24 08:04:00 -07:00
Vishnu Ks d75054fb15 billing: Add function to sign strings. 2018-07-24 07:16:12 -07:00
Tim Abbott 888434e6cd test_stripe: Delete broken test.
This is an expedient way to fix master failing, which it has been
since f2861442f7.
2018-07-23 22:20:12 -07:00
Vishnu Ks eb48197f67 billing: Get upcoming invoice only if there is a live subscription. 2018-07-23 19:18:17 -07:00
Vishnu Ks f2861442f7 billing: Enforce Customer can have only one live subscription at a time. 2018-07-23 19:03:36 -07:00
Vishnu Ks db8700513b stripe: Fix type of stripe_plan_id in do_subscribe_customer_to_plan. 2018-07-23 17:55:15 -07:00
Vishnu Ks 28167585b1 models: Rename several RealmAuditlog event types to past tense.
These event types haven't been used in production yet, and thus are
save to change without a migration.
2018-07-22 20:00:05 -07:00
Max Nussenbaum 8fd900626d billing: Style billing page.
This adds styles to /billing.
2018-07-13 18:30:38 +05:30
Vishnu Ks 895c7703a6 billing: Show the billing page only to admins and billing users. 2018-07-12 12:51:38 +05:30
Vishnu Ks 377fac2864 billing: Pass stripe_customer instead of Customer in upgrade functions. 2018-07-12 12:51:38 +05:30
Vishnu Ks ff4c1ca2c1 models: Add SUBSCRIPTION_CREATED event type constant to RealmAuditLog. 2018-07-10 15:42:26 +05:30
Vishnu Ks 89fefcd1a2 mypy: Replace Any with stripe types in zilencer/lib/stripe.py. 2018-07-09 15:24:57 +05:30
Shubham Dhama 7cbacdb8c2 populate_db: Integrate populate_analytics_db.
As detailed in the documentation changes, this simplifies the
development workflow for doing UI work on the /stats pages.

The cost is a ~10% increase the time it takes to run `populate_db`,
which doesn't happen very often (and for most purposes manifests as a
1% increase in the time it takes to rebuild the database from scratch).
2018-07-09 15:05:48 +05:30
Rishi Gupta b5753d0ddc billing: Add initial support for seat based plans.
The main remaining todo for correctly populating
RealmAuditLog.requires_billing_update is supporting the de-seating (and
corresponding re-seating) that happens after being offline for two weeks.
2018-07-09 14:33:08 +05:30
Rishi Gupta 16334a1ba7 billing: Update billing system. 2018-07-09 14:33:07 +05:30
Anders Kaseorg 037f696d26 Enable pycodestyle W605 (invalid escape sequence).
The only changes visible at the AST level, checked using
https://github.com/asottile/astpretty, are

zerver/lib/test_fixtures.py:
'\x1b\\[(1|0)m' ↦ '\\x1b\\[(1|0)m'
'\\[[X| ]\\] (\\d+_.+)\n' ↦ '\\[[X| ]\\] (\\d+_.+)\\n'

which is fine because re treats '\\x1b' and '\\n' the same way as
'\x1b' and '\n'.

Signed-off-by: Anders Kaseorg <andersk@mit.edu>
2018-07-03 16:54:46 +02:00
Yashashvi Dave 8909cb1d15 custom fields: Allow list of users in user type of custom fields.
Allow user to add more than one user-value in user type of custom
fields.

Tweaked by tabbott to improve the models.py code and type annotations.
2018-06-16 09:37:49 -07:00