2019-01-31 00:39:02 +01:00
|
|
|
import datetime
|
2019-04-23 22:32:12 +02:00
|
|
|
import logging
|
2023-04-10 00:55:16 +02:00
|
|
|
from collections import Counter
|
2022-08-01 23:51:10 +02:00
|
|
|
from typing import Any, Dict, List, Optional, Type, TypeVar
|
2021-12-22 11:02:02 +01:00
|
|
|
from uuid import UUID
|
2013-10-17 22:55:09 +02:00
|
|
|
|
2023-06-03 06:03:43 +02:00
|
|
|
import orjson
|
2018-05-04 01:40:46 +02:00
|
|
|
from django.core.exceptions import ValidationError
|
2020-06-11 00:54:34 +02:00
|
|
|
from django.core.validators import URLValidator, validate_email
|
2018-10-11 00:53:13 +02:00
|
|
|
from django.db import IntegrityError, transaction
|
2022-07-01 03:12:07 +02:00
|
|
|
from django.db.models import Model
|
2018-09-25 12:24:11 +02:00
|
|
|
from django.http import HttpRequest, HttpResponse
|
2017-11-16 00:55:49 +01:00
|
|
|
from django.utils import timezone
|
2022-08-06 06:30:08 +02:00
|
|
|
from django.utils.crypto import constant_time_compare
|
2021-04-16 00:57:30 +02:00
|
|
|
from django.utils.translation import gettext as _
|
|
|
|
from django.utils.translation import gettext as err_
|
2018-01-13 19:38:13 +01:00
|
|
|
from django.views.decorators.csrf import csrf_exempt
|
|
|
|
|
2019-01-31 00:39:02 +01:00
|
|
|
from analytics.lib.counts import COUNT_STATS
|
2022-01-12 23:45:01 +01:00
|
|
|
from corporate.lib.stripe import do_deactivate_remote_server
|
2022-08-01 22:54:47 +02:00
|
|
|
from zerver.decorator import require_post
|
2017-10-28 00:07:31 +02:00
|
|
|
from zerver.lib.exceptions import JsonableError
|
2020-06-11 00:54:34 +02:00
|
|
|
from zerver.lib.push_notifications import (
|
2023-01-02 20:50:23 +01:00
|
|
|
UserPushIdentityCompat,
|
2020-06-11 00:54:34 +02:00
|
|
|
send_android_push_notification,
|
|
|
|
send_apple_push_notification,
|
|
|
|
)
|
2017-11-16 00:55:49 +01:00
|
|
|
from zerver.lib.request import REQ, has_request_variables
|
2021-06-30 18:35:50 +02:00
|
|
|
from zerver.lib.response import json_success
|
2020-06-11 00:54:34 +02:00
|
|
|
from zerver.lib.validator import (
|
|
|
|
check_bool,
|
|
|
|
check_capped_string,
|
2023-06-03 06:03:43 +02:00
|
|
|
check_dict,
|
2020-06-11 00:54:34 +02:00
|
|
|
check_dict_only,
|
|
|
|
check_float,
|
|
|
|
check_int,
|
|
|
|
check_list,
|
|
|
|
check_none_or,
|
|
|
|
check_string,
|
|
|
|
check_string_fixed_length,
|
2023-06-03 06:03:43 +02:00
|
|
|
check_union,
|
2020-06-11 00:54:34 +02:00
|
|
|
)
|
2017-07-07 18:23:36 +02:00
|
|
|
from zerver.views.push_notifications import validate_token
|
2022-08-01 22:54:47 +02:00
|
|
|
from zilencer.auth import InvalidZulipServerKeyError
|
2020-06-11 00:54:34 +02:00
|
|
|
from zilencer.models import (
|
|
|
|
RemoteInstallationCount,
|
|
|
|
RemotePushDeviceToken,
|
|
|
|
RemoteRealmAuditLog,
|
|
|
|
RemoteRealmCount,
|
|
|
|
RemoteZulipServer,
|
2021-12-30 23:51:38 +01:00
|
|
|
RemoteZulipServerAuditLog,
|
2020-06-11 00:54:34 +02:00
|
|
|
)
|
|
|
|
|
2021-10-20 01:16:18 +02:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2018-07-13 13:33:05 +02:00
|
|
|
|
2021-12-22 11:02:02 +01:00
|
|
|
def validate_uuid(uuid: str) -> None:
|
|
|
|
try:
|
2021-12-30 15:32:48 +01:00
|
|
|
uuid_object = UUID(uuid, version=4)
|
|
|
|
# The UUID initialization under some circumstances will modify the uuid
|
|
|
|
# string to create a valid UUIDv4, instead of raising a ValueError.
|
|
|
|
# The submitted uuid needing to be modified means it's invalid, so
|
|
|
|
# we need to check for that condition.
|
|
|
|
if str(uuid_object) != uuid:
|
|
|
|
raise ValidationError(err_("Invalid UUID"))
|
2021-12-22 11:02:02 +01:00
|
|
|
except ValueError:
|
|
|
|
raise ValidationError(err_("Invalid UUID"))
|
|
|
|
|
|
|
|
|
2022-08-01 23:51:10 +02:00
|
|
|
def validate_bouncer_token_request(token: str, kind: int) -> None:
|
2017-07-07 18:29:45 +02:00
|
|
|
if kind not in [RemotePushDeviceToken.APNS, RemotePushDeviceToken.GCM]:
|
2018-02-15 20:50:37 +01:00
|
|
|
raise JsonableError(err_("Invalid token type"))
|
2017-07-07 18:23:36 +02:00
|
|
|
validate_token(token, kind)
|
2017-05-08 14:25:40 +02:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2022-01-12 23:45:01 +01:00
|
|
|
@csrf_exempt
|
|
|
|
@require_post
|
|
|
|
@has_request_variables
|
|
|
|
def deactivate_remote_server(
|
|
|
|
request: HttpRequest,
|
|
|
|
remote_server: RemoteZulipServer,
|
|
|
|
) -> HttpResponse:
|
|
|
|
do_deactivate_remote_server(remote_server)
|
2022-01-31 13:44:02 +01:00
|
|
|
return json_success(request)
|
2022-01-12 23:45:01 +01:00
|
|
|
|
|
|
|
|
2018-05-04 01:40:46 +02:00
|
|
|
@csrf_exempt
|
|
|
|
@require_post
|
|
|
|
@has_request_variables
|
|
|
|
def register_remote_server(
|
2021-02-12 08:19:30 +01:00
|
|
|
request: HttpRequest,
|
|
|
|
zulip_org_id: str = REQ(str_validator=check_string_fixed_length(RemoteZulipServer.UUID_LENGTH)),
|
|
|
|
zulip_org_key: str = REQ(
|
|
|
|
str_validator=check_string_fixed_length(RemoteZulipServer.API_KEY_LENGTH)
|
|
|
|
),
|
|
|
|
hostname: str = REQ(str_validator=check_capped_string(RemoteZulipServer.HOSTNAME_MAX_LENGTH)),
|
2021-04-07 21:53:14 +02:00
|
|
|
contact_email: str = REQ(),
|
2021-02-12 08:19:30 +01:00
|
|
|
new_org_key: Optional[str] = REQ(
|
|
|
|
str_validator=check_string_fixed_length(RemoteZulipServer.API_KEY_LENGTH), default=None
|
|
|
|
),
|
2018-05-04 01:40:46 +02:00
|
|
|
) -> HttpResponse:
|
|
|
|
# REQ validated the the field lengths, but we still need to
|
|
|
|
# validate the format of these fields.
|
|
|
|
try:
|
|
|
|
# TODO: Ideally we'd not abuse the URL validator this way
|
|
|
|
url_validator = URLValidator()
|
2021-02-12 08:20:45 +01:00
|
|
|
url_validator("http://" + hostname)
|
2018-05-04 01:40:46 +02:00
|
|
|
except ValidationError:
|
2021-02-12 08:20:45 +01:00
|
|
|
raise JsonableError(_("{} is not a valid hostname").format(hostname))
|
2018-05-04 01:40:46 +02:00
|
|
|
|
|
|
|
try:
|
|
|
|
validate_email(contact_email)
|
|
|
|
except ValidationError as e:
|
|
|
|
raise JsonableError(e.message)
|
|
|
|
|
2021-12-22 11:02:02 +01:00
|
|
|
try:
|
|
|
|
validate_uuid(zulip_org_id)
|
|
|
|
except ValidationError as e:
|
|
|
|
raise JsonableError(e.message)
|
|
|
|
|
2021-12-30 23:51:38 +01:00
|
|
|
with transaction.atomic():
|
|
|
|
remote_server, created = RemoteZulipServer.objects.get_or_create(
|
|
|
|
uuid=zulip_org_id,
|
|
|
|
defaults={
|
|
|
|
"hostname": hostname,
|
|
|
|
"contact_email": contact_email,
|
|
|
|
"api_key": zulip_org_key,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
if created:
|
|
|
|
RemoteZulipServerAuditLog.objects.create(
|
|
|
|
event_type=RemoteZulipServerAuditLog.REMOTE_SERVER_CREATED,
|
|
|
|
server=remote_server,
|
|
|
|
event_time=remote_server.last_updated,
|
|
|
|
)
|
2018-05-04 01:40:46 +02:00
|
|
|
else:
|
2022-08-06 06:30:08 +02:00
|
|
|
if not constant_time_compare(remote_server.api_key, zulip_org_key):
|
2021-12-30 23:51:38 +01:00
|
|
|
raise InvalidZulipServerKeyError(zulip_org_id)
|
|
|
|
else:
|
|
|
|
remote_server.hostname = hostname
|
|
|
|
remote_server.contact_email = contact_email
|
|
|
|
if new_org_key is not None:
|
|
|
|
remote_server.api_key = new_org_key
|
|
|
|
remote_server.save()
|
2018-05-04 01:40:46 +02:00
|
|
|
|
2022-01-31 13:44:02 +01:00
|
|
|
return json_success(request, data={"created": created})
|
2018-05-04 01:40:46 +02:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2016-10-27 23:55:31 +02:00
|
|
|
@has_request_variables
|
2021-02-12 08:19:30 +01:00
|
|
|
def register_remote_push_device(
|
|
|
|
request: HttpRequest,
|
2022-08-01 23:51:10 +02:00
|
|
|
server: RemoteZulipServer,
|
2022-02-23 20:25:30 +01:00
|
|
|
user_id: Optional[int] = REQ(json_validator=check_int, default=None),
|
|
|
|
user_uuid: Optional[str] = REQ(default=None),
|
2021-02-12 08:19:30 +01:00
|
|
|
token: str = REQ(),
|
2021-04-07 22:00:44 +02:00
|
|
|
token_kind: int = REQ(json_validator=check_int),
|
2021-02-12 08:19:30 +01:00
|
|
|
ios_app_id: Optional[str] = None,
|
|
|
|
) -> HttpResponse:
|
2022-08-01 23:51:10 +02:00
|
|
|
validate_bouncer_token_request(token, token_kind)
|
2016-10-27 23:55:31 +02:00
|
|
|
|
2022-02-23 20:25:30 +01:00
|
|
|
if user_id is None and user_uuid is None:
|
|
|
|
raise JsonableError(_("Missing user_id or user_uuid"))
|
|
|
|
if user_id is not None and user_uuid is not None:
|
2023-04-10 00:23:59 +02:00
|
|
|
kwargs: Dict[str, object] = {"user_uuid": user_uuid, "user_id": None}
|
|
|
|
# Delete pre-existing user_id registration for this user+device to avoid
|
|
|
|
# duplication. Further down, uuid registration will be created.
|
|
|
|
RemotePushDeviceToken.objects.filter(
|
|
|
|
server=server, token=token, kind=token_kind, user_id=user_id
|
|
|
|
).delete()
|
|
|
|
else:
|
2023-04-10 00:55:16 +02:00
|
|
|
# One of these is None, so these kwargs will lead to a proper registration
|
2023-04-10 00:23:59 +02:00
|
|
|
# of either user_id or user_uuid type
|
|
|
|
kwargs = {"user_id": user_id, "user_uuid": user_uuid}
|
2018-10-11 00:53:13 +02:00
|
|
|
try:
|
|
|
|
with transaction.atomic():
|
|
|
|
RemotePushDeviceToken.objects.create(
|
|
|
|
server=server,
|
|
|
|
kind=token_kind,
|
|
|
|
token=token,
|
|
|
|
ios_app_id=ios_app_id,
|
|
|
|
# last_updated is to be renamed to date_created.
|
2021-02-12 08:19:30 +01:00
|
|
|
last_updated=timezone.now(),
|
2023-04-10 00:23:59 +02:00
|
|
|
**kwargs,
|
2021-02-12 08:19:30 +01:00
|
|
|
)
|
2018-10-11 00:53:13 +02:00
|
|
|
except IntegrityError:
|
|
|
|
pass
|
2016-10-27 23:55:31 +02:00
|
|
|
|
2022-01-31 13:44:02 +01:00
|
|
|
return json_success(request)
|
2016-10-27 23:55:31 +02:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2016-10-27 23:55:31 +02:00
|
|
|
@has_request_variables
|
2021-02-12 08:19:30 +01:00
|
|
|
def unregister_remote_push_device(
|
|
|
|
request: HttpRequest,
|
2022-08-01 23:51:10 +02:00
|
|
|
server: RemoteZulipServer,
|
2021-02-12 08:19:30 +01:00
|
|
|
token: str = REQ(),
|
2021-04-07 22:00:44 +02:00
|
|
|
token_kind: int = REQ(json_validator=check_int),
|
2022-02-23 20:25:30 +01:00
|
|
|
user_id: Optional[int] = REQ(json_validator=check_int, default=None),
|
|
|
|
user_uuid: Optional[str] = REQ(default=None),
|
2021-02-12 08:19:30 +01:00
|
|
|
ios_app_id: Optional[str] = None,
|
|
|
|
) -> HttpResponse:
|
2022-08-01 23:51:10 +02:00
|
|
|
validate_bouncer_token_request(token, token_kind)
|
2023-01-02 20:50:23 +01:00
|
|
|
user_identity = UserPushIdentityCompat(user_id=user_id, user_uuid=user_uuid)
|
2022-02-23 20:25:30 +01:00
|
|
|
|
2023-03-17 08:38:23 +01:00
|
|
|
(num_deleted, ignored) = RemotePushDeviceToken.objects.filter(
|
2022-02-23 20:25:30 +01:00
|
|
|
user_identity.filter_q(), token=token, kind=token_kind, server=server
|
2021-02-12 08:19:30 +01:00
|
|
|
).delete()
|
2023-03-17 08:38:23 +01:00
|
|
|
if num_deleted == 0:
|
2021-06-30 18:35:50 +02:00
|
|
|
raise JsonableError(err_("Token does not exist"))
|
2016-10-27 23:55:31 +02:00
|
|
|
|
2022-01-31 13:44:02 +01:00
|
|
|
return json_success(request)
|
2017-05-08 13:48:16 +02:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2019-11-19 03:12:54 +01:00
|
|
|
@has_request_variables
|
2021-02-12 08:19:30 +01:00
|
|
|
def unregister_all_remote_push_devices(
|
|
|
|
request: HttpRequest,
|
2022-08-01 23:51:10 +02:00
|
|
|
server: RemoteZulipServer,
|
2022-02-23 20:25:30 +01:00
|
|
|
user_id: Optional[int] = REQ(json_validator=check_int, default=None),
|
|
|
|
user_uuid: Optional[str] = REQ(default=None),
|
2021-02-12 08:19:30 +01:00
|
|
|
) -> HttpResponse:
|
2023-01-02 20:50:23 +01:00
|
|
|
user_identity = UserPushIdentityCompat(user_id=user_id, user_uuid=user_uuid)
|
2022-02-23 20:25:30 +01:00
|
|
|
|
|
|
|
RemotePushDeviceToken.objects.filter(user_identity.filter_q(), server=server).delete()
|
2022-01-31 13:44:02 +01:00
|
|
|
return json_success(request)
|
2019-11-19 03:12:54 +01:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2023-04-10 00:55:16 +02:00
|
|
|
def delete_duplicate_registrations(
|
|
|
|
registrations: List[RemotePushDeviceToken], server_id: int, user_id: int, user_uuid: str
|
|
|
|
) -> List[RemotePushDeviceToken]:
|
|
|
|
"""
|
|
|
|
When migrating to support registration by UUID, we introduced a bug where duplicate
|
|
|
|
registrations for the same device+user could be created - one by user_id and one by
|
|
|
|
user_uuid. Given no good way of detecting these duplicates at database level, we need to
|
|
|
|
take advantage of the fact that when a remote server sends a push notification request
|
|
|
|
to us, it sends both user_id and user_uuid of the user.
|
|
|
|
See https://github.com/zulip/zulip/issues/24969 for reference.
|
|
|
|
|
|
|
|
This function, knowing the user_id and user_uuid of the user, can detect duplicates
|
|
|
|
and delete the legacy user_id registration if appropriate.
|
|
|
|
|
|
|
|
Return the list of registrations with the user_id-based duplicates removed.
|
|
|
|
"""
|
|
|
|
|
|
|
|
# All registrations passed here should be of the same kind (apple vs android).
|
|
|
|
assert len({registration.kind for registration in registrations}) == 1
|
|
|
|
kind = registrations[0].kind
|
|
|
|
|
|
|
|
tokens_counter = Counter(device.token for device in registrations)
|
|
|
|
|
|
|
|
tokens_to_deduplicate = []
|
|
|
|
for key in tokens_counter:
|
|
|
|
if tokens_counter[key] <= 1:
|
|
|
|
continue
|
|
|
|
if tokens_counter[key] > 2:
|
|
|
|
raise AssertionError(
|
|
|
|
f"More than two registrations for token {key} for user id:{user_id} uuid:{user_uuid}, shouldn't be possible"
|
|
|
|
)
|
|
|
|
assert tokens_counter[key] == 2
|
|
|
|
tokens_to_deduplicate.append(key)
|
|
|
|
|
|
|
|
if not tokens_to_deduplicate:
|
|
|
|
return registrations
|
|
|
|
|
|
|
|
logger.info(
|
|
|
|
"Deduplicating push registrations for server id:%s user id:%s uuid:%s and tokens:%s",
|
|
|
|
server_id,
|
|
|
|
user_id,
|
|
|
|
user_uuid,
|
|
|
|
sorted(tokens_to_deduplicate),
|
|
|
|
)
|
|
|
|
RemotePushDeviceToken.objects.filter(
|
|
|
|
token__in=tokens_to_deduplicate, kind=kind, server_id=server_id, user_id=user_id
|
|
|
|
).delete()
|
|
|
|
|
|
|
|
deduplicated_registrations_to_return = []
|
|
|
|
for registration in registrations:
|
|
|
|
if registration.token in tokens_to_deduplicate and registration.user_id is not None:
|
|
|
|
# user_id registrations are the ones we deleted
|
|
|
|
continue
|
|
|
|
deduplicated_registrations_to_return.append(registration)
|
|
|
|
|
|
|
|
return deduplicated_registrations_to_return
|
|
|
|
|
|
|
|
|
2017-05-08 13:48:16 +02:00
|
|
|
@has_request_variables
|
2021-02-12 08:19:30 +01:00
|
|
|
def remote_server_notify_push(
|
|
|
|
request: HttpRequest,
|
2022-08-01 23:51:10 +02:00
|
|
|
server: RemoteZulipServer,
|
2021-02-12 08:20:45 +01:00
|
|
|
payload: Dict[str, Any] = REQ(argument_type="body"),
|
2021-02-12 08:19:30 +01:00
|
|
|
) -> HttpResponse:
|
2023-04-10 00:55:16 +02:00
|
|
|
user_id = payload.get("user_id")
|
|
|
|
user_uuid = payload.get("user_uuid")
|
|
|
|
user_identity = UserPushIdentityCompat(user_id, user_uuid)
|
2022-02-23 20:25:30 +01:00
|
|
|
|
2021-02-12 08:20:45 +01:00
|
|
|
gcm_payload = payload["gcm_payload"]
|
|
|
|
apns_payload = payload["apns_payload"]
|
|
|
|
gcm_options = payload.get("gcm_options", {})
|
2017-05-09 10:31:47 +02:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
android_devices = list(
|
|
|
|
RemotePushDeviceToken.objects.filter(
|
2022-02-23 20:25:30 +01:00
|
|
|
user_identity.filter_q(),
|
2021-02-12 08:19:30 +01:00
|
|
|
kind=RemotePushDeviceToken.GCM,
|
|
|
|
server=server,
|
|
|
|
)
|
|
|
|
)
|
2023-04-10 00:55:16 +02:00
|
|
|
if android_devices and user_id is not None and user_uuid is not None:
|
|
|
|
android_devices = delete_duplicate_registrations(
|
|
|
|
android_devices, server.id, user_id, user_uuid
|
|
|
|
)
|
2017-05-09 10:31:47 +02:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
apple_devices = list(
|
|
|
|
RemotePushDeviceToken.objects.filter(
|
2022-02-23 20:25:30 +01:00
|
|
|
user_identity.filter_q(),
|
2021-02-12 08:19:30 +01:00
|
|
|
kind=RemotePushDeviceToken.APNS,
|
|
|
|
server=server,
|
|
|
|
)
|
|
|
|
)
|
2023-04-10 00:55:16 +02:00
|
|
|
if apple_devices and user_id is not None and user_uuid is not None:
|
|
|
|
apple_devices = delete_duplicate_registrations(apple_devices, server.id, user_id, user_uuid)
|
2017-05-09 10:31:47 +02:00
|
|
|
|
2021-10-20 01:16:18 +02:00
|
|
|
logger.info(
|
|
|
|
"Sending mobile push notifications for remote user %s:%s: %s via FCM devices, %s via APNs devices",
|
|
|
|
server.uuid,
|
2022-02-23 20:25:30 +01:00
|
|
|
user_identity,
|
2021-10-20 01:16:18 +02:00
|
|
|
len(android_devices),
|
|
|
|
len(apple_devices),
|
|
|
|
)
|
|
|
|
|
2021-11-09 01:32:19 +01:00
|
|
|
# Truncate incoming pushes to 200, due to APNs maximum message
|
|
|
|
# sizes; see handle_remove_push_notification for the version of
|
|
|
|
# this for notifications generated natively on the server. We
|
|
|
|
# apply this to remote-server pushes in case they predate that
|
|
|
|
# commit.
|
|
|
|
def truncate_payload(payload: Dict[str, Any]) -> Dict[str, Any]:
|
|
|
|
MAX_MESSAGE_IDS = 200
|
|
|
|
if payload and payload.get("event") == "remove" and payload.get("zulip_message_ids"):
|
|
|
|
ids = [int(id) for id in payload["zulip_message_ids"].split(",")]
|
2022-10-30 00:32:32 +02:00
|
|
|
truncated_ids = sorted(ids)[-MAX_MESSAGE_IDS:]
|
2021-11-09 01:32:19 +01:00
|
|
|
payload["zulip_message_ids"] = ",".join(str(id) for id in truncated_ids)
|
|
|
|
return payload
|
|
|
|
|
push_notifications: Drop FCM retries to 2, not 10.
This reverts bc15085098709d746ba69c99d61601f8d4316e6e (which provided
not justification for its change) and moves further, down to 2 retries
from the default of 5.
10 retries, with exponential backoff, is equivalent to sleeping 2^11
seconds, or just about 34 minutes (though the code uses a jitter which
may make this up to 51 minutes). This is an unreasonable amount of
time to spend in this codepath -- as only one worker is used, and it
is single-threaded, this could effectively block all missed message
notifications for half an hour or longer.
This is also necessary because messages sent through the push bouncer
are sent synchronously; the sending server uses a 30-second timeout,
set in PushBouncerSession. Having retries which linger longer than
this can cause duplicate messages; the sending server will time out
and re-queue the message in RabbitMQ, while the push bouncer's request
will continue, and may succeed.
Limit to 2 retries (APNS currently uses 3), and results expected max
of 4 seconds of sleep, potentially up to 6. If this fails, there
exists another retry loop above it, at the RabbitMQ layer (either
locally, or via the remote server's queue), which will result in up to
3 additional retries -- all told, the request will me made to FCM up
to 12 times.
2022-03-08 18:49:10 +01:00
|
|
|
# The full request must complete within 30s, the timeout set by
|
|
|
|
# Zulip remote hosts for push notification requests (see
|
|
|
|
# PushBouncerSession). The timeouts in the FCM and APNS codepaths
|
|
|
|
# must be set accordingly; see send_android_push_notification and
|
|
|
|
# send_apple_push_notification.
|
|
|
|
|
2021-11-09 01:32:19 +01:00
|
|
|
gcm_payload = truncate_payload(gcm_payload)
|
2021-10-20 01:52:23 +02:00
|
|
|
send_android_push_notification(
|
2022-02-23 20:25:30 +01:00
|
|
|
user_identity, android_devices, gcm_payload, gcm_options, remote=server
|
2021-10-20 01:52:23 +02:00
|
|
|
)
|
2017-05-09 10:31:47 +02:00
|
|
|
|
2022-01-03 23:06:42 +01:00
|
|
|
if isinstance(apns_payload.get("custom"), dict) and isinstance(
|
|
|
|
apns_payload["custom"].get("zulip"), dict
|
|
|
|
):
|
|
|
|
apns_payload["custom"]["zulip"] = truncate_payload(apns_payload["custom"]["zulip"])
|
2022-02-23 20:25:30 +01:00
|
|
|
send_apple_push_notification(user_identity, apple_devices, apns_payload, remote=server)
|
2017-05-09 10:31:47 +02:00
|
|
|
|
2021-09-28 14:17:16 +02:00
|
|
|
return json_success(
|
2022-01-31 13:44:02 +01:00
|
|
|
request,
|
|
|
|
data={
|
|
|
|
"total_android_devices": len(android_devices),
|
|
|
|
"total_apple_devices": len(apple_devices),
|
|
|
|
},
|
2021-09-28 14:17:16 +02:00
|
|
|
)
|
2019-01-31 00:39:02 +01:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
|
|
|
def validate_incoming_table_data(
|
|
|
|
server: RemoteZulipServer, model: Any, rows: List[Dict[str, Any]], is_count_stat: bool = False
|
|
|
|
) -> None:
|
2019-01-31 00:39:02 +01:00
|
|
|
last_id = get_last_id_from_server(server, model)
|
2019-10-03 01:54:36 +02:00
|
|
|
for row in rows:
|
2021-02-12 08:20:45 +01:00
|
|
|
if is_count_stat and row["property"] not in COUNT_STATS:
|
|
|
|
raise JsonableError(_("Invalid property {}").format(row["property"]))
|
|
|
|
if row["id"] <= last_id:
|
2019-01-31 00:39:02 +01:00
|
|
|
raise JsonableError(_("Data is out of order."))
|
2021-02-12 08:20:45 +01:00
|
|
|
last_id = row["id"]
|
2019-10-03 01:54:36 +02:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2022-07-01 03:12:07 +02:00
|
|
|
ModelT = TypeVar("ModelT", bound=Model)
|
|
|
|
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
def batch_create_table_data(
|
|
|
|
server: RemoteZulipServer,
|
2022-07-01 03:12:07 +02:00
|
|
|
model: Type[ModelT],
|
|
|
|
row_objects: List[ModelT],
|
2021-02-12 08:19:30 +01:00
|
|
|
) -> None:
|
2019-10-03 01:54:36 +02:00
|
|
|
BATCH_SIZE = 1000
|
|
|
|
while len(row_objects) > 0:
|
|
|
|
try:
|
|
|
|
model.objects.bulk_create(row_objects[:BATCH_SIZE])
|
|
|
|
except IntegrityError:
|
2020-05-02 08:44:14 +02:00
|
|
|
logging.warning(
|
|
|
|
"Invalid data saving %s for server %s/%s",
|
2021-02-12 08:19:30 +01:00
|
|
|
model._meta.db_table,
|
|
|
|
server.hostname,
|
|
|
|
server.uuid,
|
2020-05-02 08:44:14 +02:00
|
|
|
)
|
2019-10-03 01:54:36 +02:00
|
|
|
raise JsonableError(_("Invalid data."))
|
|
|
|
row_objects = row_objects[BATCH_SIZE:]
|
2019-01-31 00:39:02 +01:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2019-01-31 00:39:02 +01:00
|
|
|
@has_request_variables
|
2021-02-12 08:19:30 +01:00
|
|
|
def remote_server_post_analytics(
|
|
|
|
request: HttpRequest,
|
2022-08-01 23:51:10 +02:00
|
|
|
server: RemoteZulipServer,
|
2021-02-12 08:19:30 +01:00
|
|
|
realm_counts: List[Dict[str, Any]] = REQ(
|
2021-04-07 22:00:44 +02:00
|
|
|
json_validator=check_list(
|
2021-02-12 08:19:30 +01:00
|
|
|
check_dict_only(
|
|
|
|
[
|
2021-02-12 08:20:45 +01:00
|
|
|
("property", check_string),
|
|
|
|
("realm", check_int),
|
|
|
|
("id", check_int),
|
|
|
|
("end_time", check_float),
|
|
|
|
("subgroup", check_none_or(check_string)),
|
|
|
|
("value", check_int),
|
2021-02-12 08:19:30 +01:00
|
|
|
]
|
|
|
|
)
|
|
|
|
)
|
|
|
|
),
|
|
|
|
installation_counts: List[Dict[str, Any]] = REQ(
|
2021-04-07 22:00:44 +02:00
|
|
|
json_validator=check_list(
|
2021-02-12 08:19:30 +01:00
|
|
|
check_dict_only(
|
|
|
|
[
|
2021-02-12 08:20:45 +01:00
|
|
|
("property", check_string),
|
|
|
|
("id", check_int),
|
|
|
|
("end_time", check_float),
|
|
|
|
("subgroup", check_none_or(check_string)),
|
|
|
|
("value", check_int),
|
2021-02-12 08:19:30 +01:00
|
|
|
]
|
|
|
|
)
|
|
|
|
)
|
|
|
|
),
|
|
|
|
realmauditlog_rows: Optional[List[Dict[str, Any]]] = REQ(
|
2021-04-07 22:00:44 +02:00
|
|
|
json_validator=check_list(
|
2021-02-12 08:19:30 +01:00
|
|
|
check_dict_only(
|
|
|
|
[
|
2021-02-12 08:20:45 +01:00
|
|
|
("id", check_int),
|
|
|
|
("realm", check_int),
|
|
|
|
("event_time", check_float),
|
|
|
|
("backfilled", check_bool),
|
2023-06-03 06:03:43 +02:00
|
|
|
("extra_data", check_none_or(check_union([check_string, check_dict()]))),
|
2021-02-12 08:20:45 +01:00
|
|
|
("event_type", check_int),
|
2021-02-12 08:19:30 +01:00
|
|
|
]
|
|
|
|
)
|
|
|
|
),
|
|
|
|
default=None,
|
|
|
|
),
|
|
|
|
) -> HttpResponse:
|
2019-10-03 01:54:36 +02:00
|
|
|
validate_incoming_table_data(server, RemoteRealmCount, realm_counts, True)
|
|
|
|
validate_incoming_table_data(server, RemoteInstallationCount, installation_counts, True)
|
2019-10-03 02:01:36 +02:00
|
|
|
if realmauditlog_rows is not None:
|
|
|
|
validate_incoming_table_data(server, RemoteRealmAuditLog, realmauditlog_rows)
|
2019-10-03 01:54:36 +02:00
|
|
|
|
2022-07-01 03:12:07 +02:00
|
|
|
remote_realm_counts = [
|
2021-02-12 08:19:30 +01:00
|
|
|
RemoteRealmCount(
|
2021-02-12 08:20:45 +01:00
|
|
|
property=row["property"],
|
|
|
|
realm_id=row["realm"],
|
|
|
|
remote_id=row["id"],
|
2021-02-12 08:19:30 +01:00
|
|
|
server=server,
|
2021-02-12 08:20:45 +01:00
|
|
|
end_time=datetime.datetime.fromtimestamp(row["end_time"], tz=datetime.timezone.utc),
|
|
|
|
subgroup=row["subgroup"],
|
|
|
|
value=row["value"],
|
2021-02-12 08:19:30 +01:00
|
|
|
)
|
|
|
|
for row in realm_counts
|
|
|
|
]
|
2022-07-01 03:12:07 +02:00
|
|
|
batch_create_table_data(server, RemoteRealmCount, remote_realm_counts)
|
2019-10-03 01:54:36 +02:00
|
|
|
|
2022-07-01 03:12:07 +02:00
|
|
|
remote_installation_counts = [
|
2021-02-12 08:19:30 +01:00
|
|
|
RemoteInstallationCount(
|
2021-02-12 08:20:45 +01:00
|
|
|
property=row["property"],
|
|
|
|
remote_id=row["id"],
|
2021-02-12 08:19:30 +01:00
|
|
|
server=server,
|
2021-02-12 08:20:45 +01:00
|
|
|
end_time=datetime.datetime.fromtimestamp(row["end_time"], tz=datetime.timezone.utc),
|
|
|
|
subgroup=row["subgroup"],
|
|
|
|
value=row["value"],
|
2021-02-12 08:19:30 +01:00
|
|
|
)
|
|
|
|
for row in installation_counts
|
|
|
|
]
|
2022-07-01 03:12:07 +02:00
|
|
|
batch_create_table_data(server, RemoteInstallationCount, remote_installation_counts)
|
2019-01-31 00:39:02 +01:00
|
|
|
|
2019-10-03 02:01:36 +02:00
|
|
|
if realmauditlog_rows is not None:
|
2023-06-03 06:03:43 +02:00
|
|
|
remote_realm_audit_logs = []
|
|
|
|
for row in realmauditlog_rows:
|
|
|
|
# Remote servers that do support JSONField will pass extra_data
|
|
|
|
# as a dict. Otherwise, extra_data will be either a string or None.
|
|
|
|
if isinstance(row["extra_data"], dict):
|
|
|
|
# This is guaranteed to succeed because row["extra_data"] would be parsed
|
|
|
|
# from JSON with our json validator if it is a dict.
|
|
|
|
extra_data = orjson.dumps(row["extra_data"]).decode()
|
|
|
|
else:
|
|
|
|
extra_data = row["extra_data"]
|
|
|
|
remote_realm_audit_logs.append(
|
|
|
|
RemoteRealmAuditLog(
|
|
|
|
realm_id=row["realm"],
|
|
|
|
remote_id=row["id"],
|
|
|
|
server=server,
|
|
|
|
event_time=datetime.datetime.fromtimestamp(
|
|
|
|
row["event_time"], tz=datetime.timezone.utc
|
|
|
|
),
|
|
|
|
backfilled=row["backfilled"],
|
|
|
|
extra_data=extra_data,
|
|
|
|
event_type=row["event_type"],
|
|
|
|
)
|
2021-02-12 08:19:30 +01:00
|
|
|
)
|
2022-07-01 03:12:07 +02:00
|
|
|
batch_create_table_data(server, RemoteRealmAuditLog, remote_realm_audit_logs)
|
2019-10-03 02:01:36 +02:00
|
|
|
|
2022-01-31 13:44:02 +01:00
|
|
|
return json_success(request)
|
2019-01-31 00:39:02 +01:00
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2019-01-31 00:39:02 +01:00
|
|
|
def get_last_id_from_server(server: RemoteZulipServer, model: Any) -> int:
|
|
|
|
last_count = model.objects.filter(server=server).order_by("remote_id").last()
|
|
|
|
if last_count is not None:
|
|
|
|
return last_count.remote_id
|
|
|
|
return 0
|
|
|
|
|
2021-02-12 08:19:30 +01:00
|
|
|
|
2019-01-31 00:39:02 +01:00
|
|
|
@has_request_variables
|
2022-08-01 23:51:10 +02:00
|
|
|
def remote_server_check_analytics(request: HttpRequest, server: RemoteZulipServer) -> HttpResponse:
|
2019-01-31 00:39:02 +01:00
|
|
|
result = {
|
2021-02-12 08:20:45 +01:00
|
|
|
"last_realm_count_id": get_last_id_from_server(server, RemoteRealmCount),
|
|
|
|
"last_installation_count_id": get_last_id_from_server(server, RemoteInstallationCount),
|
|
|
|
"last_realmauditlog_id": get_last_id_from_server(server, RemoteRealmAuditLog),
|
2019-01-31 00:39:02 +01:00
|
|
|
}
|
2022-01-31 13:44:02 +01:00
|
|
|
return json_success(request, data=result)
|