本文整理汇总了Python中zerver.lib.actions.bulk_add_subscriptions函数的典型用法代码示例。如果您正苦于以下问题:Python bulk_add_subscriptions函数的具体用法?Python bulk_add_subscriptions怎么用?Python bulk_add_subscriptions使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了bulk_add_subscriptions函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: subscribe
def subscribe(self, user_profile: UserProfile, stream_name: str) -> Stream:
try:
stream = get_stream(stream_name, user_profile.realm)
from_stream_creation = False
except Stream.DoesNotExist:
stream, from_stream_creation = create_stream_if_needed(user_profile.realm, stream_name)
bulk_add_subscriptions([stream], [user_profile], from_stream_creation=from_stream_creation)
return stream
示例2: subscribe_to_stream
def subscribe_to_stream(self, email, stream_name, realm=None):
# type: (text_type, text_type, Optional[Realm]) -> None
if realm is None:
realm = get_realm_by_email_domain(email)
stream = get_stream(stream_name, realm)
if stream is None:
stream, _ = create_stream_if_needed(realm, stream_name)
user_profile = get_user_profile_by_email(email)
bulk_add_subscriptions([stream], [user_profile])
示例3: subscribe_to_stream
def subscribe_to_stream(self, email, stream_name, realm=None):
# type: (Text, Text, Optional[Realm]) -> Stream
if realm is None:
realm = get_realm_by_email_domain(email)
try:
stream = get_stream(stream_name, realm)
from_creation = False
except Stream.DoesNotExist:
stream, from_creation = create_stream_if_needed(realm, stream_name)
user_profile = get_user_profile_by_email(email)
bulk_add_subscriptions([stream], [user_profile], from_creation=from_creation)
return stream
示例4: handle
def handle(self, **options: Any) -> None:
string_id = 'realm%02d' % (
Realm.objects.filter(string_id__startswith='realm').count(),)
realm = do_create_realm(string_id, string_id)
setup_initial_streams(realm)
name = '%02d-user' % (
UserProfile.objects.filter(email__contains='[email protected]').count(),)
user = do_create_user('%[email protected]%s.zulip.com' % (name, string_id),
'password', realm, name, name, is_realm_admin=True)
bulk_add_subscriptions([realm.signup_notifications_stream], [user])
send_initial_realm_messages(realm)
示例5: stream_exists_backend
def stream_exists_backend(request, user_profile, stream_name, autosubscribe):
if not valid_stream_name(stream_name):
return json_error("Invalid characters in stream name")
stream = get_stream(stream_name, user_profile.realm)
result = {"exists": bool(stream)}
if stream is not None:
recipient = get_recipient(Recipient.STREAM, stream.id)
if autosubscribe:
bulk_add_subscriptions([stream], [user_profile])
result["subscribed"] = Subscription.objects.filter(user_profile=user_profile,
recipient=recipient,
active=True).exists()
return json_success(result) # results are ignored for HEAD requests
return json_response(data=result, status=404)
示例6: handle
def handle(self, **options):
# type: (**Any) -> None
if (
options["string_id"] is None
or options["streams"] is None
or (options["users"] is None and options["all_users"] is None)
):
self.print_help("./manage.py", "add_users_to_streams")
exit(1)
stream_names = set([stream.strip() for stream in options["streams"].split(",")])
realm = get_realm_by_string_id(options["string_id"])
if options["all_users"]:
user_profiles = UserProfile.objects.filter(realm=realm)
else:
emails = set([email.strip() for email in options["users"].split(",")])
user_profiles = []
for email in emails:
user_profiles.append(get_user_profile_by_email(email))
for stream_name in set(stream_names):
for user_profile in user_profiles:
stream, _ = create_stream_if_needed(user_profile.realm, stream_name)
_ignore, already_subscribed = bulk_add_subscriptions([stream], [user_profile])
was_there_already = user_profile.id in {tup[0].id for tup in already_subscribed}
print(
"%s %s to %s"
% ("Already subscribed" if was_there_already else "Subscribed", user_profile.email, stream_name)
)
示例7: stream_exists_backend
def stream_exists_backend(request, user_profile, stream_name, autosubscribe):
# type: (HttpRequest, UserProfile, text_type, bool) -> HttpResponse
if not valid_stream_name(stream_name):
return json_error(_("Invalid characters in stream name"))
stream = get_stream(stream_name, user_profile.realm)
result = {"exists": bool(stream)}
if stream is not None:
recipient = get_recipient(Recipient.STREAM, stream.id)
if autosubscribe:
bulk_add_subscriptions([stream], [user_profile])
result["subscribed"] = is_active_subscriber(
user_profile=user_profile,
recipient=recipient)
return json_success(result) # results are ignored for HEAD requests
return json_response(data=result, status=404)
示例8: stream_exists_backend
def stream_exists_backend(request, user_profile, stream_id, autosubscribe):
# type: (HttpRequest, UserProfile, int, bool) -> HttpResponse
try:
stream = get_and_validate_stream_by_id(stream_id, user_profile.realm)
except JsonableError:
stream = None
result = {"exists": bool(stream)}
if stream is not None:
recipient = get_recipient(Recipient.STREAM, stream.id)
if autosubscribe:
bulk_add_subscriptions([stream], [user_profile])
result["subscribed"] = is_active_subscriber(
user_profile=user_profile,
recipient=recipient)
return json_success(result) # results are ignored for HEAD requests
return json_response(data=result, status=404)
示例9: test_subscriptions
def test_subscriptions(self) -> None:
now = timezone_now()
user = [self.example_user('hamlet')]
stream = [self.make_stream('test_stream')]
bulk_add_subscriptions(stream, user)
subscription_creation_logs = RealmAuditLog.objects.filter(event_type=RealmAuditLog.SUBSCRIPTION_CREATED,
event_time__gte=now)
self.assertEqual(subscription_creation_logs.count(), 1)
self.assertEqual(subscription_creation_logs[0].modified_stream.id, stream[0].id)
self.assertEqual(subscription_creation_logs[0].modified_user, user[0])
bulk_remove_subscriptions(user, stream, get_client("website"))
subscription_deactivation_logs = RealmAuditLog.objects.filter(event_type=RealmAuditLog.SUBSCRIPTION_DEACTIVATED,
event_time__gte=now)
self.assertEqual(subscription_deactivation_logs.count(), 1)
self.assertEqual(subscription_deactivation_logs[0].modified_stream.id, stream[0].id)
self.assertEqual(subscription_deactivation_logs[0].modified_user, user[0])
示例10: test_subscriptions
def test_subscriptions(self):
# type: () -> None
now = timezone_now()
user = [self.example_user('hamlet')]
stream = [self.make_stream('test_stream')]
bulk_add_subscriptions(stream, user)
subscription_creation_logs = RealmAuditLog.objects.filter(event_type='subscription_created',
event_time__gte=now)
self.assertEqual(subscription_creation_logs.count(), 1)
self.assertEqual(subscription_creation_logs[0].modified_stream.id, stream[0].id)
self.assertEqual(subscription_creation_logs[0].modified_user, user[0])
bulk_remove_subscriptions(user, stream)
subscription_deactivation_logs = RealmAuditLog.objects.filter(event_type='subscription_deactivated',
event_time__gte=now)
self.assertEqual(subscription_deactivation_logs.count(), 1)
self.assertEqual(subscription_deactivation_logs[0].modified_stream.id, stream[0].id)
self.assertEqual(subscription_deactivation_logs[0].modified_user, user[0])
示例11: handle
def handle(self, *args: Any, **options: str) -> None:
realm = self.get_realm(options)
assert realm is not None # Should be ensured by parser
stream_to_keep = get_stream(options["stream_to_keep"], realm)
stream_to_destroy = get_stream(options["stream_to_destroy"], realm)
recipient_to_destroy = get_stream_recipient(stream_to_destroy.id)
recipient_to_keep = get_stream_recipient(stream_to_keep.id)
# The high-level approach here is to move all the messages to
# the surviving stream, deactivate all the subscriptions on
# the stream to be removed and deactivate the stream, and add
# new subscriptions to the stream to keep for any users who
# were only on the now-deactivated stream.
# Move the messages, and delete the old copies from caches.
message_ids_to_clear = list(Message.objects.filter(
recipient=recipient_to_destroy).values_list("id", flat=True))
count = Message.objects.filter(recipient=recipient_to_destroy).update(recipient=recipient_to_keep)
print("Moved %s messages" % (count,))
bulk_delete_cache_keys(message_ids_to_clear)
# Move the Subscription objects. This algorithm doesn't
# preserve any stream settings/colors/etc. from the stream
# being destroyed, but it's convenient.
existing_subs = Subscription.objects.filter(recipient=recipient_to_keep)
users_already_subscribed = dict((sub.user_profile_id, sub.active) for sub in existing_subs)
subs_to_deactivate = Subscription.objects.filter(recipient=recipient_to_destroy, active=True)
users_to_activate = [
sub.user_profile for sub in subs_to_deactivate
if not users_already_subscribed.get(sub.user_profile_id, False)
]
if len(subs_to_deactivate) > 0:
print("Deactivating %s subscriptions" % (len(subs_to_deactivate),))
bulk_remove_subscriptions([sub.user_profile for sub in subs_to_deactivate],
[stream_to_destroy],
self.get_client())
do_deactivate_stream(stream_to_destroy)
if len(users_to_activate) > 0:
print("Adding %s subscriptions" % (len(users_to_activate),))
bulk_add_subscriptions([stream_to_keep], users_to_activate)
示例12: json_stream_exists
def json_stream_exists(request: HttpRequest, user_profile: UserProfile, stream_name: Text=REQ("stream"),
autosubscribe: bool=REQ(validator=check_bool, default=False)) -> HttpResponse:
check_stream_name(stream_name)
try:
(stream, recipient, sub) = access_stream_by_name(user_profile, stream_name)
except JsonableError as e:
return json_error(e.msg, status=404)
# access_stream functions return a subscription if and only if we
# are already subscribed.
result = {"subscribed": sub is not None}
# If we got here, we're either subscribed or the stream is public.
# So if we're not yet subscribed and autosubscribe is enabled, we
# should join.
if sub is None and autosubscribe:
bulk_add_subscriptions([stream], [user_profile], acting_user=user_profile)
result["subscribed"] = True
return json_success(result) # results are ignored for HEAD requests
示例13: handle
def handle(self, **options: Any) -> None:
realm = self.get_realm(options)
assert realm is not None # Should be ensured by parser
user_profiles = self.get_users(options, realm)
stream_names = set([stream.strip() for stream in options["streams"].split(",")])
for stream_name in set(stream_names):
for user_profile in user_profiles:
stream, _ = create_stream_if_needed(realm, stream_name)
_ignore, already_subscribed = bulk_add_subscriptions([stream], [user_profile])
was_there_already = user_profile.id in {tup[0].id for tup in already_subscribed}
print("%s %s to %s" % (
"Already subscribed" if was_there_already else "Subscribed",
user_profile.email, stream_name))
示例14: add_subscriptions_backend
def add_subscriptions_backend(request, user_profile,
streams_raw = REQ("subscriptions",
validator=check_list(check_dict([('name', check_string)]))),
invite_only = REQ(validator=check_bool, default=False),
announce = REQ(validator=check_bool, default=False),
principals = REQ(validator=check_list(check_string), default=None),
authorization_errors_fatal = REQ(validator=check_bool, default=True)):
# type: (HttpRequest, UserProfile, List[Dict[str, str]], bool, bool, Optional[List[str]], bool) -> HttpResponse
stream_names = []
for stream_dict in streams_raw:
stream_name = stream_dict["name"].strip()
if len(stream_name) > Stream.MAX_NAME_LENGTH:
return json_error(_("Stream name (%s) too long.") % (stream_name,))
if not valid_stream_name(stream_name):
return json_error(_("Invalid stream name (%s).") % (stream_name,))
stream_names.append(stream_name)
# Enforcement of can_create_streams policy is inside list_to_streams.
existing_streams, created_streams = \
list_to_streams(stream_names, user_profile, autocreate=True, invite_only=invite_only)
authorized_streams, unauthorized_streams = \
filter_stream_authorization(user_profile, existing_streams)
if len(unauthorized_streams) > 0 and authorization_errors_fatal:
return json_error(_("Unable to access stream (%s).") % unauthorized_streams[0].name)
# Newly created streams are also authorized for the creator
streams = authorized_streams + created_streams
if principals is not None:
if user_profile.realm.domain == 'mit.edu' and not all(stream.invite_only for stream in streams):
return json_error(_("You can only invite other mit.edu users to invite-only streams."))
subscribers = set(principal_to_user_profile(user_profile, principal) for principal in principals)
else:
subscribers = set([user_profile])
(subscribed, already_subscribed) = bulk_add_subscriptions(streams, subscribers)
result = dict(subscribed=defaultdict(list), already_subscribed=defaultdict(list)) # type: Dict[str, Any]
for (subscriber, stream) in subscribed:
result["subscribed"][subscriber.email].append(stream.name)
for (subscriber, stream) in already_subscribed:
result["already_subscribed"][subscriber.email].append(stream.name)
private_streams = dict((stream.name, stream.invite_only) for stream in streams)
bots = dict((subscriber.email, subscriber.is_bot) for subscriber in subscribers)
# Inform the user if someone else subscribed them to stuff,
# or if a new stream was created with the "announce" option.
notifications = []
if principals and result["subscribed"]:
for email, subscriptions in six.iteritems(result["subscribed"]):
if email == user_profile.email:
# Don't send a Zulip if you invited yourself.
continue
if bots[email]:
# Don't send invitation Zulips to bots
continue
if len(subscriptions) == 1:
msg = ("Hi there! We thought you'd like to know that %s just "
"subscribed you to the%s stream [%s](%s)."
% (user_profile.full_name,
" **invite-only**" if private_streams[subscriptions[0]] else "",
subscriptions[0],
stream_link(subscriptions[0]),
))
else:
msg = ("Hi there! We thought you'd like to know that %s just "
"subscribed you to the following streams: \n\n"
% (user_profile.full_name,))
for stream in subscriptions:
msg += "* [%s](%s)%s\n" % (
stream,
stream_link(stream),
" (**invite-only**)" if private_streams[stream] else "")
if len([s for s in subscriptions if not private_streams[s]]) > 0:
msg += "\nYou can see historical content on a non-invite-only stream by narrowing to it."
notifications.append(internal_prep_message(settings.NOTIFICATION_BOT,
"private", email, "", msg))
if announce and len(created_streams) > 0:
notifications_stream = user_profile.realm.notifications_stream
if notifications_stream is not None:
if len(created_streams) > 1:
stream_msg = "the following streams: %s" % \
(", ".join('`%s`' % (s.name,) for s in created_streams),)
else:
stream_msg = "a new stream `%s`" % (created_streams[0].name)
stream_buttons = ' '.join(stream_button(s.name) for s in created_streams)
msg = ("%s just created %s. %s" % (user_profile.full_name,
stream_msg, stream_buttons))
notifications.append(internal_prep_message(settings.NOTIFICATION_BOT,
"stream",
notifications_stream.name, "Streams", msg,
realm=notifications_stream.realm))
else:
msg = ("Hi there! %s just created a new stream '%s'. %s"
% (user_profile.full_name, created_streams[0].name, stream_button(created_streams[0].name)))
for realm_user_dict in get_active_user_dicts_in_realm(user_profile.realm):
#.........这里部分代码省略.........
示例15: accounts_register
#.........这里部分代码省略.........
#
# If instead the realm is using EmailAuthBackend, we will
# set their password above.
#
# But if the realm is using LDAPAuthBackend, we need to verify
# their LDAP password (which will, as a side effect, create
# the user account) here using authenticate.
auth_result = authenticate(request,
username=email,
password=password,
realm=realm,
return_data=return_data)
if auth_result is not None:
# Since we'll have created a user, we now just log them in.
return login_and_go_to_home(request, auth_result)
if return_data.get("outside_ldap_domain") and email_auth_enabled(realm):
# If both the LDAP and Email auth backends are
# enabled, and the user's email is outside the LDAP
# domain, then the intent is to create a user in the
# realm with their email outside the LDAP organization
# (with e.g. a password stored in the Zulip database,
# not LDAP). So we fall through and create the new
# account.
#
# It's likely that we can extend this block to the
# Google and GitHub auth backends with no code changes
# other than here.
pass
else:
# TODO: This probably isn't going to give a
# user-friendly error message, but it doesn't
# particularly matter, because the registration form
# is hidden for most users.
return HttpResponseRedirect(reverse('django.contrib.auth.views.login') + '?email=' +
urllib.parse.quote_plus(email))
if existing_user_profile is not None and existing_user_profile.is_mirror_dummy:
user_profile = existing_user_profile
do_activate_user(user_profile)
do_change_password(user_profile, password)
do_change_full_name(user_profile, full_name, user_profile)
do_set_user_display_setting(user_profile, 'timezone', timezone)
# TODO: When we clean up the `do_activate_user` code path,
# make it respect invited_as_admin / is_realm_admin.
else:
user_profile = do_create_user(email, password, realm, full_name, short_name,
prereg_user=prereg_user, is_realm_admin=is_realm_admin,
tos_version=settings.TOS_VERSION,
timezone=timezone,
newsletter_data={"IP": request.META['REMOTE_ADDR']},
default_stream_groups=default_stream_groups,
source_profile=source_profile)
if realm_creation:
bulk_add_subscriptions([realm.signup_notifications_stream], [user_profile])
send_initial_realm_messages(realm)
# Because for realm creation, registration happens on the
# root domain, we need to log them into the subdomain for
# their new realm.
return redirect_and_log_into_subdomain(realm, full_name, email)
# This dummy_backend check below confirms the user is
# authenticating to the correct subdomain.
auth_result = authenticate(username=user_profile.email,
realm=realm,
return_data=return_data,
use_dummy_backend=True)
if return_data.get('invalid_subdomain'):
# By construction, this should never happen.
logging.error("Subdomain mismatch in registration %s: %s" % (
realm.subdomain, user_profile.email,))
return redirect('/')
return login_and_go_to_home(request, auth_result)
return render(
request,
'zerver/register.html',
context={'form': form,
'email': email,
'key': key,
'full_name': request.session.get('authenticated_full_name', None),
'lock_name': name_validated and name_changes_disabled(realm),
# password_auth_enabled is normally set via our context processor,
# but for the registration form, there is no logged in user yet, so
# we have to set it here.
'creating_new_team': realm_creation,
'password_required': password_auth_enabled(realm) and password_required,
'password_auth_enabled': password_auth_enabled(realm),
'root_domain_available': is_root_domain_available(),
'default_stream_groups': get_default_stream_groups(realm),
'accounts': get_accounts_for_email(email),
'MAX_REALM_NAME_LENGTH': str(Realm.MAX_REALM_NAME_LENGTH),
'MAX_NAME_LENGTH': str(UserProfile.MAX_NAME_LENGTH),
'MAX_PASSWORD_LENGTH': str(form.MAX_PASSWORD_LENGTH),
'MAX_REALM_SUBDOMAIN_LENGTH': str(Realm.MAX_REALM_SUBDOMAIN_LENGTH)
}
)