def parse_headers(self, custom_headers: Union[None, str]) -> Union[None, Dict[str, str]]: if not custom_headers: return {} try: custom_headers_dict = ujson.loads(custom_headers) except ValueError as ve: raise CommandError('Encountered an error while attempting to parse custom headers: {}\n' 'Note: all strings must be enclosed within "" instead of \'\''.format(ve)) return standardize_headers(custom_headers_dict)
def _parse_email_fixture(self, fixture_path: str) -> Message: if not self._does_fixture_path_exist(fixture_path): raise CommandError(f'Fixture {fixture_path} does not exist') if fixture_path.endswith('.json'): message = self._parse_email_json_fixture(fixture_path) else: with open(fixture_path, "rb") as fp: message = email.message_from_binary_file(fp) return message
def handle(self, *args: Any, **options: Any) -> None: realm = self.get_realm(options) if options['all']: if realm is None: raise CommandError('You must specify a realm if you choose the --all option.') self.fix_all_users(realm) return self.fix_emails(realm, options['emails'])
def _parse_email_fixture(self, fixture_path: str) -> EmailMessage: if not self._does_fixture_path_exist(fixture_path): raise CommandError(f"Fixture {fixture_path} does not exist") if fixture_path.endswith(".json"): return self._parse_email_json_fixture(fixture_path) else: with open(fixture_path, "rb") as fp: message = email.message_from_binary_file(fp, policy=email.policy.default) # https://github.com/python/typeshed/issues/2417 assert isinstance(message, EmailMessage) return message
def parse_headers( self, custom_headers: Union[None, str]) -> Union[None, Dict[str, str]]: if not custom_headers: return {} try: custom_headers_dict = orjson.loads(custom_headers) except orjson.JSONDecodeError as ve: raise CommandError( "Encountered an error while attempting to parse custom headers: {}\n" "Note: all strings must be enclosed within \"\" instead of ''". format(ve)) return standardize_headers(custom_headers_dict)
def handle(self, *args: Any, **options: str) -> None: if options["entire_server"]: users = UserProfile.objects.filter(is_active=True, is_bot=False, is_mirror_dummy=False) else: realm = self.get_realm(options) try: users = self.get_users(options, realm) except CommandError as error: if str(error) == "You have to pass either -u/--users or -a/--all-users.": raise CommandError("You have to pass -u/--users or -a/--all-users or --entire-server.") raise error self.send(users)
def handle(self, *args: Any, **options: str) -> None: realm = self.get_realm(options) assert realm is not None # Should be ensured by parser if options["op"] == "show": print(f"Domains for {realm.string_id}:") for realm_domain in get_realm_domains(realm): if realm_domain["allow_subdomains"]: print(realm_domain["domain"] + " (subdomains allowed)") else: print(realm_domain["domain"] + " (subdomains not allowed)") sys.exit(0) domain = options['domain'].strip().lower() try: validate_domain(domain) except ValidationError as e: raise CommandError(e.messages[0]) if options["op"] == "add": try: RealmDomain.objects.create( realm=realm, domain=domain, allow_subdomains=options["allow_subdomains"]) sys.exit(0) except IntegrityError: raise CommandError("The domain %(domain)s is already a part " "of your organization." % {'domain': domain}) elif options["op"] == "remove": try: RealmDomain.objects.get(realm=realm, domain=domain).delete() sys.exit(0) except RealmDomain.DoesNotExist: raise CommandError("No such entry found!") else: self.print_help("./manage.py", "realm_domain") raise CommandError
def handle(self, *args: Any, **options: Any) -> None: try: # first check if the db has been initialized Realm.objects.first() except ProgrammingError: raise CommandError("The Zulip database does not appear to exist. " "Have you run initialize-database?") url = generate_realm_creation_url(by_admin=True) self.stdout.write(self.style.SUCCESS("Please visit the following " "secure single-use link to register your ")) self.stdout.write(self.style.SUCCESS("new Zulip organization:\033[0m")) self.stdout.write("") self.stdout.write(self.style.SUCCESS(f" \033[1;92m{url}\033[0m")) self.stdout.write("")
def handle(self, *args: Any, **options: Any) -> None: if not options["flag"] or not options["op"] or not options["email"]: raise CommandError( "Please specify an operation, a flag and an email") op = options['op'] flag = getattr(UserMessage.flags, options['flag']) all_until = options['all_until'] email = options['email'] realm = self.get_realm(options) user_profile = self.get_user(email, realm) if all_until: filt = models.Q(id__lte=all_until) else: filt = models.Q(message__id__in=[ mid.strip() for mid in sys.stdin.read().split(',') ]) mids = [ m.id for m in UserMessage.objects.filter( filt, user_profile=user_profile).order_by('-id') ] if options["for_real"]: sys.stdin.close() sys.stdout.close() sys.stderr.close() def do_update(batch: Iterable[int]) -> None: msgs = UserMessage.objects.filter(id__in=batch) if op == 'add': msgs.update(flags=models.F('flags').bitor(flag)) elif op == 'remove': msgs.update(flags=models.F('flags').bitand(~flag)) if not options["for_real"]: logging.info("Updating %s by %s %s", mids, op, flag) logging.info( "Dry run completed. Run with --for-real to change message flags." ) raise CommandError utils.run_in_batches(mids, 400, do_update, sleep_time=3) exit(0)
def handle(self, *args: Any, **options: Any) -> None: realm = self.get_realm(options) user_profiles = self.get_users(options, realm) for user_profile in user_profiles: print( "{} has {} active bots that will be deactivated as a result of the user's deletion." .format( user_profile.delivery_email, get_active_bots_owned_by_user(user_profile).count(), )) if not options["for_real"]: raise CommandError( "This was a dry run. Pass -f to actually delete.") for user_profile in user_profiles: do_delete_user(user_profile) print(f"Successfully deleted user {user_profile.delivery_email}.")
def handle(self, *args: Any, **options: str) -> None: if options["entire_server"]: users = UserProfile.objects.filter(is_active=True, is_bot=False, is_mirror_dummy=False, realm__deactivated=False) elif options["all_sponsored_org_admins"]: # Sends at most one copy to each email address, even if it # is an administrator in several organizations. sponsored_realms = Realm.objects.filter( plan_type=Realm.STANDARD_FREE, deactivated=False) admin_roles = [ UserProfile.ROLE_REALM_ADMINISTRATOR, UserProfile.ROLE_REALM_OWNER ] users = UserProfile.objects.filter( is_active=True, is_bot=False, is_mirror_dummy=False, role__in=admin_roles, realm__deactivated=False, realm__in=sponsored_realms, ).distinct("delivery_email") else: realm = self.get_realm(options) try: users = self.get_users(options, realm, is_bot=False) except CommandError as error: if str( error ) == "You have to pass either -u/--users or -a/--all-users.": raise CommandError( "You have to pass -u/--users or -a/--all-users or --entire-server." ) raise error send_custom_email(users, options) if options["dry_run"]: print("Would send the above email to:") for user in users: print(f" {user.delivery_email} ({user.realm.string_id})")
def handle(self, *args: Any, **options: str) -> None: if options["entire_server"]: users = UserProfile.objects.filter(is_active=True, is_bot=False, is_mirror_dummy=False) else: realm = self.get_realm(options) try: users = self.get_users(options, realm, is_bot=False) except CommandError as error: if str(error) == "You have to pass either -u/--users or -a/--all-users.": raise CommandError( "You have to pass -u/--users or -a/--all-users or --entire-server." ) raise error send_custom_email(users, options) if options["dry_run"]: print("Would send the above email to:") for user in users: print(f" {user.email}")
def parse_headers( self, custom_headers: Union[None, str]) -> Union[None, Dict[str, str]]: headers = {} if not custom_headers: return None try: custom_headers_dict = ujson.loads(custom_headers) for header in custom_headers_dict: if len(header.split(" ")) > 1: raise ValueError("custom header '%s' contains a space." % (header, )) headers["HTTP_" + header.upper().replace("-", "_")] = str( custom_headers_dict[header]) return headers except ValueError as ve: raise CommandError( 'Encountered an error while attempting to parse custom headers: {}\n' 'Note: all strings must be enclosed within "" instead of \'\''. format(ve))
def handle(self, *args: Any, **options: Any) -> None: realm = self.get_realm(options) user_profile = self.get_user(options['email'], realm) print(f"Deactivating {user_profile.full_name} ({user_profile.delivery_email}) - {user_profile.realm.string_id}") print(f"{user_profile.delivery_email} has the following active sessions:") for session in user_sessions(user_profile): print(session.expire_date, session.get_decoded()) print("") print("{} has {} active bots that will also be deactivated.".format( user_profile.delivery_email, UserProfile.objects.filter( is_bot=True, is_active=True, bot_owner=user_profile, ).count(), )) if not options["for_real"]: raise CommandError("This was a dry run. Pass -f to actually deactivate.") do_deactivate_user(user_profile) print("Sessions deleted, user deactivated.")