2013-10-10 21:37:26 +02:00
|
|
|
from __future__ import absolute_import
|
|
|
|
|
2015-12-26 02:19:28 +01:00
|
|
|
from django.db.models import Q
|
2016-03-21 06:02:48 +01:00
|
|
|
from zerver.models import UserProfile, Realm
|
2013-09-06 20:50:25 +02:00
|
|
|
from zerver.lib.cache import cache_with_key, realm_alert_words_cache_key
|
2013-09-03 22:41:17 +02:00
|
|
|
import ujson
|
2016-03-11 10:57:29 +01:00
|
|
|
import six
|
2016-12-21 13:17:53 +01:00
|
|
|
from typing import Dict, Iterable, List, Text
|
2013-09-03 22:41:17 +02:00
|
|
|
|
2013-09-06 20:50:25 +02:00
|
|
|
@cache_with_key(realm_alert_words_cache_key, timeout=3600*24)
|
2013-09-03 22:41:17 +02:00
|
|
|
def alert_words_in_realm(realm):
|
2016-12-21 13:17:53 +01:00
|
|
|
# type: (Realm) -> Dict[int, List[Text]]
|
2016-03-21 06:02:48 +01:00
|
|
|
users_query = UserProfile.objects.filter(realm=realm, is_active=True)
|
2015-12-26 02:19:28 +01:00
|
|
|
alert_word_data = users_query.filter(~Q(alert_words=ujson.dumps([]))).values('id', 'alert_words')
|
|
|
|
all_user_words = dict((elt['id'], ujson.loads(elt['alert_words'])) for elt in alert_word_data)
|
2016-03-11 10:57:29 +01:00
|
|
|
user_ids_with_words = dict((user_id, w) for (user_id, w) in six.iteritems(all_user_words) if len(w))
|
2013-10-09 20:48:05 +02:00
|
|
|
return user_ids_with_words
|
2013-09-03 22:41:17 +02:00
|
|
|
|
|
|
|
def user_alert_words(user_profile):
|
2016-12-21 13:17:53 +01:00
|
|
|
# type: (UserProfile) -> List[Text]
|
2013-09-03 22:41:17 +02:00
|
|
|
return ujson.loads(user_profile.alert_words)
|
|
|
|
|
|
|
|
def add_user_alert_words(user_profile, alert_words):
|
2016-12-21 13:17:53 +01:00
|
|
|
# type: (UserProfile, Iterable[Text]) -> List[Text]
|
2013-09-03 22:41:17 +02:00
|
|
|
words = user_alert_words(user_profile)
|
|
|
|
|
2016-05-10 01:55:43 +02:00
|
|
|
new_words = [w for w in alert_words if w not in words]
|
2013-09-03 22:41:17 +02:00
|
|
|
words.extend(new_words)
|
|
|
|
|
|
|
|
set_user_alert_words(user_profile, words)
|
|
|
|
|
2013-09-11 17:24:27 +02:00
|
|
|
return words
|
|
|
|
|
2013-09-03 22:41:17 +02:00
|
|
|
def remove_user_alert_words(user_profile, alert_words):
|
2016-12-21 13:17:53 +01:00
|
|
|
# type: (UserProfile, Iterable[Text]) -> List[Text]
|
2013-09-03 22:41:17 +02:00
|
|
|
words = user_alert_words(user_profile)
|
2016-05-10 01:55:43 +02:00
|
|
|
words = [w for w in words if w not in alert_words]
|
2013-09-03 22:41:17 +02:00
|
|
|
|
|
|
|
set_user_alert_words(user_profile, words)
|
|
|
|
|
2013-09-11 17:24:27 +02:00
|
|
|
return words
|
|
|
|
|
2013-09-03 22:41:17 +02:00
|
|
|
def set_user_alert_words(user_profile, alert_words):
|
2016-12-21 13:17:53 +01:00
|
|
|
# type: (UserProfile, List[Text]) -> None
|
2013-09-03 22:41:17 +02:00
|
|
|
user_profile.alert_words = ujson.dumps(alert_words)
|
|
|
|
user_profile.save(update_fields=['alert_words'])
|