2017-10-29 20:19:57 +01:00
|
|
|
from typing import Dict, List, Tuple
|
|
|
|
from mypy_extensions import TypedDict
|
2017-10-29 15:52:01 +01:00
|
|
|
|
2017-10-29 15:40:07 +01:00
|
|
|
from django.db.models.query import QuerySet
|
|
|
|
from zerver.models import (
|
|
|
|
Recipient,
|
2017-10-29 20:19:57 +01:00
|
|
|
Stream,
|
2017-10-29 15:40:07 +01:00
|
|
|
Subscription,
|
2017-10-29 17:11:11 +01:00
|
|
|
UserProfile,
|
2017-10-29 15:40:07 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
def get_active_subscriptions_for_stream_id(stream_id):
|
|
|
|
# type: (int) -> QuerySet
|
|
|
|
return Subscription.objects.filter(
|
|
|
|
recipient__type=Recipient.STREAM,
|
|
|
|
recipient__type_id=stream_id,
|
|
|
|
active=True,
|
|
|
|
)
|
|
|
|
|
2017-10-29 15:52:01 +01:00
|
|
|
def get_active_subscriptions_for_stream_ids(stream_ids):
|
|
|
|
# type: (List[int]) -> QuerySet
|
|
|
|
return Subscription.objects.filter(
|
|
|
|
recipient__type=Recipient.STREAM,
|
|
|
|
recipient__type_id__in=stream_ids,
|
|
|
|
active=True
|
|
|
|
)
|
|
|
|
|
2017-10-29 17:11:11 +01:00
|
|
|
def get_stream_subscriptions_for_user(user_profile):
|
|
|
|
# type: (UserProfile) -> QuerySet
|
|
|
|
return Subscription.objects.filter(
|
|
|
|
user_profile=user_profile,
|
|
|
|
recipient__type=Recipient.STREAM,
|
|
|
|
)
|
|
|
|
|
2017-10-29 19:15:35 +01:00
|
|
|
def get_stream_subscriptions_for_users(user_profiles):
|
|
|
|
# type: (List[UserProfile]) -> QuerySet
|
|
|
|
return Subscription.objects.filter(
|
|
|
|
user_profile__in=user_profiles,
|
|
|
|
recipient__type=Recipient.STREAM,
|
|
|
|
)
|
|
|
|
|
2017-10-29 20:19:57 +01:00
|
|
|
SubInfo = TypedDict('SubInfo', {
|
|
|
|
'sub': Subscription,
|
|
|
|
'stream': Stream,
|
|
|
|
})
|
|
|
|
|
|
|
|
def get_bulk_stream_subscriber_info(user_profiles, stream_dict):
|
|
|
|
# type: (List[UserProfile], Dict[int, Stream]) -> Dict[int, List[Tuple[Subscription, Stream]]]
|
|
|
|
|
|
|
|
stream_ids = stream_dict.keys()
|
|
|
|
|
|
|
|
result = {
|
|
|
|
user_profile.id: []
|
|
|
|
for user_profile in user_profiles
|
|
|
|
} # type: Dict[int, List[Tuple[Subscription, Stream]]]
|
|
|
|
|
|
|
|
subs = Subscription.objects.filter(
|
|
|
|
user_profile__in=user_profiles,
|
|
|
|
recipient__type=Recipient.STREAM,
|
|
|
|
recipient__type_id__in=stream_ids,
|
|
|
|
active=True,
|
|
|
|
).select_related('user_profile', 'recipient')
|
|
|
|
|
|
|
|
for sub in subs:
|
|
|
|
user_profile_id = sub.user_profile_id
|
|
|
|
stream_id = sub.recipient.type_id
|
|
|
|
stream = stream_dict[stream_id]
|
|
|
|
result[user_profile_id].append((sub, stream))
|
|
|
|
|
|
|
|
return result
|
|
|
|
|
2017-10-29 15:40:07 +01:00
|
|
|
def num_subscribers_for_stream_id(stream_id):
|
|
|
|
# type: (int) -> int
|
|
|
|
return get_active_subscriptions_for_stream_id(stream_id).filter(
|
|
|
|
user_profile__is_active=True,
|
|
|
|
).count()
|