zip
stringlengths 19
109
| filename
stringlengths 4
185
| contents
stringlengths 0
30.1M
| type_annotations
sequencelengths 0
1.97k
| type_annotation_starts
sequencelengths 0
1.97k
| type_annotation_ends
sequencelengths 0
1.97k
|
---|---|---|---|---|---|
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0101_muted_topic.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-30 00:26
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
import zerver.lib.str_utils
class Migration(migrations.Migration):
dependencies = [
('zerver', '0100_usermessage_remove_is_me_message'),
]
operations = [
migrations.CreateModel(
name='MutedTopic',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('topic_name', models.CharField(max_length=60)),
('recipient', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zerver.Recipient')),
('stream', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zerver.Stream')),
('user_profile', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
bases=(models.Model,),
),
migrations.AlterUniqueTogether(
name='mutedtopic',
unique_together=set([('user_profile', 'stream', 'topic_name')]),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0102_convert_muted_topic.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-30 00:26
import ujson
from django.db import connection, migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def convert_muted_topics(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
stream_query = '''
SELECT
zerver_stream.name,
zerver_stream.realm_id,
zerver_stream.id,
zerver_recipient.id
FROM
zerver_stream
INNER JOIN zerver_recipient ON (
zerver_recipient.type_id = zerver_stream.id AND
zerver_recipient.type = 2
)
'''
stream_dict = {}
with connection.cursor() as cursor:
cursor.execute(stream_query)
rows = cursor.fetchall()
for (stream_name, realm_id, stream_id, recipient_id) in rows:
stream_name = stream_name.lower()
stream_dict[(stream_name, realm_id)] = (stream_id, recipient_id)
UserProfile = apps.get_model("zerver", "UserProfile")
MutedTopic = apps.get_model("zerver", "MutedTopic")
new_objs = []
user_query = UserProfile.objects.values(
'id',
'realm_id',
'muted_topics'
)
for row in user_query:
user_profile_id = row['id']
realm_id = row['realm_id']
muted_topics = row['muted_topics']
tups = ujson.loads(muted_topics)
for (stream_name, topic_name) in tups:
stream_name = stream_name.lower()
val = stream_dict.get((stream_name, realm_id))
if val is not None:
stream_id, recipient_id = val
muted_topic = MutedTopic(
user_profile_id=user_profile_id,
stream_id=stream_id,
recipient_id=recipient_id,
topic_name=topic_name,
)
new_objs.append(muted_topic)
with connection.cursor() as cursor:
cursor.execute('DELETE from zerver_mutedtopic')
MutedTopic.objects.bulk_create(new_objs)
class Migration(migrations.Migration):
dependencies = [
('zerver', '0101_muted_topic'),
]
operations = [
migrations.RunPython(convert_muted_topics),
]
| [
"StateApps",
"DatabaseSchemaEditor"
] | [
292,
318
] | [
301,
338
] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0103_remove_userprofile_muted_topics.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-31 00:13
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('zerver', '0102_convert_muted_topic'),
]
operations = [
migrations.RemoveField(
model_name='userprofile',
name='muted_topics',
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0104_fix_unreads.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-30 00:26
import ujson
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
from zerver.lib.fix_unreads import fix
def fix_unreads(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
UserProfile = apps.get_model("zerver", "UserProfile")
user_profiles = list(UserProfile.objects.filter(is_bot=False))
for user_profile in user_profiles:
fix(user_profile)
class Migration(migrations.Migration):
dependencies = [
('zerver', '0103_remove_userprofile_muted_topics'),
]
operations = [
migrations.RunPython(fix_unreads),
]
| [
"StateApps",
"DatabaseSchemaEditor"
] | [
311,
337
] | [
320,
357
] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0105_userprofile_enable_stream_push_notifications.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-08 17:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0104_fix_unreads'),
]
operations = [
migrations.AddField(
model_name='userprofile',
name='enable_stream_push_notifications',
field=models.BooleanField(default=False),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0106_subscription_push_notifications.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-08 17:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0105_userprofile_enable_stream_push_notifications'),
]
operations = [
migrations.AddField(
model_name='subscription',
name='push_notifications',
field=models.BooleanField(default=False),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0107_multiuseinvite.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-04 22:48
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0106_subscription_push_notifications'),
]
operations = [
migrations.CreateModel(
name='MultiuseInvite',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('realm', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zerver.Realm')),
('referred_by', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
('streams', models.ManyToManyField(to='zerver.Stream')),
],
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0108_fix_default_string_id.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-24 02:39
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def fix_realm_string_ids(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
Realm = apps.get_model('zerver', 'Realm')
if Realm.objects.filter(deactivated=False).count() != 2:
return
zulip_realm = Realm.objects.get(string_id="zulip")
try:
user_realm = Realm.objects.filter(deactivated=False).exclude(id=zulip_realm.id)[0]
except Realm.DoesNotExist:
return
user_realm.string_id = ""
user_realm.save()
class Migration(migrations.Migration):
dependencies = [
('zerver', '0107_multiuseinvite'),
]
operations = [
migrations.RunPython(fix_realm_string_ids,
reverse_code=migrations.RunPython.noop),
]
| [
"StateApps",
"DatabaseSchemaEditor"
] | [
267,
293
] | [
276,
313
] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0109_mark_tutorial_status_finished.py | # -*- coding: utf-8 -*-
from django.db import migrations, models
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def set_tutorial_status_to_finished(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
UserProfile = apps.get_model('zerver', 'UserProfile')
UserProfile.objects.update(tutorial_status='F')
class Migration(migrations.Migration):
dependencies = [
('zerver', '0108_fix_default_string_id'),
]
operations = [
migrations.RunPython(set_tutorial_status_to_finished)
]
| [
"StateApps",
"DatabaseSchemaEditor"
] | [
236,
262
] | [
245,
282
] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0110_stream_is_in_zephyr_realm.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-10-08 18:37
from django.db import connection, migrations, models
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def populate_is_zephyr(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
Realm = apps.get_model("zerver", "Realm")
Stream = apps.get_model("zerver", "Stream")
realms = Realm.objects.filter(
string_id='zephyr',
)
for realm in realms:
Stream.objects.filter(
realm_id=realm.id
).update(
is_in_zephyr_realm=True
)
class Migration(migrations.Migration):
dependencies = [
('zerver', '0109_mark_tutorial_status_finished'),
]
operations = [
migrations.AddField(
model_name='stream',
name='is_in_zephyr_realm',
field=models.BooleanField(default=False),
),
migrations.RunPython(populate_is_zephyr,
reverse_code=migrations.RunPython.noop),
]
| [
"StateApps",
"DatabaseSchemaEditor"
] | [
284,
310
] | [
293,
330
] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0111_botuserstatedata.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-10-18 16:15
from __future__ import unicode_literals
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0110_stream_is_in_zephyr_realm'),
]
operations = [
migrations.CreateModel(
name='BotUserStateData',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('key', models.TextField(db_index=True)),
('value', models.TextField()),
('bot_profile', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.AlterUniqueTogether(
name='botuserstatedata',
unique_together=set([('bot_profile', 'key')]),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0112_index_muted_topics.py | # -*- coding: utf-8 -*-
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('zerver', '0111_botuserstatedata'),
]
operations = [
migrations.RunSQL(
'''
CREATE INDEX zerver_mutedtopic_stream_topic
ON zerver_mutedtopic
(stream_id, upper(topic_name))
''',
reverse_sql='DROP INDEX zerver_mutedtopic_stream_topic;'
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0113_default_stream_group.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-10-14 15:12
from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0112_index_muted_topics'),
]
operations = [
migrations.CreateModel(
name='DefaultStreamGroup',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(db_index=True, max_length=60)),
('realm', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zerver.Realm')),
('streams', models.ManyToManyField(to='zerver.Stream')),
],
),
migrations.AlterUniqueTogether(
name='defaultstreamgroup',
unique_together=set([('realm', 'name')]),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0114_preregistrationuser_invited_as_admin.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-10-19 21:42
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0113_default_stream_group'),
]
operations = [
migrations.AddField(
model_name='preregistrationuser',
name='invited_as_admin',
field=models.BooleanField(default=False),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0115_user_groups.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-10-30 05:05
from __future__ import unicode_literals
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0114_preregistrationuser_invited_as_admin'),
]
operations = [
migrations.CreateModel(
name='UserGroup',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
],
),
migrations.CreateModel(
name='UserGroupMembership',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('user_group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zerver.UserGroup')),
('user_profile', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.AddField(
model_name='usergroup',
name='members',
field=models.ManyToManyField(through='zerver.UserGroupMembership', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='usergroup',
name='realm',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zerver.Realm'),
),
migrations.AlterUniqueTogether(
name='usergroupmembership',
unique_together=set([('user_group', 'user_profile')]),
),
migrations.AlterUniqueTogether(
name='usergroup',
unique_together=set([('realm', 'name')]),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0116_realm_allow_message_deleting.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-10-28 11:13
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0115_user_groups'),
]
operations = [
migrations.AddField(
model_name='realm',
name='allow_message_deleting',
field=models.BooleanField(default=False),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0117_add_desc_to_user_group.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-01 08:01
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0116_realm_allow_message_deleting'),
]
operations = [
migrations.AddField(
model_name='usergroup',
name='description',
field=models.CharField(default='', max_length=1024),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0118_defaultstreamgroup_description.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-14 19:52
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0117_add_desc_to_user_group'),
]
operations = [
migrations.AddField(
model_name='defaultstreamgroup',
name='description',
field=models.CharField(default='', max_length=1024),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0119_userprofile_night_mode.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-14 19:28
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0118_defaultstreamgroup_description'),
]
operations = [
migrations.AddField(
model_name='userprofile',
name='night_mode',
field=models.BooleanField(default=False),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0120_botuserconfigdata.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-01 19:12
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('zerver', '0119_userprofile_night_mode'),
]
operations = [
migrations.CreateModel(
name='BotUserConfigData',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('key', models.TextField(db_index=True)),
('value', models.TextField()),
('bot_profile', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.AlterUniqueTogether(
name='botuserconfigdata',
unique_together=set([('bot_profile', 'key')]),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0121_realm_signup_notifications_stream.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-10-19 22:01
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def set_initial_value_for_signup_notifications_stream(
apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
realm_model = apps.get_model("zerver", "Realm")
realms = realm_model.objects.exclude(notifications_stream__isnull=True)
for realm in realms:
realm.signup_notifications_stream = realm.notifications_stream
realm.save(update_fields=["signup_notifications_stream"])
class Migration(migrations.Migration):
dependencies = [
('zerver', '0120_botuserconfigdata'),
]
operations = [
migrations.AddField(
model_name='realm',
name='signup_notifications_stream',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to='zerver.Stream'),
),
migrations.RunPython(set_initial_value_for_signup_notifications_stream,
reverse_code=migrations.RunPython.noop),
]
| [
"StateApps",
"DatabaseSchemaEditor"
] | [
386,
412
] | [
395,
432
] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0122_rename_botuserstatedata_botstoragedata.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-24 09:10
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('zerver', '0121_realm_signup_notifications_stream'),
]
operations = [
migrations.RenameModel(
old_name='BotUserStateData',
new_name='BotStorageData',
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0123_userprofile_make_realm_email_pair_unique.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-22 20:45
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0122_rename_botuserstatedata_botstoragedata'),
]
operations = [
migrations.AlterField(
model_name='userprofile',
name='email',
field=models.EmailField(db_index=True, max_length=254),
),
migrations.AlterUniqueTogether(
name='userprofile',
unique_together=set([('realm', 'email')]),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0124_stream_enable_notifications.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-29 01:38
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0123_userprofile_make_realm_email_pair_unique'),
]
operations = [
migrations.AddField(
model_name='subscription',
name='email_notifications',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='userprofile',
name='enable_stream_email_notifications',
field=models.BooleanField(default=False),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0125_realm_max_invites.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-30 04:58
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0124_stream_enable_notifications'),
]
operations = [
migrations.AddField(
model_name='realm',
name='max_invites',
field=models.IntegerField(default=100),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0126_prereg_remove_users_without_realm.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-30 04:58
from __future__ import unicode_literals
from django.db import migrations, models
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def remove_prereg_users_without_realm(
apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
prereg_model = apps.get_model("zerver", "PreregistrationUser")
prereg_model.objects.filter(realm=None, realm_creation=False).delete()
class Migration(migrations.Migration):
dependencies = [
('zerver', '0125_realm_max_invites'),
]
operations = [
migrations.RunPython(remove_prereg_users_without_realm,
reverse_code=migrations.RunPython.noop),
]
| [
"StateApps",
"DatabaseSchemaEditor"
] | [
337,
363
] | [
346,
383
] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0127_disallow_chars_in_stream_and_user_name.py | # -*- coding: utf-8 -*-
from typing import Any, List
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('zerver', '0126_prereg_remove_users_without_realm'),
]
operations = [
# There was a migration here, which wasn't ready for wide deployment
# and was backed out. This placeholder is left behind to avoid
# confusing the migration engine on any installs that applied the
# migration. (Fortunately no reverse migration is needed.)
] # type: List[Any]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0128_scheduledemail_realm.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-12-05 01:08
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def set_realm_for_existing_scheduledemails(
apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
scheduledemail_model = apps.get_model("zerver", "ScheduledEmail")
preregistrationuser_model = apps.get_model("zerver", "PreregistrationUser")
for scheduledemail in scheduledemail_model.objects.all():
if scheduledemail.type == 3: # ScheduledEmail.INVITATION_REMINDER
# Don't think this can be None, but just be safe
prereg = preregistrationuser_model.objects.filter(email=scheduledemail.address).first()
if prereg is not None:
scheduledemail.realm = prereg.realm
else:
scheduledemail.realm = scheduledemail.user.realm
scheduledemail.save(update_fields=['realm'])
# Shouldn't be needed, but just in case
scheduledemail_model.objects.filter(realm=None).delete()
class Migration(migrations.Migration):
dependencies = [
('zerver', '0127_disallow_chars_in_stream_and_user_name'),
]
operations = [
# Start with ScheduledEmail.realm being non-null
migrations.AddField(
model_name='scheduledemail',
name='realm',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='zerver.Realm'),
),
# Sets realm for existing ScheduledEmails
migrations.RunPython(set_realm_for_existing_scheduledemails,
reverse_code=migrations.RunPython.noop),
# Require ScheduledEmail.realm to be non-null
migrations.AlterField(
model_name='scheduledemail',
name='realm',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zerver.Realm'),
),
]
| [
"StateApps",
"DatabaseSchemaEditor"
] | [
375,
401
] | [
384,
421
] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0129_remove_userprofile_autoscroll_forever.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-12-27 17:55
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('zerver', '0128_scheduledemail_realm'),
]
operations = [
migrations.RemoveField(
model_name='userprofile',
name='autoscroll_forever',
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0130_text_choice_in_emojiset.py | from django.db import migrations, models
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
# change emojiset to text if emoji_alt_code is true.
def change_emojiset(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
UserProfile = apps.get_model("zerver", "UserProfile")
for user in UserProfile.objects.filter(emoji_alt_code=True):
user.emojiset = "text"
user.save(update_fields=["emojiset"])
def reverse_change_emojiset(apps: StateApps,
schema_editor: DatabaseSchemaEditor) -> None:
UserProfile = apps.get_model("zerver", "UserProfile")
for user in UserProfile.objects.filter(emojiset="text"):
# Resetting `emojiset` to "google" (the default) doesn't make an
# exact round trip, but it's nearly indistinguishable -- the setting
# shouldn't really matter while `emoji_alt_code` is true.
user.emoji_alt_code = True
user.emojiset = "google"
user.save(update_fields=["emoji_alt_code", "emojiset"])
class Migration(migrations.Migration):
dependencies = [
('zerver', '0129_remove_userprofile_autoscroll_forever'),
]
operations = [
migrations.AlterField(
model_name='userprofile',
name='emojiset',
field=models.CharField(choices=[('google', 'Google'), ('apple', 'Apple'), ('twitter', 'Twitter'), ('emojione', 'EmojiOne'), ('text', 'Plain text')], default='google', max_length=20),
),
migrations.RunPython(change_emojiset, reverse_change_emojiset),
migrations.RemoveField(
model_name='userprofile',
name='emoji_alt_code',
),
]
| [
"StateApps",
"DatabaseSchemaEditor",
"StateApps",
"DatabaseSchemaEditor"
] | [
249,
275,
541,
595
] | [
258,
295,
550,
615
] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0131_realm_create_generic_bot_by_admins_only.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-30 20:05
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0130_text_choice_in_emojiset'),
]
operations = [
migrations.AddField(
model_name='realm',
name='create_generic_bot_by_admins_only',
field=models.BooleanField(default=False),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0132_realm_message_visibility_limit.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-01-03 18:14
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0131_realm_create_generic_bot_by_admins_only'),
]
operations = [
migrations.AddField(
model_name='realm',
name='message_visibility_limit',
field=models.IntegerField(null=True),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0133_rename_botuserconfigdata_botconfigdata.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-01-06 09:56
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('zerver', '0132_realm_message_visibility_limit'),
]
operations = [
migrations.RenameModel(
old_name='BotUserConfigData',
new_name='BotConfigData',
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0134_scheduledmessage.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-01-10 01:11
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('zerver', '0133_rename_botuserconfigdata_botconfigdata'),
]
operations = [
migrations.CreateModel(
name='ScheduledMessage',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('subject', models.CharField(max_length=60)),
('content', models.TextField()),
('scheduled_timestamp', models.DateTimeField(db_index=True)),
('delivered', models.BooleanField(default=False)),
('realm', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zerver.Realm')),
('recipient', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zerver.Recipient')),
('sender', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
('sending_client', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zerver.Client')),
('stream', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='zerver.Stream')),
],
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0135_scheduledmessage_delivery_type.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-01-12 10:37
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0134_scheduledmessage'),
]
operations = [
migrations.AddField(
model_name='scheduledmessage',
name='delivery_type',
field=models.PositiveSmallIntegerField(choices=[(1, 'send_later'), (2, 'remind')], default=1),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0136_remove_userprofile_quota.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-01-24 20:24
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('zerver', '0135_scheduledmessage_delivery_type'),
]
operations = [
migrations.RemoveField(
model_name='userprofile',
name='quota',
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0137_realm_upload_quota_gb.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-01-24 20:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0136_remove_userprofile_quota'),
]
operations = [
migrations.AddField(
model_name='realm',
name='upload_quota_gb',
field=models.IntegerField(null=True),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0138_userprofile_realm_name_in_notifications.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-01-21 08:47
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0137_realm_upload_quota_gb'),
]
operations = [
migrations.AddField(
model_name='userprofile',
name='realm_name_in_notifications',
field=models.BooleanField(default=False),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0139_fill_last_message_id_in_subscription_logs.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def backfill_last_message_id(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
event_type = ['subscription_created', 'subscription_deactivated', 'subscription_activated']
RealmAuditLog = apps.get_model('zerver', 'RealmAuditLog')
subscription_logs = RealmAuditLog.objects.filter(
event_last_message_id__isnull=True, event_type__in=event_type)
subscription_logs.update(event_last_message_id=-1)
class Migration(migrations.Migration):
dependencies = [
('zerver', '0138_userprofile_realm_name_in_notifications'),
]
operations = [
migrations.RunPython(backfill_last_message_id,
reverse_code=migrations.RunPython.noop),
]
| [
"StateApps",
"DatabaseSchemaEditor"
] | [
270,
296
] | [
279,
316
] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0140_realm_send_welcome_emails.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-02-18 07:02
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0139_fill_last_message_id_in_subscription_logs'),
]
operations = [
migrations.AddField(
model_name='realm',
name='send_welcome_emails',
field=models.BooleanField(default=True),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0141_change_usergroup_description_to_textfield.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-02-28 17:38
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0140_realm_send_welcome_emails'),
]
operations = [
migrations.AlterField(
model_name='usergroup',
name='description',
field=models.TextField(default=''),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0142_userprofile_translate_emoticons.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-02-19 22:27
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0141_change_usergroup_description_to_textfield'),
]
operations = [
migrations.AddField(
model_name='userprofile',
name='translate_emoticons',
field=models.BooleanField(default=False),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0143_realm_bot_creation_policy.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-03-09 18:00
from __future__ import unicode_literals
from django.db import migrations, models
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def set_initial_value_for_bot_creation_policy(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
Realm = apps.get_model("zerver", "Realm")
for realm in Realm.objects.all():
if realm.create_generic_bot_by_admins_only:
realm.bot_creation_policy = 2 # BOT_CREATION_LIMIT_GENERIC_BOTS
else:
realm.bot_creation_policy = 1 # BOT_CREATION_EVERYONE
realm.save(update_fields=["bot_creation_policy"])
def reverse_code(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
Realm = apps.get_model("zerver", "Realm")
for realm in Realm.objects.all():
if realm.bot_creation_policy == 1: # BOT_CREATION_EVERYONE
realm.create_generic_bot_by_admins_only = False
else:
realm.create_generic_bot_by_admins_only = True
realm.save(update_fields=["create_generic_bot_by_admins_only"])
class Migration(migrations.Migration):
dependencies = [
('zerver', '0142_userprofile_translate_emoticons'),
]
operations = [
migrations.AddField(
model_name='realm',
name='bot_creation_policy',
field=models.PositiveSmallIntegerField(default=1),
),
migrations.RunPython(set_initial_value_for_bot_creation_policy,
reverse_code=reverse_code),
]
| [
"StateApps",
"DatabaseSchemaEditor",
"StateApps",
"DatabaseSchemaEditor"
] | [
336,
362,
771,
797
] | [
345,
382,
780,
817
] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0144_remove_realm_create_generic_bot_by_admins_only.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-03-09 21:21
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('zerver', '0143_realm_bot_creation_policy'),
]
operations = [
migrations.RemoveField(
model_name='realm',
name='create_generic_bot_by_admins_only',
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0145_reactions_realm_emoji_name_to_id.py | # -*- coding: utf-8 -*-
import ujson
from collections import defaultdict
from django.conf import settings
from django.db import migrations, models
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
from typing import Any, Dict
def realm_emoji_name_to_id(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
Reaction = apps.get_model('zerver', 'Reaction')
RealmEmoji = apps.get_model('zerver', 'RealmEmoji')
realm_emoji_by_realm_id = defaultdict(dict) # type: Dict[int, Dict[str, Any]]
for realm_emoji in RealmEmoji.objects.all():
realm_emoji_by_realm_id[realm_emoji.realm_id][realm_emoji.name] = {
'id': str(realm_emoji.id),
'name': realm_emoji.name,
'deactivated': realm_emoji.deactivated,
}
for reaction in Reaction.objects.filter(reaction_type='realm_emoji'):
realm_id = reaction.user_profile.realm_id
emoji_name = reaction.emoji_name
realm_emoji = realm_emoji_by_realm_id.get(realm_id, {}).get(emoji_name)
if realm_emoji is None:
# Realm emoji used in this reaction has been deleted so this
# reaction should also be deleted. We don't need to reverse
# this step in migration reversal code.
print("Reaction for (%s, %s) refers to deleted custom emoji %s; deleting" %
(emoji_name, reaction.message_id, reaction.user_profile_id))
reaction.delete()
else:
reaction.emoji_code = realm_emoji["id"]
reaction.save()
def reversal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
Reaction = apps.get_model('zerver', 'Reaction')
for reaction in Reaction.objects.filter(reaction_type='realm_emoji'):
reaction.emoji_code = reaction.emoji_name
reaction.save()
class Migration(migrations.Migration):
dependencies = [
('zerver', '0144_remove_realm_create_generic_bot_by_admins_only'),
]
operations = [
migrations.RunPython(realm_emoji_name_to_id,
reverse_code=reversal),
]
| [
"StateApps",
"DatabaseSchemaEditor",
"StateApps",
"DatabaseSchemaEditor"
] | [
340,
366,
1638,
1664
] | [
349,
386,
1647,
1684
] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0146_userprofile_message_content_in_email_notifications.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-29 12:33
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0145_reactions_realm_emoji_name_to_id'),
]
operations = [
migrations.AddField(
model_name='userprofile',
name='message_content_in_email_notifications',
field=models.BooleanField(default=True),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0147_realm_disallow_disposable_email_addresses.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-03-05 19:20
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0146_userprofile_message_content_in_email_notifications'),
]
operations = [
migrations.AddField(
model_name='realm',
name='disallow_disposable_email_addresses',
field=models.BooleanField(default=True),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0148_max_invites_forget_default.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-02-10 02:59
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0147_realm_disallow_disposable_email_addresses'),
]
operations = [
migrations.AlterField(
model_name='realm',
name='max_invites',
field=models.IntegerField(null=True, db_column='max_invites'),
),
migrations.RenameField(
model_name='realm',
old_name='max_invites',
new_name='_max_invites',
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0149_realm_emoji_drop_unique_constraint.py | # -*- coding: utf-8 -*-
import os
import shutil
import tempfile
from boto.s3.connection import S3Connection
from django.conf import settings
from django.db import migrations, models
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
class Uploader:
def __init__(self) -> None:
self.old_orig_image_path_template = "{realm_id}/emoji/{emoji_file_name}.original"
self.old_path_template = "{realm_id}/emoji/{emoji_file_name}"
self.new_orig_image_path_template = "{realm_id}/emoji/images/{emoji_file_name}.original"
self.new_path_template = "{realm_id}/emoji/images/{emoji_file_name}"
def copy_files(self, src_path: str, dst_path: str) -> None:
raise NotImplementedError()
def ensure_emoji_images(self, realm_id: int, old_filename: str, new_filename: str) -> None:
# Copy original image file.
old_file_path = self.old_orig_image_path_template.format(realm_id=realm_id,
emoji_file_name=old_filename)
new_file_path = self.new_orig_image_path_template.format(realm_id=realm_id,
emoji_file_name=new_filename)
self.copy_files(old_file_path, new_file_path)
# Copy resized image file.
old_file_path = self.old_path_template.format(realm_id=realm_id,
emoji_file_name=old_filename)
new_file_path = self.new_path_template.format(realm_id=realm_id,
emoji_file_name=new_filename)
self.copy_files(old_file_path, new_file_path)
class LocalUploader(Uploader):
def __init__(self) -> None:
super().__init__()
@staticmethod
def mkdirs(path: str) -> None:
dirname = os.path.dirname(path)
if not os.path.isdir(dirname):
os.makedirs(dirname)
def copy_files(self, src_path: str, dst_path: str) -> None:
src_path = os.path.join(settings.LOCAL_UPLOADS_DIR, 'avatars', src_path)
self.mkdirs(src_path)
dst_path = os.path.join(settings.LOCAL_UPLOADS_DIR, 'avatars', dst_path)
self.mkdirs(dst_path)
shutil.copyfile(src_path, dst_path)
class S3Uploader(Uploader):
def __init__(self) -> None:
super().__init__()
conn = S3Connection(settings.S3_KEY, settings.S3_SECRET_KEY)
self.bucket_name = settings.S3_AVATAR_BUCKET
self.bucket = conn.get_bucket(self.bucket_name, validate=False)
def copy_files(self, src_key: str, dst_key: str) -> None:
self.bucket.copy_key(dst_key, self.bucket_name, src_key)
def get_uploader() -> Uploader:
if settings.LOCAL_UPLOADS_DIR is None:
return S3Uploader()
return LocalUploader()
def get_emoji_file_name(emoji_file_name: str, new_name: str) -> str:
_, image_ext = os.path.splitext(emoji_file_name)
return ''.join((new_name, image_ext))
def migrate_realm_emoji_image_files(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
RealmEmoji = apps.get_model('zerver', 'RealmEmoji')
uploader = get_uploader()
for realm_emoji in RealmEmoji.objects.all():
old_file_name = realm_emoji.file_name
new_file_name = get_emoji_file_name(old_file_name, str(realm_emoji.id))
uploader.ensure_emoji_images(realm_emoji.realm_id, old_file_name, new_file_name)
realm_emoji.file_name = new_file_name
realm_emoji.save(update_fields=['file_name'])
def reversal(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
# Ensures that migration can be re-run in case of a failure.
RealmEmoji = apps.get_model('zerver', 'RealmEmoji')
for realm_emoji in RealmEmoji.objects.all():
corrupt_file_name = realm_emoji.file_name
correct_file_name = get_emoji_file_name(corrupt_file_name, realm_emoji.name)
realm_emoji.file_name = correct_file_name
realm_emoji.save(update_fields=['file_name'])
class Migration(migrations.Migration):
dependencies = [
('zerver', '0148_max_invites_forget_default'),
]
operations = [
migrations.AlterUniqueTogether(
name='realmemoji',
unique_together=set([]),
),
migrations.AlterField(
model_name='realmemoji',
name='file_name',
field=models.TextField(db_index=True, null=True, blank=True),
),
migrations.RunPython(
migrate_realm_emoji_image_files,
reverse_code=reversal),
]
| [
"str",
"str",
"int",
"str",
"str",
"str",
"str",
"str",
"str",
"str",
"str",
"str",
"StateApps",
"DatabaseSchemaEditor",
"StateApps",
"DatabaseSchemaEditor"
] | [
730,
745,
840,
859,
878,
1875,
2037,
2052,
2649,
2663,
2915,
2930,
3081,
3107,
3608,
3634
] | [
733,
748,
843,
862,
881,
1878,
2040,
2055,
2652,
2666,
2918,
2933,
3090,
3127,
3617,
3654
] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0150_realm_allow_community_topic_editing.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-28 22:56
from __future__ import unicode_literals
from django.db import migrations, models
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
class Migration(migrations.Migration):
dependencies = [
('zerver', '0149_realm_emoji_drop_unique_constraint'),
]
operations = [
migrations.AddField(
model_name='realm',
name='allow_community_topic_editing',
field=models.BooleanField(default=False),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0151_last_reminder_default_none.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-03-29 18:47
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0150_realm_allow_community_topic_editing'),
]
operations = [
migrations.AlterField(
model_name='userprofile',
name='last_reminder',
field=models.DateTimeField(default=None, null=True),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0152_realm_default_twenty_four_hour_time.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-03-30 17:18
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0151_last_reminder_default_none'),
]
operations = [
migrations.AddField(
model_name='realm',
name='default_twenty_four_hour_time',
field=models.BooleanField(default=False),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0153_remove_int_float_custom_fields.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-04-02 12:42
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0152_realm_default_twenty_four_hour_time'),
]
operations = [
migrations.AlterField(
model_name='customprofilefield',
name='field_type',
field=models.PositiveSmallIntegerField(choices=[(1, 'Short text'), (2, 'Long text')], default=1),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0154_fix_invalid_bot_owner.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-04-03 01:52
from __future__ import unicode_literals
from django.db import migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def migrate_fix_invalid_bot_owner_values(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
"""Fixes UserProfile objects that incorrectly had a bot_owner set"""
UserProfile = apps.get_model('zerver', 'UserProfile')
UserProfile.objects.filter(is_bot=False).exclude(bot_owner=None).update(bot_owner=None)
class Migration(migrations.Migration):
dependencies = [
('zerver', '0153_remove_int_float_custom_fields'),
]
operations = [
migrations.RunPython(
migrate_fix_invalid_bot_owner_values,
reverse_code=migrations.RunPython.noop),
]
| [
"StateApps",
"DatabaseSchemaEditor"
] | [
323,
349
] | [
332,
369
] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0155_change_default_realm_description.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-04-06 19:17
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0154_fix_invalid_bot_owner'),
]
operations = [
migrations.AlterField(
model_name='realm',
name='description',
field=models.TextField(default=''),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0156_add_hint_to_profile_field.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-04-06 04:10
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0155_change_default_realm_description'),
]
operations = [
migrations.AddField(
model_name='customprofilefield',
name='hint',
field=models.CharField(default='', max_length=80, null=True),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0157_userprofile_is_guest.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-04-20 19:29
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0156_add_hint_to_profile_field'),
]
operations = [
migrations.AddField(
model_name='userprofile',
name='is_guest',
field=models.BooleanField(db_index=True, default=False),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0158_realm_video_chat_provider.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-04-10 14:57
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0157_userprofile_is_guest'),
]
operations = [
migrations.AddField(
model_name='realm',
name='video_chat_provider',
field=models.CharField(default='Jitsi', max_length=40),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0159_realm_google_hangouts_domain.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-04-23 16:37
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0158_realm_video_chat_provider'),
]
operations = [
migrations.AddField(
model_name='realm',
name='google_hangouts_domain',
field=models.TextField(default=''),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0160_add_choice_field.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-04-10 04:57
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0159_realm_google_hangouts_domain'),
]
operations = [
migrations.AddField(
model_name='customprofilefield',
name='field_data',
field=models.TextField(default='', null=True),
),
migrations.AlterField(
model_name='customprofilefield',
name='field_type',
field=models.PositiveSmallIntegerField(choices=[(1, 'Short text'), (2, 'Long text'), (3, 'Choice')], default=1),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0161_realm_message_content_delete_limit_seconds.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-04-24 22:12
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0160_add_choice_field'),
]
operations = [
migrations.AddField(
model_name='realm',
name='message_content_delete_limit_seconds',
field=models.IntegerField(default=600),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0162_change_default_community_topic_editing.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-04-24 09:10
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0161_realm_message_content_delete_limit_seconds'),
]
operations = [
migrations.AlterField(
model_name='realm',
name='allow_community_topic_editing',
field=models.BooleanField(default=True),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0163_remove_userprofile_default_desktop_notifications.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-04-28 20:34
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('zerver', '0162_change_default_community_topic_editing'),
]
operations = [
migrations.RemoveField(
model_name='userprofile',
name='default_desktop_notifications',
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0164_stream_history_public_to_subscribers.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-04-28 22:31
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def set_initial_value_for_history_public_to_subscribers(
apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
stream_model = apps.get_model("zerver", "Stream")
streams = stream_model.objects.all()
for stream in streams:
if stream.invite_only:
stream.history_public_to_subscribers = getattr(settings, 'PRIVATE_STREAM_HISTORY_FOR_SUBSCRIBERS', False)
else:
stream.history_public_to_subscribers = True
if stream.is_in_zephyr_realm:
stream.history_public_to_subscribers = False
stream.save(update_fields=["history_public_to_subscribers"])
class Migration(migrations.Migration):
dependencies = [
('zerver', '0163_remove_userprofile_default_desktop_notifications'),
]
operations = [
migrations.AddField(
model_name='stream',
name='history_public_to_subscribers',
field=models.BooleanField(default=False),
),
migrations.RunPython(set_initial_value_for_history_public_to_subscribers,
reverse_code=migrations.RunPython.noop),
]
| [
"StateApps",
"DatabaseSchemaEditor"
] | [
390,
416
] | [
399,
436
] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0165_add_date_to_profile_field.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-04-29 17:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0164_stream_history_public_to_subscribers'),
]
operations = [
migrations.AlterField(
model_name='customprofilefield',
name='field_type',
field=models.PositiveSmallIntegerField(choices=[(1, 'Short text'), (2, 'Long text'), (4, 'Date'), (3, 'Choice')], default=1),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0166_add_url_to_profile_field.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-04-29 17:25
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0165_add_date_to_profile_field'),
]
operations = [
migrations.AlterField(
model_name='customprofilefield',
name='field_type',
field=models.PositiveSmallIntegerField(choices=[(1, 'Short text'), (2, 'Long text'), (4, 'Date'), (5, 'URL'), (3, 'Choice')], default=1),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0167_custom_profile_fields_sort_order.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-04-08 15:49
from __future__ import unicode_literals
from django.db import migrations, models
from django.db.models import F
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def migrate_set_order_value(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
CustomProfileField = apps.get_model('zerver', 'CustomProfileField')
CustomProfileField.objects.all().update(order=F('id'))
class Migration(migrations.Migration):
dependencies = [
('zerver', '0166_add_url_to_profile_field'),
]
operations = [
migrations.AddField(
model_name='customprofilefield',
name='order',
field=models.IntegerField(default=0),
),
migrations.RunPython(migrate_set_order_value,
reverse_code=migrations.RunPython.noop),
]
| [
"StateApps",
"DatabaseSchemaEditor"
] | [
350,
376
] | [
359,
396
] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0168_stream_is_web_public.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-04-27 08:03
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0167_custom_profile_fields_sort_order'),
]
operations = [
migrations.AddField(
model_name='stream',
name='is_web_public',
field=models.BooleanField(default=False),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0169_stream_is_announcement_only.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-05-12 04:57
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0168_stream_is_web_public'),
]
operations = [
migrations.AddField(
model_name='stream',
name='is_announcement_only',
field=models.BooleanField(default=False),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0170_submessage.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-01-26 21:54
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('zerver', '0169_stream_is_announcement_only'),
]
operations = [
migrations.CreateModel(
name='SubMessage',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('msg_type', models.TextField()),
('content', models.TextField()),
('message', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='zerver.Message')),
('sender', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0171_userprofile_dense_mode.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-05-24 18:45
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0170_submessage'),
]
operations = [
migrations.AddField(
model_name='userprofile',
name='dense_mode',
field=models.BooleanField(default=True),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0172_add_user_type_of_custom_profile_field.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-05-08 17:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0171_userprofile_dense_mode'),
]
operations = [
migrations.AlterField(
model_name='customprofilefield',
name='field_type',
field=models.PositiveSmallIntegerField(choices=[(1, 'Short text'), (2, 'Long text'), (4, 'Date'), (5, 'URL'), (3, 'Choice'), (6, 'User')], default=1),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0173_support_seat_based_plans.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-06-28 01:09
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0172_add_user_type_of_custom_profile_field'),
]
operations = [
migrations.AddField(
model_name='realm',
name='has_seat_based_plan',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='realmauditlog',
name='requires_billing_update',
field=models.BooleanField(default=False),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0174_userprofile_delivery_email.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-07-05 17:57
from __future__ import unicode_literals
from django.db import migrations, models
from django.apps import apps
from django.db.models import F
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def copy_email_field(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
UserProfile = apps.get_model('zerver', 'UserProfile')
UserProfile.objects.all().update(delivery_email=F('email'))
class Migration(migrations.Migration):
atomic = False
dependencies = [
('zerver', '0173_support_seat_based_plans'),
]
operations = [
migrations.AddField(
model_name='userprofile',
name='delivery_email',
field=models.EmailField(db_index=True, default='', max_length=254),
preserve_default=False,
),
migrations.RunPython(copy_email_field,
reverse_code=migrations.RunPython.noop),
]
| [
"StateApps",
"DatabaseSchemaEditor"
] | [
373,
399
] | [
382,
419
] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0175_change_realm_audit_log_event_type_tense.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.apps import apps
from django.db.models import F
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def change_realm_audit_log_event_type_tense(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
RealmAuditLog = apps.get_model('zerver', 'RealmAuditLog')
RealmAuditLog.objects.filter(event_type="user_change_password").update(event_type="user_password_changed")
RealmAuditLog.objects.filter(event_type="user_change_avatar_source").update(event_type="user_avatar_source_changed")
RealmAuditLog.objects.filter(event_type="bot_owner_changed").update(event_type="user_bot_owner_changed")
class Migration(migrations.Migration):
dependencies = [
('zerver', '0174_userprofile_delivery_email'),
]
operations = [
migrations.RunPython(change_realm_audit_log_event_type_tense,
reverse_code=migrations.RunPython.noop),
]
| [
"StateApps",
"DatabaseSchemaEditor"
] | [
346,
372
] | [
355,
392
] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0176_remove_subscription_notifications.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-07-26 18:38
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('zerver', '0175_change_realm_audit_log_event_type_tense'),
]
operations = [
migrations.RemoveField(
model_name='subscription',
name='notifications',
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0177_user_message_add_and_index_is_private_flag.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-06-14 13:39
from __future__ import unicode_literals
import sys
import bitfield.models
from django.db import migrations, transaction
from zerver.lib.migrate import create_index_if_not_exist # nolint
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
from django.db.models import F
def reset_is_private_flag(
apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
UserMessage = apps.get_model("zerver", "UserMessage")
UserProfile = apps.get_model("zerver", "UserProfile")
user_profile_ids = UserProfile.objects.all().order_by("id").values_list("id", flat=True)
# We only need to do this because previous migration
# zerver/migrations/0100_usermessage_remove_is_me_message.py
# didn't clean the field after removing it.
i = 0
total = len(user_profile_ids)
print("Setting default values for the new flag...")
sys.stdout.flush()
for user_id in user_profile_ids:
while True:
# Ideally, we'd just do a single database query per user.
# Unfortunately, Django doesn't use the fancy new index on
# is_private that we just generated if we do that,
# resulting in a very slow migration that could take hours
# on a large server. We address this issue by doing a bit
# of hackery to generate the SQL just right (with an
# `ORDER BY` clause that forces using the new index).
flag_set_objects = UserMessage.objects.filter(user_profile__id = user_id).extra(
where=["flags & 2048 != 0"]).order_by("message_id")[0:1000]
user_message_ids = flag_set_objects.values_list("id", flat=True)
count = UserMessage.objects.filter(id__in=user_message_ids).update(
flags=F('flags').bitand(~UserMessage.flags.is_private))
if count < 1000:
break
i += 1
if (i % 50 == 0 or i == total):
percent = round((i / total) * 100, 2)
print("Processed %s/%s %s%%" % (i, total, percent))
sys.stdout.flush()
class Migration(migrations.Migration):
atomic = False
dependencies = [
('zerver', '0176_remove_subscription_notifications'),
]
operations = [
migrations.AlterField(
model_name='archivedusermessage',
name='flags',
field=bitfield.models.BitField(['read', 'starred', 'collapsed', 'mentioned', 'wildcard_mentioned', 'summarize_in_home', 'summarize_in_stream', 'force_expand', 'force_collapse', 'has_alert_word', 'historical', 'is_private'], default=0),
),
migrations.AlterField(
model_name='usermessage',
name='flags',
field=bitfield.models.BitField(['read', 'starred', 'collapsed', 'mentioned', 'wildcard_mentioned', 'summarize_in_home', 'summarize_in_stream', 'force_expand', 'force_collapse', 'has_alert_word', 'historical', 'is_private'], default=0),
),
migrations.RunSQL(
create_index_if_not_exist(
index_name='zerver_usermessage_is_private_message_id',
table_name='zerver_usermessage',
column_string='user_profile_id, message_id',
where_clause='WHERE (flags & 2048) != 0',
),
reverse_sql='DROP INDEX zerver_usermessage_is_private_message_id;'
),
migrations.RunPython(reset_is_private_flag,
reverse_code=migrations.RunPython.noop),
]
| [
"StateApps",
"DatabaseSchemaEditor"
] | [
463,
489
] | [
472,
509
] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0178_rename_to_emails_restricted_to_domains.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-07-27 21:47
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('zerver', '0177_user_message_add_and_index_is_private_flag'),
]
operations = [
migrations.RenameField(
model_name='realm',
old_name='restricted_to_domain',
new_name='emails_restricted_to_domains',
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0179_rename_to_digest_emails_enabled.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-08-01 10:59
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('zerver', '0178_rename_to_emails_restricted_to_domains'),
]
operations = [
migrations.RenameField(
model_name='realm',
old_name='show_digest_email',
new_name='digest_emails_enabled',
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0180_usermessage_add_active_mobile_push_notification.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-08-01 23:05
from __future__ import unicode_literals
import bitfield.models
from django.db import migrations
from zerver.lib.migrate import create_index_if_not_exist # nolint
class Migration(migrations.Migration):
dependencies = [
('zerver', '0179_rename_to_digest_emails_enabled'),
]
operations = [
migrations.AlterField(
model_name='archivedusermessage',
name='flags',
field=bitfield.models.BitField(['read', 'starred', 'collapsed', 'mentioned', 'wildcard_mentioned', 'summarize_in_home', 'summarize_in_stream', 'force_expand', 'force_collapse', 'has_alert_word', 'historical', 'is_private', 'active_mobile_push_notification'], default=0),
),
migrations.AlterField(
model_name='usermessage',
name='flags',
field=bitfield.models.BitField(['read', 'starred', 'collapsed', 'mentioned', 'wildcard_mentioned', 'summarize_in_home', 'summarize_in_stream', 'force_expand', 'force_collapse', 'has_alert_word', 'historical', 'is_private', 'active_mobile_push_notification'], default=0),
),
migrations.RunSQL(
create_index_if_not_exist(
index_name='zerver_usermessage_active_mobile_push_notification_id',
table_name='zerver_usermessage',
column_string='user_profile_id, message_id',
where_clause='WHERE (flags & 4096) != 0',
),
reverse_sql='DROP INDEX zerver_usermessage_active_mobile_push_notification_id;'
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0181_userprofile_change_emojiset.py | # -*- coding: utf-8 -*-
from django.db import migrations, models
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def change_emojiset_choice(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
UserProfile = apps.get_model('zerver', 'UserProfile')
UserProfile.objects.exclude(emojiset__in=['google', 'text']).update(emojiset='google')
class Migration(migrations.Migration):
dependencies = [
('zerver', '0180_usermessage_add_active_mobile_push_notification'),
]
operations = [
migrations.RunPython(
change_emojiset_choice,
reverse_code=migrations.RunPython.noop),
migrations.AlterField(
model_name='userprofile',
name='emojiset',
field=models.CharField(choices=[('google', 'Google'), ('text', 'Plain text')], default='google', max_length=20),
),
]
| [
"StateApps",
"DatabaseSchemaEditor"
] | [
227,
253
] | [
236,
273
] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0182_set_initial_value_is_private_flag.py | # -*- coding: utf-8 -*-
import sys
from django.db import migrations
from django.db import migrations, transaction
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
from django.db.models import F
def set_initial_value_of_is_private_flag(
apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
UserMessage = apps.get_model("zerver", "UserMessage")
Message = apps.get_model("zerver", "Message")
if not Message.objects.exists():
return
i = 0
# Total is only used for the progress bar
total = Message.objects.filter(recipient__type__in=[1, 3]).count()
processed = 0
print("\nStart setting initial value for is_private flag...")
sys.stdout.flush()
while True:
range_end = i + 10000
# Can't use [Recipient.PERSONAL, Recipient.HUDDLE] in migration files
message_ids = list(Message.objects.filter(recipient__type__in=[1, 3],
id__gt=i,
id__lte=range_end).values_list("id", flat=True).order_by("id"))
count = UserMessage.objects.filter(message_id__in=message_ids).update(flags=F('flags').bitor(UserMessage.flags.is_private))
if count == 0 and range_end >= Message.objects.last().id:
break
i = range_end
processed += len(message_ids)
if total != 0:
percent = round((processed / total) * 100, 2)
else:
percent = 100.00
print("Processed %s/%s %s%%" % (processed, total, percent))
sys.stdout.flush()
class Migration(migrations.Migration):
atomic = False
dependencies = [
('zerver', '0181_userprofile_change_emojiset'),
]
operations = [
migrations.RunPython(set_initial_value_of_is_private_flag,
reverse_code=migrations.RunPython.noop),
]
| [
"StateApps",
"DatabaseSchemaEditor"
] | [
331,
357
] | [
340,
377
] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0183_change_custom_field_name_max_length.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-08-16 18:10
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0182_set_initial_value_is_private_flag'),
]
operations = [
migrations.AlterField(
model_name='customprofilefield',
name='name',
field=models.CharField(max_length=40),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0184_rename_custom_field_types.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-08-15 13:41
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0183_change_custom_field_name_max_length'),
]
operations = [
migrations.AlterField(
model_name='customprofilefield',
name='field_type',
field=models.PositiveSmallIntegerField(choices=[(1, 'Short text'), (2, 'Long text'), (4, 'Date picker'), (5, 'Link'), (3, 'List of options'), (6, 'Person picker')], default=1),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0185_realm_plan_type.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-08-10 21:36
from __future__ import unicode_literals
from django.db import migrations, models
import zerver.models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0184_rename_custom_field_types'),
]
operations = [
migrations.AddField(
model_name='realm',
name='plan_type',
# Realm.SELF_HOSTED
field=models.PositiveSmallIntegerField(default=1),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0186_userprofile_starred_message_counts.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-08-17 06:06
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0185_realm_plan_type'),
]
operations = [
migrations.AddField(
model_name='userprofile',
name='starred_message_counts',
field=models.BooleanField(default=False),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0187_userprofile_is_billing_admin.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-08-22 05:45
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0186_userprofile_starred_message_counts'),
]
operations = [
migrations.AddField(
model_name='userprofile',
name='is_billing_admin',
field=models.BooleanField(db_index=True, default=False),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0188_userprofile_enable_login_emails.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-08-22 09:57
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0187_userprofile_is_billing_admin'),
]
operations = [
migrations.AddField(
model_name='userprofile',
name='enable_login_emails',
field=models.BooleanField(default=True),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0189_userprofile_add_some_emojisets.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-08-28 19:01
from __future__ import unicode_literals
from django.db import migrations, models
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
def change_emojiset_choice(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
UserProfile = apps.get_model('zerver', 'UserProfile')
UserProfile.objects.filter(emojiset='google').update(emojiset='google-blob')
class Migration(migrations.Migration):
dependencies = [
('zerver', '0188_userprofile_enable_login_emails'),
]
operations = [
migrations.AlterField(
model_name='userprofile',
name='emojiset',
field=models.CharField(choices=[('google', 'Google modern'), ('google-blob', 'Google classic'), ('twitter', 'Twitter'), ('text', 'Plain text')], default='google-blob', max_length=20),
),
migrations.RunPython(
change_emojiset_choice,
reverse_code=migrations.RunPython.noop),
]
| [
"StateApps",
"DatabaseSchemaEditor"
] | [
318,
344
] | [
327,
364
] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0190_cleanup_pushdevicetoken.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-10-10 22:52
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0189_userprofile_add_some_emojisets'),
]
operations = [
migrations.AlterField(
model_name='pushdevicetoken',
name='token',
field=models.CharField(db_index=True, max_length=4096),
),
migrations.AlterUniqueTogether(
name='pushdevicetoken',
unique_together=set([('user', 'kind', 'token')]),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/0191_realm_seat_limit.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-11-20 04:43
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('zerver', '0190_cleanup_pushdevicetoken'),
]
operations = [
migrations.AddField(
model_name='realm',
name='seat_limit',
field=models.PositiveIntegerField(null=True),
),
]
| [] | [] | [] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/migrations/__init__.py | [] | [] | [] |
|
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/models.py | from typing import Any, DefaultDict, Dict, List, Set, Tuple, TypeVar, \
Union, Optional, Sequence, AbstractSet, Pattern, AnyStr, Callable, Iterable
from typing.re import Match
from zerver.lib.str_utils import NonBinaryStr
from django.db import models
from django.db.models.query import QuerySet, F
from django.db.models import Manager, CASCADE, Sum
from django.db.models.functions import Length
from django.conf import settings
from django.contrib.auth.models import AbstractBaseUser, UserManager, \
PermissionsMixin
import django.contrib.auth
from django.core.exceptions import ValidationError
from django.core.validators import URLValidator, MinLengthValidator, \
RegexValidator
from django.dispatch import receiver
from zerver.lib.cache import cache_with_key, flush_user_profile, flush_realm, \
user_profile_by_api_key_cache_key, active_non_guest_user_ids_cache_key, \
user_profile_by_id_cache_key, user_profile_by_email_cache_key, \
user_profile_cache_key, generic_bulk_cached_fetch, cache_set, flush_stream, \
display_recipient_cache_key, cache_delete, active_user_ids_cache_key, \
get_stream_cache_key, realm_user_dicts_cache_key, \
bot_dicts_in_realm_cache_key, realm_user_dict_fields, \
bot_dict_fields, flush_message, flush_submessage, bot_profile_cache_key
from zerver.lib.utils import make_safe_digest, generate_random_token
from django.db import transaction
from django.utils.timezone import now as timezone_now
from django.contrib.sessions.models import Session
from zerver.lib.timestamp import datetime_to_timestamp
from django.db.models.signals import pre_save, post_save, post_delete
from django.utils.translation import ugettext_lazy as _
from zerver.lib import cache
from zerver.lib.validator import check_int, check_float, \
check_short_string, check_long_string, validate_choice_field, check_date, \
check_url, check_list
from zerver.lib.name_restrictions import is_disposable_domain
from zerver.lib.types import Validator, ExtendedValidator, \
ProfileDataElement, ProfileData, FieldTypeData, FieldElement, \
RealmUserValidator
from django.utils.encoding import force_text
from bitfield import BitField
from bitfield.types import BitHandler
from collections import defaultdict, OrderedDict
from datetime import timedelta
import pylibmc
import re
import logging
import sre_constants
import time
import datetime
import sys
MAX_TOPIC_NAME_LENGTH = 60
MAX_MESSAGE_LENGTH = 10000
MAX_LANGUAGE_ID_LENGTH = 50 # type: int
STREAM_NAMES = TypeVar('STREAM_NAMES', Sequence[str], AbstractSet[str])
def query_for_ids(query: QuerySet, user_ids: List[int], field: str) -> QuerySet:
'''
This function optimizes searches of the form
`user_profile_id in (1, 2, 3, 4)` by quickly
building the where clauses. Profiling shows significant
speedups over the normal Django-based approach.
Use this very carefully! Also, the caller should
guard against empty lists of user_ids.
'''
assert(user_ids)
value_list = ', '.join(str(int(user_id)) for user_id in user_ids)
clause = '%s in (%s)' % (field, value_list)
query = query.extra(
where=[clause]
)
return query
# Doing 1000 remote cache requests to get_display_recipient is quite slow,
# so add a local cache as well as the remote cache cache.
per_request_display_recipient_cache = {} # type: Dict[int, Union[str, List[Dict[str, Any]]]]
def get_display_recipient_by_id(recipient_id: int, recipient_type: int,
recipient_type_id: Optional[int]) -> Union[str, List[Dict[str, Any]]]:
"""
returns: an object describing the recipient (using a cache).
If the type is a stream, the type_id must be an int; a string is returned.
Otherwise, type_id may be None; an array of recipient dicts is returned.
"""
if recipient_id not in per_request_display_recipient_cache:
result = get_display_recipient_remote_cache(recipient_id, recipient_type, recipient_type_id)
per_request_display_recipient_cache[recipient_id] = result
return per_request_display_recipient_cache[recipient_id]
def get_display_recipient(recipient: 'Recipient') -> Union[str, List[Dict[str, Any]]]:
return get_display_recipient_by_id(
recipient.id,
recipient.type,
recipient.type_id
)
def flush_per_request_caches() -> None:
global per_request_display_recipient_cache
per_request_display_recipient_cache = {}
global per_request_realm_filters_cache
per_request_realm_filters_cache = {}
DisplayRecipientCacheT = Union[str, List[Dict[str, Any]]]
@cache_with_key(lambda *args: display_recipient_cache_key(args[0]),
timeout=3600*24*7)
def get_display_recipient_remote_cache(recipient_id: int, recipient_type: int,
recipient_type_id: Optional[int]) -> DisplayRecipientCacheT:
"""
returns: an appropriate object describing the recipient. For a
stream this will be the stream name as a string. For a huddle or
personal, it will be an array of dicts about each recipient.
"""
if recipient_type == Recipient.STREAM:
assert recipient_type_id is not None
stream = Stream.objects.get(id=recipient_type_id)
return stream.name
# The main priority for ordering here is being deterministic.
# Right now, we order by ID, which matches the ordering of user
# names in the left sidebar.
user_profile_list = (UserProfile.objects.filter(subscription__recipient_id=recipient_id)
.select_related()
.order_by('id'))
return [{'email': user_profile.email,
'full_name': user_profile.full_name,
'short_name': user_profile.short_name,
'id': user_profile.id,
'is_mirror_dummy': user_profile.is_mirror_dummy} for user_profile in user_profile_list]
def get_realm_emoji_cache_key(realm: 'Realm') -> str:
return u'realm_emoji:%s' % (realm.id,)
def get_active_realm_emoji_cache_key(realm: 'Realm') -> str:
return u'active_realm_emoji:%s' % (realm.id,)
class Realm(models.Model):
MAX_REALM_NAME_LENGTH = 40
MAX_REALM_SUBDOMAIN_LENGTH = 40
MAX_VIDEO_CHAT_PROVIDER_LENGTH = 40
MAX_GOOGLE_HANGOUTS_DOMAIN_LENGTH = 255 # This is just the maximum domain length by RFC
INVITES_STANDARD_REALM_DAILY_MAX = 3000
MESSAGE_VISIBILITY_LIMITED = 10000
VIDEO_CHAT_PROVIDERS = [u"Jitsi", u"Google Hangouts"]
AUTHENTICATION_FLAGS = [u'Google', u'Email', u'GitHub', u'LDAP', u'Dev', u'RemoteUser']
SUBDOMAIN_FOR_ROOT_DOMAIN = ''
# User-visible display name and description used on e.g. the organization homepage
name = models.CharField(max_length=MAX_REALM_NAME_LENGTH, null=True) # type: Optional[str]
description = models.TextField(default=u"") # type: str
# A short, identifier-like name for the organization. Used in subdomains;
# e.g. on a server at example.com, an org with string_id `foo` is reached
# at `foo.example.com`.
string_id = models.CharField(max_length=MAX_REALM_SUBDOMAIN_LENGTH, unique=True) # type: str
date_created = models.DateTimeField(default=timezone_now) # type: datetime.datetime
deactivated = models.BooleanField(default=False) # type: bool
# See RealmDomain for the domains that apply for a given organization.
emails_restricted_to_domains = models.BooleanField(default=False) # type: bool
invite_required = models.BooleanField(default=True) # type: bool
invite_by_admins_only = models.BooleanField(default=False) # type: bool
_max_invites = models.IntegerField(null=True, db_column='max_invites') # type: Optional[int]
disallow_disposable_email_addresses = models.BooleanField(default=True) # type: bool
authentication_methods = BitField(flags=AUTHENTICATION_FLAGS,
default=2**31 - 1) # type: BitHandler
# Whether the organization has enabled inline image and URL previews.
inline_image_preview = models.BooleanField(default=True) # type: bool
inline_url_embed_preview = models.BooleanField(default=True) # type: bool
# Whether digest emails are enabled for the organization.
digest_emails_enabled = models.BooleanField(default=True) # type: bool
send_welcome_emails = models.BooleanField(default=True) # type: bool
mandatory_topics = models.BooleanField(default=False) # type: bool
create_stream_by_admins_only = models.BooleanField(default=False) # type: bool
add_emoji_by_admins_only = models.BooleanField(default=False) # type: bool
name_changes_disabled = models.BooleanField(default=False) # type: bool
email_changes_disabled = models.BooleanField(default=False) # type: bool
# Threshold in days for new users to create streams, and potentially take
# some other actions.
waiting_period_threshold = models.PositiveIntegerField(default=0) # type: int
allow_message_deleting = models.BooleanField(default=False) # type: bool
DEFAULT_MESSAGE_CONTENT_DELETE_LIMIT_SECONDS = 600 # if changed, also change in admin.js, setting_org.js
message_content_delete_limit_seconds = models.IntegerField(default=DEFAULT_MESSAGE_CONTENT_DELETE_LIMIT_SECONDS) # type: int
allow_message_editing = models.BooleanField(default=True) # type: bool
DEFAULT_MESSAGE_CONTENT_EDIT_LIMIT_SECONDS = 600 # if changed, also change in admin.js, setting_org.js
message_content_edit_limit_seconds = models.IntegerField(default=DEFAULT_MESSAGE_CONTENT_EDIT_LIMIT_SECONDS) # type: int
# Whether users have access to message edit history
allow_edit_history = models.BooleanField(default=True) # type: bool
DEFAULT_COMMUNITY_TOPIC_EDITING_LIMIT_SECONDS = 86400
allow_community_topic_editing = models.BooleanField(default=True) # type: bool
# Defaults for new users
default_twenty_four_hour_time = models.BooleanField(default=False) # type: bool
default_language = models.CharField(default=u'en', max_length=MAX_LANGUAGE_ID_LENGTH) # type: str
DEFAULT_NOTIFICATION_STREAM_NAME = u'announce'
INITIAL_PRIVATE_STREAM_NAME = u'core team'
notifications_stream = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE) # type: Optional[Stream]
signup_notifications_stream = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE) # type: Optional[Stream]
# For old messages being automatically deleted
message_retention_days = models.IntegerField(null=True) # type: Optional[int]
# When non-null, all but the latest this many messages in the organization
# are inaccessible to users (but not deleted).
message_visibility_limit = models.IntegerField(null=True) # type: Optional[int]
# Valid org_types are {CORPORATE, COMMUNITY}
CORPORATE = 1
COMMUNITY = 2
org_type = models.PositiveSmallIntegerField(default=CORPORATE) # type: int
# plan_type controls various features around resource/feature
# limitations for a Zulip organization on multi-tenant servers
# like zulipchat.com.
SELF_HOSTED = 1
LIMITED = 2
STANDARD = 3
STANDARD_FREE = 4
plan_type = models.PositiveSmallIntegerField(default=SELF_HOSTED) # type: int
# This value is also being used in static/js/settings_bots.bot_creation_policy_values.
# On updating it here, update it there as well.
BOT_CREATION_EVERYONE = 1
BOT_CREATION_LIMIT_GENERIC_BOTS = 2
BOT_CREATION_ADMINS_ONLY = 3
bot_creation_policy = models.PositiveSmallIntegerField(default=BOT_CREATION_EVERYONE) # type: int
# See upload_quota_bytes; don't interpret upload_quota_gb directly.
upload_quota_gb = models.IntegerField(null=True) # type: Optional[int]
video_chat_provider = models.CharField(default=u"Jitsi", max_length=MAX_VIDEO_CHAT_PROVIDER_LENGTH)
google_hangouts_domain = models.TextField(default="")
# Define the types of the various automatically managed properties
property_types = dict(
add_emoji_by_admins_only=bool,
allow_edit_history=bool,
allow_message_deleting=bool,
bot_creation_policy=int,
create_stream_by_admins_only=bool,
default_language=str,
default_twenty_four_hour_time = bool,
description=str,
disallow_disposable_email_addresses=bool,
email_changes_disabled=bool,
google_hangouts_domain=str,
invite_required=bool,
invite_by_admins_only=bool,
inline_image_preview=bool,
inline_url_embed_preview=bool,
mandatory_topics=bool,
message_retention_days=(int, type(None)),
name=str,
name_changes_disabled=bool,
emails_restricted_to_domains=bool,
send_welcome_emails=bool,
video_chat_provider=str,
waiting_period_threshold=int,
) # type: Dict[str, Union[type, Tuple[type, ...]]]
ICON_FROM_GRAVATAR = u'G'
ICON_UPLOADED = u'U'
ICON_SOURCES = (
(ICON_FROM_GRAVATAR, 'Hosted by Gravatar'),
(ICON_UPLOADED, 'Uploaded by administrator'),
)
icon_source = models.CharField(default=ICON_FROM_GRAVATAR, choices=ICON_SOURCES,
max_length=1) # type: str
icon_version = models.PositiveSmallIntegerField(default=1) # type: int
BOT_CREATION_POLICY_TYPES = [
BOT_CREATION_EVERYONE,
BOT_CREATION_LIMIT_GENERIC_BOTS,
BOT_CREATION_ADMINS_ONLY,
]
has_seat_based_plan = models.BooleanField(default=False) # type: bool
seat_limit = models.PositiveIntegerField(null=True) # type: Optional[int]
def authentication_methods_dict(self) -> Dict[str, bool]:
"""Returns the a mapping from authentication flags to their status,
showing only those authentication flags that are supported on
the current server (i.e. if EmailAuthBackend is not configured
on the server, this will not return an entry for "Email")."""
# This mapping needs to be imported from here due to the cyclic
# dependency.
from zproject.backends import AUTH_BACKEND_NAME_MAP
ret = {} # type: Dict[str, bool]
supported_backends = {backend.__class__ for backend in django.contrib.auth.get_backends()}
for k, v in self.authentication_methods.iteritems():
backend = AUTH_BACKEND_NAME_MAP[k]
if backend in supported_backends:
ret[k] = v
return ret
def __str__(self) -> str:
return "<Realm: %s %s>" % (self.string_id, self.id)
@cache_with_key(get_realm_emoji_cache_key, timeout=3600*24*7)
def get_emoji(self) -> Dict[str, Dict[str, Iterable[str]]]:
return get_realm_emoji_uncached(self)
@cache_with_key(get_active_realm_emoji_cache_key, timeout=3600*24*7)
def get_active_emoji(self) -> Dict[str, Dict[str, Iterable[str]]]:
return get_active_realm_emoji_uncached(self)
def get_admin_users(self) -> Sequence['UserProfile']:
# TODO: Change return type to QuerySet[UserProfile]
return UserProfile.objects.filter(realm=self, is_realm_admin=True,
is_active=True)
def get_active_users(self) -> Sequence['UserProfile']:
# TODO: Change return type to QuerySet[UserProfile]
return UserProfile.objects.filter(realm=self, is_active=True).select_related()
def get_bot_domain(self) -> str:
# Remove the port. Mainly needed for development environment.
return self.host.split(':')[0]
def get_notifications_stream(self) -> Optional['Stream']:
if self.notifications_stream is not None and not self.notifications_stream.deactivated:
return self.notifications_stream
return None
def get_signup_notifications_stream(self) -> Optional['Stream']:
if self.signup_notifications_stream is not None and not self.signup_notifications_stream.deactivated:
return self.signup_notifications_stream
return None
@property
def max_invites(self) -> int:
if self._max_invites is None:
return settings.INVITES_DEFAULT_REALM_DAILY_MAX
return self._max_invites
@max_invites.setter
def max_invites(self, value: int) -> None:
self._max_invites = value
def upload_quota_bytes(self) -> Optional[int]:
if self.upload_quota_gb is None:
return None
# We describe the quota to users in "GB" or "gigabytes", but actually apply
# it as gibibytes (GiB) to be a bit more generous in case of confusion.
return self.upload_quota_gb << 30
@property
def subdomain(self) -> str:
return self.string_id
@property
def display_subdomain(self) -> str:
"""Likely to be temporary function to avoid signup messages being sent
to an empty topic"""
if self.string_id == "":
return "."
return self.string_id
@property
def uri(self) -> str:
return settings.EXTERNAL_URI_SCHEME + self.host
@property
def host(self) -> str:
return self.host_for_subdomain(self.subdomain)
@staticmethod
def host_for_subdomain(subdomain: str) -> str:
if subdomain == Realm.SUBDOMAIN_FOR_ROOT_DOMAIN:
return settings.EXTERNAL_HOST
default_host = "%s.%s" % (subdomain, settings.EXTERNAL_HOST)
return settings.REALM_HOSTS.get(subdomain, default_host)
@property
def is_zephyr_mirror_realm(self) -> bool:
return self.string_id == "zephyr"
@property
def webathena_enabled(self) -> bool:
return self.is_zephyr_mirror_realm
@property
def presence_disabled(self) -> bool:
return self.is_zephyr_mirror_realm
class Meta:
permissions = (
('administer', "Administer a realm"),
('api_super_user', "Can send messages as other users for mirroring"),
)
post_save.connect(flush_realm, sender=Realm)
def get_realm(string_id: str) -> Realm:
return Realm.objects.filter(string_id=string_id).first()
def name_changes_disabled(realm: Optional[Realm]) -> bool:
if realm is None:
return settings.NAME_CHANGES_DISABLED
return settings.NAME_CHANGES_DISABLED or realm.name_changes_disabled
class RealmDomain(models.Model):
"""For an organization with emails_restricted_to_domains enabled, the list of
allowed domains"""
realm = models.ForeignKey(Realm, on_delete=CASCADE) # type: Realm
# should always be stored lowercase
domain = models.CharField(max_length=80, db_index=True) # type: str
allow_subdomains = models.BooleanField(default=False)
class Meta:
unique_together = ("realm", "domain")
# These functions should only be used on email addresses that have
# been validated via django.core.validators.validate_email
#
# Note that we need to use some care, since can you have multiple @-signs; e.g.
# "tabbott@test"@zulip.com
# is valid email address
def email_to_username(email: str) -> str:
return "@".join(email.split("@")[:-1]).lower()
# Returns the raw domain portion of the desired email address
def email_to_domain(email: str) -> str:
return email.split("@")[-1].lower()
class DomainNotAllowedForRealmError(Exception):
pass
class DisposableEmailError(Exception):
pass
class EmailContainsPlusError(Exception):
pass
# Is a user with the given email address allowed to be in the given realm?
# (This function does not check whether the user has been invited to the realm.
# So for invite-only realms, this is the test for whether a user can be invited,
# not whether the user can sign up currently.)
def email_allowed_for_realm(email: str, realm: Realm) -> None:
if not realm.emails_restricted_to_domains:
if realm.disallow_disposable_email_addresses and \
is_disposable_domain(email_to_domain(email)):
raise DisposableEmailError
return
elif '+' in email_to_username(email):
raise EmailContainsPlusError
domain = email_to_domain(email)
query = RealmDomain.objects.filter(realm=realm)
if query.filter(domain=domain).exists():
return
else:
query = query.filter(allow_subdomains=True)
while len(domain) > 0:
subdomain, sep, domain = domain.partition('.')
if query.filter(domain=domain).exists():
return
raise DomainNotAllowedForRealmError
def get_realm_domains(realm: Realm) -> List[Dict[str, str]]:
return list(realm.realmdomain_set.values('domain', 'allow_subdomains'))
class RealmEmoji(models.Model):
author = models.ForeignKey('UserProfile', blank=True, null=True, on_delete=CASCADE) # type: Optional[UserProfile]
realm = models.ForeignKey(Realm, on_delete=CASCADE) # type: Realm
name = models.TextField(validators=[
MinLengthValidator(1),
# The second part of the regex (negative lookbehind) disallows names
# ending with one of the punctuation characters.
RegexValidator(regex=r'^[0-9a-z.\-_]+(?<![.\-_])$',
message=_("Invalid characters in emoji name"))]) # type: str
# The basename of the custom emoji's filename; see PATH_ID_TEMPLATE for the full path.
file_name = models.TextField(db_index=True, null=True, blank=True) # type: Optional[str]
deactivated = models.BooleanField(default=False) # type: bool
PATH_ID_TEMPLATE = "{realm_id}/emoji/images/{emoji_file_name}"
def __str__(self) -> str:
return "<RealmEmoji(%s): %s %s %s %s>" % (self.realm.string_id,
self.id,
self.name,
self.deactivated,
self.file_name)
def get_realm_emoji_dicts(realm: Realm,
only_active_emojis: bool=False) -> Dict[str, Dict[str, Any]]:
query = RealmEmoji.objects.filter(realm=realm).select_related('author')
if only_active_emojis:
query = query.filter(deactivated=False)
d = {}
from zerver.lib.emoji import get_emoji_url
for realm_emoji in query.all():
author = None
if realm_emoji.author:
author = {
'id': realm_emoji.author.id,
'email': realm_emoji.author.email,
'full_name': realm_emoji.author.full_name}
emoji_url = get_emoji_url(realm_emoji.file_name, realm_emoji.realm_id)
d[str(realm_emoji.id)] = dict(id=str(realm_emoji.id),
name=realm_emoji.name,
source_url=emoji_url,
deactivated=realm_emoji.deactivated,
author=author)
return d
def get_realm_emoji_uncached(realm: Realm) -> Dict[str, Dict[str, Any]]:
return get_realm_emoji_dicts(realm)
def get_active_realm_emoji_uncached(realm: Realm) -> Dict[str, Dict[str, Any]]:
realm_emojis = get_realm_emoji_dicts(realm, only_active_emojis=True)
d = {}
for emoji_id, emoji_dict in realm_emojis.items():
d[emoji_dict['name']] = emoji_dict
return d
def flush_realm_emoji(sender: Any, **kwargs: Any) -> None:
realm = kwargs['instance'].realm
cache_set(get_realm_emoji_cache_key(realm),
get_realm_emoji_uncached(realm),
timeout=3600*24*7)
cache_set(get_active_realm_emoji_cache_key(realm),
get_active_realm_emoji_uncached(realm),
timeout=3600*24*7)
post_save.connect(flush_realm_emoji, sender=RealmEmoji)
post_delete.connect(flush_realm_emoji, sender=RealmEmoji)
def filter_pattern_validator(value: str) -> None:
regex = re.compile(r'(?:[\w\-#]*)(\(\?P<\w+>.+\))')
error_msg = 'Invalid filter pattern, you must use the following format OPTIONAL_PREFIX(?P<id>.+)'
if not regex.match(str(value)):
raise ValidationError(error_msg)
try:
re.compile(value)
except sre_constants.error:
# Regex is invalid
raise ValidationError(error_msg)
def filter_format_validator(value: str) -> None:
regex = re.compile(r'^[\.\/:a-zA-Z0-9#_?=-]+%\(([a-zA-Z0-9_-]+)\)s[a-zA-Z0-9_-]*$')
if not regex.match(value):
raise ValidationError('URL format string must be in the following format: '
r'`https://example.com/%(\w+)s`')
class RealmFilter(models.Model):
"""Realm-specific regular expressions to automatically linkify certain
strings inside the markdown processor. See "Custom filters" in the settings UI.
"""
realm = models.ForeignKey(Realm, on_delete=CASCADE) # type: Realm
pattern = models.TextField(validators=[filter_pattern_validator]) # type: str
url_format_string = models.TextField(validators=[URLValidator(), filter_format_validator]) # type: str
class Meta:
unique_together = ("realm", "pattern")
def __str__(self) -> str:
return "<RealmFilter(%s): %s %s>" % (self.realm.string_id, self.pattern, self.url_format_string)
def get_realm_filters_cache_key(realm_id: int) -> str:
return u'%s:all_realm_filters:%s' % (cache.KEY_PREFIX, realm_id,)
# We have a per-process cache to avoid doing 1000 remote cache queries during page load
per_request_realm_filters_cache = {} # type: Dict[int, List[Tuple[str, str, int]]]
def realm_in_local_realm_filters_cache(realm_id: int) -> bool:
return realm_id in per_request_realm_filters_cache
def realm_filters_for_realm(realm_id: int) -> List[Tuple[str, str, int]]:
if not realm_in_local_realm_filters_cache(realm_id):
per_request_realm_filters_cache[realm_id] = realm_filters_for_realm_remote_cache(realm_id)
return per_request_realm_filters_cache[realm_id]
@cache_with_key(get_realm_filters_cache_key, timeout=3600*24*7)
def realm_filters_for_realm_remote_cache(realm_id: int) -> List[Tuple[str, str, int]]:
filters = []
for realm_filter in RealmFilter.objects.filter(realm_id=realm_id):
filters.append((realm_filter.pattern, realm_filter.url_format_string, realm_filter.id))
return filters
def all_realm_filters() -> Dict[int, List[Tuple[str, str, int]]]:
filters = defaultdict(list) # type: DefaultDict[int, List[Tuple[str, str, int]]]
for realm_filter in RealmFilter.objects.all():
filters[realm_filter.realm_id].append((realm_filter.pattern,
realm_filter.url_format_string,
realm_filter.id))
return filters
def flush_realm_filter(sender: Any, **kwargs: Any) -> None:
realm_id = kwargs['instance'].realm_id
cache_delete(get_realm_filters_cache_key(realm_id))
try:
per_request_realm_filters_cache.pop(realm_id)
except KeyError:
pass
post_save.connect(flush_realm_filter, sender=RealmFilter)
post_delete.connect(flush_realm_filter, sender=RealmFilter)
class UserProfile(AbstractBaseUser, PermissionsMixin):
USERNAME_FIELD = 'email'
MAX_NAME_LENGTH = 100
MIN_NAME_LENGTH = 2
API_KEY_LENGTH = 32
NAME_INVALID_CHARS = ['*', '`', '>', '"', '@']
DEFAULT_BOT = 1
"""
Incoming webhook bots are limited to only sending messages via webhooks.
Thus, it is less of a security risk to expose their API keys to third-party services,
since they can't be used to read messages.
"""
INCOMING_WEBHOOK_BOT = 2
# This value is also being used in static/js/settings_bots.js.
# On updating it here, update it there as well.
OUTGOING_WEBHOOK_BOT = 3
"""
Embedded bots run within the Zulip server itself; events are added to the
embedded_bots queue and then handled by a QueueProcessingWorker.
"""
EMBEDDED_BOT = 4
BOT_TYPES = {
DEFAULT_BOT: 'Generic bot',
INCOMING_WEBHOOK_BOT: 'Incoming webhook',
OUTGOING_WEBHOOK_BOT: 'Outgoing webhook',
EMBEDDED_BOT: 'Embedded bot',
}
SERVICE_BOT_TYPES = [
OUTGOING_WEBHOOK_BOT,
EMBEDDED_BOT,
]
# The display email address, used for Zulip APIs, etc.
email = models.EmailField(blank=False, db_index=True) # type: str
# delivery_email is just used for sending emails. In almost all
# organizations, it matches `email`; this field is part of our
# transition towards supporting organizations where email
# addresses are not public.
delivery_email = models.EmailField(blank=False, db_index=True) # type: str
realm = models.ForeignKey(Realm, on_delete=CASCADE) # type: Realm
full_name = models.CharField(max_length=MAX_NAME_LENGTH) # type: str
# short_name is currently unused.
short_name = models.CharField(max_length=MAX_NAME_LENGTH) # type: str
date_joined = models.DateTimeField(default=timezone_now) # type: datetime.datetime
tos_version = models.CharField(null=True, max_length=10) # type: Optional[str]
api_key = models.CharField(max_length=API_KEY_LENGTH) # type: str
# pointer points to Message.id, NOT UserMessage.id.
pointer = models.IntegerField() # type: int
last_pointer_updater = models.CharField(max_length=64) # type: str
# Whether the user has access to server-level administrator pages, like /activity
is_staff = models.BooleanField(default=False) # type: bool
# For a normal user, this is True unless the user or an admin has
# deactivated their account. The name comes from Django; this field
# isn't related to presence or to whether the user has recently used Zulip.
#
# See also `long_term_idle`.
is_active = models.BooleanField(default=True, db_index=True) # type: bool
is_realm_admin = models.BooleanField(default=False, db_index=True) # type: bool
is_billing_admin = models.BooleanField(default=False, db_index=True) # type: bool
# Guest users are limited users without default access to public streams (etc.)
is_guest = models.BooleanField(default=False, db_index=True) # type: bool
is_bot = models.BooleanField(default=False, db_index=True) # type: bool
bot_type = models.PositiveSmallIntegerField(null=True, db_index=True) # type: Optional[int]
bot_owner = models.ForeignKey('self', null=True, on_delete=models.SET_NULL) # type: Optional[UserProfile]
# Whether the user has been "soft-deactivated" due to weeks of inactivity.
# For these users we avoid doing UserMessage table work, as an optimization
# for large Zulip organizations with lots of single-visit users.
long_term_idle = models.BooleanField(default=False, db_index=True) # type: bool
# When we last added basic UserMessage rows for a long_term_idle user.
last_active_message_id = models.IntegerField(null=True) # type: Optional[int]
# Mirror dummies are fake (!is_active) users used to provide
# message senders in our cross-protocol Zephyr<->Zulip content
# mirroring integration, so that we can display mirrored content
# like native Zulip messages (with a name + avatar, etc.).
is_mirror_dummy = models.BooleanField(default=False) # type: bool
# API super users are allowed to forge messages as sent by another
# user; also used for Zephyr/Jabber mirroring.
is_api_super_user = models.BooleanField(default=False, db_index=True) # type: bool
### Notifications settings. ###
# Stream notifications.
enable_stream_desktop_notifications = models.BooleanField(default=False) # type: bool
enable_stream_email_notifications = models.BooleanField(default=False) # type: bool
enable_stream_push_notifications = models.BooleanField(default=False) # type: bool
enable_stream_sounds = models.BooleanField(default=False) # type: bool
# PM + @-mention notifications.
enable_desktop_notifications = models.BooleanField(default=True) # type: bool
pm_content_in_desktop_notifications = models.BooleanField(default=True) # type: bool
enable_sounds = models.BooleanField(default=True) # type: bool
enable_offline_email_notifications = models.BooleanField(default=True) # type: bool
message_content_in_email_notifications = models.BooleanField(default=True) # type: bool
enable_offline_push_notifications = models.BooleanField(default=True) # type: bool
enable_online_push_notifications = models.BooleanField(default=False) # type: bool
enable_digest_emails = models.BooleanField(default=True) # type: bool
enable_login_emails = models.BooleanField(default=True) # type: bool
realm_name_in_notifications = models.BooleanField(default=False) # type: bool
# Words that trigger a mention for this user, formatted as a json-serialized list of strings
alert_words = models.TextField(default=u'[]') # type: str
# Used for rate-limiting certain automated messages generated by bots
last_reminder = models.DateTimeField(default=None, null=True) # type: Optional[datetime.datetime]
# Minutes to wait before warning a bot owner that their bot sent a message
# to a nonexistent stream
BOT_OWNER_STREAM_ALERT_WAITPERIOD = 1
# API rate limits, formatted as a comma-separated list of range:max pairs
rate_limits = models.CharField(default=u"", max_length=100) # type: str
# Hours to wait before sending another email to a user
EMAIL_REMINDER_WAITPERIOD = 24
# Default streams for some deprecated/legacy classes of bot users.
default_sending_stream = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE) # type: Optional[Stream]
default_events_register_stream = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE) # type: Optional[Stream]
default_all_public_streams = models.BooleanField(default=False) # type: bool
# UI vars
enter_sends = models.NullBooleanField(default=False) # type: Optional[bool]
left_side_userlist = models.BooleanField(default=False) # type: bool
# display settings
twenty_four_hour_time = models.BooleanField(default=False) # type: bool
default_language = models.CharField(default=u'en', max_length=MAX_LANGUAGE_ID_LENGTH) # type: str
high_contrast_mode = models.BooleanField(default=False) # type: bool
night_mode = models.BooleanField(default=False) # type: bool
translate_emoticons = models.BooleanField(default=False) # type: bool
dense_mode = models.BooleanField(default=True) # type: bool
starred_message_counts = models.BooleanField(default=False) # type: bool
# A timezone name from the `tzdata` database, as found in pytz.all_timezones.
#
# The longest existing name is 32 characters long, so max_length=40 seems
# like a safe choice.
#
# In Django, the convention is to use an empty string instead of NULL/None
# for text-based fields. For more information, see
# https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.Field.null.
timezone = models.CharField(max_length=40, default=u'') # type: str
# Emojisets
GOOGLE_EMOJISET = 'google'
GOOGLE_BLOB_EMOJISET = 'google-blob'
TEXT_EMOJISET = 'text'
TWITTER_EMOJISET = 'twitter'
EMOJISET_CHOICES = ((GOOGLE_EMOJISET, "Google modern"),
(GOOGLE_BLOB_EMOJISET, "Google classic"),
(TWITTER_EMOJISET, "Twitter"),
(TEXT_EMOJISET, "Plain text"))
emojiset = models.CharField(default=GOOGLE_BLOB_EMOJISET, choices=EMOJISET_CHOICES, max_length=20) # type: str
AVATAR_FROM_GRAVATAR = u'G'
AVATAR_FROM_USER = u'U'
AVATAR_SOURCES = (
(AVATAR_FROM_GRAVATAR, 'Hosted by Gravatar'),
(AVATAR_FROM_USER, 'Uploaded by user'),
)
avatar_source = models.CharField(default=AVATAR_FROM_GRAVATAR, choices=AVATAR_SOURCES, max_length=1) # type: str
avatar_version = models.PositiveSmallIntegerField(default=1) # type: int
TUTORIAL_WAITING = u'W'
TUTORIAL_STARTED = u'S'
TUTORIAL_FINISHED = u'F'
TUTORIAL_STATES = ((TUTORIAL_WAITING, "Waiting"),
(TUTORIAL_STARTED, "Started"),
(TUTORIAL_FINISHED, "Finished"))
tutorial_status = models.CharField(default=TUTORIAL_WAITING, choices=TUTORIAL_STATES, max_length=1) # type: str
# Contains serialized JSON of the form:
# [("step 1", true), ("step 2", false)]
# where the second element of each tuple is if the step has been
# completed.
onboarding_steps = models.TextField(default=u'[]') # type: str
objects = UserManager() # type: UserManager
# Define the types of the various automatically managed properties
property_types = dict(
default_language=str,
dense_mode=bool,
emojiset=str,
left_side_userlist=bool,
timezone=str,
twenty_four_hour_time=bool,
high_contrast_mode=bool,
night_mode=bool,
translate_emoticons=bool,
starred_message_counts=bool,
)
notification_setting_types = dict(
enable_desktop_notifications=bool,
enable_digest_emails=bool,
enable_login_emails=bool,
enable_offline_email_notifications=bool,
enable_offline_push_notifications=bool,
enable_online_push_notifications=bool,
enable_sounds=bool,
enable_stream_desktop_notifications=bool,
enable_stream_email_notifications=bool,
enable_stream_push_notifications=bool,
enable_stream_sounds=bool,
message_content_in_email_notifications=bool,
pm_content_in_desktop_notifications=bool,
realm_name_in_notifications=bool,
)
class Meta:
unique_together = (('realm', 'email'),)
@property
def profile_data(self) -> ProfileData:
values = CustomProfileFieldValue.objects.filter(user_profile=self)
user_data = {v.field_id: v.value for v in values}
data = [] # type: ProfileData
for field in custom_profile_fields_for_realm(self.realm_id):
value = user_data.get(field.id, None)
field_type = field.field_type
if value is not None:
converter = field.FIELD_CONVERTERS[field_type]
value = converter(value)
field_data = {} # type: ProfileDataElement
for k, v in field.as_dict().items():
field_data[k] = v
field_data['value'] = value
data.append(field_data)
return data
def can_admin_user(self, target_user: 'UserProfile') -> bool:
"""Returns whether this user has permission to modify target_user"""
if target_user.bot_owner == self:
return True
elif self.is_realm_admin and self.realm == target_user.realm:
return True
else:
return False
def __str__(self) -> str:
return "<UserProfile: %s %s>" % (self.email, self.realm)
@property
def is_incoming_webhook(self) -> bool:
return self.bot_type == UserProfile.INCOMING_WEBHOOK_BOT
@property
def allowed_bot_types(self) -> List[int]:
allowed_bot_types = []
if self.is_realm_admin or \
not self.realm.bot_creation_policy == Realm.BOT_CREATION_LIMIT_GENERIC_BOTS:
allowed_bot_types.append(UserProfile.DEFAULT_BOT)
allowed_bot_types += [
UserProfile.INCOMING_WEBHOOK_BOT,
UserProfile.OUTGOING_WEBHOOK_BOT,
]
if settings.EMBEDDED_BOTS_ENABLED:
allowed_bot_types.append(UserProfile.EMBEDDED_BOT)
return allowed_bot_types
@staticmethod
def emojiset_choices() -> Dict[str, str]:
return OrderedDict((emojiset[0], emojiset[1]) for emojiset in UserProfile.EMOJISET_CHOICES)
@staticmethod
def emails_from_ids(user_ids: Sequence[int]) -> Dict[int, str]:
rows = UserProfile.objects.filter(id__in=user_ids).values('id', 'email')
return {row['id']: row['email'] for row in rows}
def can_create_streams(self) -> bool:
if self.is_realm_admin:
return True
if self.realm.create_stream_by_admins_only:
return False
if self.is_guest:
return False
diff = (timezone_now() - self.date_joined).days
if diff >= self.realm.waiting_period_threshold:
return True
return False
def can_subscribe_other_users(self) -> bool:
if self.is_realm_admin:
return True
if self.is_guest:
return False
diff = (timezone_now() - self.date_joined).days
if diff >= self.realm.waiting_period_threshold:
return True
return False
def can_access_public_streams(self) -> bool:
return not (self.is_guest or self.realm.is_zephyr_mirror_realm)
def can_access_all_realm_members(self) -> bool:
return not (self.realm.is_zephyr_mirror_realm or self.is_guest)
def major_tos_version(self) -> int:
if self.tos_version is not None:
return int(self.tos_version.split('.')[0])
else:
return -1
class UserGroup(models.Model):
name = models.CharField(max_length=100)
members = models.ManyToManyField(UserProfile, through='UserGroupMembership')
realm = models.ForeignKey(Realm, on_delete=CASCADE)
description = models.TextField(default=u'') # type: str
class Meta:
unique_together = (('realm', 'name'),)
class UserGroupMembership(models.Model):
user_group = models.ForeignKey(UserGroup, on_delete=CASCADE)
user_profile = models.ForeignKey(UserProfile, on_delete=CASCADE)
class Meta:
unique_together = (('user_group', 'user_profile'),)
def receives_offline_push_notifications(user_profile: UserProfile) -> bool:
return (user_profile.enable_offline_push_notifications and
not user_profile.is_bot)
def receives_offline_email_notifications(user_profile: UserProfile) -> bool:
return (user_profile.enable_offline_email_notifications and
not user_profile.is_bot)
def receives_online_notifications(user_profile: UserProfile) -> bool:
return (user_profile.enable_online_push_notifications and
not user_profile.is_bot)
def receives_stream_notifications(user_profile: UserProfile) -> bool:
return (user_profile.enable_stream_push_notifications and
not user_profile.is_bot)
def remote_user_to_email(remote_user: str) -> str:
if settings.SSO_APPEND_DOMAIN is not None:
remote_user += "@" + settings.SSO_APPEND_DOMAIN
return remote_user
# Make sure we flush the UserProfile object from our remote cache
# whenever we save it.
post_save.connect(flush_user_profile, sender=UserProfile)
class PreregistrationUser(models.Model):
email = models.EmailField() # type: str
referred_by = models.ForeignKey(UserProfile, null=True, on_delete=CASCADE) # type: Optional[UserProfile]
streams = models.ManyToManyField('Stream') # type: Manager
invited_at = models.DateTimeField(auto_now=True) # type: datetime.datetime
realm_creation = models.BooleanField(default=False)
# Indicates whether the user needs a password. Users who were
# created via SSO style auth (e.g. GitHub/Google) generally do not.
password_required = models.BooleanField(default=True)
# status: whether an object has been confirmed.
# if confirmed, set to confirmation.settings.STATUS_ACTIVE
status = models.IntegerField(default=0) # type: int
realm = models.ForeignKey(Realm, null=True, on_delete=CASCADE) # type: Optional[Realm]
invited_as_admin = models.BooleanField(default=False) # type: bool
class MultiuseInvite(models.Model):
referred_by = models.ForeignKey(UserProfile, on_delete=CASCADE) # Optional[UserProfile]
streams = models.ManyToManyField('Stream') # type: Manager
realm = models.ForeignKey(Realm, on_delete=CASCADE) # type: Realm
class EmailChangeStatus(models.Model):
new_email = models.EmailField() # type: str
old_email = models.EmailField() # type: str
updated_at = models.DateTimeField(auto_now=True) # type: datetime.datetime
user_profile = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
# status: whether an object has been confirmed.
# if confirmed, set to confirmation.settings.STATUS_ACTIVE
status = models.IntegerField(default=0) # type: int
realm = models.ForeignKey(Realm, on_delete=CASCADE) # type: Realm
class AbstractPushDeviceToken(models.Model):
APNS = 1
GCM = 2
KINDS = (
(APNS, 'apns'),
(GCM, 'gcm'),
)
kind = models.PositiveSmallIntegerField(choices=KINDS) # type: int
# The token is a unique device-specific token that is
# sent to us from each device:
# - APNS token if kind == APNS
# - GCM registration id if kind == GCM
# TODO: last_updated should be renamed date_created, since it is
# no longer maintained as a last_updated value.
last_updated = models.DateTimeField(auto_now=True) # type: datetime.datetime
# [optional] Contains the app id of the device if it is an iOS device
ios_app_id = models.TextField(null=True) # type: Optional[str]
class Meta:
abstract = True
class PushDeviceToken(AbstractPushDeviceToken):
# The user who's device this is
user = models.ForeignKey(UserProfile, db_index=True, on_delete=CASCADE) # type: UserProfile
token = models.CharField(max_length=4096, db_index=True) # type: bytes
class Meta:
unique_together = ("user", "kind", "token")
def generate_email_token_for_stream() -> str:
return generate_random_token(32)
class Stream(models.Model):
MAX_NAME_LENGTH = 60
MAX_DESCRIPTION_LENGTH = 1024
name = models.CharField(max_length=MAX_NAME_LENGTH, db_index=True) # type: str
realm = models.ForeignKey(Realm, db_index=True, on_delete=CASCADE) # type: Realm
date_created = models.DateTimeField(default=timezone_now) # type: datetime.datetime
deactivated = models.BooleanField(default=False) # type: bool
description = models.CharField(max_length=MAX_DESCRIPTION_LENGTH, default=u'') # type: str
invite_only = models.NullBooleanField(default=False) # type: Optional[bool]
history_public_to_subscribers = models.BooleanField(default=False) # type: bool
# Whether this stream's content should be published by the web-public archive features
is_web_public = models.BooleanField(default=False) # type: bool
# Whether only organization administrators can send messages to this stream
is_announcement_only = models.BooleanField(default=False) # type: bool
# The unique thing about Zephyr public streams is that we never list their
# users. We may try to generalize this concept later, but for now
# we just use a concrete field. (Zephyr public streams aren't exactly like
# invite-only streams--while both are private in terms of listing users,
# for Zephyr we don't even list users to stream members, yet membership
# is more public in the sense that you don't need a Zulip invite to join.
# This field is populated directly from UserProfile.is_zephyr_mirror_realm,
# and the reason for denormalizing field is performance.
is_in_zephyr_realm = models.BooleanField(default=False) # type: bool
# Used by the e-mail forwarder. The e-mail RFC specifies a maximum
# e-mail length of 254, and our max stream length is 30, so we
# have plenty of room for the token.
email_token = models.CharField(
max_length=32, default=generate_email_token_for_stream) # type: str
def __str__(self) -> str:
return "<Stream: %s>" % (self.name,)
def is_public(self) -> bool:
# All streams are private in Zephyr mirroring realms.
return not self.invite_only and not self.is_in_zephyr_realm
def is_history_realm_public(self) -> bool:
return self.is_public()
def is_history_public_to_subscribers(self) -> bool:
return self.history_public_to_subscribers
class Meta:
unique_together = ("name", "realm")
# This is stream information that is sent to clients
def to_dict(self) -> Dict[str, Any]:
return dict(
name=self.name,
stream_id=self.id,
description=self.description,
invite_only=self.invite_only,
is_announcement_only=self.is_announcement_only,
history_public_to_subscribers=self.history_public_to_subscribers
)
post_save.connect(flush_stream, sender=Stream)
post_delete.connect(flush_stream, sender=Stream)
# The Recipient table is used to map Messages to the set of users who
# received the message. It is implemented as a set of triples (id,
# type_id, type). We have 3 types of recipients: Huddles (for group
# private messages), UserProfiles (for 1:1 private messages), and
# Streams. The recipient table maps a globally unique recipient id
# (used by the Message table) to the type-specific unique id (the
# stream id, user_profile id, or huddle id).
class Recipient(models.Model):
type_id = models.IntegerField(db_index=True) # type: int
type = models.PositiveSmallIntegerField(db_index=True) # type: int
# Valid types are {personal, stream, huddle}
PERSONAL = 1
STREAM = 2
HUDDLE = 3
class Meta:
unique_together = ("type", "type_id")
# N.B. If we used Django's choice=... we would get this for free (kinda)
_type_names = {
PERSONAL: 'personal',
STREAM: 'stream',
HUDDLE: 'huddle'}
def type_name(self) -> str:
# Raises KeyError if invalid
return self._type_names[self.type]
def __str__(self) -> str:
display_recipient = get_display_recipient(self)
return "<Recipient: %s (%d, %s)>" % (display_recipient, self.type_id, self.type)
class MutedTopic(models.Model):
user_profile = models.ForeignKey(UserProfile, on_delete=CASCADE)
stream = models.ForeignKey(Stream, on_delete=CASCADE)
recipient = models.ForeignKey(Recipient, on_delete=CASCADE)
topic_name = models.CharField(max_length=MAX_TOPIC_NAME_LENGTH)
class Meta:
unique_together = ('user_profile', 'stream', 'topic_name')
def __str__(self) -> str:
return "<MutedTopic: (%s, %s, %s)>" % (self.user_profile.email, self.stream.name, self.topic_name)
class Client(models.Model):
name = models.CharField(max_length=30, db_index=True, unique=True) # type: str
def __str__(self) -> str:
return "<Client: %s>" % (self.name,)
get_client_cache = {} # type: Dict[str, Client]
def get_client(name: str) -> Client:
# Accessing KEY_PREFIX through the module is necessary
# because we need the updated value of the variable.
cache_name = cache.KEY_PREFIX + name
if cache_name not in get_client_cache:
result = get_client_remote_cache(name)
get_client_cache[cache_name] = result
return get_client_cache[cache_name]
def get_client_cache_key(name: str) -> str:
return u'get_client:%s' % (make_safe_digest(name),)
@cache_with_key(get_client_cache_key, timeout=3600*24*7)
def get_client_remote_cache(name: str) -> Client:
(client, _) = Client.objects.get_or_create(name=name)
return client
@cache_with_key(get_stream_cache_key, timeout=3600*24*7)
def get_realm_stream(stream_name: str, realm_id: int) -> Stream:
return Stream.objects.select_related("realm").get(
name__iexact=stream_name.strip(), realm_id=realm_id)
def stream_name_in_use(stream_name: str, realm_id: int) -> bool:
return Stream.objects.filter(
name__iexact=stream_name.strip(),
realm_id=realm_id
).exists()
def get_active_streams(realm: Optional[Realm]) -> QuerySet:
# TODO: Change return type to QuerySet[Stream]
# NOTE: Return value is used as a QuerySet, so cannot currently be Sequence[QuerySet]
"""
Return all streams (including invite-only streams) that have not been deactivated.
"""
return Stream.objects.filter(realm=realm, deactivated=False)
def get_stream(stream_name: str, realm: Realm) -> Stream:
'''
Callers that don't have a Realm object already available should use
get_realm_stream directly, to avoid unnecessarily fetching the
Realm object.
'''
return get_realm_stream(stream_name, realm.id)
def bulk_get_streams(realm: Realm, stream_names: STREAM_NAMES) -> Dict[str, Any]:
def fetch_streams_by_name(stream_names: List[str]) -> Sequence[Stream]:
#
# This should be just
#
# Stream.objects.select_related("realm").filter(name__iexact__in=stream_names,
# realm_id=realm_id)
#
# But chaining __in and __iexact doesn't work with Django's
# ORM, so we have the following hack to construct the relevant where clause
if len(stream_names) == 0:
return []
upper_list = ", ".join(["UPPER(%s)"] * len(stream_names))
where_clause = "UPPER(zerver_stream.name::text) IN (%s)" % (upper_list,)
return get_active_streams(realm.id).select_related("realm").extra(
where=[where_clause],
params=stream_names)
return generic_bulk_cached_fetch(lambda stream_name: get_stream_cache_key(stream_name, realm.id),
fetch_streams_by_name,
[stream_name.lower() for stream_name in stream_names],
id_fetcher=lambda stream: stream.name.lower())
def get_recipient_cache_key(type: int, type_id: int) -> str:
return u"%s:get_recipient:%s:%s" % (cache.KEY_PREFIX, type, type_id,)
@cache_with_key(get_recipient_cache_key, timeout=3600*24*7)
def get_recipient(type: int, type_id: int) -> Recipient:
return Recipient.objects.get(type_id=type_id, type=type)
def get_stream_recipient(stream_id: int) -> Recipient:
return get_recipient(Recipient.STREAM, stream_id)
def get_personal_recipient(user_profile_id: int) -> Recipient:
return get_recipient(Recipient.PERSONAL, user_profile_id)
def get_huddle_recipient(user_profile_ids: Set[int]) -> Recipient:
# The caller should ensure that user_profile_ids includes
# the sender. Note that get_huddle hits the cache, and then
# we hit another cache to get the recipient. We may want to
# unify our caching strategy here.
huddle = get_huddle(list(user_profile_ids))
return get_recipient(Recipient.HUDDLE, huddle.id)
def get_huddle_user_ids(recipient: Recipient) -> List[int]:
assert(recipient.type == Recipient.HUDDLE)
return Subscription.objects.filter(
recipient=recipient,
active=True,
).order_by('user_profile_id').values_list('user_profile_id', flat=True)
def bulk_get_recipients(type: int, type_ids: List[int]) -> Dict[int, Any]:
def cache_key_function(type_id: int) -> str:
return get_recipient_cache_key(type, type_id)
def query_function(type_ids: List[int]) -> Sequence[Recipient]:
# TODO: Change return type to QuerySet[Recipient]
return Recipient.objects.filter(type=type, type_id__in=type_ids)
return generic_bulk_cached_fetch(cache_key_function, query_function, type_ids,
id_fetcher=lambda recipient: recipient.type_id)
def get_stream_recipients(stream_ids: List[int]) -> List[Recipient]:
'''
We could call bulk_get_recipients(...).values() here, but it actually
leads to an extra query in test mode.
'''
return Recipient.objects.filter(
type=Recipient.STREAM,
type_id__in=stream_ids,
)
class AbstractMessage(models.Model):
sender = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
recipient = models.ForeignKey(Recipient, on_delete=CASCADE) # type: Recipient
# The message's topic.
#
# Early versions of Zulip called this concept a "subject", as in an email
# "subject line", before changing to "topic" in 2013 (commit dac5a46fa).
# UI and user documentation now consistently say "topic". New APIs and
# new code should generally also say "topic".
#
# See also the `topic_name` method on `Message`.
subject = models.CharField(max_length=MAX_TOPIC_NAME_LENGTH, db_index=True) # type: str
content = models.TextField() # type: str
rendered_content = models.TextField(null=True) # type: Optional[str]
rendered_content_version = models.IntegerField(null=True) # type: Optional[int]
pub_date = models.DateTimeField('date published', db_index=True) # type: datetime.datetime
sending_client = models.ForeignKey(Client, on_delete=CASCADE) # type: Client
last_edit_time = models.DateTimeField(null=True) # type: Optional[datetime.datetime]
# A JSON-encoded list of objects describing any past edits to this
# message, oldest first.
edit_history = models.TextField(null=True) # type: Optional[str]
has_attachment = models.BooleanField(default=False, db_index=True) # type: bool
has_image = models.BooleanField(default=False, db_index=True) # type: bool
has_link = models.BooleanField(default=False, db_index=True) # type: bool
class Meta:
abstract = True
def __str__(self) -> str:
display_recipient = get_display_recipient(self.recipient)
return "<%s: %s / %s / %s>" % (self.__class__.__name__, display_recipient,
self.subject, self.sender)
class ArchivedMessage(AbstractMessage):
"""Used as a temporary holding place for deleted messages before they
are permanently deleted. This is an important part of a robust
'message retention' feature.
"""
archive_timestamp = models.DateTimeField(default=timezone_now, db_index=True) # type: datetime.datetime
class Message(AbstractMessage):
def topic_name(self) -> str:
"""
Please start using this helper to facilitate an
eventual switch over to a separate topic table.
"""
return self.subject
def set_topic_name(self, topic_name: str) -> None:
self.subject = topic_name
def is_stream_message(self) -> bool:
'''
Find out whether a message is a stream message by
looking up its recipient.type. TODO: Make this
an easier operation by denormalizing the message
type onto Message, either explicity (message.type)
or implicitly (message.stream_id is not None).
'''
return self.recipient.type == Recipient.STREAM
def get_realm(self) -> Realm:
return self.sender.realm
def save_rendered_content(self) -> None:
self.save(update_fields=["rendered_content", "rendered_content_version"])
@staticmethod
def need_to_render_content(rendered_content: Optional[str],
rendered_content_version: Optional[int],
bugdown_version: int) -> bool:
return (rendered_content is None or
rendered_content_version is None or
rendered_content_version < bugdown_version)
def to_log_dict(self) -> Dict[str, Any]:
return dict(
id = self.id,
sender_id = self.sender.id,
sender_email = self.sender.email,
sender_realm_str = self.sender.realm.string_id,
sender_full_name = self.sender.full_name,
sender_short_name = self.sender.short_name,
sending_client = self.sending_client.name,
type = self.recipient.type_name(),
recipient = get_display_recipient(self.recipient),
subject = self.topic_name(),
content = self.content,
timestamp = datetime_to_timestamp(self.pub_date))
def sent_by_human(self) -> bool:
"""Used to determine whether a message was sent by a full Zulip UI
style client (and thus whether the message should be treated
as sent by a human and automatically marked as read for the
sender). The purpose of this distinction is to ensure that
message sent to the user by e.g. a Google Calendar integration
using the user's own API key don't get marked as read
automatically.
"""
sending_client = self.sending_client.name.lower()
return (sending_client in ('zulipandroid', 'zulipios', 'zulipdesktop',
'zulipmobile', 'zulipelectron', 'zulipterminal', 'snipe',
'website', 'ios', 'android')) or (
'desktop app' in sending_client)
@staticmethod
def content_has_attachment(content: str) -> Match:
return re.search(r'[/\-]user[\-_]uploads[/\.-]', content)
@staticmethod
def content_has_image(content: str) -> bool:
return bool(re.search(r'[/\-]user[\-_]uploads[/\.-]\S+\.(bmp|gif|jpg|jpeg|png|webp)',
content, re.IGNORECASE))
@staticmethod
def content_has_link(content: str) -> bool:
return ('http://' in content or
'https://' in content or
'/user_uploads' in content or
(settings.ENABLE_FILE_LINKS and 'file:///' in content) or
'bitcoin:' in content)
@staticmethod
def is_status_message(content: str, rendered_content: str) -> bool:
"""
Returns True if content and rendered_content are from 'me_message'
"""
if content.startswith('/me ') and '\n' not in content:
if rendered_content.startswith('<p>') and rendered_content.endswith('</p>'):
return True
return False
def update_calculated_fields(self) -> None:
# TODO: rendered_content could also be considered a calculated field
content = self.content
self.has_attachment = bool(Message.content_has_attachment(content))
self.has_image = bool(Message.content_has_image(content))
self.has_link = bool(Message.content_has_link(content))
@receiver(pre_save, sender=Message)
def pre_save_message(sender: Any, **kwargs: Any) -> None:
if kwargs['update_fields'] is None or "content" in kwargs['update_fields']:
message = kwargs['instance']
message.update_calculated_fields()
def get_context_for_message(message: Message) -> Sequence[Message]:
# TODO: Change return type to QuerySet[Message]
return Message.objects.filter(
recipient_id=message.recipient_id,
subject=message.subject,
id__lt=message.id,
pub_date__gt=message.pub_date - timedelta(minutes=15),
).order_by('-id')[:10]
post_save.connect(flush_message, sender=Message)
class SubMessage(models.Model):
# We can send little text messages that are associated with a regular
# Zulip message. These can be used for experimental widgets like embedded
# games, surveys, mini threads, etc. These are designed to be pretty
# generic in purpose.
message = models.ForeignKey(Message, on_delete=CASCADE) # type: Message
sender = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
msg_type = models.TextField()
content = models.TextField()
@staticmethod
def get_raw_db_rows(needed_ids: List[int]) -> List[Dict[str, Any]]:
fields = ['id', 'message_id', 'sender_id', 'msg_type', 'content']
query = SubMessage.objects.filter(message_id__in=needed_ids).values(*fields)
query = query.order_by('message_id', 'id')
return list(query)
post_save.connect(flush_submessage, sender=SubMessage)
class Reaction(models.Model):
"""For emoji reactions to messages (and potentially future reaction types).
Emoji are surprisingly complicated to implement correctly. For details
on how this subsystem works, see:
https://zulip.readthedocs.io/en/latest/subsystems/emoji.html
"""
user_profile = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
message = models.ForeignKey(Message, on_delete=CASCADE) # type: Message
# The user-facing name for an emoji reaction. With emoji aliases,
# there may be multiple accepted names for a given emoji; this
# field encodes which one the user selected.
emoji_name = models.TextField() # type: str
UNICODE_EMOJI = u'unicode_emoji'
REALM_EMOJI = u'realm_emoji'
ZULIP_EXTRA_EMOJI = u'zulip_extra_emoji'
REACTION_TYPES = ((UNICODE_EMOJI, _("Unicode emoji")),
(REALM_EMOJI, _("Custom emoji")),
(ZULIP_EXTRA_EMOJI, _("Zulip extra emoji")))
reaction_type = models.CharField(default=UNICODE_EMOJI, choices=REACTION_TYPES, max_length=30) # type: str
# A string that uniquely identifies a particular emoji. The format varies
# by type:
#
# * For Unicode emoji, a dash-separated hex encoding of the sequence of
# Unicode codepoints that define this emoji in the Unicode
# specification. For examples, see "non_qualified" or "unified" in the
# following data, with "non_qualified" taking precedence when both present:
# https://raw.githubusercontent.com/iamcal/emoji-data/master/emoji_pretty.json
#
# * For realm emoji (aka user uploaded custom emoji), the ID
# (in ASCII decimal) of the RealmEmoji object.
#
# * For "Zulip extra emoji" (like :zulip:), the filename of the emoji.
emoji_code = models.TextField() # type: str
class Meta:
unique_together = ("user_profile", "message", "emoji_name")
@staticmethod
def get_raw_db_rows(needed_ids: List[int]) -> List[Dict[str, Any]]:
fields = ['message_id', 'emoji_name', 'emoji_code', 'reaction_type',
'user_profile__email', 'user_profile__id', 'user_profile__full_name']
return Reaction.objects.filter(message_id__in=needed_ids).values(*fields)
# Whenever a message is sent, for each user subscribed to the
# corresponding Recipient object, we add a row to the UserMessage
# table indicating that that user received that message. This table
# allows us to quickly query any user's last 1000 messages to generate
# the home view.
#
# Additionally, the flags field stores metadata like whether the user
# has read the message, starred or collapsed the message, was
# mentioned in the message, etc.
#
# UserMessage is the largest table in a Zulip installation, even
# though each row is only 4 integers.
class AbstractUserMessage(models.Model):
user_profile = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
ALL_FLAGS = ['read', 'starred', 'collapsed', 'mentioned', 'wildcard_mentioned',
'summarize_in_home', 'summarize_in_stream', 'force_expand', 'force_collapse',
'has_alert_word', "historical", "is_private", "active_mobile_push_notification"]
# Certain flags are used only for internal accounting within the
# Zulip backend, and don't make sense to expose to the API. A
# good example is is_private, which is just a denormalization of
# message.recipient_type for database query performance.
NON_API_FLAGS = {"is_private", "active_mobile_push_notification"}
flags = BitField(flags=ALL_FLAGS, default=0) # type: BitHandler
class Meta:
abstract = True
unique_together = ("user_profile", "message")
@staticmethod
def where_unread() -> str:
# Use this for Django ORM queries to access unread message.
# This custom SQL plays nice with our partial indexes. Grep
# the code for example usage.
return 'flags & 1 = 0'
@staticmethod
def where_starred() -> str:
# Use this for Django ORM queries to access starred messages.
# This custom SQL plays nice with our partial indexes. Grep
# the code for example usage.
#
# The key detail is that e.g.
# UserMessage.objects.filter(user_profile=user_profile, flags=UserMessage.flags.starred)
# will generate a query involving `flags & 2 = 2`, which doesn't match our index.
return 'flags & 2 <> 0'
@staticmethod
def where_active_push_notification() -> str:
# See where_starred for documentation.
return 'flags & 4096 <> 0'
def flags_list(self) -> List[str]:
flags = int(self.flags)
return self.flags_list_for_flags(flags)
@staticmethod
def flags_list_for_flags(val: int) -> List[str]:
'''
This function is highly optimized, because it actually slows down
sending messages in a naive implementation.
'''
flags = []
mask = 1
for flag in UserMessage.ALL_FLAGS:
if (val & mask) and flag not in AbstractUserMessage.NON_API_FLAGS:
flags.append(flag)
mask <<= 1
return flags
def __str__(self) -> str:
display_recipient = get_display_recipient(self.message.recipient)
return "<%s: %s / %s (%s)>" % (self.__class__.__name__, display_recipient,
self.user_profile.email, self.flags_list())
class UserMessage(AbstractUserMessage):
message = models.ForeignKey(Message, on_delete=CASCADE) # type: Message
def get_usermessage_by_message_id(user_profile: UserProfile, message_id: int) -> Optional[UserMessage]:
try:
return UserMessage.objects.select_related().get(user_profile=user_profile,
message__id=message_id)
except UserMessage.DoesNotExist:
return None
class ArchivedUserMessage(AbstractUserMessage):
"""Used as a temporary holding place for deleted UserMessages objects
before they are permanently deleted. This is an important part of
a robust 'message retention' feature.
"""
message = models.ForeignKey(ArchivedMessage, on_delete=CASCADE) # type: Message
archive_timestamp = models.DateTimeField(default=timezone_now, db_index=True) # type: datetime.datetime
class AbstractAttachment(models.Model):
file_name = models.TextField(db_index=True) # type: str
# path_id is a storage location agnostic representation of the path of the file.
# If the path of a file is http://localhost:9991/user_uploads/a/b/abc/temp_file.py
# then its path_id will be a/b/abc/temp_file.py.
path_id = models.TextField(db_index=True, unique=True) # type: str
owner = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
realm = models.ForeignKey(Realm, blank=True, null=True, on_delete=CASCADE) # type: Optional[Realm]
create_time = models.DateTimeField(default=timezone_now,
db_index=True) # type: datetime.datetime
size = models.IntegerField(null=True) # type: Optional[int]
# Whether this attachment has been posted to a public stream, and
# thus should be available to all non-guest users in the
# organization (even if they weren't a recipient of a message
# linking to it). This lets us avoid looking up the corresponding
# messages/streams to check permissions before serving these files.
is_realm_public = models.BooleanField(default=False) # type: bool
class Meta:
abstract = True
def __str__(self) -> str:
return "<%s: %s>" % (self.__class__.__name__, self.file_name,)
class ArchivedAttachment(AbstractAttachment):
"""Used as a temporary holding place for deleted Attachment objects
before they are permanently deleted. This is an important part of
a robust 'message retention' feature.
"""
archive_timestamp = models.DateTimeField(default=timezone_now, db_index=True) # type: datetime.datetime
messages = models.ManyToManyField(ArchivedMessage) # type: Manager
class Attachment(AbstractAttachment):
messages = models.ManyToManyField(Message) # type: Manager
def is_claimed(self) -> bool:
return self.messages.count() > 0
def to_dict(self) -> Dict[str, Any]:
return {
'id': self.id,
'name': self.file_name,
'path_id': self.path_id,
'size': self.size,
# convert to JavaScript-style UNIX timestamp so we can take
# advantage of client timezones.
'create_time': time.mktime(self.create_time.timetuple()) * 1000,
'messages': [{
'id': m.id,
'name': time.mktime(m.pub_date.timetuple()) * 1000
} for m in self.messages.all()]
}
def validate_attachment_request(user_profile: UserProfile, path_id: str) -> Optional[bool]:
try:
attachment = Attachment.objects.get(path_id=path_id)
except Attachment.DoesNotExist:
return None
if user_profile == attachment.owner:
# If you own the file, you can access it.
return True
if (attachment.is_realm_public and attachment.realm == user_profile.realm and
user_profile.can_access_public_streams()):
# Any user in the realm can access realm-public files
return True
messages = attachment.messages.all()
if UserMessage.objects.filter(user_profile=user_profile, message__in=messages).exists():
# If it was sent in a private message or private stream
# message, then anyone who received that message can access it.
return True
# The user didn't receive any of the messages that included this
# attachment. But they might still have access to it, if it was
# sent to a stream they are on where history is public to
# subscribers.
# These are subscriptions to a stream one of the messages was sent to
relevant_stream_ids = Subscription.objects.filter(
user_profile=user_profile,
active=True,
recipient__type=Recipient.STREAM,
recipient__in=[m.recipient_id for m in messages]).values_list("recipient__type_id", flat=True)
if len(relevant_stream_ids) == 0:
return False
return Stream.objects.filter(id__in=relevant_stream_ids,
history_public_to_subscribers=True).exists()
def get_old_unclaimed_attachments(weeks_ago: int) -> Sequence[Attachment]:
# TODO: Change return type to QuerySet[Attachment]
delta_weeks_ago = timezone_now() - datetime.timedelta(weeks=weeks_ago)
old_attachments = Attachment.objects.filter(messages=None, create_time__lt=delta_weeks_ago)
return old_attachments
class Subscription(models.Model):
user_profile = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
recipient = models.ForeignKey(Recipient, on_delete=CASCADE) # type: Recipient
# Whether the user has since unsubscribed. We mark Subscription
# objects as inactive, rather than deleting them, when a user
# unsubscribes, so we can preseve user customizations like
# notification settings, stream color, etc., if the user later
# resubscribes.
active = models.BooleanField(default=True) # type: bool
# Whether the stream is muted. TODO: Remove to !muted.
in_home_view = models.NullBooleanField(default=True) # type: Optional[bool]
DEFAULT_STREAM_COLOR = u"#c2c2c2"
color = models.CharField(max_length=10, default=DEFAULT_STREAM_COLOR) # type: str
pin_to_top = models.BooleanField(default=False) # type: bool
desktop_notifications = models.BooleanField(default=True) # type: bool
audible_notifications = models.BooleanField(default=True) # type: bool
push_notifications = models.BooleanField(default=False) # type: bool
email_notifications = models.BooleanField(default=False) # type: bool
class Meta:
unique_together = ("user_profile", "recipient")
def __str__(self) -> str:
return "<Subscription: %s -> %s>" % (self.user_profile, self.recipient)
@cache_with_key(user_profile_by_id_cache_key, timeout=3600*24*7)
def get_user_profile_by_id(uid: int) -> UserProfile:
return UserProfile.objects.select_related().get(id=uid)
@cache_with_key(user_profile_by_email_cache_key, timeout=3600*24*7)
def get_user_profile_by_email(email: str) -> UserProfile:
return UserProfile.objects.select_related().get(email__iexact=email.strip())
@cache_with_key(user_profile_by_api_key_cache_key, timeout=3600*24*7)
def get_user_profile_by_api_key(api_key: str) -> UserProfile:
return UserProfile.objects.select_related().get(api_key=api_key)
@cache_with_key(user_profile_cache_key, timeout=3600*24*7)
def get_user(email: str, realm: Realm) -> UserProfile:
return UserProfile.objects.select_related().get(email__iexact=email.strip(), realm=realm)
def get_active_user(email: str, realm: Realm) -> UserProfile:
user_profile = get_user(email, realm)
if not user_profile.is_active:
raise UserProfile.DoesNotExist()
return user_profile
def get_user_profile_by_id_in_realm(uid: int, realm: Realm) -> UserProfile:
return UserProfile.objects.select_related().get(id=uid, realm=realm)
def get_user_including_cross_realm(email: str, realm: Optional[Realm]=None) -> UserProfile:
if is_cross_realm_bot_email(email):
return get_system_bot(email)
assert realm is not None
return get_user(email, realm)
@cache_with_key(bot_profile_cache_key, timeout=3600*24*7)
def get_system_bot(email: str) -> UserProfile:
return UserProfile.objects.select_related().get(email__iexact=email.strip())
def get_user_by_id_in_realm_including_cross_realm(
uid: int,
realm: Realm
) -> UserProfile:
user_profile = get_user_profile_by_id(uid)
if user_profile.realm == realm:
return user_profile
# Note: This doesn't validate whether the `realm` passed in is
# None/invalid for the CROSS_REALM_BOT_EMAILS case.
if user_profile.email in settings.CROSS_REALM_BOT_EMAILS:
return user_profile
raise UserProfile.DoesNotExist()
@cache_with_key(realm_user_dicts_cache_key, timeout=3600*24*7)
def get_realm_user_dicts(realm_id: int) -> List[Dict[str, Any]]:
return UserProfile.objects.filter(
realm_id=realm_id,
).values(*realm_user_dict_fields)
@cache_with_key(active_user_ids_cache_key, timeout=3600*24*7)
def active_user_ids(realm_id: int) -> List[int]:
query = UserProfile.objects.filter(
realm_id=realm_id,
is_active=True
).values_list('id', flat=True)
return list(query)
@cache_with_key(active_non_guest_user_ids_cache_key, timeout=3600*24*7)
def active_non_guest_user_ids(realm_id: int) -> List[int]:
query = UserProfile.objects.filter(
realm_id=realm_id,
is_active=True,
is_guest=False,
).values_list('id', flat=True)
return list(query)
def get_source_profile(email: str, string_id: str) -> Optional[UserProfile]:
realm = get_realm(string_id)
if realm is None:
return None
try:
return get_user(email, realm)
except UserProfile.DoesNotExist:
return None
@cache_with_key(bot_dicts_in_realm_cache_key, timeout=3600*24*7)
def get_bot_dicts_in_realm(realm: Realm) -> List[Dict[str, Any]]:
return UserProfile.objects.filter(realm=realm, is_bot=True).values(*bot_dict_fields)
def is_cross_realm_bot_email(email: str) -> bool:
return email.lower() in settings.CROSS_REALM_BOT_EMAILS
# The Huddle class represents a group of individuals who have had a
# Group Private Message conversation together. The actual membership
# of the Huddle is stored in the Subscription table just like with
# Streams, and a hash of that list is stored in the huddle_hash field
# below, to support efficiently mapping from a set of users to the
# corresponding Huddle object.
class Huddle(models.Model):
# TODO: We should consider whether using
# CommaSeparatedIntegerField would be better.
huddle_hash = models.CharField(max_length=40, db_index=True, unique=True) # type: str
def get_huddle_hash(id_list: List[int]) -> str:
id_list = sorted(set(id_list))
hash_key = ",".join(str(x) for x in id_list)
return make_safe_digest(hash_key)
def huddle_hash_cache_key(huddle_hash: str) -> str:
return u"huddle_by_hash:%s" % (huddle_hash,)
def get_huddle(id_list: List[int]) -> Huddle:
huddle_hash = get_huddle_hash(id_list)
return get_huddle_backend(huddle_hash, id_list)
@cache_with_key(lambda huddle_hash, id_list: huddle_hash_cache_key(huddle_hash), timeout=3600*24*7)
def get_huddle_backend(huddle_hash: str, id_list: List[int]) -> Huddle:
with transaction.atomic():
(huddle, created) = Huddle.objects.get_or_create(huddle_hash=huddle_hash)
if created:
recipient = Recipient.objects.create(type_id=huddle.id,
type=Recipient.HUDDLE)
subs_to_create = [Subscription(recipient=recipient,
user_profile_id=user_profile_id)
for user_profile_id in id_list]
Subscription.objects.bulk_create(subs_to_create)
return huddle
def clear_database() -> None: # nocoverage # Only used in populate_db
pylibmc.Client(['127.0.0.1']).flush_all()
model = None # type: Any
for model in [Message, Stream, UserProfile, Recipient,
Realm, Subscription, Huddle, UserMessage, Client,
DefaultStream]:
model.objects.all().delete()
Session.objects.all().delete()
class UserActivity(models.Model):
user_profile = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
client = models.ForeignKey(Client, on_delete=CASCADE) # type: Client
query = models.CharField(max_length=50, db_index=True) # type: str
count = models.IntegerField() # type: int
last_visit = models.DateTimeField('last visit') # type: datetime.datetime
class Meta:
unique_together = ("user_profile", "client", "query")
class UserActivityInterval(models.Model):
MIN_INTERVAL_LENGTH = datetime.timedelta(minutes=15)
user_profile = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
start = models.DateTimeField('start time', db_index=True) # type: datetime.datetime
end = models.DateTimeField('end time', db_index=True) # type: datetime.datetime
class UserPresence(models.Model):
"""A record from the last time we heard from a given user on a given client.
This is a tricky subsystem, because it is highly optimized. See the docs:
https://zulip.readthedocs.io/en/latest/subsystems/presence.html
"""
class Meta:
unique_together = ("user_profile", "client")
user_profile = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
client = models.ForeignKey(Client, on_delete=CASCADE) # type: Client
# The time we heard this update from the client.
timestamp = models.DateTimeField('presence changed') # type: datetime.datetime
# The user was actively using this Zulip client as of `timestamp` (i.e.,
# they had interacted with the client recently). When the timestamp is
# itself recent, this is the green "active" status in the webapp.
ACTIVE = 1
# There had been no user activity (keyboard/mouse/etc.) on this client
# recently. So the client was online at the specified time, but it
# could be the user's desktop which they were away from. Displayed as
# orange/idle if the timestamp is current.
IDLE = 2
# Information from the client about the user's recent interaction with
# that client, as of `timestamp`. Possible values above.
#
# There is no "inactive" status, because that is encoded by the
# timestamp being old.
status = models.PositiveSmallIntegerField(default=ACTIVE) # type: int
@staticmethod
def status_to_string(status: int) -> str:
if status == UserPresence.ACTIVE:
return 'active'
elif status == UserPresence.IDLE:
return 'idle'
else: # nocoverage # TODO: Add a presence test to cover this.
raise ValueError('Unknown status: %s' % (status,))
@staticmethod
def get_status_dict_by_user(user_profile: UserProfile) -> Dict[str, Dict[str, Any]]:
query = UserPresence.objects.filter(user_profile=user_profile).values(
'client__name',
'status',
'timestamp',
'user_profile__email',
'user_profile__id',
'user_profile__enable_offline_push_notifications',
)
presence_rows = list(query)
mobile_user_ids = set() # type: Set[int]
if PushDeviceToken.objects.filter(user=user_profile).exists(): # nocoverage
# TODO: Add a test, though this is low priority, since we don't use mobile_user_ids yet.
mobile_user_ids.add(user_profile.id)
return UserPresence.get_status_dicts_for_rows(presence_rows, mobile_user_ids)
@staticmethod
def get_status_dict_by_realm(realm_id: int) -> Dict[str, Dict[str, Any]]:
user_profile_ids = UserProfile.objects.filter(
realm_id=realm_id,
is_active=True,
is_bot=False
).order_by('id').values_list('id', flat=True)
user_profile_ids = list(user_profile_ids)
if not user_profile_ids: # nocoverage
# This conditional is necessary because query_for_ids
# throws an exception if passed an empty list.
#
# It's not clear this condition is actually possible,
# though, because it shouldn't be possible to end up with
# a realm with 0 active users.
return {}
two_weeks_ago = timezone_now() - datetime.timedelta(weeks=2)
query = UserPresence.objects.filter(
timestamp__gte=two_weeks_ago
).values(
'client__name',
'status',
'timestamp',
'user_profile__email',
'user_profile__id',
'user_profile__enable_offline_push_notifications',
)
query = query_for_ids(
query=query,
user_ids=user_profile_ids,
field='user_profile_id'
)
presence_rows = list(query)
mobile_query = PushDeviceToken.objects.distinct(
'user_id'
).values_list(
'user_id',
flat=True
)
mobile_query = query_for_ids(
query=mobile_query,
user_ids=user_profile_ids,
field='user_id'
)
mobile_user_ids = set(mobile_query)
return UserPresence.get_status_dicts_for_rows(presence_rows, mobile_user_ids)
@staticmethod
def get_status_dicts_for_rows(presence_rows: List[Dict[str, Any]],
mobile_user_ids: Set[int]) -> Dict[str, Dict[str, Any]]:
info_row_dct = defaultdict(list) # type: DefaultDict[str, List[Dict[str, Any]]]
for row in presence_rows:
email = row['user_profile__email']
client_name = row['client__name']
status = UserPresence.status_to_string(row['status'])
dt = row['timestamp']
timestamp = datetime_to_timestamp(dt)
push_enabled = row['user_profile__enable_offline_push_notifications']
has_push_devices = row['user_profile__id'] in mobile_user_ids
pushable = (push_enabled and has_push_devices)
info = dict(
client=client_name,
status=status,
dt=dt,
timestamp=timestamp,
pushable=pushable,
)
info_row_dct[email].append(info)
user_statuses = dict() # type: Dict[str, Dict[str, Any]]
for email, info_rows in info_row_dct.items():
# Note that datetime values have sub-second granularity, which is
# mostly important for avoiding test flakes, but it's also technically
# more precise for real users.
by_time = lambda row: row['dt']
most_recent_info = max(info_rows, key=by_time)
# We don't send datetime values to the client.
for r in info_rows:
del r['dt']
client_dict = {info['client']: info for info in info_rows}
user_statuses[email] = client_dict
# The word "aggegrated" here is possibly misleading.
# It's really just the most recent client's info.
user_statuses[email]['aggregated'] = dict(
client=most_recent_info['client'],
status=most_recent_info['status'],
timestamp=most_recent_info['timestamp'],
)
return user_statuses
@staticmethod
def to_presence_dict(client_name: str, status: int, dt: datetime.datetime, push_enabled: bool=False,
has_push_devices: bool=False) -> Dict[str, Any]:
presence_val = UserPresence.status_to_string(status)
timestamp = datetime_to_timestamp(dt)
return dict(
client=client_name,
status=presence_val,
timestamp=timestamp,
pushable=(push_enabled and has_push_devices),
)
def to_dict(self) -> Dict[str, Any]:
return UserPresence.to_presence_dict(
self.client.name,
self.status,
self.timestamp
)
@staticmethod
def status_from_string(status: NonBinaryStr) -> Optional[int]:
if status == 'active':
status_val = UserPresence.ACTIVE # type: Optional[int] # See https://github.com/python/mypy/issues/2611
elif status == 'idle':
status_val = UserPresence.IDLE
else:
status_val = None
return status_val
class DefaultStream(models.Model):
realm = models.ForeignKey(Realm, on_delete=CASCADE) # type: Realm
stream = models.ForeignKey(Stream, on_delete=CASCADE) # type: Stream
class Meta:
unique_together = ("realm", "stream")
class DefaultStreamGroup(models.Model):
MAX_NAME_LENGTH = 60
name = models.CharField(max_length=MAX_NAME_LENGTH, db_index=True) # type: str
realm = models.ForeignKey(Realm, on_delete=CASCADE) # type: Realm
streams = models.ManyToManyField('Stream') # type: Manager
description = models.CharField(max_length=1024, default=u'') # type: str
class Meta:
unique_together = ("realm", "name")
def to_dict(self) -> Dict[str, Any]:
return dict(name=self.name,
id=self.id,
description=self.description,
streams=[stream.to_dict() for stream in self.streams.all()])
def get_default_stream_groups(realm: Realm) -> List[DefaultStreamGroup]:
return DefaultStreamGroup.objects.filter(realm=realm)
class AbstractScheduledJob(models.Model):
scheduled_timestamp = models.DateTimeField(db_index=True) # type: datetime.datetime
# JSON representation of arguments to consumer
data = models.TextField() # type: str
realm = models.ForeignKey(Realm, on_delete=CASCADE) # type: Realm
class Meta:
abstract = True
class ScheduledEmail(AbstractScheduledJob):
# Exactly one of user or address should be set. These are used to
# filter the set of ScheduledEmails.
user = models.ForeignKey(UserProfile, null=True, on_delete=CASCADE) # type: Optional[UserProfile]
# Just the address part of a full "name <address>" email address
address = models.EmailField(null=True, db_index=True) # type: Optional[str]
# Valid types are below
WELCOME = 1
DIGEST = 2
INVITATION_REMINDER = 3
type = models.PositiveSmallIntegerField() # type: int
def __str__(self) -> str:
return "<ScheduledEmail: %s %s %s>" % (self.type, self.user or self.address,
self.scheduled_timestamp)
class ScheduledMessage(models.Model):
sender = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
recipient = models.ForeignKey(Recipient, on_delete=CASCADE) # type: Recipient
subject = models.CharField(max_length=MAX_TOPIC_NAME_LENGTH) # type: str
content = models.TextField() # type: str
sending_client = models.ForeignKey(Client, on_delete=CASCADE) # type: Client
stream = models.ForeignKey(Stream, null=True, on_delete=CASCADE) # type: Optional[Stream]
realm = models.ForeignKey(Realm, on_delete=CASCADE) # type: Realm
scheduled_timestamp = models.DateTimeField(db_index=True) # type: datetime.datetime
delivered = models.BooleanField(default=False) # type: bool
SEND_LATER = 1
REMIND = 2
DELIVERY_TYPES = (
(SEND_LATER, 'send_later'),
(REMIND, 'remind'),
)
delivery_type = models.PositiveSmallIntegerField(choices=DELIVERY_TYPES,
default=SEND_LATER) # type: int
def topic_name(self) -> str:
return self.subject
def set_topic_name(self, topic_name: str) -> None:
self.subject = topic_name
def __str__(self) -> str:
display_recipient = get_display_recipient(self.recipient)
return "<ScheduledMessage: %s %s %s %s>" % (display_recipient,
self.subject, self.sender,
self.scheduled_timestamp)
EMAIL_TYPES = {
'followup_day1': ScheduledEmail.WELCOME,
'followup_day2': ScheduledEmail.WELCOME,
'digest': ScheduledEmail.DIGEST,
'invitation_reminder': ScheduledEmail.INVITATION_REMINDER,
}
class RealmAuditLog(models.Model):
"""
RealmAuditLog tracks important changes to users, streams, and
realms in Zulip. It is intended to support both
debugging/introspection (e.g. determining when a user's left a
given stream?) as well as help with some database migrations where
we might be able to do a better data backfill with it. Here are a
few key details about how this works:
* acting_user is the user who initiated the state change
* modified_user (if present) is the user being modified
* modified_stream (if present) is the stream being modified
For example:
* When a user subscribes another user to a stream, modified_user,
acting_user, and modified_stream will all be present and different.
* When an administrator changes an organization's realm icon,
acting_user is that administrator and both modified_user and
modified_stream will be None.
"""
realm = models.ForeignKey(Realm, on_delete=CASCADE) # type: Realm
acting_user = models.ForeignKey(UserProfile, null=True, related_name='+', on_delete=CASCADE) # type: Optional[UserProfile]
modified_user = models.ForeignKey(UserProfile, null=True, related_name='+', on_delete=CASCADE) # type: Optional[UserProfile]
modified_stream = models.ForeignKey(Stream, null=True, on_delete=CASCADE) # type: Optional[Stream]
event_last_message_id = models.IntegerField(null=True) # type: Optional[int]
event_time = models.DateTimeField(db_index=True) # type: datetime.datetime
# If True, event_time is an overestimate of the true time. Can be used
# by migrations when introducing a new event_type.
backfilled = models.BooleanField(default=False) # type: bool
requires_billing_update = models.BooleanField(default=False) # type: bool
extra_data = models.TextField(null=True) # type: Optional[str]
STRIPE_CUSTOMER_CREATED = 'stripe_customer_created'
STRIPE_CARD_CHANGED = 'stripe_card_changed'
STRIPE_PLAN_CHANGED = 'stripe_plan_changed'
STRIPE_PLAN_QUANTITY_RESET = 'stripe_plan_quantity_reset'
USER_CREATED = 'user_created'
USER_ACTIVATED = 'user_activated'
USER_DEACTIVATED = 'user_deactivated'
USER_REACTIVATED = 'user_reactivated'
USER_SOFT_ACTIVATED = 'user_soft_activated'
USER_SOFT_DEACTIVATED = 'user_soft_deactivated'
USER_PASSWORD_CHANGED = 'user_password_changed'
USER_AVATAR_SOURCE_CHANGED = 'user_avatar_source_changed'
USER_FULL_NAME_CHANGED = 'user_full_name_changed'
USER_EMAIL_CHANGED = 'user_email_changed'
USER_TOS_VERSION_CHANGED = 'user_tos_version_changed'
USER_API_KEY_CHANGED = 'user_api_key_changed'
USER_BOT_OWNER_CHANGED = 'user_bot_owner_changed'
REALM_DEACTIVATED = 'realm_deactivated'
REALM_REACTIVATED = 'realm_reactivated'
REALM_SCRUBBED = 'realm_scrubbed'
REALM_PLAN_TYPE_CHANGED = 'realm_plan_type_changed'
SUBSCRIPTION_CREATED = 'subscription_created'
SUBSCRIPTION_ACTIVATED = 'subscription_activated'
SUBSCRIPTION_DEACTIVATED = 'subscription_deactivated'
event_type = models.CharField(max_length=40) # type: str
def __str__(self) -> str:
if self.modified_user is not None:
return "<RealmAuditLog: %s %s %s %s>" % (
self.modified_user, self.event_type, self.event_time, self.id)
if self.modified_stream is not None:
return "<RealmAuditLog: %s %s %s %s>" % (
self.modified_stream, self.event_type, self.event_time, self.id)
return "<RealmAuditLog: %s %s %s %s>" % (
self.realm, self.event_type, self.event_time, self.id)
class UserHotspot(models.Model):
user = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
hotspot = models.CharField(max_length=30) # type: str
timestamp = models.DateTimeField(default=timezone_now) # type: datetime.datetime
class Meta:
unique_together = ("user", "hotspot")
def check_valid_user_ids(realm_id: int, user_ids: List[int],
allow_deactivated: bool=False) -> Optional[str]:
error = check_list(check_int)("User IDs", user_ids)
if error:
return error
realm = Realm.objects.get(id=realm_id)
for user_id in user_ids:
# TODO: Structurally, we should be doing a bulk fetch query to
# get the users here, not doing these in a loop. But because
# this is a rarely used feature and likely to never have more
# than a handful of users, it's probably mostly OK.
try:
user_profile = get_user_profile_by_id_in_realm(user_id, realm)
except UserProfile.DoesNotExist:
return _('Invalid user ID: %d') % (user_id)
if not allow_deactivated:
if not user_profile.is_active:
return _('User with ID %d is deactivated') % (user_id)
if (user_profile.is_bot):
return _('User with ID %d is a bot') % (user_id)
return None
class CustomProfileField(models.Model):
"""Defines a form field for the per-realm custom profile fields feature.
See CustomProfileFieldValue for an individual user's values for one of
these fields.
"""
HINT_MAX_LENGTH = 80
NAME_MAX_LENGTH = 40
realm = models.ForeignKey(Realm, on_delete=CASCADE) # type: Realm
name = models.CharField(max_length=NAME_MAX_LENGTH) # type: str
hint = models.CharField(max_length=HINT_MAX_LENGTH, default='', null=True) # type: Optional[str]
order = models.IntegerField(default=0) # type: int
SHORT_TEXT = 1
LONG_TEXT = 2
CHOICE = 3
DATE = 4
URL = 5
USER = 6
# These are the fields whose validators require more than var_name
# and value argument. i.e. CHOICE require field_data, USER require
# realm as argument.
CHOICE_FIELD_TYPE_DATA = [
(CHOICE, str(_('List of options')), validate_choice_field, str, "CHOICE"),
] # type: FieldTypeData
USER_FIELD_TYPE_DATA = [
(USER, str(_('Person picker')), check_valid_user_ids, eval, "USER"),
] # type: FieldTypeData
CHOICE_FIELD_VALIDATORS = {
item[0]: item[2] for item in CHOICE_FIELD_TYPE_DATA
} # type: Dict[int, ExtendedValidator]
USER_FIELD_VALIDATORS = {
item[0]: item[2] for item in USER_FIELD_TYPE_DATA
} # type: Dict[int, RealmUserValidator]
FIELD_TYPE_DATA = [
# Type, Display Name, Validator, Converter, Keyword
(SHORT_TEXT, str(_('Short text')), check_short_string, str, "SHORT_TEXT"),
(LONG_TEXT, str(_('Long text')), check_long_string, str, "LONG_TEXT"),
(DATE, str(_('Date picker')), check_date, str, "DATE"),
(URL, str(_('Link')), check_url, str, "URL"),
] # type: FieldTypeData
ALL_FIELD_TYPES = FIELD_TYPE_DATA + CHOICE_FIELD_TYPE_DATA + USER_FIELD_TYPE_DATA
FIELD_VALIDATORS = {item[0]: item[2] for item in FIELD_TYPE_DATA} # type: Dict[int, Validator]
FIELD_CONVERTERS = {item[0]: item[3] for item in ALL_FIELD_TYPES} # type: Dict[int, Callable[[Any], Any]]
FIELD_TYPE_CHOICES = [(item[0], item[1]) for item in ALL_FIELD_TYPES] # type: List[Tuple[int, str]]
FIELD_TYPE_CHOICES_DICT = {
item[4]: {"id": item[0], "name": item[1]} for item in ALL_FIELD_TYPES
} # type: Dict[str, Dict[str, Union[str, int]]]
field_type = models.PositiveSmallIntegerField(choices=FIELD_TYPE_CHOICES,
default=SHORT_TEXT) # type: int
# A JSON blob of any additional data needed to define the field beyond
# type/name/hint.
#
# The format depends on the type. Field types SHORT_TEXT, LONG_TEXT,
# DATE, URL, and USER leave this null. Fields of type CHOICE store the
# choices' descriptions.
#
# Note: There is no performance overhead of using TextField in PostgreSQL.
# See https://www.postgresql.org/docs/9.0/static/datatype-character.html
field_data = models.TextField(default='', null=True) # type: Optional[str]
class Meta:
unique_together = ('realm', 'name')
def as_dict(self) -> ProfileDataElement:
return {
'id': self.id,
'name': self.name,
'type': self.field_type,
'hint': self.hint,
'field_data': self.field_data,
'order': self.order,
}
def __str__(self) -> str:
return "<CustomProfileField: %s %s %s %d>" % (self.realm, self.name, self.field_type, self.order)
def custom_profile_fields_for_realm(realm_id: int) -> List[CustomProfileField]:
return CustomProfileField.objects.filter(realm=realm_id).order_by('order')
class CustomProfileFieldValue(models.Model):
user_profile = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
field = models.ForeignKey(CustomProfileField, on_delete=CASCADE) # type: CustomProfileField
value = models.TextField() # type: str
class Meta:
unique_together = ('user_profile', 'field')
def __str__(self) -> str:
return "<CustomProfileFieldValue: %s %s %s>" % (self.user_profile, self.field, self.value)
# Interfaces for services
# They provide additional functionality like parsing message to obtain query url, data to be sent to url,
# and parsing the response.
GENERIC_INTERFACE = u'GenericService'
SLACK_INTERFACE = u'SlackOutgoingWebhookService'
# A Service corresponds to either an outgoing webhook bot or an embedded bot.
# The type of Service is determined by the bot_type field of the referenced
# UserProfile.
#
# If the Service is an outgoing webhook bot:
# - name is any human-readable identifier for the Service
# - base_url is the address of the third-party site
# - token is used for authentication with the third-party site
#
# If the Service is an embedded bot:
# - name is the canonical name for the type of bot (e.g. 'xkcd' for an instance
# of the xkcd bot); multiple embedded bots can have the same name, but all
# embedded bots with the same name will run the same code
# - base_url and token are currently unused
class Service(models.Model):
name = models.CharField(max_length=UserProfile.MAX_NAME_LENGTH) # type: str
# Bot user corresponding to the Service. The bot_type of this user
# deterines the type of service. If non-bot services are added later,
# user_profile can also represent the owner of the Service.
user_profile = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
base_url = models.TextField() # type: str
token = models.TextField() # type: str
# Interface / API version of the service.
interface = models.PositiveSmallIntegerField(default=1) # type: int
# Valid interfaces are {generic, zulip_bot_service, slack}
GENERIC = 1
SLACK = 2
ALLOWED_INTERFACE_TYPES = [
GENERIC,
SLACK,
]
# N.B. If we used Django's choice=... we would get this for free (kinda)
_interfaces = {
GENERIC: GENERIC_INTERFACE,
SLACK: SLACK_INTERFACE,
} # type: Dict[int, str]
def interface_name(self) -> str:
# Raises KeyError if invalid
return self._interfaces[self.interface]
def get_bot_services(user_profile_id: str) -> List[Service]:
return list(Service.objects.filter(user_profile__id=user_profile_id))
def get_service_profile(user_profile_id: str, service_name: str) -> Service:
return Service.objects.get(user_profile__id=user_profile_id, name=service_name)
class BotStorageData(models.Model):
bot_profile = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
key = models.TextField(db_index=True) # type: str
value = models.TextField() # type: str
class Meta:
unique_together = ("bot_profile", "key")
class BotConfigData(models.Model):
bot_profile = models.ForeignKey(UserProfile, on_delete=CASCADE) # type: UserProfile
key = models.TextField(db_index=True) # type: str
value = models.TextField() # type: str
class Meta(object):
unique_together = ("bot_profile", "key")
| [
"QuerySet",
"List[int]",
"str",
"int",
"int",
"Optional[int]",
"'Recipient'",
"int",
"int",
"Optional[int]",
"'Realm'",
"'Realm'",
"int",
"str",
"str",
"Optional[Realm]",
"str",
"str",
"str",
"Realm",
"Realm",
"Realm",
"Realm",
"Realm",
"Any",
"Any",
"str",
"str",
"int",
"int",
"int",
"int",
"Any",
"Any",
"'UserProfile'",
"Sequence[int]",
"UserProfile",
"UserProfile",
"UserProfile",
"UserProfile",
"str",
"str",
"str",
"str",
"str",
"int",
"str",
"int",
"Optional[Realm]",
"str",
"Realm",
"Realm",
"STREAM_NAMES",
"List[str]",
"int",
"int",
"int",
"int",
"int",
"int",
"Set[int]",
"Recipient",
"int",
"List[int]",
"int",
"List[int]",
"List[int]",
"str",
"Optional[str]",
"Optional[int]",
"int",
"str",
"str",
"str",
"str",
"str",
"Any",
"Any",
"Message",
"List[int]",
"List[int]",
"int",
"UserProfile",
"int",
"UserProfile",
"str",
"int",
"int",
"str",
"str",
"str",
"Realm",
"str",
"Realm",
"int",
"Realm",
"str",
"str",
"int",
"Realm",
"int",
"int",
"int",
"str",
"str",
"Realm",
"str",
"List[int]",
"str",
"List[int]",
"str",
"List[int]",
"int",
"UserProfile",
"int",
"List[Dict[str, Any]]",
"Set[int]",
"str",
"int",
"datetime.datetime",
"NonBinaryStr",
"Realm",
"str",
"int",
"List[int]",
"int",
"str",
"str",
"str"
] | [
2595,
2615,
2633,
3460,
3481,
3537,
4157,
4757,
4778,
4841,
5978,
6083,
16333,
17281,
18083,
18193,
19094,
19248,
19778,
19790,
20554,
21949,
22961,
23082,
23344,
23359,
23832,
24254,
25243,
25549,
25657,
26018,
26727,
26742,
38676,
39968,
41906,
42084,
42256,
42426,
42586,
50793,
51174,
51335,
51519,
51534,
51703,
51718,
51880,
52248,
52260,
52531,
52552,
52630,
53756,
53770,
53942,
53956,
54073,
54191,
54316,
54710,
54980,
54995,
55061,
55162,
55536,
58265,
58983,
59055,
59118,
60941,
61076,
61292,
61600,
61623,
62366,
62381,
62593,
63524,
65882,
68707,
69552,
69577,
72835,
72857,
74425,
76181,
76368,
76582,
76752,
76764,
76909,
76921,
77128,
77140,
77279,
77554,
77721,
77741,
78227,
78454,
78734,
78957,
78973,
79285,
79443,
80135,
80316,
80403,
80657,
80671,
84009,
84359,
85167,
86905,
86978,
88959,
88972,
88981,
89629,
90901,
93207,
97788,
97803,
102313,
104984,
105123,
105142
] | [
2603,
2624,
2636,
3463,
3484,
3550,
4168,
4760,
4781,
4854,
5985,
6090,
16336,
17284,
18086,
18208,
19097,
19251,
19781,
19795,
20559,
21954,
22966,
23087,
23347,
23362,
23835,
24257,
25246,
25552,
25660,
26021,
26730,
26745,
38689,
39981,
41917,
42095,
42267,
42437,
42589,
50796,
51177,
51338,
51522,
51537,
51706,
51721,
51895,
52251,
52265,
52536,
52564,
52639,
53759,
53773,
53945,
53959,
54076,
54194,
54324,
54719,
54983,
55004,
55064,
55171,
55545,
58268,
58996,
59068,
59121,
60944,
61079,
61295,
61603,
61626,
62369,
62384,
62600,
63533,
65891,
68710,
69563,
69580,
72846,
72860,
74428,
76184,
76371,
76585,
76755,
76769,
76912,
76926,
77131,
77145,
77282,
77557,
77724,
77746,
78230,
78457,
78737,
78960,
78976,
79290,
79446,
80144,
80319,
80412,
80660,
80680,
84012,
84370,
85170,
86925,
86986,
88962,
88975,
88998,
89641,
90906,
93210,
97791,
97812,
102316,
104987,
105126,
105145
] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/signals.py |
from typing import Any, Dict, Optional
from django.conf import settings
from django.contrib.auth.signals import user_logged_in
from django.dispatch import receiver
from django.template import loader
from django.utils.timezone import \
get_current_timezone_name as timezone_get_current_timezone_name
from django.utils.timezone import now as timezone_now
from django.utils.translation import ugettext_lazy as _
from confirmation.models import one_click_unsubscribe_link
from zerver.lib.queue import queue_json_publish
from zerver.lib.send_email import FromAddress
from zerver.models import UserProfile
from zerver.lib.timezone import get_timezone
JUST_CREATED_THRESHOLD = 60
def get_device_browser(user_agent: str) -> Optional[str]:
user_agent = user_agent.lower()
if "zulip" in user_agent:
return "Zulip"
elif "edge" in user_agent:
return "Edge"
elif "opera" in user_agent or "opr/" in user_agent:
return "Opera"
elif ("chrome" in user_agent or "crios" in user_agent) and "chromium" not in user_agent:
return 'Chrome'
elif "firefox" in user_agent and "seamonkey" not in user_agent and "chrome" not in user_agent:
return "Firefox"
elif "chromium" in user_agent:
return "Chromium"
elif "safari" in user_agent and "chrome" not in user_agent and "chromium" not in user_agent:
return "Safari"
elif "msie" in user_agent or "trident" in user_agent:
return "Internet Explorer"
else:
return None
def get_device_os(user_agent: str) -> Optional[str]:
user_agent = user_agent.lower()
if "windows" in user_agent:
return "Windows"
elif "macintosh" in user_agent:
return "macOS"
elif "linux" in user_agent and "android" not in user_agent:
return "Linux"
elif "android" in user_agent:
return "Android"
elif "ios" in user_agent:
return "iOS"
elif "like mac os x" in user_agent:
return "iOS"
elif " cros " in user_agent:
return "ChromeOS"
else:
return None
@receiver(user_logged_in, dispatch_uid="only_on_login")
def email_on_new_login(sender: Any, user: UserProfile, request: Any, **kwargs: Any) -> None:
if not user.enable_login_emails:
return
# We import here to minimize the dependencies of this module,
# since it runs as part of `manage.py` initialization
from zerver.context_processors import common_context
if not settings.SEND_LOGIN_EMAILS:
return
if request:
# If the user's account was just created, avoid sending an email.
if (timezone_now() - user.date_joined).total_seconds() <= JUST_CREATED_THRESHOLD:
return
user_agent = request.META.get('HTTP_USER_AGENT', "").lower()
context = common_context(user)
context['user_email'] = user.email
user_tz = user.timezone
if user_tz == '':
user_tz = timezone_get_current_timezone_name()
local_time = timezone_now().astimezone(get_timezone(user_tz))
if user.twenty_four_hour_time:
hhmm_string = local_time.strftime('%H:%M')
else:
hhmm_string = local_time.strftime('%I:%M%p')
context['login_time'] = local_time.strftime('%A, %B %d, %Y at {} %Z'.format(hhmm_string))
context['device_ip'] = request.META.get('REMOTE_ADDR') or _("Unknown IP address")
context['device_os'] = get_device_os(user_agent)
context['device_browser'] = get_device_browser(user_agent)
context['unsubscribe_link'] = one_click_unsubscribe_link(user, 'login')
email_dict = {
'template_prefix': 'zerver/emails/notify_new_login',
'to_user_id': user.id,
'from_name': 'Zulip Account Security',
'from_address': FromAddress.NOREPLY,
'context': context}
queue_json_publish("email_senders", email_dict)
| [
"str",
"str",
"Any",
"UserProfile",
"Any",
"Any"
] | [
717,
1539,
2150,
2161,
2183,
2198
] | [
720,
1542,
2153,
2172,
2186,
2201
] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/templatetags/__init__.py | [] | [] | [] |
|
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/templatetags/app_filters.py | import os
from html import unescape
from typing import Any, Dict, List, Optional
import markdown
import markdown.extensions.admonition
import markdown.extensions.codehilite
import markdown.extensions.extra
import markdown.extensions.toc
import markdown_include.include
from django.conf import settings
from django.template import Library, engines, loader
from django.utils.safestring import mark_safe
from jinja2.exceptions import TemplateNotFound
import zerver.lib.bugdown.fenced_code
import zerver.lib.bugdown.api_arguments_table_generator
import zerver.lib.bugdown.api_code_examples
import zerver.lib.bugdown.nested_code_blocks
import zerver.lib.bugdown.tabbed_sections
import zerver.lib.bugdown.help_settings_links
import zerver.lib.bugdown.help_relative_links
import zerver.lib.bugdown.help_emoticon_translations_table
from zerver.context_processors import zulip_default_context
from zerver.lib.cache import ignore_unhashable_lru_cache
register = Library()
def and_n_others(values: List[str], limit: int) -> str:
# A helper for the commonly appended "and N other(s)" string, with
# the appropriate pluralization.
return " and %d other%s" % (len(values) - limit,
"" if len(values) == limit + 1 else "s")
@register.filter(name='display_list', is_safe=True)
def display_list(values: List[str], display_limit: int) -> str:
"""
Given a list of values, return a string nicely formatting those values,
summarizing when you have more than `display_limit`. Eg, for a
`display_limit` of 3 we get the following possible cases:
Jessica
Jessica and Waseem
Jessica, Waseem, and Tim
Jessica, Waseem, Tim, and 1 other
Jessica, Waseem, Tim, and 2 others
"""
if len(values) == 1:
# One value, show it.
display_string = "%s" % (values[0],)
elif len(values) <= display_limit:
# Fewer than `display_limit` values, show all of them.
display_string = ", ".join(
"%s" % (value,) for value in values[:-1])
display_string += " and %s" % (values[-1],)
else:
# More than `display_limit` values, only mention a few.
display_string = ", ".join(
"%s" % (value,) for value in values[:display_limit])
display_string += and_n_others(values, display_limit)
return display_string
md_extensions = None # type: Optional[List[Any]]
md_macro_extension = None # type: Optional[Any]
# Prevent the automatic substitution of macros in these docs. If
# they contain a macro, it is always used literally for documenting
# the macro system.
docs_without_macros = [
"incoming-webhooks-walkthrough.md",
]
# Much of the time, render_markdown_path is called with hashable
# arguments, so this decorator is effective even though it only caches
# the results when called if none of the arguments are unhashable.
@ignore_unhashable_lru_cache(512)
@register.filter(name='render_markdown_path', is_safe=True)
def render_markdown_path(markdown_file_path: str,
context: Optional[Dict[Any, Any]]=None,
pure_markdown: Optional[bool]=False) -> str:
"""Given a path to a markdown file, return the rendered html.
Note that this assumes that any HTML in the markdown file is
trusted; it is intended to be used for documentation, not user
data."""
if context is None:
context = {}
# We set this global hackishly
from zerver.lib.bugdown.help_settings_links import set_relative_settings_links
set_relative_settings_links(bool(context.get('html_settings_links')))
from zerver.lib.bugdown.help_relative_links import set_relative_help_links
set_relative_help_links(bool(context.get('html_settings_links')))
global md_extensions
global md_macro_extension
if md_extensions is None:
md_extensions = [
markdown.extensions.extra.makeExtension(),
markdown.extensions.toc.makeExtension(),
markdown.extensions.admonition.makeExtension(),
markdown.extensions.codehilite.makeExtension(
linenums=False,
guess_lang=False
),
zerver.lib.bugdown.fenced_code.makeExtension(),
zerver.lib.bugdown.api_arguments_table_generator.makeExtension(
base_path='templates/zerver/api/'),
zerver.lib.bugdown.api_code_examples.makeExtension(),
zerver.lib.bugdown.nested_code_blocks.makeExtension(),
zerver.lib.bugdown.tabbed_sections.makeExtension(),
zerver.lib.bugdown.help_settings_links.makeExtension(),
zerver.lib.bugdown.help_relative_links.makeExtension(),
zerver.lib.bugdown.help_emoticon_translations_table.makeExtension(),
]
if md_macro_extension is None:
md_macro_extension = markdown_include.include.makeExtension(
base_path='templates/zerver/help/include/')
if any(doc in markdown_file_path for doc in docs_without_macros):
md_engine = markdown.Markdown(extensions=md_extensions)
else:
md_engine = markdown.Markdown(extensions=md_extensions + [md_macro_extension])
md_engine.reset()
jinja = engines['Jinja2']
try:
# By default, we do both Jinja2 templating and markdown
# processing on the file, to make it easy to use both Jinja2
# context variables and markdown includes in the file.
markdown_string = jinja.env.loader.get_source(jinja.env, markdown_file_path)[0]
except TemplateNotFound as e:
if pure_markdown:
# For files such as /etc/zulip/terms.md where we don't intend
# to use Jinja2 template variables, we still try to load the
# template using Jinja2 (in case the file path isn't absolute
# and does happen to be in Jinja's recognized template
# directories), and if that fails, we try to load it directly
# from disk.
with open(markdown_file_path) as fp:
markdown_string = fp.read()
else:
raise e
html = md_engine.convert(markdown_string)
rendered_html = jinja.from_string(html).render(context)
if context.get('unescape_rendered_html', False):
# In some exceptional cases (such as our Freshdesk webhook docs),
# code blocks in some of our Markdown templates have characters such
# as '{' encoded as '{' to prevent clashes with Jinja2 syntax,
# but the encoded form never gets decoded because the text ends up
# inside a <pre> tag. So here, we explicitly "unescape" such characters
# if 'unescape_rendered_html' is True.
rendered_html = unescape(rendered_html)
return mark_safe(rendered_html)
| [
"List[str]",
"int",
"List[str]",
"int",
"str"
] | [
991,
1009,
1334,
1360,
3006
] | [
1000,
1012,
1343,
1363,
3009
] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/templatetags/minified_js.py | from typing import Any, Dict
from django.conf import settings
from django.contrib.staticfiles.storage import staticfiles_storage
from django.template import Library, Node
register = Library()
class MinifiedJSNode(Node):
def __init__(self, sourcefile: str, csp_nonce: str) -> None:
self.sourcefile = sourcefile
self.csp_nonce = csp_nonce
def render(self, context: Dict[str, Any]) -> str:
if settings.DEBUG:
source_files = settings.JS_SPECS[self.sourcefile]
normal_source = source_files['source_filenames']
minified_source = source_files.get('minifed_source_filenames', [])
# Minified source files (most likely libraries) should be loaded
# first to prevent any dependency errors.
scripts = minified_source + normal_source
else:
scripts = [settings.JS_SPECS[self.sourcefile]['output_filename']]
script_urls = [staticfiles_storage.url(script) for script in scripts]
script_tags = ['<script nonce="%s" src="%s"></script>' % (self.csp_nonce, url)
for url in script_urls]
return '\n'.join(script_tags)
| [
"str",
"str",
"Dict[str, Any]"
] | [
259,
275,
392
] | [
262,
278,
406
] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/tests/__init__.py | [] | [] | [] |
|
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/tests/test_alert_words.py | # -*- coding: utf-8 -*-
from zerver.lib.alert_words import (
add_user_alert_words,
alert_words_in_realm,
remove_user_alert_words,
user_alert_words,
)
from zerver.lib.test_helpers import (
most_recent_message,
most_recent_usermessage,
)
from zerver.lib.test_classes import (
ZulipTestCase,
)
from zerver.models import (
Recipient,
UserProfile,
)
import ujson
class AlertWordTests(ZulipTestCase):
interesting_alert_word_list = ['alert', 'multi-word word', u'☃']
def test_internal_endpoint(self) -> None:
user_name = "cordelia"
email = self.example_email(user_name)
self.login(email)
params = {
'alert_words': ujson.dumps(['milk', 'cookies'])
}
result = self.client_post('/json/users/me/alert_words', params)
self.assert_json_success(result)
user = self.example_user(user_name)
words = user_alert_words(user)
self.assertEqual(words, ['milk', 'cookies'])
def test_default_no_words(self) -> None:
"""
Users start out with no alert words.
"""
user = self.example_user('cordelia')
words = user_alert_words(user)
self.assertEqual(words, [])
def test_add_word(self) -> None:
"""
add_user_alert_words can add multiple alert words at once.
"""
user = self.example_user('cordelia')
# Add several words, including multi-word and non-ascii words.
add_user_alert_words(user, self.interesting_alert_word_list)
words = user_alert_words(user)
self.assertEqual(words, self.interesting_alert_word_list)
def test_remove_word(self) -> None:
"""
Removing alert words works via remove_user_alert_words, even
for multi-word and non-ascii words.
"""
user = self.example_user('cordelia')
add_user_alert_words(user, self.interesting_alert_word_list)
theoretical_remaining_alerts = self.interesting_alert_word_list[:]
for alert_word in self.interesting_alert_word_list:
remove_user_alert_words(user, alert_word)
theoretical_remaining_alerts.remove(alert_word)
actual_remaining_alerts = user_alert_words(user)
self.assertEqual(actual_remaining_alerts,
theoretical_remaining_alerts)
def test_realm_words(self) -> None:
"""
We can gather alert words for an entire realm via
alert_words_in_realm. Alerts added for one user do not impact other
users.
"""
user1 = self.example_user('cordelia')
add_user_alert_words(user1, self.interesting_alert_word_list)
user2 = self.example_user('othello')
add_user_alert_words(user2, ['another'])
realm_words = alert_words_in_realm(user2.realm)
self.assertEqual(len(realm_words), 2)
self.assertEqual(list(realm_words.keys()), [user1.id, user2.id])
self.assertEqual(realm_words[user1.id],
self.interesting_alert_word_list)
self.assertEqual(realm_words[user2.id], ['another'])
def test_json_list_default(self) -> None:
self.login(self.example_email("hamlet"))
result = self.client_get('/json/users/me/alert_words')
self.assert_json_success(result)
self.assertEqual(result.json()['alert_words'], [])
def test_json_list_nonempty(self) -> None:
hamlet = self.example_user('hamlet')
add_user_alert_words(hamlet, ['one', 'two', 'three'])
self.login(self.example_email('hamlet'))
result = self.client_get('/json/users/me/alert_words')
self.assert_json_success(result)
self.assertEqual(result.json()['alert_words'], ['one', 'two', 'three'])
def test_json_list_add(self) -> None:
self.login(self.example_email("hamlet"))
result = self.client_post('/json/users/me/alert_words', {'alert_words': ujson.dumps(['one ', '\n two', 'three'])})
self.assert_json_success(result)
self.assertEqual(result.json()['alert_words'], ['one', 'two', 'three'])
def test_json_list_remove(self) -> None:
self.login(self.example_email("hamlet"))
result = self.client_post('/json/users/me/alert_words', {'alert_words': ujson.dumps(['one', 'two', 'three'])})
self.assert_json_success(result)
self.assertEqual(result.json()['alert_words'], ['one', 'two', 'three'])
result = self.client_delete('/json/users/me/alert_words', {'alert_words': ujson.dumps(['one'])})
self.assert_json_success(result)
self.assertEqual(result.json()['alert_words'], ['two', 'three'])
def message_does_alert(self, user_profile: UserProfile, message: str) -> bool:
"""Send a bunch of messages as othello, so Hamlet is notified"""
self.send_stream_message(self.example_email("othello"), "Denmark", message)
user_message = most_recent_usermessage(user_profile)
return 'has_alert_word' in user_message.flags_list()
def test_alert_flags(self) -> None:
self.login(self.example_email("hamlet"))
user_profile_hamlet = self.example_user('hamlet')
result = self.client_post('/json/users/me/alert_words', {'alert_words': ujson.dumps(['one', 'two', 'three'])})
self.assert_json_success(result)
self.assertEqual(result.json()['alert_words'], ['one', 'two', 'three'])
# Alerts in the middle of messages work.
self.assertTrue(self.message_does_alert(user_profile_hamlet, "Normal alert one time"))
# Alerts at the end of messages work.
self.assertTrue(self.message_does_alert(user_profile_hamlet, "Normal alert one"))
# Alerts at the beginning of messages work.
self.assertTrue(self.message_does_alert(user_profile_hamlet, "two normal alerts"))
# Alerts with surrounding punctuation work.
self.assertTrue(self.message_does_alert(user_profile_hamlet, "This one? should alert"))
self.assertTrue(self.message_does_alert(user_profile_hamlet, "Definitely time for three."))
# Multiple alerts in a message work.
self.assertTrue(self.message_does_alert(user_profile_hamlet, "One two three o'clock"))
# Alerts are case-insensitive.
self.assertTrue(self.message_does_alert(user_profile_hamlet, "One o'clock"))
self.assertTrue(self.message_does_alert(user_profile_hamlet, "Case of ONE, won't stop me"))
# We don't cause alerts for matches in URLs.
self.assertFalse(self.message_does_alert(user_profile_hamlet, "Don't alert on http://t.co/one/ urls"))
self.assertFalse(self.message_does_alert(user_profile_hamlet, "Don't alert on http://t.co/one urls"))
def test_update_alert_words(self) -> None:
user_profile = self.example_user('hamlet')
me_email = user_profile.email
self.login(me_email)
result = self.client_post('/json/users/me/alert_words', {'alert_words': ujson.dumps(['ALERT'])})
content = 'this is an ALERT for you'
self.send_stream_message(me_email, "Denmark", content)
self.assert_json_success(result)
original_message = most_recent_message(user_profile)
user_message = most_recent_usermessage(user_profile)
self.assertIn('has_alert_word', user_message.flags_list())
result = self.client_patch("/json/messages/" + str(original_message.id), {
'message_id': original_message.id,
'content': 'new ALERT for you',
})
self.assert_json_success(result)
user_message = most_recent_usermessage(user_profile)
self.assertEqual(user_message.message.content, 'new ALERT for you')
self.assertIn('has_alert_word', user_message.flags_list())
result = self.client_patch("/json/messages/" + str(original_message.id), {
'message_id': original_message.id,
'content': 'sorry false alarm',
})
self.assert_json_success(result)
user_message = most_recent_usermessage(user_profile)
self.assertEqual(user_message.message.content, 'sorry false alarm')
self.assertNotIn('has_alert_word', user_message.flags_list())
| [
"UserProfile",
"str"
] | [
4731,
4753
] | [
4742,
4756
] |
archives/18-2-SKKU-OSS_2018-2-OSS-L5.zip | zerver/tests/test_archive.py | # -*- coding: utf-8 -*-
from django.http import HttpResponse
from zerver.lib.test_classes import ZulipTestCase
from zerver.lib.actions import do_change_stream_web_public
from zerver.lib.actions import get_web_public_streams, get_web_public_subs, \
do_deactivate_stream
from zerver.models import get_realm
class GlobalPublicStreamTest(ZulipTestCase):
def test_non_existant_stream_id(self) -> None:
# Here we use a relatively big number as stream id assumming such an id
# won't exist in the test DB.
result = self.client_get("/archive/streams/100000000/topics/TopicGlobal")
self.assert_in_success_response(["This stream does not exist."], result)
def test_non_web_public_stream(self) -> None:
test_stream = self.make_stream('Test Public Archives')
result = self.client_get(
"/archive/streams/" + str(test_stream.id) + "/topics/notpublicglobalstream"
)
self.assert_in_success_response(["This stream does not exist."], result)
def test_non_existant_topic(self) -> None:
test_stream = self.make_stream('Test Public Archives')
do_change_stream_web_public(test_stream, True)
result = self.client_get(
"/archive/streams/" + str(test_stream.id) + "/topics/nonexistenttopic"
)
self.assert_in_success_response(["This topic does not exist."], result)
def test_web_public_stream_topic(self) -> None:
test_stream = self.make_stream('Test Public Archives')
do_change_stream_web_public(test_stream, True)
def send_msg_and_get_result(msg: str) -> HttpResponse:
self.send_stream_message(
self.example_email("iago"),
"Test Public Archives",
msg,
'TopicGlobal'
)
return self.client_get(
"/archive/streams/" + str(test_stream.id) + "/topics/TopicGlobal"
)
result = send_msg_and_get_result('Test Message 1')
self.assert_in_success_response(["Test Message 1"], result)
result = send_msg_and_get_result('/me goes testing.')
self.assert_in_success_response(["goes testing."], result)
def test_get_web_public_streams(self) -> None:
realm = get_realm("zulip")
public_streams = get_web_public_streams(realm)
self.assert_length(public_streams, 1)
public_stream = public_streams[0]
self.assertEqual(public_stream['name'], "Rome")
public_subs, public_unsubs, public_neversubs = get_web_public_subs(realm)
self.assert_length(public_subs, 1)
public_sub = public_subs[0]
self.assertEqual(public_sub['name'], "Rome")
self.assert_length(public_unsubs, 0)
self.assert_length(public_neversubs, 0)
# Now add a second public stream
test_stream = self.make_stream('Test Public Archives')
do_change_stream_web_public(test_stream, True)
public_streams = get_web_public_streams(realm)
self.assert_length(public_streams, 2)
public_subs, public_unsubs, public_neversubs = get_web_public_subs(realm)
self.assert_length(public_subs, 2)
self.assert_length(public_unsubs, 0)
self.assert_length(public_neversubs, 0)
self.assertNotEqual(public_subs[0]['color'], public_subs[1]['color'])
do_deactivate_stream(test_stream)
public_streams = get_web_public_streams(realm)
self.assert_length(public_streams, 1)
public_subs, public_unsubs, public_neversubs = get_web_public_subs(realm)
self.assert_length(public_subs, 1)
self.assert_length(public_unsubs, 0)
self.assert_length(public_neversubs, 0)
class WebPublicTopicHistoryTest(ZulipTestCase):
def test_non_existant_stream_id(self) -> None:
result = self.client_get("/archive/streams/100000000/topics")
self.assert_json_success(result)
history = result.json()['topics']
self.assertEqual(history, [])
def test_non_web_public_stream(self) -> None:
test_stream = self.make_stream('Test Public Archives')
self.send_stream_message(
self.example_email("iago"),
"Test Public Archives",
'Test Message',
'TopicGlobal'
)
result = self.client_get(
"/archive/streams/" + str(test_stream.id) + "/topics"
)
self.assert_json_success(result)
history = result.json()['topics']
self.assertEqual(history, [])
def test_web_public_stream(self) -> None:
test_stream = self.make_stream('Test Public Archives')
do_change_stream_web_public(test_stream, True)
self.send_stream_message(
self.example_email("iago"),
"Test Public Archives",
'Test Message 3',
topic_name='first_topic'
)
self.send_stream_message(
self.example_email("iago"),
"Test Public Archives",
'Test Message',
topic_name='TopicGlobal'
)
self.send_stream_message(
self.example_email("iago"),
"Test Public Archives",
'Test Message 2',
topic_name='topicglobal'
)
self.send_stream_message(
self.example_email("iago"),
"Test Public Archives",
'Test Message 3',
topic_name='second_topic'
)
self.send_stream_message(
self.example_email("iago"),
"Test Public Archives",
'Test Message 4',
topic_name='TopicGlobal'
)
result = self.client_get(
"/archive/streams/" + str(test_stream.id) + "/topics"
)
self.assert_json_success(result)
history = result.json()['topics']
self.assert_length(history, 3)
# Should be sorted with latest topic first
self.assertEqual(history[0]['name'], 'TopicGlobal')
self.assertEqual(history[1]['name'], 'second_topic')
self.assertEqual(history[2]['name'], 'first_topic')
| [
"str"
] | [
1600
] | [
1603
] |
Subsets and Splits