Advertisement
Guest User

Untitled

a guest
Nov 30th, 2016
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 159.90 KB | None | 0 0
  1. from __future__ import absolute_import
  2. from __future__ import print_function
  3. from typing import (
  4. AbstractSet, Any, AnyStr, Callable, Dict, Iterable, Mapping, MutableMapping,
  5. Optional, Sequence, Set, Tuple, TypeVar, Union
  6. )
  7.  
  8. from django.utils.translation import ugettext as _
  9. from django.conf import settings
  10. from django.core import validators
  11. from django.contrib.sessions.models import Session
  12. from zerver.lib.bugdown import (
  13. BugdownRenderingException,
  14. version as bugdown_version
  15. )
  16. from zerver.lib.cache import (
  17. to_dict_cache_key,
  18. to_dict_cache_key_id,
  19. )
  20. from zerver.lib.context_managers import lockfile
  21. from zerver.lib.message import (
  22. access_message,
  23. MessageDict,
  24. message_to_dict,
  25. render_markdown,
  26. )
  27. from zerver.models import Realm, RealmEmoji, Stream, UserProfile, UserActivity, RealmAlias, \
  28. Subscription, Recipient, Message, Attachment, UserMessage, valid_stream_name, \
  29. Client, DefaultStream, UserPresence, Referral, PushDeviceToken, MAX_SUBJECT_LENGTH, \
  30. MAX_MESSAGE_LENGTH, get_client, get_stream, get_recipient, get_huddle, \
  31. get_user_profile_by_id, PreregistrationUser, get_display_recipient, \
  32. get_realm, get_realm_by_string_id, bulk_get_recipients, \
  33. email_allowed_for_realm, email_to_username, display_recipient_cache_key, \
  34. get_user_profile_by_email, get_stream_cache_key, \
  35. UserActivityInterval, get_active_user_dicts_in_realm, get_active_streams, \
  36. realm_filters_for_domain, RealmFilter, receives_offline_notifications, \
  37. ScheduledJob, realm_filters_for_domain, get_owned_bot_dicts, \
  38. get_old_unclaimed_attachments, get_cross_realm_emails, receives_online_notifications
  39.  
  40. from zerver.lib.alert_words import alert_words_in_realm
  41. from zerver.lib.avatar import get_avatar_url, avatar_url
  42.  
  43. from django.db import transaction, IntegrityError, connection
  44. from django.db.models import F, Q
  45. from django.db.models.query import QuerySet
  46. from django.core.exceptions import ValidationError
  47. from importlib import import_module
  48. from django.core.mail import EmailMessage
  49. from django.utils.timezone import now
  50.  
  51. from confirmation.models import Confirmation
  52. import six
  53. from six import text_type
  54. from six.moves import filter
  55. from six.moves import map
  56. from six.moves import range
  57. from six import unichr
  58.  
  59. session_engine = import_module(settings.SESSION_ENGINE)
  60.  
  61. from zerver.lib.create_user import random_api_key
  62. from zerver.lib.timestamp import timestamp_to_datetime, datetime_to_timestamp
  63. from zerver.lib.queue import queue_json_publish
  64. from django.utils import timezone
  65. from zerver.lib.create_user import create_user
  66. from zerver.lib import bugdown
  67. from zerver.lib.cache import cache_with_key, cache_set, \
  68. user_profile_by_email_cache_key, cache_set_many, \
  69. cache_delete, cache_delete_many
  70. from zerver.decorator import statsd_increment
  71. from zerver.lib.event_queue import request_event_queue, get_user_events, send_event
  72. from zerver.lib.utils import log_statsd_event, statsd
  73. from zerver.lib.html_diff import highlight_html_differences
  74. from zerver.lib.alert_words import user_alert_words, add_user_alert_words, \
  75. remove_user_alert_words, set_user_alert_words
  76. from zerver.lib.push_notifications import num_push_devices_for_user, \
  77. send_apple_push_notification, send_android_push_notification
  78. from zerver.lib.notifications import clear_followup_emails_queue
  79. from zerver.lib.narrow import check_supported_events_narrow_filter
  80. from zerver.lib.request import JsonableError
  81. from zerver.lib.session_user import get_session_user
  82. from zerver.lib.upload import attachment_url_re, attachment_url_to_path_id, \
  83. claim_attachment, delete_message_image
  84. from zerver.lib.str_utils import NonBinaryStr, force_str
  85.  
  86. import DNS
  87. import ujson
  88. import time
  89. import traceback
  90. import re
  91. import datetime
  92. import os
  93. import platform
  94. import logging
  95. import itertools
  96. from collections import defaultdict
  97. import copy
  98.  
  99. # This will be used to type annotate parameters in a function if the function
  100. # works on both str and unicode in python 2 but in python 3 it only works on str.
  101. SizedTextIterable = Union[Sequence[text_type], AbstractSet[text_type]]
  102.  
  103. STREAM_ASSIGNMENT_COLORS = [
  104. "#76ce90", "#fae589", "#a6c7e5", "#e79ab5",
  105. "#bfd56f", "#f4ae55", "#b0a5fd", "#addfe5",
  106. "#f5ce6e", "#c2726a", "#94c849", "#bd86e5",
  107. "#ee7e4a", "#a6dcbf", "#95a5fd", "#53a063",
  108. "#9987e1", "#e4523d", "#c2c2c2", "#4f8de4",
  109. "#c6a8ad", "#e7cc4d", "#c8bebf", "#a47462"]
  110.  
  111. # Store an event in the log for re-importing messages
  112. def log_event(event):
  113. # type: (MutableMapping[str, Any]) -> None
  114. if settings.EVENT_LOG_DIR is None:
  115. return
  116.  
  117. if "timestamp" not in event:
  118. event["timestamp"] = time.time()
  119.  
  120. if not os.path.exists(settings.EVENT_LOG_DIR):
  121. os.mkdir(settings.EVENT_LOG_DIR)
  122.  
  123. template = os.path.join(settings.EVENT_LOG_DIR,
  124. '%s.' + platform.node()
  125. + datetime.datetime.now().strftime('.%Y-%m-%d'))
  126.  
  127. with lockfile(template % ('lock',)):
  128. with open(template % ('events',), 'a') as log:
  129. log.write(force_str(ujson.dumps(event) + u'\n'))
  130.  
  131. def active_user_ids(realm):
  132. # type: (Realm) -> List[int]
  133. return [userdict['id'] for userdict in get_active_user_dicts_in_realm(realm)]
  134.  
  135. def can_access_stream_user_ids(stream):
  136. # type: (Stream) -> Set[int]
  137.  
  138. # return user ids of users who can access the attributes of
  139. # a stream, such as its name/description
  140. if stream.is_public():
  141. return set(active_user_ids(stream.realm))
  142. else:
  143. return private_stream_user_ids(stream)
  144.  
  145. def private_stream_user_ids(stream):
  146. # type: (Stream) -> Set[int]
  147.  
  148. # TODO: Find similar queries elsewhere and de-duplicate this code.
  149. subscriptions = Subscription.objects.filter(
  150. recipient__type=Recipient.STREAM,
  151. recipient__type_id=stream.id,
  152. active=True)
  153.  
  154. return {sub['user_profile_id'] for sub in subscriptions.values('user_profile_id')}
  155.  
  156. def bot_owner_userids(user_profile):
  157. # type: (UserProfile) -> Sequence[int]
  158. is_private_bot = (
  159. user_profile.default_sending_stream and user_profile.default_sending_stream.invite_only or
  160. user_profile.default_events_register_stream and user_profile.default_events_register_stream.invite_only)
  161. if is_private_bot:
  162. return (user_profile.bot_owner_id,) # TODO: change this to list instead of tuple
  163. else:
  164. return active_user_ids(user_profile.realm)
  165.  
  166. def realm_user_count(realm):
  167. # type: (Realm) -> int
  168. return UserProfile.objects.filter(realm=realm, is_active=True, is_bot=False).count()
  169.  
  170. def get_topic_history_for_stream(user_profile, recipient):
  171. # type: (UserProfile, Recipient) -> List[Tuple[str, int]]
  172.  
  173. # We tested the below query on some large prod datasets, and we never
  174. # saw more than 50ms to execute it, so we think that's acceptable,
  175. # but we will monitor it, and we may later optimize it further.
  176. query = '''
  177. SELECT topic, read, count(*)
  178. FROM (
  179. SELECT
  180. ("zerver_usermessage"."flags" & 1) as read,
  181. "zerver_message"."subject" as topic,
  182. "zerver_message"."id" as message_id
  183. FROM "zerver_usermessage"
  184. INNER JOIN "zerver_message" ON (
  185. "zerver_usermessage"."message_id" = "zerver_message"."id"
  186. ) WHERE (
  187. "zerver_usermessage"."user_profile_id" = %s AND
  188. "zerver_message"."recipient_id" = %s
  189. ) ORDER BY "zerver_usermessage"."message_id" DESC
  190. ) messages_for_stream
  191. GROUP BY topic, read
  192. ORDER BY max(message_id) desc
  193. '''
  194. cursor = connection.cursor()
  195. cursor.execute(query, [user_profile.id, recipient.id])
  196. rows = cursor.fetchall()
  197. cursor.close()
  198.  
  199. topic_names = dict() # type: Dict[str, str]
  200. topic_counts = dict() # type: Dict[str, int]
  201. topics = []
  202. for row in rows:
  203. topic_name, read, count = row
  204. if topic_name.lower() not in topic_names:
  205. topic_names[topic_name.lower()] = topic_name
  206. topic_name = topic_names[topic_name.lower()]
  207. if topic_name not in topic_counts:
  208. topic_counts[topic_name] = 0
  209. topics.append(topic_name)
  210. if not read:
  211. topic_counts[topic_name] += count
  212.  
  213. history = [(topic, topic_counts[topic]) for topic in topics]
  214. return history
  215.  
  216. def send_signup_message(sender, signups_stream, user_profile,
  217. internal=False, realm=None):
  218. # type: (UserProfile, text_type, UserProfile, bool, Optional[Realm]) -> None
  219. if internal:
  220. # When this is done using manage.py vs. the web interface
  221. internal_blurb = " **INTERNAL SIGNUP** "
  222. else:
  223. internal_blurb = " "
  224.  
  225. user_count = realm_user_count(user_profile.realm)
  226. # Send notification to realm notifications stream if it exists
  227. # Don't send notification for the first user in a realm
  228. if user_profile.realm.notifications_stream is not None and user_count > 1:
  229. internal_send_message(sender, "stream",
  230. user_profile.realm.notifications_stream.name,
  231. "New users", "%s just signed up for Zulip. Say hello!" % \
  232. (user_profile.full_name,),
  233. realm=user_profile.realm)
  234.  
  235. internal_send_message(sender,
  236. "stream", signups_stream, user_profile.realm.domain,
  237. "%s <`%s`> just signed up for Zulip!%s(total: **%i**)" % (
  238. user_profile.full_name,
  239. user_profile.email,
  240. internal_blurb,
  241. user_count,
  242. )
  243. )
  244.  
  245. def notify_new_user(user_profile, internal=False):
  246. # type: (UserProfile, bool) -> None
  247. if settings.NEW_USER_BOT is not None:
  248. send_signup_message(settings.NEW_USER_BOT, "signups", user_profile, internal)
  249. statsd.gauge("users.signups.%s" % (user_profile.realm.domain.replace('.', '_')), 1, delta=True)
  250.  
  251. def add_new_user_history(user_profile, streams):
  252. # type: (UserProfile, Iterable[Stream]) -> None
  253. """Give you the last 100 messages on your public streams, so you have
  254. something to look at in your home view once you finish the
  255. tutorial."""
  256. one_week_ago = now() - datetime.timedelta(weeks=1)
  257. recipients = Recipient.objects.filter(type=Recipient.STREAM,
  258. type_id__in=[stream.id for stream in streams
  259. if not stream.invite_only])
  260. recent_messages = Message.objects.filter(recipient_id__in=recipients,
  261. pub_date__gt=one_week_ago).order_by("-id")
  262. message_ids_to_use = list(reversed(recent_messages.values_list('id', flat=True)[0:100]))
  263. if len(message_ids_to_use) == 0:
  264. return
  265.  
  266. # Handle the race condition where a message arrives between
  267. # bulk_add_subscriptions above and the Message query just above
  268. already_ids = set(UserMessage.objects.filter(message_id__in=message_ids_to_use,
  269. user_profile=user_profile).values_list("message_id", flat=True))
  270. ums_to_create = [UserMessage(user_profile=user_profile, message_id=message_id,
  271. flags=UserMessage.flags.read)
  272. for message_id in message_ids_to_use
  273. if message_id not in already_ids]
  274.  
  275. UserMessage.objects.bulk_create(ums_to_create)
  276.  
  277. # Does the processing for a new user account:
  278. # * Subscribes to default/invitation streams
  279. # * Fills in some recent historical messages
  280. # * Notifies other users in realm and Zulip about the signup
  281. # * Deactivates PreregistrationUser objects
  282. # * subscribe the user to newsletter if newsletter_data is specified
  283. def process_new_human_user(user_profile, prereg_user=None, newsletter_data=None):
  284. # type: (UserProfile, Optional[PreregistrationUser], Optional[Dict[str, str]]) -> None
  285. mit_beta_user = user_profile.realm.is_zephyr_mirror_realm
  286. try:
  287. streams = prereg_user.streams.all()
  288. except AttributeError:
  289. # This will catch both the case where prereg_user is None and where it
  290. # is a MitUser.
  291. streams = []
  292.  
  293. # If the user's invitation didn't explicitly list some streams, we
  294. # add the default streams
  295. if len(streams) == 0:
  296. streams = get_default_subs(user_profile)
  297. bulk_add_subscriptions(streams, [user_profile])
  298.  
  299. add_new_user_history(user_profile, streams)
  300.  
  301. # mit_beta_users don't have a referred_by field
  302. if not mit_beta_user and prereg_user is not None and prereg_user.referred_by is not None \
  303. and settings.NOTIFICATION_BOT is not None:
  304. # This is a cross-realm private message.
  305. internal_send_message(settings.NOTIFICATION_BOT,
  306. "private", prereg_user.referred_by.email, user_profile.realm.domain,
  307. "%s <`%s`> accepted your invitation to join Zulip!" % (
  308. user_profile.full_name,
  309. user_profile.email,
  310. )
  311. )
  312. # Mark any other PreregistrationUsers that are STATUS_ACTIVE as
  313. # inactive so we can keep track of the PreregistrationUser we
  314. # actually used for analytics
  315. if prereg_user is not None:
  316. PreregistrationUser.objects.filter(email__iexact=user_profile.email).exclude(
  317. id=prereg_user.id).update(status=0)
  318. else:
  319. PreregistrationUser.objects.filter(email__iexact=user_profile.email).update(status=0)
  320.  
  321. notify_new_user(user_profile)
  322.  
  323. if newsletter_data is not None:
  324. # If the user was created automatically via the API, we may
  325. # not want to register them for the newsletter
  326. queue_json_publish(
  327. "signups",
  328. {
  329. 'EMAIL': user_profile.email,
  330. 'merge_vars': {
  331. 'NAME': user_profile.full_name,
  332. 'REALM_ID': user_profile.realm.id,
  333. 'OPTIN_IP': newsletter_data["IP"],
  334. 'OPTIN_TIME': datetime.datetime.isoformat(now().replace(microsecond=0)),
  335. },
  336. },
  337. lambda event: None)
  338.  
  339. def notify_created_user(user_profile):
  340. # type: (UserProfile) -> None
  341. event = dict(type="realm_user", op="add",
  342. person=dict(email=user_profile.email,
  343. user_id=user_profile.id,
  344. is_admin=user_profile.is_realm_admin,
  345. full_name=user_profile.full_name,
  346. is_bot=user_profile.is_bot))
  347. send_event(event, active_user_ids(user_profile.realm))
  348.  
  349. def notify_created_bot(user_profile):
  350. # type: (UserProfile) -> None
  351.  
  352. def stream_name(stream):
  353. # type: (Stream) -> Optional[text_type]
  354. if not stream:
  355. return None
  356. return stream.name
  357.  
  358. default_sending_stream_name = stream_name(user_profile.default_sending_stream)
  359. default_events_register_stream_name = stream_name(user_profile.default_events_register_stream)
  360.  
  361. event = dict(type="realm_bot", op="add",
  362. bot=dict(email=user_profile.email,
  363. user_id=user_profile.id,
  364. full_name=user_profile.full_name,
  365. api_key=user_profile.api_key,
  366. default_sending_stream=default_sending_stream_name,
  367. default_events_register_stream=default_events_register_stream_name,
  368. default_all_public_streams=user_profile.default_all_public_streams,
  369. avatar_url=avatar_url(user_profile),
  370. owner=user_profile.bot_owner.email,
  371. ))
  372. send_event(event, bot_owner_userids(user_profile))
  373.  
  374. def do_create_user(email, password, realm, full_name, short_name,
  375. active=True, bot_type=None, bot_owner=None, tos_version=None,
  376. avatar_source=UserProfile.AVATAR_FROM_GRAVATAR,
  377. default_sending_stream=None, default_events_register_stream=None,
  378. default_all_public_streams=None, prereg_user=None,
  379. newsletter_data=None):
  380. # type: (text_type, text_type, Realm, text_type, text_type, bool, Optional[int], Optional[UserProfile], Optional[text_type], text_type, Optional[Stream], Optional[Stream], bool, Optional[PreregistrationUser], Optional[Dict[str, str]]) -> UserProfile
  381. event = {'type': 'user_created',
  382. 'timestamp': time.time(),
  383. 'full_name': full_name,
  384. 'short_name': short_name,
  385. 'user': email,
  386. 'domain': realm.domain,
  387. 'bot': bool(bot_type)}
  388. if bot_type:
  389. event['bot_owner'] = bot_owner.email
  390. log_event(event)
  391.  
  392. user_profile = create_user(email=email, password=password, realm=realm,
  393. full_name=full_name, short_name=short_name,
  394. active=active, bot_type=bot_type, bot_owner=bot_owner,
  395. tos_version=tos_version, avatar_source=avatar_source,
  396. default_sending_stream=default_sending_stream,
  397. default_events_register_stream=default_events_register_stream,
  398. default_all_public_streams=default_all_public_streams)
  399.  
  400. notify_created_user(user_profile)
  401. if bot_type:
  402. notify_created_bot(user_profile)
  403. else:
  404. process_new_human_user(user_profile, prereg_user=prereg_user,
  405. newsletter_data=newsletter_data)
  406. return user_profile
  407.  
  408. def user_sessions(user_profile):
  409. # type: (UserProfile) -> List[Session]
  410. return [s for s in Session.objects.all()
  411. if get_session_user(s) == user_profile.id]
  412.  
  413. def delete_session(session):
  414. # type: (Session) -> None
  415. session_engine.SessionStore(session.session_key).delete() # type: ignore # import_module
  416.  
  417. def delete_user_sessions(user_profile):
  418. # type: (UserProfile) -> None
  419. for session in Session.objects.all():
  420. if get_session_user(session) == user_profile.id:
  421. delete_session(session)
  422.  
  423. def delete_realm_user_sessions(realm):
  424. # type: (Realm) -> None
  425. realm_user_ids = [user_profile.id for user_profile in
  426. UserProfile.objects.filter(realm=realm)]
  427. for session in Session.objects.filter(expire_date__gte=datetime.datetime.now()):
  428. if get_session_user(session) in realm_user_ids:
  429. delete_session(session)
  430.  
  431. def delete_all_user_sessions():
  432. # type: () -> None
  433. for session in Session.objects.all():
  434. delete_session(session)
  435.  
  436. def delete_all_deactivated_user_sessions():
  437. # type: () -> None
  438. for session in Session.objects.all():
  439. user_profile_id = get_session_user(session)
  440. if user_profile_id is None:
  441. continue
  442. user_profile = get_user_profile_by_id(user_profile_id)
  443. if not user_profile.is_active or user_profile.realm.deactivated:
  444. logging.info("Deactivating session for deactivated user %s" % (user_profile.email,))
  445. delete_session(session)
  446.  
  447. def active_humans_in_realm(realm):
  448. # type: (Realm) -> Sequence[UserProfile]
  449. return UserProfile.objects.filter(realm=realm, is_active=True, is_bot=False)
  450.  
  451. def do_set_realm_name(realm, name):
  452. # type: (Realm, text_type) -> None
  453. realm.name = name
  454. realm.save(update_fields=['name'])
  455. event = dict(
  456. type="realm",
  457. op="update",
  458. property='name',
  459. value=name,
  460. )
  461. send_event(event, active_user_ids(realm))
  462.  
  463. def do_set_realm_restricted_to_domain(realm, restricted):
  464. # type: (Realm, bool) -> None
  465. realm.restricted_to_domain = restricted
  466. realm.save(update_fields=['restricted_to_domain'])
  467. event = dict(
  468. type="realm",
  469. op="update",
  470. property='restricted_to_domain',
  471. value=restricted,
  472. )
  473. send_event(event, active_user_ids(realm))
  474.  
  475. def do_set_realm_invite_required(realm, invite_required):
  476. # type: (Realm, bool) -> None
  477. realm.invite_required = invite_required
  478. realm.save(update_fields=['invite_required'])
  479. event = dict(
  480. type="realm",
  481. op="update",
  482. property='invite_required',
  483. value=invite_required,
  484. )
  485. send_event(event, active_user_ids(realm))
  486.  
  487. def do_set_realm_invite_by_admins_only(realm, invite_by_admins_only):
  488. # type: (Realm, bool) -> None
  489. realm.invite_by_admins_only = invite_by_admins_only
  490. realm.save(update_fields=['invite_by_admins_only'])
  491. event = dict(
  492. type="realm",
  493. op="update",
  494. property='invite_by_admins_only',
  495. value=invite_by_admins_only,
  496. )
  497. send_event(event, active_user_ids(realm))
  498.  
  499. def do_set_realm_authentication_methods(realm, authentication_methods):
  500. # type: (Realm, Dict[str, bool]) -> None
  501. for key, value in list(authentication_methods.items()):
  502. index = getattr(realm.authentication_methods, key).number
  503. realm.authentication_methods.set_bit(index, int(value))
  504. realm.save(update_fields=['authentication_methods'])
  505. event = dict(
  506. type="realm",
  507. op="update_dict",
  508. property='default',
  509. data=dict(authentication_methods=realm.authentication_methods_dict())
  510. )
  511. send_event(event, active_user_ids(realm))
  512.  
  513. def do_set_realm_create_stream_by_admins_only(realm, create_stream_by_admins_only):
  514. # type: (Realm, bool) -> None
  515. realm.create_stream_by_admins_only = create_stream_by_admins_only
  516. realm.save(update_fields=['create_stream_by_admins_only'])
  517. event = dict(
  518. type="realm",
  519. op="update",
  520. property='create_stream_by_admins_only',
  521. value=create_stream_by_admins_only,
  522. )
  523. send_event(event, active_user_ids(realm))
  524.  
  525. def do_set_realm_message_editing(realm, allow_message_editing, message_content_edit_limit_seconds):
  526. # type: (Realm, bool, int) -> None
  527. realm.allow_message_editing = allow_message_editing
  528. realm.message_content_edit_limit_seconds = message_content_edit_limit_seconds
  529. realm.save(update_fields=['allow_message_editing', 'message_content_edit_limit_seconds'])
  530. event = dict(
  531. type="realm",
  532. op="update_dict",
  533. property="default",
  534. data=dict(allow_message_editing=allow_message_editing,
  535. message_content_edit_limit_seconds=message_content_edit_limit_seconds),
  536. )
  537. send_event(event, active_user_ids(realm))
  538.  
  539. def do_set_realm_default_language(realm, default_language):
  540. # type: (Realm, text_type) -> None
  541.  
  542. if default_language == 'zh_CN':
  543. # NB: remove this once we upgrade to Django 1.9
  544. # zh-cn and zh-tw will be replaced by zh-hans and zh-hant in
  545. # Django 1.9
  546. default_language= 'zh_HANS'
  547.  
  548. realm.default_language = default_language
  549. realm.save(update_fields=['default_language'])
  550. event = dict(
  551. type="realm",
  552. op="update",
  553. property="default_language",
  554. value=default_language
  555. )
  556. send_event(event, active_user_ids(realm))
  557.  
  558. def do_deactivate_realm(realm):
  559. # type: (Realm) -> None
  560. """
  561. Deactivate this realm. Do NOT deactivate the users -- we need to be able to
  562. tell the difference between users that were intentionally deactivated,
  563. e.g. by a realm admin, and users who can't currently use Zulip because their
  564. realm has been deactivated.
  565. """
  566. if realm.deactivated:
  567. return
  568.  
  569. realm.deactivated = True
  570. realm.save(update_fields=["deactivated"])
  571.  
  572. for user in active_humans_in_realm(realm):
  573. # Don't deactivate the users, but do delete their sessions so they get
  574. # bumped to the login screen, where they'll get a realm deactivation
  575. # notice when they try to log in.
  576. delete_user_sessions(user)
  577.  
  578. def do_reactivate_realm(realm):
  579. # type: (Realm) -> None
  580. realm.deactivated = False
  581. realm.save(update_fields=["deactivated"])
  582.  
  583. def do_deactivate_user(user_profile, log=True, _cascade=True):
  584. # type: (UserProfile, bool, bool) -> None
  585. if not user_profile.is_active:
  586. return
  587.  
  588. user_profile.is_active = False
  589. user_profile.save(update_fields=["is_active"])
  590.  
  591. delete_user_sessions(user_profile)
  592.  
  593. if log:
  594. log_event({'type': 'user_deactivated',
  595. 'timestamp': time.time(),
  596. 'user': user_profile.email,
  597. 'domain': user_profile.realm.domain})
  598.  
  599. event = dict(type="realm_user", op="remove",
  600. person=dict(email=user_profile.email,
  601. user_id=user_profile.id,
  602. full_name=user_profile.full_name))
  603. send_event(event, active_user_ids(user_profile.realm))
  604.  
  605. if user_profile.is_bot:
  606. event = dict(type="realm_bot", op="remove",
  607. bot=dict(email=user_profile.email,
  608. user_id=user_profile.id,
  609. full_name=user_profile.full_name))
  610. send_event(event, bot_owner_userids(user_profile))
  611.  
  612. if _cascade:
  613. bot_profiles = UserProfile.objects.filter(is_bot=True, is_active=True,
  614. bot_owner=user_profile)
  615. for profile in bot_profiles:
  616. do_deactivate_user(profile, _cascade=False)
  617.  
  618. def do_deactivate_stream(stream, log=True):
  619. # type: (Stream, bool) -> None
  620. user_profiles = UserProfile.objects.filter(realm=stream.realm)
  621. for user_profile in user_profiles:
  622. bulk_remove_subscriptions([user_profile], [stream])
  623.  
  624. was_invite_only = stream.invite_only
  625. stream.deactivated = True
  626. stream.invite_only = True
  627. # Preserve as much as possible the original stream name while giving it a
  628. # special prefix that both indicates that the stream is deactivated and
  629. # frees up the original name for reuse.
  630. old_name = stream.name
  631. new_name = ("!DEACTIVATED:" + old_name)[:Stream.MAX_NAME_LENGTH]
  632. for i in range(20):
  633. existing_deactivated_stream = get_stream(new_name, stream.realm)
  634. if existing_deactivated_stream:
  635. # This stream has alrady been deactivated, keep prepending !s until
  636. # we have a unique stream name or you've hit a rename limit.
  637. new_name = ("!" + new_name)[:Stream.MAX_NAME_LENGTH]
  638. else:
  639. break
  640.  
  641. # If you don't have a unique name at this point, this will fail later in the
  642. # code path.
  643.  
  644. stream.name = new_name[:Stream.MAX_NAME_LENGTH]
  645. stream.save()
  646.  
  647. # Remove the old stream information from remote cache.
  648. old_cache_key = get_stream_cache_key(old_name, stream.realm)
  649. cache_delete(old_cache_key)
  650.  
  651. if not was_invite_only:
  652. stream_dict = stream.to_dict()
  653. stream_dict.update(dict(name=old_name, invite_only=was_invite_only))
  654. event = dict(type="stream", op="delete",
  655. streams=[stream_dict])
  656. send_event(event, active_user_ids(stream.realm))
  657.  
  658. def do_change_user_email(user_profile, new_email):
  659. # type: (UserProfile, text_type) -> None
  660. old_email = user_profile.email
  661. user_profile.email = new_email
  662. user_profile.save(update_fields=["email"])
  663.  
  664. log_event({'type': 'user_email_changed',
  665. 'old_email': old_email,
  666. 'new_email': new_email})
  667.  
  668. def compute_irc_user_fullname(email):
  669. # type: (NonBinaryStr) -> NonBinaryStr
  670. return email.split("@")[0] + " (IRC)"
  671.  
  672. def compute_jabber_user_fullname(email):
  673. # type: (NonBinaryStr) -> NonBinaryStr
  674. return email.split("@")[0] + " (XMPP)"
  675.  
  676. def compute_mit_user_fullname(email):
  677. # type: (NonBinaryStr) -> NonBinaryStr
  678. try:
  679. # Input is either e.g. username@mit.edu or user|CROSSREALM.INVALID@mit.edu
  680. match_user = re.match(r'^([a-zA-Z0-9_.-]+)(\|.+)?@mit\.edu$', email.lower())
  681. if match_user and match_user.group(2) is None:
  682. answer = DNS.dnslookup(
  683. "%s.passwd.ns.athena.mit.edu" % (match_user.group(1),),
  684. DNS.Type.TXT)
  685. hesiod_name = force_str(answer[0][0]).split(':')[4].split(',')[0].strip()
  686. if hesiod_name != "":
  687. return hesiod_name
  688. elif match_user:
  689. return match_user.group(1).lower() + "@" + match_user.group(2).upper()[1:]
  690. except DNS.Base.ServerError:
  691. pass
  692. except:
  693. print ("Error getting fullname for %s:" % (email,))
  694. traceback.print_exc()
  695. return email.lower()
  696.  
  697. @cache_with_key(lambda realm, email, f: user_profile_by_email_cache_key(email),
  698. timeout=3600*24*7)
  699. def create_mirror_user_if_needed(realm, email, email_to_fullname):
  700. # type: (Realm, text_type, Callable[[text_type], text_type]) -> UserProfile
  701. try:
  702. return get_user_profile_by_email(email)
  703. except UserProfile.DoesNotExist:
  704. try:
  705. # Forge a user for this person
  706. return create_user(email, None, realm,
  707. email_to_fullname(email), email_to_username(email),
  708. active=False, is_mirror_dummy=True)
  709. except IntegrityError:
  710. return get_user_profile_by_email(email)
  711.  
  712. def log_message(message):
  713. # type: (Message) -> None
  714. if not message.sending_client.name.startswith("test:"):
  715. log_event(message.to_log_dict())
  716.  
  717. # Helper function. Defaults here are overriden by those set in do_send_messages
  718. def do_send_message(message, rendered_content = None, no_log = False, stream = None, local_id = None):
  719. # type: (Union[int, Message], Optional[text_type], bool, Optional[Stream], Optional[int]) -> int
  720. return do_send_messages([{'message': message,
  721. 'rendered_content': rendered_content,
  722. 'no_log': no_log,
  723. 'stream': stream,
  724. 'local_id': local_id}])[0]
  725.  
  726. def render_incoming_message(message, content, message_users):
  727. # type: (Message, text_type, Set[UserProfile]) -> text_type
  728. realm_alert_words = alert_words_in_realm(message.get_realm())
  729. try:
  730. rendered_content = render_markdown(
  731. message=message,
  732. content=content,
  733. realm_alert_words=realm_alert_words,
  734. message_users=message_users,
  735. )
  736. except BugdownRenderingException:
  737. raise JsonableError(_('Unable to render message'))
  738. return rendered_content
  739.  
  740. def get_recipient_user_profiles(recipient, sender_id):
  741. # type: (Recipient, text_type) -> List[UserProfile]
  742. if recipient.type == Recipient.PERSONAL:
  743. recipients = list(set([get_user_profile_by_id(recipient.type_id),
  744. get_user_profile_by_id(sender_id)]))
  745. # For personals, you send out either 1 or 2 copies, for
  746. # personals to yourself or to someone else, respectively.
  747. assert((len(recipients) == 1) or (len(recipients) == 2))
  748. elif (recipient.type == Recipient.STREAM or recipient.type == Recipient.HUDDLE):
  749. # We use select_related()/only() here, while the PERSONAL case above uses
  750. # get_user_profile_by_id() to get UserProfile objects from cache. Streams will
  751. # typically have more recipients than PMs, so get_user_profile_by_id() would be
  752. # a bit more expensive here, given that we need to hit the DB anyway and only
  753. # care about the email from the user profile.
  754. fields = [
  755. 'user_profile__id',
  756. 'user_profile__email',
  757. 'user_profile__enable_online_push_notifications',
  758. 'user_profile__is_active',
  759. 'user_profile__realm__domain'
  760. ]
  761. query = Subscription.objects.select_related("user_profile", "user_profile__realm").only(*fields).filter(
  762. recipient=recipient, active=True)
  763. recipients = [s.user_profile for s in query]
  764. else:
  765. raise ValueError('Bad recipient type')
  766. return recipients
  767.  
  768. def do_send_messages(messages):
  769. # type: (Sequence[Optional[MutableMapping[str, Any]]]) -> List[int]
  770. # Filter out messages which didn't pass internal_prep_message properly
  771. messages = [message for message in messages if message is not None]
  772.  
  773. # Filter out zephyr mirror anomalies where the message was already sent
  774. already_sent_ids = [] # type: List[int]
  775. new_messages = [] # type: List[MutableMapping[str, Any]]
  776. for message in messages:
  777. if isinstance(message['message'], int):
  778. already_sent_ids.append(message['message'])
  779. else:
  780. new_messages.append(message)
  781. messages = new_messages
  782.  
  783. # For consistency, changes to the default values for these gets should also be applied
  784. # to the default args in do_send_message
  785. for message in messages:
  786. message['rendered_content'] = message.get('rendered_content', None)
  787. message['no_log'] = message.get('no_log', False)
  788. message['stream'] = message.get('stream', None)
  789. message['local_id'] = message.get('local_id', None)
  790. message['sender_queue_id'] = message.get('sender_queue_id', None)
  791.  
  792. # Log the message to our message log for populate_db to refill
  793. for message in messages:
  794. if not message['no_log']:
  795. log_message(message['message'])
  796.  
  797. for message in messages:
  798. message['recipients'] = get_recipient_user_profiles(message['message'].recipient,
  799. message['message'].sender_id)
  800. # Only deliver the message to active user recipients
  801. message['active_recipients'] = [user_profile for user_profile in message['recipients']
  802. if user_profile.is_active]
  803.  
  804. # Render our messages.
  805. for message in messages:
  806. assert message['message'].rendered_content is None
  807. rendered_content = render_incoming_message(
  808. message['message'],
  809. message['message'].content,
  810. message_users=message['active_recipients'])
  811. message['message'].rendered_content = rendered_content
  812. message['message'].rendered_content_version = bugdown_version
  813.  
  814. for message in messages:
  815. message['message'].update_calculated_fields()
  816.  
  817. # Save the message receipts in the database
  818. user_message_flags = defaultdict(dict) # type: Dict[int, Dict[int, List[str]]]
  819. with transaction.atomic():
  820. Message.objects.bulk_create([message['message'] for message in messages])
  821. ums = [] # type: List[UserMessage]
  822. for message in messages:
  823. ums_to_create = [UserMessage(user_profile=user_profile, message=message['message'])
  824. for user_profile in message['active_recipients']]
  825.  
  826. # These properties on the Message are set via
  827. # render_markdown by code in the bugdown inline patterns
  828. wildcard = message['message'].mentions_wildcard
  829. mentioned_ids = message['message'].mentions_user_ids
  830. ids_with_alert_words = message['message'].user_ids_with_alert_words
  831. is_me_message = message['message'].is_me_message
  832.  
  833. for um in ums_to_create:
  834. if um.user_profile.id == message['message'].sender.id and \
  835. message['message'].sent_by_human():
  836. um.flags |= UserMessage.flags.read
  837. if wildcard:
  838. um.flags |= UserMessage.flags.wildcard_mentioned
  839. if um.user_profile_id in mentioned_ids:
  840. um.flags |= UserMessage.flags.mentioned
  841. if um.user_profile_id in ids_with_alert_words:
  842. um.flags |= UserMessage.flags.has_alert_word
  843. if is_me_message:
  844. um.flags |= UserMessage.flags.is_me_message
  845. user_message_flags[message['message'].id][um.user_profile_id] = um.flags_list()
  846. ums.extend(ums_to_create)
  847. UserMessage.objects.bulk_create(ums)
  848.  
  849. # Claim attachments in message
  850. for message in messages:
  851. if Message.content_has_attachment(message['message'].content):
  852. do_claim_attachments(message['message'])
  853.  
  854. for message in messages:
  855. # Render Markdown etc. here and store (automatically) in
  856. # remote cache, so that the single-threaded Tornado server
  857. # doesn't have to.
  858. user_flags = user_message_flags.get(message['message'].id, {})
  859. sender = message['message'].sender
  860. user_presences = get_status_dict(sender)
  861. presences = {}
  862. for user_profile in message['active_recipients']:
  863. if user_profile.email in user_presences:
  864. presences[user_profile.id] = user_presences[user_profile.email]
  865.  
  866. event = dict(
  867. type = 'message',
  868. message = message['message'].id,
  869. message_dict_markdown = message_to_dict(message['message'], apply_markdown=True),
  870. message_dict_no_markdown = message_to_dict(message['message'], apply_markdown=False),
  871. presences = presences)
  872. users = [{'id': user.id,
  873. 'flags': user_flags.get(user.id, []),
  874. 'always_push_notify': user.enable_online_push_notifications}
  875. for user in message['active_recipients']]
  876. if message['message'].recipient.type == Recipient.STREAM:
  877. # Note: This is where authorization for single-stream
  878. # get_updates happens! We only attach stream data to the
  879. # notify new_message request if it's a public stream,
  880. # ensuring that in the tornado server, non-public stream
  881. # messages are only associated to their subscribed users.
  882. if message['stream'] is None:
  883. message['stream'] = Stream.objects.select_related("realm").get(id=message['message'].recipient.type_id)
  884. if message['stream'].is_public():
  885. event['realm_id'] = message['stream'].realm.id
  886. event['stream_name'] = message['stream'].name
  887. if message['stream'].invite_only:
  888. event['invite_only'] = True
  889. if message['local_id'] is not None:
  890. event['local_id'] = message['local_id']
  891. if message['sender_queue_id'] is not None:
  892. event['sender_queue_id'] = message['sender_queue_id']
  893. send_event(event, users)
  894. if (settings.ENABLE_FEEDBACK and
  895. message['message'].recipient.type == Recipient.PERSONAL and
  896. settings.FEEDBACK_BOT in [up.email for up in message['recipients']]):
  897. queue_json_publish(
  898. 'feedback_messages',
  899. message_to_dict(message['message'], apply_markdown=False),
  900. lambda x: None
  901. )
  902.  
  903. # Note that this does not preserve the order of message ids
  904. # returned. In practice, this shouldn't matter, as we only
  905. # mirror single zephyr messages at a time and don't otherwise
  906. # intermingle sending zephyr messages with other messages.
  907. return already_sent_ids + [message['message'].id for message in messages]
  908.  
  909. def do_send_typing_notification(notification):
  910. # type: (Dict[str, Any]) -> None
  911. recipient_user_profiles = get_recipient_user_profiles(notification['recipient'],
  912. notification['sender'].id)
  913. # Only deliver the notification to active user recipients
  914. user_ids_to_notify = [profile.id for profile in recipient_user_profiles if profile.is_active]
  915. sender_dict = {'user_id': notification['sender'].id, 'email': notification['sender'].email}
  916. # Include a list of recipients in the event body to help identify where the typing is happening
  917. recipient_dicts = [{'user_id': profile.id, 'email': profile.email} for profile in recipient_user_profiles]
  918. event = dict(
  919. type = 'typing',
  920. op = notification['op'],
  921. sender = sender_dict,
  922. recipients = recipient_dicts)
  923.  
  924. send_event(event, user_ids_to_notify)
  925.  
  926. # check_send_typing_notification:
  927. # Checks the typing notification and sends it
  928. def check_send_typing_notification(sender, notification_to, operator):
  929. # type: (UserProfile, Sequence[text_type], text_type) -> None
  930. typing_notification = check_typing_notification(sender, notification_to, operator)
  931. do_send_typing_notification(typing_notification)
  932.  
  933. # check_typing_notification:
  934. # Returns typing notification ready for sending with do_send_typing_notification on success
  935. # or the error message (string) on error.
  936. def check_typing_notification(sender, notification_to, operator):
  937. # type: (UserProfile, Sequence[text_type], text_type) -> Dict[str, Any]
  938. if len(notification_to) == 0:
  939. raise JsonableError(_('Missing parameter: \'to\' (recipient)'))
  940. elif operator not in ('start', 'stop'):
  941. raise JsonableError(_('Invalid \'op\' value (should be start or stop)'))
  942. else:
  943. try:
  944. recipient = recipient_for_emails(notification_to, False,
  945. sender, sender)
  946. except ValidationError as e:
  947. assert isinstance(e.messages[0], six.string_types)
  948. raise JsonableError(e.messages[0])
  949. if recipient.type == Recipient.STREAM:
  950. raise ValueError('Forbidden recipient type')
  951. return {'sender': sender, 'recipient': recipient, 'op': operator}
  952.  
  953. def do_create_stream(realm, stream_name):
  954. # type: (Realm, text_type) -> None
  955. # This is used by a management command now, mostly to facilitate testing. It
  956. # doesn't simulate every single aspect of creating a subscription; for example,
  957. # we don't send Zulips to users to tell them they have been subscribed.
  958. stream = Stream()
  959. stream.realm = realm
  960. stream.name = stream_name
  961. stream.save()
  962. Recipient.objects.create(type_id=stream.id, type=Recipient.STREAM)
  963. subscribers = UserProfile.objects.filter(realm=realm, is_active=True, is_bot=False)
  964. bulk_add_subscriptions([stream], subscribers)
  965.  
  966. def create_stream_if_needed(realm, stream_name, invite_only=False):
  967. # type: (Realm, text_type, bool) -> Tuple[Stream, bool]
  968. (stream, created) = Stream.objects.get_or_create(
  969. realm=realm, name__iexact=stream_name,
  970. defaults={'name': stream_name, 'invite_only': invite_only})
  971. if created:
  972. Recipient.objects.create(type_id=stream.id, type=Recipient.STREAM)
  973. if not invite_only:
  974. event = dict(type="stream", op="create",
  975. streams=[stream.to_dict()])
  976. send_event(event, active_user_ids(realm))
  977. return stream, created
  978.  
  979. def create_streams_if_needed(realm, stream_names, invite_only):
  980. # type: (Realm, List[text_type], bool) -> Tuple[List[Stream], List[Stream]]
  981. added_streams = [] # type: List[Stream]
  982. existing_streams = [] # type: List[Stream]
  983. for stream_name in stream_names:
  984. stream, created = create_stream_if_needed(realm,
  985. stream_name,
  986. invite_only=invite_only)
  987. if created:
  988. added_streams.append(stream)
  989. else:
  990. existing_streams.append(stream)
  991.  
  992. return added_streams, existing_streams
  993.  
  994. def recipient_for_emails(emails, not_forged_mirror_message,
  995. user_profile, sender):
  996. # type: (Iterable[text_type], bool, UserProfile, UserProfile) -> Recipient
  997. recipient_profile_ids = set()
  998.  
  999. # We exempt cross-realm bots from the check that all the recipients
  1000. # are in the same domain.
  1001. realm_domains = set()
  1002. exempt_emails = get_cross_realm_emails()
  1003. if sender.email not in exempt_emails:
  1004. realm_domains.add(sender.realm.domain)
  1005.  
  1006. for email in emails:
  1007. try:
  1008. user_profile = get_user_profile_by_email(email)
  1009. except UserProfile.DoesNotExist:
  1010. raise ValidationError(_("Invalid email '%s'") % (email,))
  1011. if (not user_profile.is_active and not user_profile.is_mirror_dummy) or \
  1012. user_profile.realm.deactivated:
  1013. raise ValidationError(_("'%s' is no longer using Zulip.") % (email,))
  1014. recipient_profile_ids.add(user_profile.id)
  1015. if email not in exempt_emails:
  1016. realm_domains.add(user_profile.realm.domain)
  1017.  
  1018. if not_forged_mirror_message and user_profile.id not in recipient_profile_ids:
  1019. raise ValidationError(_("User not authorized for this query"))
  1020.  
  1021. if len(realm_domains) > 1:
  1022. raise ValidationError(_("You can't send private messages outside of your organization."))
  1023.  
  1024. # If the private message is just between the sender and
  1025. # another person, force it to be a personal internally
  1026. if (len(recipient_profile_ids) == 2
  1027. and sender.id in recipient_profile_ids):
  1028. recipient_profile_ids.remove(sender.id)
  1029.  
  1030. if len(recipient_profile_ids) > 1:
  1031. # Make sure the sender is included in huddle messages
  1032. recipient_profile_ids.add(sender.id)
  1033. huddle = get_huddle(list(recipient_profile_ids))
  1034. return get_recipient(Recipient.HUDDLE, huddle.id)
  1035. else:
  1036. return get_recipient(Recipient.PERSONAL, list(recipient_profile_ids)[0])
  1037.  
  1038. def already_sent_mirrored_message_id(message):
  1039. # type: (Message) -> Optional[int]
  1040. if message.recipient.type == Recipient.HUDDLE:
  1041. # For huddle messages, we use a 10-second window because the
  1042. # timestamps aren't guaranteed to actually match between two
  1043. # copies of the same message.
  1044. time_window = datetime.timedelta(seconds=10)
  1045. else:
  1046. time_window = datetime.timedelta(seconds=0)
  1047.  
  1048. messages = Message.objects.filter(
  1049. sender=message.sender,
  1050. recipient=message.recipient,
  1051. content=message.content,
  1052. subject=message.subject,
  1053. sending_client=message.sending_client,
  1054. pub_date__gte=message.pub_date - time_window,
  1055. pub_date__lte=message.pub_date + time_window)
  1056.  
  1057. if messages.exists():
  1058. return messages[0].id
  1059. return None
  1060.  
  1061. def extract_recipients(s):
  1062. # type: (Union[str, Iterable[text_type]]) -> List[text_type]
  1063. # We try to accept multiple incoming formats for recipients.
  1064. # See test_extract_recipients() for examples of what we allow.
  1065. try:
  1066. data = ujson.loads(s) # type: ignore # This function has a super weird union argument.
  1067. except ValueError:
  1068. data = s
  1069.  
  1070. if isinstance(data, six.string_types):
  1071. data = data.split(',') # type: ignore # https://github.com/python/typeshed/pull/138
  1072.  
  1073. if not isinstance(data, list):
  1074. raise ValueError("Invalid data type for recipients")
  1075.  
  1076. recipients = data
  1077.  
  1078. # Strip recipients, and then remove any duplicates and any that
  1079. # are the empty string after being stripped.
  1080. recipients = [recipient.strip() for recipient in recipients]
  1081. return list(set(recipient for recipient in recipients if recipient))
  1082.  
  1083. # check_send_message:
  1084. # Returns the id of the sent message. Has same argspec as check_message.
  1085. def check_send_message(sender, client, message_type_name, message_to,
  1086. subject_name, message_content, realm=None, forged=False,
  1087. forged_timestamp=None, forwarder_user_profile=None, local_id=None,
  1088. sender_queue_id=None):
  1089. if message_content == 'Nanananana':
  1090. message_content = 'Nanananana Batman!'
  1091. pass
  1092. # type: (UserProfile, Client, text_type, Sequence[text_type], text_type, text_type, Optional[Realm], bool, Optional[float], Optional[UserProfile], Optional[text_type], Optional[text_type]) -> int
  1093. message = check_message(sender, client, message_type_name, message_to,
  1094. subject_name, message_content, realm, forged, forged_timestamp,
  1095. forwarder_user_profile, local_id, sender_queue_id)
  1096. return do_send_messages([message])[0]
  1097.  
  1098. def check_stream_name(stream_name):
  1099. # type: (text_type) -> None
  1100. if stream_name == "":
  1101. raise JsonableError(_("Stream can't be empty"))
  1102. if len(stream_name) > Stream.MAX_NAME_LENGTH:
  1103. raise JsonableError(_("Stream name too long"))
  1104. if not valid_stream_name(stream_name):
  1105. raise JsonableError(_("Invalid stream name"))
  1106.  
  1107. def send_pm_if_empty_stream(sender, stream, stream_name, realm):
  1108. # type: (UserProfile, Stream, text_type, Realm) -> None
  1109. """If a bot sends a message to a stream that doesn't exist or has no
  1110. subscribers, sends a notification to the bot owner (if not a
  1111. cross-realm bot) so that the owner can correct the issue."""
  1112. if sender.realm.is_zephyr_mirror_realm or sender.realm.deactivated:
  1113. return
  1114.  
  1115. if not sender.is_bot or sender.bot_owner is None:
  1116. return
  1117.  
  1118. # Don't send these notifications for cross-realm bot messages
  1119. # (e.g. from EMAIL_GATEWAY_BOT) since the owner for
  1120. # EMAIL_GATEWAY_BOT is probably the server administrator, not
  1121. # the owner of the bot who could potentially fix the problem.
  1122. if sender.realm != realm:
  1123. return
  1124.  
  1125. if stream is not None:
  1126. num_subscribers = stream.num_subscribers()
  1127. if num_subscribers > 0:
  1128. return
  1129.  
  1130. # We warn the user once every 5 minutes to avoid a flood of
  1131. # PMs on a misconfigured integration, re-using the
  1132. # UserProfile.last_reminder field, which is not used for bots.
  1133. last_reminder = sender.last_reminder
  1134. waitperiod = datetime.timedelta(minutes=UserProfile.BOT_OWNER_STREAM_ALERT_WAITPERIOD)
  1135. if last_reminder and timezone.now() - last_reminder <= waitperiod:
  1136. return
  1137.  
  1138. if stream is None:
  1139. error_msg = "that stream does not yet exist. To create it, "
  1140. else:
  1141. # num_subscribers == 0
  1142. error_msg = "there are no subscribers to that stream. To join it, "
  1143.  
  1144. content = ("Hi there! We thought you'd like to know that your bot **%s** just "
  1145. "tried to send a message to stream `%s`, but %s"
  1146. "click the gear in the left-side stream list." %
  1147. (sender.full_name, stream_name, error_msg))
  1148. message = internal_prep_message(settings.NOTIFICATION_BOT, "private",
  1149. sender.bot_owner.email, "", content)
  1150.  
  1151. do_send_messages([message])
  1152.  
  1153. sender.last_reminder = timezone.now()
  1154. sender.save(update_fields=['last_reminder'])
  1155.  
  1156. # check_message:
  1157. # Returns message ready for sending with do_send_message on success or the error message (string) on error.
  1158. def check_message(sender, client, message_type_name, message_to,
  1159. subject_name, message_content, realm=None, forged=False,
  1160. forged_timestamp=None, forwarder_user_profile=None, local_id=None,
  1161. sender_queue_id=None):
  1162. # type: (UserProfile, Client, text_type, Sequence[text_type], text_type, text_type, Optional[Realm], bool, Optional[float], Optional[UserProfile], Optional[text_type], Optional[text_type]) -> Dict[str, Any]
  1163. stream = None
  1164. if not message_to and message_type_name == 'stream' and sender.default_sending_stream:
  1165. # Use the users default stream
  1166. message_to = [sender.default_sending_stream.name]
  1167. elif len(message_to) == 0:
  1168. raise JsonableError(_("Message must have recipients"))
  1169. if len(message_content.strip()) == 0:
  1170. raise JsonableError(_("Message must not be empty"))
  1171. message_content = truncate_body(message_content)
  1172.  
  1173. if realm is None:
  1174. realm = sender.realm
  1175.  
  1176. if message_type_name == 'stream':
  1177. if len(message_to) > 1:
  1178. raise JsonableError(_("Cannot send to multiple streams"))
  1179.  
  1180. stream_name = message_to[0].strip()
  1181. check_stream_name(stream_name)
  1182.  
  1183. if subject_name is None:
  1184. raise JsonableError(_("Missing topic"))
  1185. subject = subject_name.strip()
  1186. if subject == "":
  1187. raise JsonableError(_("Topic can't be empty"))
  1188. subject = truncate_topic(subject)
  1189. ## FIXME: Commented out temporarily while we figure out what we want
  1190. # if not valid_stream_name(subject):
  1191. # return json_error(_("Invalid subject name"))
  1192.  
  1193. stream = get_stream(stream_name, realm)
  1194.  
  1195. send_pm_if_empty_stream(sender, stream, stream_name, realm)
  1196.  
  1197. if stream is None:
  1198. raise JsonableError(_("Stream does not exist"))
  1199. recipient = get_recipient(Recipient.STREAM, stream.id)
  1200.  
  1201. if not stream.invite_only:
  1202. # This if not stream.invite_only:
  1203. # This is a public stream
  1204. pass
  1205. elif subscribed_to_stream(sender, stream):
  1206. # Or it is private, but your are subscribed
  1207. pass
  1208. elif sender.is_api_super_user or (forwarder_user_profile is not None and
  1209. forwarder_user_profile.is_api_super_user):
  1210. pass
  1211. elif subscribed_to_stream(sender, stream):
  1212. # Or it is private, but your are subscribed
  1213. pass
  1214. elif sender.is_api_super_user or (forwarder_user_profile is not None and
  1215. forwarder_user_profile.is_api_super_user):
  1216. # Or this request is being done on behalf of a super user
  1217. pass
  1218. elif sender.is_bot and subscribed_to_stream(sender.bot_owner, stream):
  1219. # Or you're a bot and your owner is subscribed.
  1220. pass
  1221. else:
  1222. # All other cases are an error.
  1223. raise JsonableError(_("Not authorized to send to stream '%s'") % (stream.name,))
  1224.  
  1225. elif message_type_name == 'private':
  1226. mirror_message = client and client.name in ["zephyr_mirror", "irc_mirror", "jabber_mirror", "JabberMirror"]
  1227. not_forged_mirror_message = mirror_message and not forged
  1228. try:
  1229. recipient = recipient_for_emails(message_to, not_forged_mirror_message,forwarder_user_profile,sender)
  1230. except ValidationError as e:
  1231. assert isinstance(e.messages[0], six.string_types)
  1232. raise JsonableError(e.messages[0])
  1233. else:
  1234. raise JsonableError(_("Invalid message type"))
  1235.  
  1236. message = Message()
  1237. message.sender = sender
  1238. message.content = message_content
  1239. message.recipient = recipient
  1240. if message_type_name == 'stream':
  1241. message.subject = subject
  1242. if forged and forged_timestamp is not None:
  1243. # Forged messages come with a timestamp
  1244. message.pub_date = timestamp_to_datetime(forged_timestamp)
  1245. else:
  1246. message.pub_date = timezone.now()
  1247. message.sending_client = client
  1248. # We render messages later in the process.
  1249. assert message.rendered_content is None
  1250.  
  1251. if client.name == "zephyr_mirror":
  1252. id = already_sent_mirrored_message_id(message)
  1253. if id is not None:
  1254. return {'message': id}
  1255.  
  1256. return {'message': message, 'stream': stream, 'local_id': local_id, 'sender_queue_id': sender_queue_id}
  1257.  
  1258. def internal_prep_message(sender_email, recipient_type_name, recipients,
  1259. subject, content, realm=None):
  1260. # type: (text_type, str, text_type, text_type, text_type, Optional[Realm]) -> Optional[Dict[str, Any]]
  1261. """
  1262. Create a message object and checks it, but doesn't send it or save it to the database.
  1263. The internal function that calls this can therefore batch send a bunch of created
  1264. messages together as one database query.
  1265. Call do_send_messages with a list of the return values of this method.
  1266. """
  1267. if len(content) > MAX_MESSAGE_LENGTH:
  1268. content = content[0:3900] + "\n\n[message was too long and has been truncated]"
  1269. # This is a public stream
  1270. pass
  1271. elif subscribed_to_stream(sender, stream):
  1272. # Or it is private, but your are subscribed
  1273. pass
  1274. elif sender.is_api_super_user or (forwarder_user_profile is not None and
  1275. forwarder_user_profile.is_api_super_user):
  1276. content = content[0:3900] + "\n\n[message was too long and has been truncated]"
  1277.  
  1278. sender = get_user_profile_by_email(sender_email)
  1279. if realm is None:
  1280. realm = sender.realm
  1281. parsed_recipients = extract_recipients(recipients)
  1282. if recipient_type_name == "stream":
  1283. stream, _ = create_stream_if_needed(realm, parsed_recipients[0])
  1284.  
  1285. try:
  1286. return check_message(sender, get_client("Internal"), recipient_type_name,
  1287. parsed_recipients, subject, content, realm)
  1288. except JsonableError as e:
  1289. logging.error("Error queueing internal message by %s: %s" % (sender_email, str(e)))
  1290.  
  1291. return None
  1292.  
  1293. def internal_send_message(sender_email, recipient_type_name, recipients,
  1294. subject, content, realm=None):
  1295. # type: (text_type, str, text_type, text_type, text_type, Optional[Realm]) -> None
  1296. msg = internal_prep_message(sender_email, recipient_type_name, recipients,
  1297. subject, content, realm)
  1298.  
  1299. # internal_prep_message encountered an error
  1300. if msg is None:
  1301. return
  1302.  
  1303. do_send_messages([msg])
  1304.  
  1305. def pick_color(user_profile):
  1306. # type: (UserProfile) -> text_type
  1307. subs = Subscription.objects.filter(user_profile=user_profile,
  1308. active=True,
  1309. recipient__type=Recipient.STREAM)
  1310. return pick_color_helper(user_profile, subs)
  1311.  
  1312. def pick_color_helper(user_profile, subs):
  1313. # type: (UserProfile, Iterable[Subscription]) -> text_type
  1314. # These colors are shared with the palette in subs.js.
  1315. used_colors = [sub.color for sub in subs if sub.active]
  1316. available_colors = [s for s in STREAM_ASSIGNMENT_COLORS if s not in used_colors]
  1317.  
  1318. if available_colors:
  1319. return available_colors[0]
  1320. else:
  1321. return STREAM_ASSIGNMENT_COLORS[len(used_colors) % len(STREAM_ASSIGNMENT_COLORS)]
  1322.  
  1323. def get_subscription(stream_name, user_profile):
  1324. # type: (text_type, UserProfile) -> Subscription
  1325. stream = get_stream(stream_name, user_profile.realm)
  1326. recipient = get_recipient(Recipient.STREAM, stream.id)
  1327. return Subscription.objects.get(user_profile=user_profile,
  1328. recipient=recipient, active=True)
  1329.  
  1330. def validate_user_access_to_subscribers(user_profile, stream):
  1331. # type: (Optional[UserProfile], Stream) -> None
  1332. """ Validates whether the user can view the subscribers of a stream. Raises a JsonableError if:
  1333. * The user and the stream are in different realms
  1334. * The realm is MIT and the stream is not invite only.
  1335. * The stream is invite only, requesting_user is passed, and that user
  1336. does not subscribe to the stream.
  1337. """
  1338. validate_user_access_to_subscribers_helper(
  1339. user_profile,
  1340. {"realm__domain": stream.realm.domain,
  1341. "realm_id": stream.realm_id,
  1342. "invite_only": stream.invite_only},
  1343. # We use a lambda here so that we only compute whether the
  1344. # user is subscribed if we have to
  1345. lambda: subscribed_to_stream(user_profile, stream))
  1346.  
  1347. def validate_user_access_to_subscribers_helper(user_profile, stream_dict, check_user_subscribed):
  1348. # type: (Optional[UserProfile], Mapping[str, Any], Callable[[], bool]) -> None
  1349. """ Helper for validate_user_access_to_subscribers that doesn't require a full stream object
  1350. * check_user_subscribed is a function that when called with no
  1351. arguments, will report whether the user is subscribed to the stream
  1352. """
  1353. if user_profile is None:
  1354. raise ValidationError("Missing user to validate access for")
  1355.  
  1356. if user_profile.realm_id != stream_dict["realm_id"]:
  1357. raise ValidationError("Requesting user not in given realm")
  1358.  
  1359. if user_profile.realm.is_zephyr_mirror_realm and not stream_dict["invite_only"]:
  1360. raise JsonableError(_("You cannot get subscribers for public streams in this realm"))
  1361.  
  1362. if (stream_dict["invite_only"] and not check_user_subscribed()):
  1363. raise JsonableError(_("Unable to retrieve subscribers for invite-only stream"))
  1364.  
  1365. # sub_dict is a dictionary mapping stream_id => whether the user is subscribed to that stream
  1366. def bulk_get_subscriber_user_ids(stream_dicts, user_profile, sub_dict):
  1367. # type: (Iterable[Mapping[str, Any]], UserProfile, Mapping[int, bool]) -> Dict[int, List[int]]
  1368. target_stream_dicts = []
  1369. for stream_dict in stream_dicts:
  1370. try:
  1371. validate_user_access_to_subscribers_helper(user_profile, stream_dict,
  1372. lambda: sub_dict[stream_dict["id"]])
  1373. except JsonableError:
  1374. continue
  1375. target_stream_dicts.append(stream_dict)
  1376.  
  1377. subscriptions = Subscription.objects.select_related("recipient").filter(
  1378. recipient__type=Recipient.STREAM,
  1379. recipient__type_id__in=[stream["id"] for stream in target_stream_dicts],
  1380. user_profile__is_active=True,
  1381. active=True).values("user_profile_id", "recipient__type_id")
  1382.  
  1383. result = dict((stream["id"], []) for stream in stream_dicts) # type: Dict[int, List[int]]
  1384. for sub in subscriptions:
  1385. result[sub["recipient__type_id"]].append(sub["user_profile_id"])
  1386.  
  1387. return result
  1388.  
  1389. def get_subscribers_query(stream, requesting_user):
  1390. # type: (Stream, UserProfile) -> QuerySet
  1391. # TODO: Make a generic stub for QuerySet
  1392. """ Build a query to get the subscribers list for a stream, raising a JsonableError if:
  1393.  
  1394. 'realm' is optional in stream.
  1395.  
  1396. The caller can refine this query with select_related(), values(), etc. depending
  1397. on whether it wants objects or just certain fields
  1398. """
  1399. validate_user_access_to_subscribers(requesting_user, stream)
  1400.  
  1401. # Note that non-active users may still have "active" subscriptions, because we
  1402. # want to be able to easily reactivate them with their old subscriptions. This
  1403. # is why the query here has to look at the UserProfile.is_active flag.
  1404. subscriptions = Subscription.objects.filter(recipient__type=Recipient.STREAM,
  1405. recipient__type_id=stream.id,
  1406. user_profile__is_active=True,
  1407. active=True)
  1408. return subscriptions
  1409.  
  1410. def get_subscribers(stream, requesting_user=None):
  1411. # type: (Stream, Optional[UserProfile]) -> List[UserProfile]
  1412. subscriptions = get_subscribers_query(stream, requesting_user).select_related()
  1413. return [subscription.user_profile for subscription in subscriptions]
  1414.  
  1415. def get_subscriber_emails(stream, requesting_user=None):
  1416. # type: (Stream, Optional[UserProfile]) -> List[text_type]
  1417. subscriptions_query = get_subscribers_query(stream, requesting_user)
  1418. subscriptions = subscriptions_query.values('user_profile__email')
  1419. return [subscription['user_profile__email'] for subscription in subscriptions]
  1420.  
  1421. def maybe_get_subscriber_emails(stream, user_profile):
  1422. # type: (Stream, UserProfile) -> List[text_type]
  1423. """ Alternate version of get_subscriber_emails that takes a Stream object only
  1424. (not a name), and simply returns an empty list if unable to get a real
  1425. subscriber list (because we're on the MIT realm). """
  1426. try:
  1427. subscribers = get_subscriber_emails(stream, requesting_user=user_profile)
  1428. except JsonableError:
  1429. subscribers = []
  1430. return subscribers
  1431.  
  1432. def set_stream_color(user_profile, stream_name, color=None):
  1433. # type: (UserProfile, text_type, Optional[text_type]) -> text_type
  1434. subscription = get_subscription(stream_name, user_profile)
  1435. if not color:
  1436. color = pick_color(user_profile)
  1437. subscription.color = color
  1438. subscription.save(update_fields=["color"])
  1439. return color
  1440.  
  1441. def notify_subscriptions_added(user_profile, sub_pairs, stream_emails, no_log=False):
  1442. # type: (UserProfile, Iterable[Tuple[Subscription, Stream]], Callable[[Stream], List[text_type]], bool) -> None
  1443. if not no_log:
  1444. log_event({'type': 'subscription_added',
  1445. 'user': user_profile.email,
  1446. 'names': [stream.name for sub, stream in sub_pairs],
  1447. 'domain': user_profile.realm.domain})
  1448.  
  1449. # Send a notification to the user who subscribed.
  1450. payload = [dict(name=stream.name,
  1451. stream_id=stream.id,
  1452. in_home_view=subscription.in_home_view,
  1453. invite_only=stream.invite_only,
  1454. color=subscription.color,
  1455. email_address=encode_email_address(stream),
  1456. desktop_notifications=subscription.desktop_notifications,
  1457. audible_notifications=subscription.audible_notifications,
  1458. description=stream.description,
  1459. pin_to_top=subscription.pin_to_top,
  1460. subscribers=stream_emails(stream))
  1461. for (subscription, stream) in sub_pairs]
  1462. event = dict(type="subscription", op="add",
  1463. subscriptions=payload)
  1464. send_event(event, [user_profile.id])
  1465.  
  1466. def get_peer_user_ids_for_stream_change(stream, altered_users, subscribed_users):
  1467. # type: (Stream, Iterable[UserProfile], Iterable[UserProfile]) -> Set[int]
  1468.  
  1469. '''
  1470. altered_users is a list of users that we are adding/removing
  1471. subscribed_users is the list of already subscribed users
  1472.  
  1473. Based on stream policy, we notify the correct bystanders, while
  1474. not notifying altered_users (who get subscribers via another event)
  1475. '''
  1476.  
  1477. altered_user_ids = [user.id for user in altered_users]
  1478.  
  1479. if stream.invite_only:
  1480. # PRIVATE STREAMS
  1481. all_subscribed_ids = [user.id for user in subscribed_users]
  1482. return set(all_subscribed_ids) - set(altered_user_ids)
  1483.  
  1484. else:
  1485. # PUBLIC STREAMS
  1486. # We now do "peer_add" or "peer_remove" events even for streams
  1487. # users were never subscribed to, in order for the neversubscribed
  1488. # structure to stay up-to-date.
  1489. return set(active_user_ids(stream.realm)) - set(altered_user_ids)
  1490.  
  1491. def query_all_subs_by_stream(streams):
  1492. # type: (Iterable[Stream]) -> Dict[int, List[UserProfile]]
  1493. all_subs = Subscription.objects.filter(recipient__type=Recipient.STREAM,
  1494. recipient__type_id__in=[stream.id for stream in streams],
  1495. user_profile__is_active=True,
  1496. active=True).select_related('recipient', 'user_profile')
  1497.  
  1498. all_subs_by_stream = defaultdict(list) # type: Dict[int, List[UserProfile]]
  1499. for sub in all_subs:
  1500. all_subs_by_stream[sub.recipient.type_id].append(sub.user_profile)
  1501. return all_subs_by_stream
  1502.  
  1503. def bulk_add_subscriptions(streams, users):
  1504. # type: (Iterable[Stream], Iterable[UserProfile]) -> Tuple[List[Tuple[UserProfile, Stream]], List[Tuple[UserProfile, Stream]]]
  1505. recipients_map = bulk_get_recipients(Recipient.STREAM, [stream.id for stream in streams]) # type: Mapping[int, Recipient]
  1506. recipients = [recipient.id for recipient in recipients_map.values()] # type: List[int]
  1507.  
  1508. stream_map = {} # type: Dict[int, Stream]
  1509. for stream in streams:
  1510. stream_map[recipients_map[stream.id].id] = stream
  1511.  
  1512. subs_by_user = defaultdict(list) # type: Dict[int, List[Subscription]]
  1513. all_subs_query = Subscription.objects.select_related("user_profile")
  1514. for sub in all_subs_query.filter(user_profile__in=users,
  1515. recipient__type=Recipient.STREAM):
  1516. subs_by_user[sub.user_profile_id].append(sub)
  1517.  
  1518. already_subscribed = [] # type: List[Tuple[UserProfile, Stream]]
  1519. subs_to_activate = [] # type: List[Tuple[Subscription, Stream]]
  1520. new_subs = [] # type: List[Tuple[UserProfile, int, Stream]]
  1521. for user_profile in users:
  1522. needs_new_sub = set(recipients) # type: Set[int]
  1523. for sub in subs_by_user[user_profile.id]:
  1524. if sub.recipient_id in needs_new_sub:
  1525. needs_new_sub.remove(sub.recipient_id)
  1526. if sub.active:
  1527. already_subscribed.append((user_profile, stream_map[sub.recipient_id]))
  1528. else:
  1529. subs_to_activate.append((sub, stream_map[sub.recipient_id]))
  1530. # Mark the sub as active, without saving, so that
  1531. # pick_color will consider this to be an active
  1532. # subscription when picking colors
  1533. sub.active = True
  1534. for recipient_id in needs_new_sub:
  1535. new_subs.append((user_profile, recipient_id, stream_map[recipient_id]))
  1536.  
  1537. subs_to_add = [] # type: List[Tuple[Subscription, Stream]]
  1538. for (user_profile, recipient_id, stream) in new_subs:
  1539. color = pick_color_helper(user_profile, subs_by_user[user_profile.id])
  1540. sub_to_add = Subscription(user_profile=user_profile, active=True,
  1541. color=color, recipient_id=recipient_id,
  1542. desktop_notifications=user_profile.enable_stream_desktop_notifications,
  1543. audible_notifications=user_profile.enable_stream_sounds)
  1544. subs_by_user[user_profile.id].append(sub_to_add)
  1545. subs_to_add.append((sub_to_add, stream))
  1546.  
  1547. # TODO: XXX: This transaction really needs to be done at the serializeable
  1548. # transaction isolation level.
  1549. with transaction.atomic():
  1550. occupied_streams_before = list(get_occupied_streams(user_profile.realm))
  1551. Subscription.objects.bulk_create([sub for (sub, stream) in subs_to_add])
  1552. Subscription.objects.filter(id__in=[sub.id for (sub, stream) in subs_to_activate]).update(active=True)
  1553. occupied_streams_after = list(get_occupied_streams(user_profile.realm))
  1554.  
  1555. new_occupied_streams = [stream for stream in
  1556. set(occupied_streams_after) - set(occupied_streams_before)
  1557. if not stream.invite_only]
  1558. if new_occupied_streams:
  1559. event = dict(type="stream", op="occupy",
  1560. streams=[stream.to_dict()
  1561. for stream in new_occupied_streams])
  1562. send_event(event, active_user_ids(user_profile.realm))
  1563.  
  1564. # Notify all existing users on streams that users have joined
  1565.  
  1566. # First, get all users subscribed to the streams that we care about
  1567. # We fetch all subscription information upfront, as it's used throughout
  1568. # the following code and we want to minize DB queries
  1569. all_subs_by_stream = query_all_subs_by_stream(streams=streams)
  1570.  
  1571. def fetch_stream_subscriber_emails(stream):
  1572. # type: (Stream) -> List[text_type]
  1573. if stream.realm.is_zephyr_mirror_realm and not stream.invite_only:
  1574. return []
  1575. users = all_subs_by_stream[stream.id]
  1576. return [u.email for u in users]
  1577.  
  1578. sub_tuples_by_user = defaultdict(list) # type: Dict[int, List[Tuple[Subscription, Stream]]]
  1579. new_streams = set() # type: Set[Tuple[int, int]]
  1580. for (sub, stream) in subs_to_add + subs_to_activate:
  1581. sub_tuples_by_user[sub.user_profile.id].append((sub, stream))
  1582. new_streams.add((sub.user_profile.id, stream.id))
  1583.  
  1584. for user_profile in users:
  1585. if len(sub_tuples_by_user[user_profile.id]) == 0:
  1586. continue
  1587. sub_pairs = sub_tuples_by_user[user_profile.id]
  1588. notify_subscriptions_added(user_profile, sub_pairs, fetch_stream_subscriber_emails)
  1589.  
  1590. for stream in streams:
  1591. if stream.realm.is_zephyr_mirror_realm and not stream.invite_only:
  1592. continue
  1593.  
  1594. new_users = [user for user in users if (user.id, stream.id) in new_streams]
  1595.  
  1596. peer_user_ids = get_peer_user_ids_for_stream_change(
  1597. stream=stream,
  1598. altered_users=new_users,
  1599. subscribed_users=all_subs_by_stream[stream.id]
  1600. )
  1601.  
  1602. if peer_user_ids:
  1603. for added_user in new_users:
  1604. event = dict(type="subscription", op="peer_add",
  1605. subscriptions=[stream.name],
  1606. user_id=added_user.id)
  1607. send_event(event, peer_user_ids)
  1608.  
  1609.  
  1610. return ([(user_profile, stream) for (user_profile, recipient_id, stream) in new_subs] +
  1611. [(sub.user_profile, stream) for (sub, stream) in subs_to_activate],
  1612. already_subscribed)
  1613.  
  1614. def notify_subscriptions_removed(user_profile, streams, no_log=False):
  1615. # type: (UserProfile, Iterable[Stream], bool) -> None
  1616. if not no_log:
  1617. log_event({'type': 'subscription_removed',
  1618. 'user': user_profile.email,
  1619. 'names': [stream.name for stream in streams],
  1620. 'domain': user_profile.realm.domain})
  1621.  
  1622. payload = [dict(name=stream.name, stream_id=stream.id) for stream in streams]
  1623. event = dict(type="subscription", op="remove",
  1624. subscriptions=payload)
  1625. send_event(event, [user_profile.id])
  1626.  
  1627. def bulk_remove_subscriptions(users, streams):
  1628. # type: (Iterable[UserProfile], Iterable[Stream]) -> Tuple[List[Tuple[UserProfile, Stream]], List[Tuple[UserProfile, Stream]]]
  1629.  
  1630. recipients_map = bulk_get_recipients(Recipient.STREAM,
  1631. [stream.id for stream in streams]) # type: Mapping[int, Recipient]
  1632. stream_map = {} # type: Dict[int, Stream]
  1633. for stream in streams:
  1634. stream_map[recipients_map[stream.id].id] = stream
  1635.  
  1636. subs_by_user = dict((user_profile.id, []) for user_profile in users) # type: Dict[int, List[Subscription]]
  1637. for sub in Subscription.objects.select_related("user_profile").filter(user_profile__in=users,
  1638. recipient__in=list(recipients_map.values()),
  1639. active=True):
  1640. subs_by_user[sub.user_profile_id].append(sub)
  1641.  
  1642. subs_to_deactivate = [] # type: List[Tuple[Subscription, Stream]]
  1643. not_subscribed = [] # type: List[Tuple[UserProfile, Stream]]
  1644. for user_profile in users:
  1645. recipients_to_unsub = set([recipient.id for recipient in recipients_map.values()])
  1646. for sub in subs_by_user[user_profile.id]:
  1647. recipients_to_unsub.remove(sub.recipient_id)
  1648. subs_to_deactivate.append((sub, stream_map[sub.recipient_id]))
  1649. for recipient_id in recipients_to_unsub:
  1650. not_subscribed.append((user_profile, stream_map[recipient_id]))
  1651.  
  1652. # TODO: XXX: This transaction really needs to be done at the serializeable
  1653. # transaction isolation level.
  1654. with transaction.atomic():
  1655. occupied_streams_before = list(get_occupied_streams(user_profile.realm))
  1656. Subscription.objects.filter(id__in=[sub.id for (sub, stream_name) in
  1657. subs_to_deactivate]).update(active=False)
  1658. occupied_streams_after = list(get_occupied_streams(user_profile.realm))
  1659.  
  1660. new_vacant_streams = [stream for stream in
  1661. set(occupied_streams_before) - set(occupied_streams_after)
  1662. if not stream.invite_only]
  1663. if new_vacant_streams:
  1664. event = dict(type="stream", op="vacate",
  1665. streams=[stream.to_dict()
  1666. for stream in new_vacant_streams])
  1667. send_event(event, active_user_ids(user_profile.realm))
  1668.  
  1669. altered_user_dict = defaultdict(list) # type: Dict[int, List[UserProfile]]
  1670. streams_by_user = defaultdict(list) # type: Dict[int, List[Stream]]
  1671. for (sub, stream) in subs_to_deactivate:
  1672. streams_by_user[sub.user_profile_id].append(stream)
  1673. altered_user_dict[stream.id].append(sub.user_profile)
  1674.  
  1675. for user_profile in users:
  1676. if len(streams_by_user[user_profile.id]) == 0:
  1677. continue
  1678. notify_subscriptions_removed(user_profile, streams_by_user[user_profile.id])
  1679.  
  1680. all_subs_by_stream = query_all_subs_by_stream(streams=streams)
  1681.  
  1682. for stream in streams:
  1683. if stream.realm.is_zephyr_mirror_realm and not stream.invite_only:
  1684. continue
  1685.  
  1686. altered_users = altered_user_dict[stream.id]
  1687.  
  1688. peer_user_ids = get_peer_user_ids_for_stream_change(
  1689. stream=stream,
  1690. altered_users=altered_users,
  1691. subscribed_users=all_subs_by_stream[stream.id]
  1692. )
  1693.  
  1694. if peer_user_ids:
  1695. for removed_user in altered_users:
  1696. event = dict(type="subscription",
  1697. op="peer_remove",
  1698. subscriptions=[stream.name],
  1699. user_id=removed_user.id)
  1700. send_event(event, peer_user_ids)
  1701.  
  1702. return ([(sub.user_profile, stream) for (sub, stream) in subs_to_deactivate],
  1703. not_subscribed)
  1704.  
  1705. def log_subscription_property_change(user_email, stream_name, property, value):
  1706. # type: (text_type, text_type, text_type, Any) -> None
  1707. event = {'type': 'subscription_property',
  1708. 'property': property,
  1709. 'user': user_email,
  1710. 'stream_name': stream_name,
  1711. 'value': value}
  1712. log_event(event)
  1713.  
  1714. def do_change_subscription_property(user_profile, sub, stream_name,
  1715. property_name, value):
  1716. # type: (UserProfile, Subscription, text_type, text_type, Any) -> None
  1717. setattr(sub, property_name, value)
  1718. sub.save(update_fields=[property_name])
  1719. log_subscription_property_change(user_profile.email, stream_name,
  1720. property_name, value)
  1721.  
  1722. event = dict(type="subscription",
  1723. op="update",
  1724. email=user_profile.email,
  1725. property=property_name,
  1726. value=value,
  1727. name=stream_name)
  1728. send_event(event, [user_profile.id])
  1729.  
  1730. def do_activate_user(user_profile, log=True, join_date=timezone.now()):
  1731. # type: (UserProfile, bool, datetime.datetime) -> None
  1732. user_profile.is_active = True
  1733. user_profile.is_mirror_dummy = False
  1734. user_profile.set_unusable_password()
  1735. user_profile.date_joined = join_date
  1736. user_profile.tos_version = settings.TOS_VERSION
  1737. user_profile.save(update_fields=["is_active", "date_joined", "password",
  1738. "is_mirror_dummy", "tos_version"])
  1739.  
  1740. if log:
  1741. domain = user_profile.realm.domain
  1742. log_event({'type': 'user_activated',
  1743. 'user': user_profile.email,
  1744. 'domain': domain})
  1745.  
  1746. notify_created_user(user_profile)
  1747.  
  1748. def do_reactivate_user(user_profile):
  1749. # type: (UserProfile) -> None
  1750. # Unlike do_activate_user, this is meant for re-activating existing users,
  1751. # so it doesn't reset their password, etc.
  1752. user_profile.is_active = True
  1753. user_profile.save(update_fields=["is_active"])
  1754.  
  1755. domain = user_profile.realm.domain
  1756. log_event({'type': 'user_reactivated',
  1757. 'user': user_profile.email,
  1758. 'domain': domain})
  1759.  
  1760. notify_created_user(user_profile)
  1761.  
  1762. def do_change_password(user_profile, password, log=True, commit=True,
  1763. hashed_password=False):
  1764. # type: (UserProfile, text_type, bool, bool, bool) -> None
  1765. if hashed_password:
  1766. # This is a hashed password, not the password itself.
  1767. user_profile.set_password(password)
  1768. else:
  1769. user_profile.set_password(password)
  1770. if commit:
  1771. user_profile.save(update_fields=["password"])
  1772. if log:
  1773. log_event({'type': 'user_change_password',
  1774. 'user': user_profile.email,
  1775. 'pwhash': user_profile.password})
  1776.  
  1777. def do_change_full_name(user_profile, full_name, log=True):
  1778. # type: (UserProfile, text_type, bool) -> None
  1779. user_profile.full_name = full_name
  1780. user_profile.save(update_fields=["full_name"])
  1781. if log:
  1782. log_event({'type': 'user_change_full_name',
  1783. 'user': user_profile.email,
  1784. 'full_name': full_name})
  1785.  
  1786. payload = dict(email=user_profile.email,
  1787. user_id=user_profile.id,
  1788. full_name=user_profile.full_name)
  1789. send_event(dict(type='realm_user', op='update', person=payload),
  1790. active_user_ids(user_profile.realm))
  1791. if user_profile.is_bot:
  1792. send_event(dict(type='realm_bot', op='update', bot=payload),
  1793. bot_owner_userids(user_profile))
  1794.  
  1795. def do_change_tos_version(user_profile, tos_version, log=True):
  1796. # type: (UserProfile, text_type, bool) -> None
  1797. user_profile.tos_version = tos_version
  1798. user_profile.save(update_fields=["tos_version"])
  1799. if log:
  1800. log_event({'type': 'user_change_tos_version',
  1801. 'user': user_profile.email,
  1802. 'tos_version': tos_version})
  1803.  
  1804. def do_regenerate_api_key(user_profile, log=True):
  1805. # type: (UserProfile, bool) -> None
  1806. user_profile.api_key = random_api_key()
  1807. user_profile.save(update_fields=["api_key"])
  1808.  
  1809. if log:
  1810. log_event({'type': 'user_change_api_key',
  1811. 'user': user_profile.email})
  1812.  
  1813. if user_profile.is_bot:
  1814. send_event(dict(type='realm_bot',
  1815. op='update',
  1816. bot=dict(email=user_profile.email,
  1817. user_id=user_profile.id,
  1818. api_key=user_profile.api_key,
  1819. )),
  1820. bot_owner_userids(user_profile))
  1821.  
  1822. def do_change_avatar_source(user_profile, avatar_source, log=True):
  1823. # type: (UserProfile, text_type, bool) -> None
  1824. user_profile.avatar_source = avatar_source
  1825. user_profile.save(update_fields=["avatar_source"])
  1826.  
  1827. if log:
  1828. log_event({'type': 'user_change_avatar_source',
  1829. 'user': user_profile.email,
  1830. 'avatar_source': avatar_source})
  1831.  
  1832. if user_profile.is_bot:
  1833. send_event(dict(type='realm_bot',
  1834. op='update',
  1835. bot=dict(email=user_profile.email,
  1836. user_id=user_profile.id,
  1837. avatar_url=avatar_url(user_profile),
  1838. )),
  1839. bot_owner_userids(user_profile))
  1840. else:
  1841. payload = dict(
  1842. email=user_profile.email,
  1843. avatar_url=avatar_url(user_profile),
  1844. user_id=user_profile.id
  1845. )
  1846.  
  1847. send_event(dict(type='realm_user',
  1848. op='update',
  1849. person=payload),
  1850. active_user_ids(user_profile.realm))
  1851.  
  1852. def _default_stream_permision_check(user_profile, stream):
  1853. # type: (UserProfile, Optional[Stream]) -> None
  1854. # Any user can have a None default stream
  1855. if stream is not None:
  1856. if user_profile.is_bot:
  1857. user = user_profile.bot_owner
  1858. else:
  1859. user = user_profile
  1860. if stream.invite_only and not subscribed_to_stream(user, stream):
  1861. raise JsonableError(_('Insufficient permission'))
  1862.  
  1863. def do_change_default_sending_stream(user_profile, stream, log=True):
  1864. # type: (UserProfile, Stream, bool) -> None
  1865. _default_stream_permision_check(user_profile, stream)
  1866.  
  1867. user_profile.default_sending_stream = stream
  1868. user_profile.save(update_fields=['default_sending_stream'])
  1869. if log:
  1870. log_event({'type': 'user_change_default_sending_stream',
  1871. 'user': user_profile.email,
  1872. 'stream': str(stream)})
  1873. if user_profile.is_bot:
  1874. if stream:
  1875. stream_name = stream.name
  1876. else:
  1877. stream_name = None
  1878. send_event(dict(type='realm_bot',
  1879. op='update',
  1880. bot=dict(email=user_profile.email,
  1881. user_id=user_profile.id,
  1882. default_sending_stream=stream_name,
  1883. )),
  1884. bot_owner_userids(user_profile))
  1885.  
  1886. def do_change_default_events_register_stream(user_profile, stream, log=True):
  1887. # type: (UserProfile, Stream, bool) -> None
  1888. _default_stream_permision_check(user_profile, stream)
  1889.  
  1890. user_profile.default_events_register_stream = stream
  1891. user_profile.save(update_fields=['default_events_register_stream'])
  1892. if log:
  1893. log_event({'type': 'user_change_default_events_register_stream',
  1894. 'user': user_profile.email,
  1895. 'stream': str(stream)})
  1896. if user_profile.is_bot:
  1897. if stream:
  1898. stream_name = stream.name
  1899. else:
  1900. stream_name = None
  1901. send_event(dict(type='realm_bot',
  1902. op='update',
  1903. bot=dict(email=user_profile.email,
  1904. user_id=user_profile.id,
  1905. default_events_register_stream=stream_name,
  1906. )),
  1907. bot_owner_userids(user_profile))
  1908.  
  1909. def do_change_default_all_public_streams(user_profile, value, log=True):
  1910. # type: (UserProfile, bool, bool) -> None
  1911. user_profile.default_all_public_streams = value
  1912. user_profile.save(update_fields=['default_all_public_streams'])
  1913. if log:
  1914. log_event({'type': 'user_change_default_all_public_streams',
  1915. 'user': user_profile.email,
  1916. 'value': str(value)})
  1917. if user_profile.is_bot:
  1918. send_event(dict(type='realm_bot',
  1919. op='update',
  1920. bot=dict(email=user_profile.email,
  1921. user_id=user_profile.id,
  1922. default_all_public_streams=user_profile.default_all_public_streams,
  1923. )),
  1924. bot_owner_userids(user_profile))
  1925.  
  1926. def do_change_is_admin(user_profile, value, permission='administer'):
  1927. # type: (UserProfile, bool, str) -> None
  1928. if permission == "administer":
  1929. user_profile.is_realm_admin = value
  1930. user_profile.save(update_fields=["is_realm_admin"])
  1931. elif permission == "api_super_user":
  1932. user_profile.is_api_super_user = value
  1933. user_profile.save(update_fields=["is_api_super_user"])
  1934. else:
  1935. raise Exception("Unknown permission")
  1936.  
  1937. if permission == 'administer':
  1938. event = dict(type="realm_user", op="update",
  1939. person=dict(email=user_profile.email,
  1940. is_admin=value))
  1941. send_event(event, active_user_ids(user_profile.realm))
  1942.  
  1943. def do_change_bot_type(user_profile, value):
  1944. # type: (UserProfile, int) -> None
  1945. user_profile.bot_type = value
  1946. user_profile.save(update_fields=["bot_type"])
  1947.  
  1948. def do_make_stream_public(user_profile, realm, stream_name):
  1949. # type: (UserProfile, Realm, text_type) -> None
  1950. stream_name = stream_name.strip()
  1951. stream = get_stream(stream_name, realm)
  1952.  
  1953. if not stream:
  1954. raise JsonableError(_('Unknown stream "%s"') % (stream_name,))
  1955.  
  1956. if not subscribed_to_stream(user_profile, stream):
  1957. raise JsonableError(_('You are not invited to this stream.'))
  1958.  
  1959. stream.invite_only = False
  1960. stream.save(update_fields=['invite_only'])
  1961.  
  1962. def do_make_stream_private(realm, stream_name):
  1963. # type: (Realm, text_type) -> None
  1964. stream_name = stream_name.strip()
  1965. stream = get_stream(stream_name, realm)
  1966.  
  1967. if not stream:
  1968. raise JsonableError(_('Unknown stream "%s"') % (stream_name,))
  1969.  
  1970. stream.invite_only = True
  1971. stream.save(update_fields=['invite_only'])
  1972.  
  1973. def do_rename_stream(realm, old_name, new_name, log=True):
  1974. # type: (Realm, text_type, text_type, bool) -> Dict[str, text_type]
  1975. old_name = old_name.strip()
  1976. new_name = new_name.strip()
  1977.  
  1978. stream = get_stream(old_name, realm)
  1979.  
  1980. if not stream:
  1981. raise JsonableError(_('Unknown stream "%s"') % (old_name,))
  1982.  
  1983. # Will raise if there's an issue.
  1984. check_stream_name(new_name)
  1985.  
  1986. if get_stream(new_name, realm) and old_name.lower() != new_name.lower():
  1987. raise JsonableError(_('Stream name "%s" is already taken') % (new_name,))
  1988.  
  1989. old_name = stream.name
  1990. stream.name = new_name
  1991. stream.save(update_fields=["name"])
  1992.  
  1993. if log:
  1994. log_event({'type': 'stream_name_change',
  1995. 'domain': realm.domain,
  1996. 'new_name': new_name})
  1997.  
  1998. recipient = get_recipient(Recipient.STREAM, stream.id)
  1999. messages = Message.objects.filter(recipient=recipient).only("id")
  2000.  
  2001. # Update the display recipient and stream, which are easy single
  2002. # items to set.
  2003. old_cache_key = get_stream_cache_key(old_name, realm)
  2004. new_cache_key = get_stream_cache_key(stream.name, realm)
  2005. if old_cache_key != new_cache_key:
  2006. cache_delete(old_cache_key)
  2007. cache_set(new_cache_key, stream)
  2008. cache_set(display_recipient_cache_key(recipient.id), stream.name)
  2009.  
  2010. # Delete cache entries for everything else, which is cheaper and
  2011. # clearer than trying to set them. display_recipient is the out of
  2012. # date field in all cases.
  2013. cache_delete_many(
  2014. to_dict_cache_key_id(message.id, True) for message in messages)
  2015. cache_delete_many(
  2016. to_dict_cache_key_id(message.id, False) for message in messages)
  2017. new_email = encode_email_address(stream)
  2018.  
  2019. # We will tell our users to essentially
  2020. # update stream.name = new_name where name = old_name
  2021. # and update stream.email = new_email where name = old_name.
  2022. # We could optimize this by trying to send one message, but the
  2023. # client code really wants one property update at a time, and
  2024. # updating stream names is a pretty infrequent operation.
  2025. # More importantly, we want to key these updates by id, not name,
  2026. # since id is the immutable primary key, and obviously name is not.
  2027. data_updates = [
  2028. ['email_address', new_email],
  2029. ['name', new_name],
  2030. ]
  2031. for property, value in data_updates:
  2032. event = dict(
  2033. op="update",
  2034. type="stream",
  2035. property=property,
  2036. value=value,
  2037. name=old_name
  2038. )
  2039. send_event(event, can_access_stream_user_ids(stream))
  2040.  
  2041. # Even though the token doesn't change, the web client needs to update the
  2042. # email forwarding address to display the correctly-escaped new name.
  2043. return {"email_address": new_email}
  2044.  
  2045. def do_change_stream_description(realm, stream_name, new_description):
  2046. # type: (Realm, text_type, text_type) -> None
  2047. stream = get_stream(stream_name, realm)
  2048. stream.description = new_description
  2049. stream.save(update_fields=['description'])
  2050.  
  2051. event = dict(type='stream', op='update',
  2052. property='description', name=stream_name,
  2053. value=new_description)
  2054. send_event(event, can_access_stream_user_ids(stream))
  2055.  
  2056. def do_create_realm(string_id, name, restricted_to_domain=None,
  2057. invite_required=None, org_type=None):
  2058. # type: (text_type, text_type, Optional[bool], Optional[bool], Optional[int]) -> Tuple[Realm, bool]
  2059. realm = get_realm_by_string_id(string_id)
  2060. created = not realm
  2061. if created:
  2062. kwargs = {} # type: Dict[str, Any]
  2063. if restricted_to_domain is not None:
  2064. kwargs['restricted_to_domain'] = restricted_to_domain
  2065. if invite_required is not None:
  2066. kwargs['invite_required'] = invite_required
  2067. if org_type is not None:
  2068. kwargs['org_type'] = org_type
  2069. realm = Realm(string_id=string_id, name=name,
  2070. domain=string_id + '@acme.com', **kwargs)
  2071. realm.save()
  2072.  
  2073. # Create stream once Realm object has been saved
  2074. notifications_stream, _ = create_stream_if_needed(realm, Realm.DEFAULT_NOTIFICATION_STREAM_NAME)
  2075. realm.notifications_stream = notifications_stream
  2076. realm.save(update_fields=['notifications_stream'])
  2077.  
  2078. # Include a welcome message in this notifications stream
  2079. product_name = "Zulip"
  2080. content = """Hello, and welcome to %s!
  2081.  
  2082. This is a message on stream `%s` with the topic `welcome`. We'll use this stream for
  2083. system-generated notifications.""" % (product_name, notifications_stream.name,)
  2084. msg = internal_prep_message(settings.WELCOME_BOT, 'stream',
  2085. notifications_stream.name, "welcome",
  2086. content, realm=realm)
  2087. do_send_messages([msg])
  2088.  
  2089. # Log the event
  2090. log_event({"type": "realm_created",
  2091. "string_id": string_id,
  2092. "restricted_to_domain": restricted_to_domain,
  2093. "invite_required": invite_required,
  2094. "org_type": org_type})
  2095.  
  2096. if settings.NEW_USER_BOT is not None:
  2097. signup_message = "Signups enabled"
  2098. internal_send_message(settings.NEW_USER_BOT, "stream",
  2099. "signups", string_id, signup_message)
  2100. return (realm, created)
  2101.  
  2102. def do_change_enable_stream_desktop_notifications(user_profile,
  2103. enable_stream_desktop_notifications,
  2104. log=True):
  2105. # type: (UserProfile, bool, bool) -> None
  2106. user_profile.enable_stream_desktop_notifications = enable_stream_desktop_notifications
  2107. user_profile.save(update_fields=["enable_stream_desktop_notifications"])
  2108. event = {'type': 'update_global_notifications',
  2109. 'user': user_profile.email,
  2110. 'notification_name': 'enable_stream_desktop_notifications',
  2111. 'setting': enable_stream_desktop_notifications}
  2112. if log:
  2113. log_event(event)
  2114. send_event(event, [user_profile.id])
  2115.  
  2116. def do_change_enable_stream_sounds(user_profile, enable_stream_sounds, log=True):
  2117. # type: (UserProfile, bool, bool) -> None
  2118. user_profile.enable_stream_sounds = enable_stream_sounds
  2119. user_profile.save(update_fields=["enable_stream_sounds"])
  2120. event = {'type': 'update_global_notifications',
  2121. 'user': user_profile.email,
  2122. 'notification_name': 'enable_stream_sounds',
  2123. 'setting': enable_stream_sounds}
  2124. if log:
  2125. log_event(event)
  2126. send_event(event, [user_profile.id])
  2127.  
  2128. def do_change_enable_desktop_notifications(user_profile, enable_desktop_notifications, log=True):
  2129. # type: (UserProfile, bool, bool) -> None
  2130. user_profile.enable_desktop_notifications = enable_desktop_notifications
  2131. user_profile.save(update_fields=["enable_desktop_notifications"])
  2132. event = {'type': 'update_global_notifications',
  2133. 'user': user_profile.email,
  2134. 'notification_name': 'enable_desktop_notifications',
  2135. 'setting': enable_desktop_notifications}
  2136. if log:
  2137. log_event(event)
  2138. send_event(event, [user_profile.id])
  2139.  
  2140. def do_change_enable_sounds(user_profile, enable_sounds, log=True):
  2141. # type: (UserProfile, bool, bool) -> None
  2142. user_profile.enable_sounds = enable_sounds
  2143. user_profile.save(update_fields=["enable_sounds"])
  2144. event = {'type': 'update_global_notifications',
  2145. 'user': user_profile.email,
  2146. 'notification_name': 'enable_sounds',
  2147. 'setting': enable_sounds}
  2148. if log:
  2149. log_event(event)
  2150. send_event(event, [user_profile.id])
  2151.  
  2152. def do_change_enable_offline_email_notifications(user_profile, offline_email_notifications, log=True):
  2153. # type: (UserProfile, bool, bool) -> None
  2154. user_profile.enable_offline_email_notifications = offline_email_notifications
  2155. user_profile.save(update_fields=["enable_offline_email_notifications"])
  2156. event = {'type': 'update_global_notifications',
  2157. 'user': user_profile.email,
  2158. 'notification_name': 'enable_offline_email_notifications',
  2159. 'setting': offline_email_notifications}
  2160. if log:
  2161. log_event(event)
  2162. send_event(event, [user_profile.id])
  2163.  
  2164. def do_change_enable_offline_push_notifications(user_profile, offline_push_notifications, log=True):
  2165. # type: (UserProfile, bool, bool) -> None
  2166. user_profile.enable_offline_push_notifications = offline_push_notifications
  2167. user_profile.save(update_fields=["enable_offline_push_notifications"])
  2168. event = {'type': 'update_global_notifications',
  2169. 'user': user_profile.email,
  2170. 'notification_name': 'enable_offline_push_notifications',
  2171. 'setting': offline_push_notifications}
  2172. if log:
  2173. log_event(event)
  2174. send_event(event, [user_profile.id])
  2175.  
  2176. def do_change_enable_online_push_notifications(user_profile, online_push_notifications, log=True):
  2177. # type: (UserProfile, bool, bool) -> None
  2178. user_profile.enable_online_push_notifications = online_push_notifications
  2179. user_profile.save(update_fields=["enable_online_push_notifications"])
  2180. event = {'type': 'update_global_notifications',
  2181. 'user': user_profile.email,
  2182. 'notification_name': 'online_push_notifications',
  2183. 'setting': online_push_notifications}
  2184. if log:
  2185. log_event(event)
  2186. send_event(event, [user_profile.id])
  2187.  
  2188. def do_change_enable_digest_emails(user_profile, enable_digest_emails, log=True):
  2189. # type: (UserProfile, bool, bool) -> None
  2190. user_profile.enable_digest_emails = enable_digest_emails
  2191. user_profile.save(update_fields=["enable_digest_emails"])
  2192.  
  2193. if not enable_digest_emails:
  2194. # Remove any digest emails that have been enqueued.
  2195. clear_followup_emails_queue(user_profile.email)
  2196.  
  2197. event = {'type': 'update_global_notifications',
  2198. 'user': user_profile.email,
  2199. 'notification_name': 'enable_digest_emails',
  2200. 'setting': enable_digest_emails}
  2201. if log:
  2202. log_event(event)
  2203. send_event(event, [user_profile.id])
  2204.  
  2205. def do_change_autoscroll_forever(user_profile, autoscroll_forever, log=True):
  2206. # type: (UserProfile, bool, bool) -> None
  2207. user_profile.autoscroll_forever = autoscroll_forever
  2208. user_profile.save(update_fields=["autoscroll_forever"])
  2209.  
  2210. if log:
  2211. log_event({'type': 'autoscroll_forever',
  2212. 'user': user_profile.email,
  2213. 'autoscroll_forever': autoscroll_forever})
  2214.  
  2215. def do_change_enter_sends(user_profile, enter_sends):
  2216. # type: (UserProfile, bool) -> None
  2217. user_profile.enter_sends = enter_sends
  2218. user_profile.save(update_fields=["enter_sends"])
  2219.  
  2220. def do_change_default_desktop_notifications(user_profile, default_desktop_notifications):
  2221. # type: (UserProfile, bool) -> None
  2222. user_profile.default_desktop_notifications = default_desktop_notifications
  2223. user_profile.save(update_fields=["default_desktop_notifications"])
  2224.  
  2225. def do_change_twenty_four_hour_time(user_profile, setting_value, log=True):
  2226. # type: (UserProfile, bool, bool) -> None
  2227. user_profile.twenty_four_hour_time = setting_value
  2228. user_profile.save(update_fields=["twenty_four_hour_time"])
  2229. event = {'type': 'update_display_settings',
  2230. 'user': user_profile.email,
  2231. 'setting_name': 'twenty_four_hour_time',
  2232. 'setting': setting_value}
  2233. if log:
  2234. log_event(event)
  2235. send_event(event, [user_profile.id])
  2236.  
  2237. def do_change_left_side_userlist(user_profile, setting_value, log=True):
  2238. # type: (UserProfile, bool, bool) -> None
  2239. user_profile.left_side_userlist = setting_value
  2240. user_profile.save(update_fields=["left_side_userlist"])
  2241. event = {'type': 'update_display_settings',
  2242. 'user': user_profile.email,
  2243. 'setting_name':'left_side_userlist',
  2244. 'setting': setting_value}
  2245. if log:
  2246. log_event(event)
  2247. send_event(event, [user_profile.id])
  2248.  
  2249. def do_change_default_language(user_profile, setting_value, log=True):
  2250. # type: (UserProfile, text_type, bool) -> None
  2251.  
  2252. if setting_value == 'zh_CN':
  2253. # NB: remove this once we upgrade to Django 1.9
  2254. # zh-cn and zh-tw will be replaced by zh-hans and zh-hant in
  2255. # Django 1.9
  2256. setting_value = 'zh_HANS'
  2257.  
  2258. user_profile.default_language = setting_value
  2259. user_profile.save(update_fields=["default_language"])
  2260. event = {'type': 'update_display_settings',
  2261. 'user': user_profile.email,
  2262. 'setting_name':'default_language',
  2263. 'setting': setting_value}
  2264. if log:
  2265. log_event(event)
  2266. send_event(event, [user_profile.id])
  2267.  
  2268. def set_default_streams(realm, stream_names):
  2269. # type: (Realm, Iterable[text_type]) -> None
  2270. DefaultStream.objects.filter(realm=realm).delete()
  2271. for stream_name in stream_names:
  2272. stream, _ = create_stream_if_needed(realm, stream_name)
  2273. DefaultStream.objects.create(stream=stream, realm=realm)
  2274.  
  2275. # Always include the realm's default notifications streams, if it exists
  2276. if realm.notifications_stream is not None:
  2277. DefaultStream.objects.get_or_create(stream=realm.notifications_stream, realm=realm)
  2278.  
  2279. log_event({'type': 'default_streams',
  2280. 'domain': realm.domain,
  2281. 'streams': stream_names})
  2282.  
  2283.  
  2284. def notify_default_streams(realm):
  2285. # type: (Realm) -> None
  2286. event = dict(
  2287. type="default_streams",
  2288. default_streams=streams_to_dicts_sorted(get_default_streams_for_realm(realm))
  2289. )
  2290. send_event(event, active_user_ids(realm))
  2291.  
  2292. def do_add_default_stream(realm, stream_name):
  2293. # type: (Realm, text_type) -> None
  2294. stream, _ = create_stream_if_needed(realm, stream_name)
  2295. if not DefaultStream.objects.filter(realm=realm, stream=stream).exists():
  2296. DefaultStream.objects.create(realm=realm, stream=stream)
  2297. notify_default_streams(realm)
  2298.  
  2299. def do_remove_default_stream(realm, stream_name):
  2300. # type: (Realm, text_type) -> None
  2301. stream = get_stream(stream_name, realm)
  2302. if stream is None:
  2303. raise JsonableError(_("Stream does not exist"))
  2304. DefaultStream.objects.filter(realm=realm, stream=stream).delete()
  2305. notify_default_streams(realm)
  2306.  
  2307. def get_default_streams_for_realm(realm):
  2308. # type: (Realm) -> List[Stream]
  2309. return [default.stream for default in
  2310. DefaultStream.objects.select_related("stream", "stream__realm").filter(realm=realm)]
  2311.  
  2312. def get_default_subs(user_profile):
  2313. # type: (UserProfile) -> List[Stream]
  2314. # Right now default streams are realm-wide. This wrapper gives us flexibility
  2315. # to some day further customize how we set up default streams for new users.
  2316. return get_default_streams_for_realm(user_profile.realm)
  2317.  
  2318. # returns default streams in json serializeable format
  2319. def streams_to_dicts_sorted(streams):
  2320. # type: (List[Stream]) -> List[Dict[str, Any]]
  2321. return sorted([stream.to_dict() for stream in streams], key=lambda elt: elt["name"])
  2322.  
  2323. def do_update_user_activity_interval(user_profile, log_time):
  2324. # type: (UserProfile, datetime.datetime) -> None
  2325. effective_end = log_time + datetime.timedelta(minutes=15)
  2326. # This code isn't perfect, because with various races we might end
  2327. # up creating two overlapping intervals, but that shouldn't happen
  2328. # often, and can be corrected for in post-processing
  2329. try:
  2330. last = UserActivityInterval.objects.filter(user_profile=user_profile).order_by("-end")[0]
  2331. # There are two ways our intervals could overlap:
  2332. # (1) The start of the new interval could be inside the old interval
  2333. # (2) The end of the new interval could be inside the old interval
  2334. # In either case, we just extend the old interval to include the new interval.
  2335. if ((log_time <= last.end and log_time >= last.start) or
  2336. (effective_end <= last.end and effective_end >= last.start)):
  2337. last.end = max(last.end, effective_end)
  2338. last.start = min(last.start, log_time)
  2339. last.save(update_fields=["start", "end"])
  2340. return
  2341. except IndexError:
  2342. pass
  2343.  
  2344. # Otherwise, the intervals don't overlap, so we should make a new one
  2345. UserActivityInterval.objects.create(user_profile=user_profile, start=log_time,
  2346. end=effective_end)
  2347.  
  2348. @statsd_increment('user_activity')
  2349. def do_update_user_activity(user_profile, client, query, log_time):
  2350. # type: (UserProfile, Client, text_type, datetime.datetime) -> None
  2351. (activity, created) = UserActivity.objects.get_or_create(
  2352. user_profile = user_profile,
  2353. client = client,
  2354. query = query,
  2355. defaults={'last_visit': log_time, 'count': 0})
  2356.  
  2357. activity.count += 1
  2358. activity.last_visit = log_time
  2359. activity.save(update_fields=["last_visit", "count"])
  2360.  
  2361. def send_presence_changed(user_profile, presence):
  2362. # type: (UserProfile, UserPresence) -> None
  2363. presence_dict = presence.to_dict()
  2364. event = dict(type="presence", email=user_profile.email,
  2365. server_timestamp=time.time(),
  2366. presence={presence_dict['client']: presence.to_dict()})
  2367. send_event(event, active_user_ids(user_profile.realm))
  2368.  
  2369. def consolidate_client(client):
  2370. # type: (Client) -> Client
  2371. # The web app reports a client as 'website'
  2372. # The desktop app reports a client as ZulipDesktop
  2373. # due to it setting a custom user agent. We want both
  2374. # to count as web users
  2375.  
  2376. # Alias ZulipDesktop to website
  2377. if client.name in ['ZulipDesktop']:
  2378. return get_client('website')
  2379. else:
  2380. return client
  2381.  
  2382. @statsd_increment('user_presence')
  2383. def do_update_user_presence(user_profile, client, log_time, status):
  2384. # type: (UserProfile, Client, datetime.datetime, int) -> None
  2385. client = consolidate_client(client)
  2386. (presence, created) = UserPresence.objects.get_or_create(
  2387. user_profile = user_profile,
  2388. client = client,
  2389. defaults = {'timestamp': log_time,
  2390. 'status': status})
  2391.  
  2392. stale_status = (log_time - presence.timestamp) > datetime.timedelta(minutes=1, seconds=10)
  2393. was_idle = presence.status == UserPresence.IDLE
  2394. became_online = (status == UserPresence.ACTIVE) and (stale_status or was_idle)
  2395.  
  2396. # If an object was created, it has already been saved.
  2397. #
  2398. # We suppress changes from ACTIVE to IDLE before stale_status is reached;
  2399. # this protects us from the user having two clients open: one active, the
  2400. # other idle. Without this check, we would constantly toggle their status
  2401. # between the two states.
  2402. if not created and stale_status or was_idle or status == presence.status:
  2403. # The following block attempts to only update the "status"
  2404. # field in the event that it actually changed. This is
  2405. # important to avoid flushing the UserPresence cache when the
  2406. # data it would return to a client hasn't actually changed
  2407. # (see the UserPresence post_save hook for details).
  2408. presence.timestamp = log_time
  2409. update_fields = ["timestamp"]
  2410. if presence.status != status:
  2411. presence.status = status
  2412. update_fields.append("status")
  2413. presence.save(update_fields=update_fields)
  2414.  
  2415. if not user_profile.realm.is_zephyr_mirror_realm and (created or became_online):
  2416. # Push event to all users in the realm so they see the new user
  2417. # appear in the presence list immediately, or the newly online
  2418. # user without delay. Note that we won't send an update here for a
  2419. # timestamp update, because we rely on the browser to ping us every 50
  2420. # seconds for realm-wide status updates, and those updates should have
  2421. # recent timestamps, which means the browser won't think active users
  2422. # have gone idle. If we were more aggressive in this function about
  2423. # sending timestamp updates, we could eliminate the ping responses, but
  2424. # that's not a high priority for now, considering that most of our non-MIT
  2425. # realms are pretty small.
  2426. send_presence_changed(user_profile, presence)
  2427.  
  2428. def update_user_activity_interval(user_profile, log_time):
  2429. # type: (UserProfile, datetime.datetime) -> None
  2430. event={'user_profile_id': user_profile.id,
  2431. 'time': datetime_to_timestamp(log_time)}
  2432. queue_json_publish("user_activity_interval", event,
  2433. lambda e: do_update_user_activity_interval(user_profile, log_time))
  2434.  
  2435. def update_user_presence(user_profile, client, log_time, status,
  2436. new_user_input):
  2437. # type: (UserProfile, Client, datetime.datetime, int, bool) -> None
  2438. event={'user_profile_id': user_profile.id,
  2439. 'status': status,
  2440. 'time': datetime_to_timestamp(log_time),
  2441. 'client': client.name}
  2442.  
  2443. queue_json_publish("user_presence", event,
  2444. lambda e: do_update_user_presence(user_profile, client,
  2445. log_time, status))
  2446.  
  2447. if new_user_input:
  2448. update_user_activity_interval(user_profile, log_time)
  2449.  
  2450. def do_update_pointer(user_profile, pointer, update_flags=False):
  2451. # type: (UserProfile, int, bool) -> None
  2452. prev_pointer = user_profile.pointer
  2453. user_profile.pointer = pointer
  2454. user_profile.save(update_fields=["pointer"])
  2455.  
  2456. if update_flags:
  2457. # Until we handle the new read counts in the Android app
  2458. # natively, this is a shim that will mark as read any messages
  2459. # up until the pointer move
  2460. UserMessage.objects.filter(user_profile=user_profile,
  2461. message__id__gt=prev_pointer,
  2462. message__id__lte=pointer,
  2463. flags=~UserMessage.flags.read) \
  2464. .update(flags=F('flags').bitor(UserMessage.flags.read))
  2465.  
  2466. event = dict(type='pointer', pointer=pointer)
  2467. send_event(event, [user_profile.id])
  2468.  
  2469. def do_update_message_flags(user_profile, operation, flag, messages, all, stream_obj, topic_name):
  2470. # type: (UserProfile, text_type, text_type, Sequence[int], bool, Optional[Stream], Optional[text_type]) -> int
  2471. flagattr = getattr(UserMessage.flags, flag)
  2472.  
  2473. if all:
  2474. log_statsd_event('bankruptcy')
  2475. msgs = UserMessage.objects.filter(user_profile=user_profile)
  2476. elif stream_obj is not None:
  2477. recipient = get_recipient(Recipient.STREAM, stream_obj.id)
  2478. if topic_name:
  2479. msgs = UserMessage.objects.filter(message__recipient=recipient,
  2480. user_profile=user_profile,
  2481. message__subject__iexact=topic_name)
  2482. else:
  2483. msgs = UserMessage.objects.filter(message__recipient=recipient, user_profile=user_profile)
  2484. else:
  2485. msgs = UserMessage.objects.filter(user_profile=user_profile,
  2486. message__id__in=messages)
  2487. # Hack to let you star any message
  2488. if msgs.count() == 0:
  2489. if not len(messages) == 1:
  2490. raise JsonableError(_("Invalid message(s)"))
  2491. if flag != "starred":
  2492. raise JsonableError(_("Invalid message(s)"))
  2493. # Validate that the user could have read the relevant message
  2494. message = access_message(user_profile, messages[0])[0]
  2495.  
  2496. # OK, this is a message that you legitimately have access
  2497. # to via narrowing to the stream it is on, even though you
  2498. # didn't actually receive it. So we create a historical,
  2499. # read UserMessage message row for you to star.
  2500. UserMessage.objects.create(user_profile=user_profile,
  2501. message=message,
  2502. flags=UserMessage.flags.historical | UserMessage.flags.read)
  2503.  
  2504. # The filter() statements below prevent postgres from doing a lot of
  2505. # unnecessary work, which is a big deal for users updating lots of
  2506. # flags (e.g. bankruptcy). This patch arose from seeing slow calls
  2507. # to POST /json/messages/flags in the logs. The filter() statements
  2508. # are kind of magical; they are actually just testing the one bit.
  2509. if operation == 'add':
  2510. msgs = msgs.filter(flags=~flagattr)
  2511. if stream_obj:
  2512. messages = list(msgs.values_list('message__id', flat=True))
  2513. count = msgs.update(flags=F('flags').bitor(flagattr))
  2514. elif operation == 'remove':
  2515. msgs = msgs.filter(flags=flagattr)
  2516. if stream_obj:
  2517. messages = list(msgs.values_list('message__id', flat=True))
  2518. count = msgs.update(flags=F('flags').bitand(~flagattr))
  2519.  
  2520. event = {'type': 'update_message_flags',
  2521. 'operation': operation,
  2522. 'flag': flag,
  2523. 'messages': messages,
  2524. 'all': all}
  2525. log_event(event)
  2526. send_event(event, [user_profile.id])
  2527.  
  2528. statsd.incr("flags.%s.%s" % (flag, operation), count)
  2529. return count
  2530.  
  2531. def subscribed_to_stream(user_profile, stream):
  2532. # type: (UserProfile, Stream) -> bool
  2533. try:
  2534. if Subscription.objects.get(user_profile=user_profile,
  2535. active=True,
  2536. recipient__type=Recipient.STREAM,
  2537. recipient__type_id=stream.id):
  2538. return True
  2539. return False
  2540. except Subscription.DoesNotExist:
  2541. return False
  2542.  
  2543. def truncate_content(content, max_length, truncation_message):
  2544. # type: (text_type, int, text_type) -> text_type
  2545. if len(content) > max_length:
  2546. content = content[:max_length - len(truncation_message)] + truncation_message
  2547. return content
  2548.  
  2549. def truncate_body(body):
  2550. # type: (text_type) -> text_type
  2551. return truncate_content(body, MAX_MESSAGE_LENGTH, "...")
  2552.  
  2553. def truncate_topic(topic):
  2554. # type: (text_type) -> text_type
  2555. return truncate_content(topic, MAX_SUBJECT_LENGTH, "...")
  2556.  
  2557.  
  2558. def update_user_message_flags(message, ums):
  2559. # type: (Message, Iterable[UserMessage]) -> None
  2560. wildcard = message.mentions_wildcard
  2561. mentioned_ids = message.mentions_user_ids
  2562. ids_with_alert_words = message.user_ids_with_alert_words
  2563. changed_ums = set() # type: Set[UserMessage]
  2564.  
  2565. def update_flag(um, should_set, flag):
  2566. # type: (UserMessage, bool, int) -> None
  2567. if should_set:
  2568. if not (um.flags & flag):
  2569. um.flags |= flag
  2570. changed_ums.add(um)
  2571. else:
  2572. if (um.flags & flag):
  2573. um.flags &= ~flag
  2574. changed_ums.add(um)
  2575.  
  2576. for um in ums:
  2577. has_alert_word = um.user_profile_id in ids_with_alert_words
  2578. update_flag(um, has_alert_word, UserMessage.flags.has_alert_word)
  2579.  
  2580. mentioned = um.user_profile_id in mentioned_ids
  2581. update_flag(um, mentioned, UserMessage.flags.mentioned)
  2582.  
  2583. update_flag(um, wildcard, UserMessage.flags.wildcard_mentioned)
  2584.  
  2585. is_me_message = getattr(message, 'is_me_message', False)
  2586. update_flag(um, is_me_message, UserMessage.flags.is_me_message)
  2587.  
  2588. for um in changed_ums:
  2589. um.save(update_fields=['flags'])
  2590.  
  2591. # We use transaction.atomic to support select_for_update in the attachment codepath.
  2592. @transaction.atomic
  2593. def do_update_message(user_profile, message, subject, propagate_mode, content, rendered_content):
  2594. # type: (UserProfile, Message, Optional[text_type], str, Optional[text_type], Optional[text_type]) -> None
  2595. event = {'type': 'update_message',
  2596. 'sender': user_profile.email,
  2597. 'message_id': message.id} # type: Dict[str, Any]
  2598. edit_history_event = {} # type: Dict[str, Any]
  2599. changed_messages = [message]
  2600.  
  2601. # Set first_rendered_content to be the oldest version of the
  2602. # rendered content recorded; which is the current version if the
  2603. # content hasn't been edited before. Note that because one could
  2604. # have edited just the subject, not every edit history event
  2605. # contains a prev_rendered_content element.
  2606. first_rendered_content = message.rendered_content
  2607. if message.edit_history is not None:
  2608. edit_history = ujson.loads(message.edit_history)
  2609. for old_edit_history_event in edit_history:
  2610. if 'prev_rendered_content' in old_edit_history_event:
  2611. first_rendered_content = old_edit_history_event['prev_rendered_content']
  2612.  
  2613. ums = UserMessage.objects.filter(message=message.id)
  2614.  
  2615. if content is not None:
  2616. update_user_message_flags(message, ums)
  2617.  
  2618. # We are turning off diff highlighting everywhere until ticket #1532 is addressed.
  2619. if False:
  2620. # Don't highlight message edit diffs on prod
  2621. rendered_content = highlight_html_differences(first_rendered_content, rendered_content)
  2622.  
  2623. event['orig_content'] = message.content
  2624. event['orig_rendered_content'] = message.rendered_content
  2625. edit_history_event["prev_content"] = message.content
  2626. edit_history_event["prev_rendered_content"] = message.rendered_content
  2627. edit_history_event["prev_rendered_content_version"] = message.rendered_content_version
  2628. message.content = content
  2629. message.rendered_content = rendered_content
  2630. message.rendered_content_version = bugdown_version
  2631. event["content"] = content
  2632. event["rendered_content"] = rendered_content
  2633.  
  2634. prev_content = edit_history_event['prev_content']
  2635. if Message.content_has_attachment(prev_content) or Message.content_has_attachment(message.content):
  2636. check_attachment_reference_change(prev_content, message)
  2637.  
  2638. if subject is not None:
  2639. orig_subject = message.topic_name()
  2640. subject = truncate_topic(subject)
  2641. event["orig_subject"] = orig_subject
  2642. event["propagate_mode"] = propagate_mode
  2643. message.subject = subject
  2644. event["stream_id"] = message.recipient.type_id
  2645. event["subject"] = subject
  2646. event['subject_links'] = bugdown.subject_links(message.sender.realm.domain.lower(), subject)
  2647. edit_history_event["prev_subject"] = orig_subject
  2648.  
  2649.  
  2650. if propagate_mode in ["change_later", "change_all"]:
  2651. propagate_query = Q(recipient = message.recipient, subject = orig_subject)
  2652. # We only change messages up to 2 days in the past, to avoid hammering our
  2653. # DB by changing an unbounded amount of messages
  2654. if propagate_mode == 'change_all':
  2655. before_bound = now() - datetime.timedelta(days=2)
  2656.  
  2657. propagate_query = propagate_query & ~Q(id = message.id) & \
  2658. Q(pub_date__range=(before_bound, now()))
  2659. if propagate_mode == 'change_later':
  2660. propagate_query = propagate_query & Q(id__gt = message.id)
  2661.  
  2662. messages = Message.objects.filter(propagate_query).select_related()
  2663.  
  2664. # Evaluate the query before running the update
  2665. messages_list = list(messages)
  2666. messages.update(subject=subject)
  2667.  
  2668. for m in messages_list:
  2669. # The cached ORM object is not changed by messages.update()
  2670. # and the remote cache update requires the new value
  2671. m.subject = subject
  2672.  
  2673. changed_messages += messages_list
  2674.  
  2675. message.last_edit_time = timezone.now()
  2676. event['edit_timestamp'] = datetime_to_timestamp(message.last_edit_time)
  2677. edit_history_event['timestamp'] = event['edit_timestamp']
  2678. if message.edit_history is not None:
  2679. edit_history.insert(0, edit_history_event)
  2680. else:
  2681. edit_history = [edit_history_event]
  2682. message.edit_history = ujson.dumps(edit_history)
  2683.  
  2684. log_event(event)
  2685. message.save(update_fields=["subject", "content", "rendered_content",
  2686. "rendered_content_version", "last_edit_time",
  2687. "edit_history"])
  2688.  
  2689. # Update the message as stored in the (deprecated) message
  2690. # cache (for shunting the message over to Tornado in the old
  2691. # get_messages API) and also the to_dict caches.
  2692. items_for_remote_cache = {}
  2693. event['message_ids'] = []
  2694. for changed_message in changed_messages:
  2695. event['message_ids'].append(changed_message.id)
  2696. items_for_remote_cache[to_dict_cache_key(changed_message, True)] = \
  2697. (MessageDict.to_dict_uncached(changed_message, apply_markdown=True),)
  2698. items_for_remote_cache[to_dict_cache_key(changed_message, False)] = \
  2699. (MessageDict.to_dict_uncached(changed_message, apply_markdown=False),)
  2700. cache_set_many(items_for_remote_cache)
  2701.  
  2702. def user_info(um):
  2703. # type: (UserMessage) -> Dict[str, Any]
  2704. return {
  2705. 'id': um.user_profile_id,
  2706. 'flags': um.flags_list()
  2707. }
  2708. send_event(event, list(map(user_info, ums)))
  2709.  
  2710. def encode_email_address(stream):
  2711. # type: (Stream) -> text_type
  2712. return encode_email_address_helper(stream.name, stream.email_token)
  2713.  
  2714. def encode_email_address_helper(name, email_token):
  2715. # type: (text_type, text_type) -> text_type
  2716. # Some deployments may not use the email gateway
  2717. if settings.EMAIL_GATEWAY_PATTERN == '':
  2718. return ''
  2719.  
  2720. # Given the fact that we have almost no restrictions on stream names and
  2721. # that what characters are allowed in e-mail addresses is complicated and
  2722. # dependent on context in the address, we opt for a very simple scheme:
  2723. #
  2724. # Only encode the stream name (leave the + and token alone). Encode
  2725. # everything that isn't alphanumeric plus _ as the percent-prefixed integer
  2726. # ordinal of that character, padded with zeroes to the maximum number of
  2727. # bytes of a UTF-8 encoded Unicode character.
  2728. encoded_name = re.sub("\W", lambda x: "%" + str(ord(x.group(0))).zfill(4), name)
  2729. encoded_token = "%s+%s" % (encoded_name, email_token)
  2730. return settings.EMAIL_GATEWAY_PATTERN % (encoded_token,)
  2731.  
  2732. def get_email_gateway_message_string_from_address(address):
  2733. # type: (text_type) -> Optional[text_type]
  2734. pattern_parts = [re.escape(part) for part in settings.EMAIL_GATEWAY_PATTERN.split('%s')]
  2735. if settings.EMAIL_GATEWAY_EXTRA_PATTERN_HACK:
  2736. # Accept mails delivered to any Zulip server
  2737. pattern_parts[-1] = settings.EMAIL_GATEWAY_EXTRA_PATTERN_HACK
  2738. match_email_re = re.compile("(.*?)".join(pattern_parts))
  2739. match = match_email_re.match(address)
  2740.  
  2741. if not match:
  2742. return None
  2743.  
  2744. msg_string = match.group(1)
  2745.  
  2746. return msg_string
  2747.  
  2748. def decode_email_address(email):
  2749. # type: (text_type) -> Tuple[text_type, text_type]
  2750. # Perform the reverse of encode_email_address. Returns a tuple of (streamname, email_token)
  2751. msg_string = get_email_gateway_message_string_from_address(email)
  2752.  
  2753. if '.' in msg_string:
  2754. # Workaround for Google Groups and other programs that don't accept emails
  2755. # that have + signs in them (see Trac #2102)
  2756. encoded_stream_name, token = msg_string.split('.')
  2757. else:
  2758. encoded_stream_name, token = msg_string.split('+')
  2759. stream_name = re.sub("%\d{4}", lambda x: unichr(int(x.group(0)[1:])), encoded_stream_name)
  2760. return stream_name, token
  2761.  
  2762. # In general, it's better to avoid using .values() because it makes
  2763. # the code pretty ugly, but in this case, it has significant
  2764. # performance impact for loading / for users with large numbers of
  2765. # subscriptions, so it's worth optimizing.
  2766. def gather_subscriptions_helper(user_profile):
  2767. # type: (UserProfile) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]], List[Dict[str, Any]]]
  2768. sub_dicts = Subscription.objects.select_related("recipient").filter(
  2769. user_profile = user_profile,
  2770. recipient__type = Recipient.STREAM).values(
  2771. "recipient__type_id", "in_home_view", "color", "desktop_notifications",
  2772. "audible_notifications", "active", "pin_to_top")
  2773.  
  2774. stream_ids = set([sub["recipient__type_id"] for sub in sub_dicts])
  2775. all_streams = get_active_streams(user_profile.realm).select_related(
  2776. "realm").values("id", "name", "invite_only", "realm_id", \
  2777. "realm__domain", "email_token", "description")
  2778.  
  2779. stream_dicts = [stream for stream in all_streams if stream['id'] in stream_ids]
  2780. stream_hash = {}
  2781. for stream in stream_dicts:
  2782. stream_hash[stream["id"]] = stream
  2783.  
  2784. all_streams_id = [stream["id"] for stream in all_streams]
  2785.  
  2786. subscribed = []
  2787. unsubscribed = []
  2788. never_subscribed = []
  2789.  
  2790. # Deactivated streams aren't in stream_hash.
  2791. streams = [stream_hash[sub["recipient__type_id"]] for sub in sub_dicts \
  2792. if sub["recipient__type_id"] in stream_hash]
  2793. streams_subscribed_map = dict((sub["recipient__type_id"], sub["active"]) for sub in sub_dicts)
  2794.  
  2795. # Add never subscribed streams to streams_subscribed_map
  2796. streams_subscribed_map.update({stream['id']: False for stream in all_streams if stream not in streams})
  2797.  
  2798. subscriber_map = bulk_get_subscriber_user_ids(all_streams, user_profile, streams_subscribed_map)
  2799.  
  2800. sub_unsub_stream_ids = set()
  2801. for sub in sub_dicts:
  2802. sub_unsub_stream_ids.add(sub["recipient__type_id"])
  2803. stream = stream_hash.get(sub["recipient__type_id"])
  2804. if not stream:
  2805. # This stream has been deactivated, don't include it.
  2806. continue
  2807.  
  2808. subscribers = subscriber_map[stream["id"]]
  2809.  
  2810. # Important: don't show the subscribers if the stream is invite only
  2811. # and this user isn't on it anymore.
  2812. if stream["invite_only"] and not sub["active"]:
  2813. subscribers = None
  2814.  
  2815. stream_dict = {'name': stream["name"],
  2816. 'in_home_view': sub["in_home_view"],
  2817. 'invite_only': stream["invite_only"],
  2818. 'color': sub["color"],
  2819. 'desktop_notifications': sub["desktop_notifications"],
  2820. 'audible_notifications': sub["audible_notifications"],
  2821. 'pin_to_top': sub["pin_to_top"],
  2822. 'stream_id': stream["id"],
  2823. 'description': stream["description"],
  2824. 'email_address': encode_email_address_helper(stream["name"], stream["email_token"])}
  2825. if subscribers is not None:
  2826. stream_dict['subscribers'] = subscribers
  2827. if sub["active"]:
  2828. subscribed.append(stream_dict)
  2829. else:
  2830. unsubscribed.append(stream_dict)
  2831.  
  2832. all_streams_id_set = set(all_streams_id)
  2833. # Listing public streams are disabled for Zephyr mirroring realms.
  2834. if user_profile.realm.is_zephyr_mirror_realm:
  2835. never_subscribed_stream_ids = set() # type: Set[int]
  2836. else:
  2837. never_subscribed_stream_ids = all_streams_id_set - sub_unsub_stream_ids
  2838. never_subscribed_streams = [ns_stream_dict for ns_stream_dict in all_streams
  2839. if ns_stream_dict['id'] in never_subscribed_stream_ids]
  2840.  
  2841. for stream in never_subscribed_streams:
  2842. if not stream['invite_only']:
  2843. stream_dict = {'name': stream['name'],
  2844. 'invite_only': stream['invite_only'],
  2845. 'stream_id': stream['id'],
  2846. 'description': stream['description']}
  2847. subscribers = subscriber_map[stream["id"]]
  2848. if subscribers is not None:
  2849. stream_dict['subscribers'] = subscribers
  2850. never_subscribed.append(stream_dict)
  2851.  
  2852. return (sorted(subscribed, key=lambda x: x['name']),
  2853. sorted(unsubscribed, key=lambda x: x['name']),
  2854. sorted(never_subscribed, key=lambda x: x['name']))
  2855.  
  2856. def gather_subscriptions(user_profile):
  2857. # type: (UserProfile) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]
  2858. subscribed, unsubscribed, never_subscribed = gather_subscriptions_helper(user_profile)
  2859. user_ids = set()
  2860. for subs in [subscribed, unsubscribed, never_subscribed]:
  2861. for sub in subs:
  2862. if 'subscribers' in sub:
  2863. for subscriber in sub['subscribers']:
  2864. user_ids.add(subscriber)
  2865. email_dict = get_emails_from_user_ids(list(user_ids))
  2866.  
  2867. for subs in [subscribed, unsubscribed]:
  2868. for sub in subs:
  2869. if 'subscribers' in sub:
  2870. sub['subscribers'] = [email_dict[user_id] for user_id in sub['subscribers']]
  2871.  
  2872. return (subscribed, unsubscribed)
  2873.  
  2874. def get_status_dict(requesting_user_profile):
  2875. # type: (UserProfile) -> Dict[text_type, Dict[text_type, Dict[str, Any]]]
  2876. if requesting_user_profile.realm.presence_disabled:
  2877. # Return an empty dict if presence is disabled in this realm
  2878. return defaultdict(dict)
  2879.  
  2880. return UserPresence.get_status_dict_by_realm(requesting_user_profile.realm_id)
  2881.  
  2882.  
  2883. def get_realm_user_dicts(user_profile):
  2884. # type: (UserProfile) -> List[Dict[str, text_type]]
  2885. return [{'email' : userdict['email'],
  2886. 'user_id' : userdict['id'],
  2887. 'is_admin' : userdict['is_realm_admin'],
  2888. 'is_bot' : userdict['is_bot'],
  2889. 'full_name' : userdict['full_name']}
  2890. for userdict in get_active_user_dicts_in_realm(user_profile.realm)]
  2891.  
  2892. def get_cross_realm_dicts():
  2893. # type: () -> List[Dict[str, Any]]
  2894. users = [get_user_profile_by_email(email) for email in get_cross_realm_emails()]
  2895. return [{'email' : user.email,
  2896. 'user_id' : user.id,
  2897. 'is_admin' : user.is_realm_admin,
  2898. 'is_bot' : user.is_bot,
  2899. 'full_name' : user.full_name}
  2900. for user in users]
  2901.  
  2902. # Fetch initial data. When event_types is not specified, clients want
  2903. # all event types. Whenever you add new code to this function, you
  2904. # should also add corresponding events for changes in the data
  2905. # structures and new code to apply_events (and add a test in EventsRegisterTest).
  2906. def fetch_initial_state_data(user_profile, event_types, queue_id):
  2907. # type: (UserProfile, Optional[Iterable[str]], str) -> Dict[str, Any]
  2908. state = {'queue_id': queue_id} # type: Dict[str, Any]
  2909.  
  2910. if event_types is None:
  2911. want = lambda msg_type: True
  2912. else:
  2913. want = set(event_types).__contains__
  2914.  
  2915. if want('alert_words'):
  2916. state['alert_words'] = user_alert_words(user_profile)
  2917.  
  2918. if want('message'):
  2919. # The client should use get_old_messages() to fetch messages
  2920. # starting with the max_message_id. They will get messages
  2921. # newer than that ID via get_events()
  2922. messages = Message.objects.filter(usermessage__user_profile=user_profile).order_by('-id')[:1]
  2923. if messages:
  2924. state['max_message_id'] = messages[0].id
  2925. else:
  2926. state['max_message_id'] = -1
  2927.  
  2928. if want('muted_topics'):
  2929. state['muted_topics'] = ujson.loads(user_profile.muted_topics)
  2930.  
  2931. if want('pointer'):
  2932. state['pointer'] = user_profile.pointer
  2933.  
  2934. if want('presence'):
  2935. state['presences'] = get_status_dict(user_profile)
  2936.  
  2937. if want('realm'):
  2938. state['realm_name'] = user_profile.realm.name
  2939. state['realm_restricted_to_domain'] = user_profile.realm.restricted_to_domain
  2940. state['realm_invite_required'] = user_profile.realm.invite_required
  2941. state['realm_invite_by_admins_only'] = user_profile.realm.invite_by_admins_only
  2942. state['realm_authentication_methods'] = user_profile.realm.authentication_methods_dict()
  2943. state['realm_create_stream_by_admins_only'] = user_profile.realm.create_stream_by_admins_only
  2944. state['realm_allow_message_editing'] = user_profile.realm.allow_message_editing
  2945. state['realm_message_content_edit_limit_seconds'] = user_profile.realm.message_content_edit_limit_seconds
  2946. state['realm_default_language'] = user_profile.realm.default_language
  2947.  
  2948. if want('realm_domain'):
  2949. state['realm_domain'] = user_profile.realm.domain
  2950.  
  2951. if want('realm_emoji'):
  2952. state['realm_emoji'] = user_profile.realm.get_emoji()
  2953.  
  2954. if want('realm_filters'):
  2955. state['realm_filters'] = realm_filters_for_domain(user_profile.realm.domain)
  2956.  
  2957. if want('realm_user'):
  2958. state['realm_users'] = get_realm_user_dicts(user_profile)
  2959.  
  2960. if want('realm_bot'):
  2961. state['realm_bots'] = get_owned_bot_dicts(user_profile)
  2962.  
  2963. if want('referral'):
  2964. state['referrals'] = {'granted': user_profile.invites_granted,
  2965. 'used': user_profile.invites_used}
  2966.  
  2967. if want('subscription'):
  2968. subscriptions, unsubscribed, never_subscribed = gather_subscriptions_helper(user_profile)
  2969. state['subscriptions'] = subscriptions
  2970. state['unsubscribed'] = unsubscribed
  2971. state['never_subscribed'] = never_subscribed
  2972.  
  2973. if want('update_message_flags'):
  2974. # There's no initial data for message flag updates, client will
  2975. # get any updates during a session from get_events()
  2976. pass
  2977.  
  2978. if want('stream'):
  2979. state['streams'] = do_get_streams(user_profile)
  2980. if want('default_streams'):
  2981. state['realm_default_streams'] = streams_to_dicts_sorted(get_default_streams_for_realm(user_profile.realm))
  2982.  
  2983. if want('update_display_settings'):
  2984. state['twenty_four_hour_time'] = user_profile.twenty_four_hour_time
  2985. state['left_side_userlist'] = user_profile.left_side_userlist
  2986.  
  2987. default_language = user_profile.default_language
  2988. if user_profile.default_language == 'zh_HANS':
  2989. # NB: remove this once we upgrade to Django 1.9
  2990. # zh-cn and zh-tw will be replaced by zh-hans and zh-hant in
  2991. # Django 1.9
  2992. default_language = 'zh_CN'
  2993.  
  2994. state['default_language'] = default_language
  2995.  
  2996. return state
  2997.  
  2998. def apply_events(state, events, user_profile):
  2999. # type: (Dict[str, Any], Iterable[Dict[str, Any]], UserProfile) -> None
  3000. for event in events:
  3001. if event['type'] == "message":
  3002. state['max_message_id'] = max(state['max_message_id'], event['message']['id'])
  3003. elif event['type'] == "pointer":
  3004. state['pointer'] = max(state['pointer'], event['pointer'])
  3005. elif event['type'] == "realm_user":
  3006. person = event['person']
  3007.  
  3008. def our_person(p):
  3009. # type: (Dict[str, Any]) -> bool
  3010. return p['email'] == person['email']
  3011.  
  3012. if event['op'] == "add":
  3013. state['realm_users'].append(person)
  3014. elif event['op'] == "remove":
  3015. state['realm_users'] = [user for user in state['realm_users'] if not our_person(user)]
  3016. elif event['op'] == 'update':
  3017. for p in state['realm_users']:
  3018. if our_person(p):
  3019. # In the unlikely event that the current user
  3020. # just changed to/from being an admin, we need
  3021. # to add/remove the data on all bots in the
  3022. # realm. This is ugly and probably better
  3023. # solved by removing the all-realm-bots data
  3024. # given to admin users from this flow.
  3025. if ('is_admin' in person and 'realm_bots' in state and
  3026. user_profile.email == person['email']):
  3027. if p['is_admin'] and not person['is_admin']:
  3028. state['realm_bots'] = []
  3029. if not p['is_admin'] and person['is_admin']:
  3030. state['realm_bots'] = get_owned_bot_dicts(user_profile)
  3031. # Now update the person
  3032. p.update(person)
  3033. elif event['type'] == 'realm_bot':
  3034. if event['op'] == 'add':
  3035. state['realm_bots'].append(event['bot'])
  3036.  
  3037. if event['op'] == 'remove':
  3038. email = event['bot']['email']
  3039. state['realm_bots'] = [b for b in state['realm_bots'] if b['email'] != email]
  3040.  
  3041. if event['op'] == 'update':
  3042. for bot in state['realm_bots']:
  3043. if bot['email'] == event['bot']['email']:
  3044. bot.update(event['bot'])
  3045.  
  3046. elif event['type'] == 'stream':
  3047. if event['op'] == 'create':
  3048. for stream in event['streams']:
  3049. if not stream['invite_only']:
  3050. stream_data = copy.deepcopy(stream)
  3051. stream_data['subscribers'] = []
  3052. # Add stream to never_subscribed (if not invite_only)
  3053. state['never_subscribed'].append(stream_data)
  3054.  
  3055. if event['op'] == 'delete':
  3056. deleted_stream_ids = {stream['stream_id'] for stream in event['streams']}
  3057. state['streams'] = [s for s in state['streams'] if s['stream_id'] not in deleted_stream_ids]
  3058. state['never_subscribed'] = [stream for stream in state['never_subscribed'] if
  3059. stream['stream_id'] not in deleted_stream_ids]
  3060.  
  3061. if event['op'] == 'update':
  3062. # For legacy reasons, we call stream data 'subscriptions' in
  3063. # the state var here, for the benefit of the JS code.
  3064. for obj in state['subscriptions']:
  3065. if obj['name'].lower() == event['name'].lower():
  3066. obj[event['property']] = event['value']
  3067. # Also update the pure streams data
  3068. for stream in state['streams']:
  3069. if stream['name'].lower() == event['name'].lower():
  3070. prop = event['property']
  3071. if prop in stream:
  3072. stream[prop] = event['value']
  3073. elif event['op'] == "occupy":
  3074. state['streams'] += event['streams']
  3075. elif event['op'] == "vacate":
  3076. stream_ids = [s["stream_id"] for s in event['streams']]
  3077. state['streams'] = [s for s in state['streams'] if s["stream_id"] not in stream_ids]
  3078. elif event['type'] == 'default_streams':
  3079. state['realm_default_streams'] = event['default_streams']
  3080. elif event['type'] == 'realm':
  3081. if event['op'] == "update":
  3082. field = 'realm_' + event['property']
  3083. state[field] = event['value']
  3084. elif event['op'] == "update_dict":
  3085. for key, value in event['data'].items():
  3086. state['realm_' + key] = value
  3087. elif event['type'] == "subscription":
  3088. if event['op'] in ["add"]:
  3089. # Convert the user_profile IDs to emails since that's what register() returns
  3090. # TODO: Clean up this situation
  3091. for item in event["subscriptions"]:
  3092. item["subscribers"] = [get_user_profile_by_email(email).id for email in item["subscribers"]]
  3093.  
  3094. def name(sub):
  3095. # type: (Dict[str, Any]) -> text_type
  3096. return sub['name'].lower()
  3097.  
  3098. if event['op'] == "add":
  3099. added_names = set(map(name, event["subscriptions"]))
  3100. was_added = lambda s: name(s) in added_names
  3101.  
  3102. # add the new subscriptions
  3103. state['subscriptions'] += event['subscriptions']
  3104.  
  3105. # remove them from unsubscribed if they had been there
  3106. state['unsubscribed'] = [s for s in state['unsubscribed'] if not was_added(s)]
  3107.  
  3108. # remove them from never_subscribed if they had been there
  3109. state['never_subscribed'] = [s for s in state['never_subscribed'] if not was_added(s)]
  3110.  
  3111. elif event['op'] == "remove":
  3112. removed_names = set(map(name, event["subscriptions"]))
  3113. was_removed = lambda s: name(s) in removed_names
  3114.  
  3115. # Find the subs we are affecting.
  3116. removed_subs = list(filter(was_removed, state['subscriptions']))
  3117.  
  3118. # Remove our user from the subscribers of the removed subscriptions.
  3119. for sub in removed_subs:
  3120. sub['subscribers'] = [id for id in sub['subscribers'] if id != user_profile.id]
  3121.  
  3122. # We must effectively copy the removed subscriptions from subscriptions to
  3123. # unsubscribe, since we only have the name in our data structure.
  3124. state['unsubscribed'] += removed_subs
  3125.  
  3126. # Now filter out the removed subscriptions from subscriptions.
  3127. state['subscriptions'] = [s for s in state['subscriptions'] if not was_removed(s)]
  3128.  
  3129. elif event['op'] == 'update':
  3130. for sub in state['subscriptions']:
  3131. if sub['name'].lower() == event['name'].lower():
  3132. sub[event['property']] = event['value']
  3133. elif event['op'] == 'peer_add':
  3134. user_id = event['user_id']
  3135. for sub in state['subscriptions']:
  3136. if (sub['name'] in event['subscriptions'] and
  3137. user_id not in sub['subscribers']):
  3138. sub['subscribers'].append(user_id)
  3139. for sub in state['never_subscribed']:
  3140. if (sub['name'] in event['subscriptions'] and
  3141. user_id not in sub['subscribers']):
  3142. sub['subscribers'].append(user_id)
  3143. elif event['op'] == 'peer_remove':
  3144. user_id = event['user_id']
  3145. for sub in state['subscriptions']:
  3146. if (sub['name'] in event['subscriptions'] and
  3147. user_id in sub['subscribers']):
  3148. sub['subscribers'].remove(user_id)
  3149. elif event['type'] == "presence":
  3150. state['presences'][event['email']] = event['presence']
  3151. elif event['type'] == "update_message":
  3152. # The client will get the updated message directly
  3153. pass
  3154. elif event['type'] == "referral":
  3155. state['referrals'] = event['referrals']
  3156. elif event['type'] == "update_message_flags":
  3157. # The client will get the message with the updated flags directly
  3158. pass
  3159. elif event['type'] == "realm_emoji":
  3160. state['realm_emoji'] = event['realm_emoji']
  3161. elif event['type'] == "alert_words":
  3162. state['alert_words'] = event['alert_words']
  3163. elif event['type'] == "muted_topics":
  3164. state['muted_topics'] = event["muted_topics"]
  3165. elif event['type'] == "realm_filters":
  3166. state['realm_filters'] = event["realm_filters"]
  3167. elif event['type'] == "update_display_settings":
  3168. if event['setting_name'] == "twenty_four_hour_time":
  3169. state['twenty_four_hour_time'] = event["setting"]
  3170. if event['setting_name'] == 'left_side_userlist':
  3171. state['left_side_userlist'] = event["setting"]
  3172. else:
  3173. raise ValueError("Unexpected event type %s" % (event['type'],))
  3174.  
  3175. def do_events_register(user_profile, user_client, apply_markdown=True,
  3176. event_types=None, queue_lifespan_secs=0, all_public_streams=False,
  3177. narrow=[]):
  3178. # type: (UserProfile, Client, bool, Optional[Iterable[str]], int, bool, Iterable[Sequence[text_type]]) -> Dict[str, Any]
  3179. # Technically we don't need to check this here because
  3180. # build_narrow_filter will check it, but it's nicer from an error
  3181. # handling perspective to do it before contacting Tornado
  3182. check_supported_events_narrow_filter(narrow)
  3183. queue_id = request_event_queue(user_profile, user_client, apply_markdown,
  3184. queue_lifespan_secs, event_types, all_public_streams,
  3185. narrow=narrow)
  3186.  
  3187. if queue_id is None:
  3188. raise JsonableError(_("Could not allocate event queue"))
  3189. if event_types is not None:
  3190. event_types_set = set(event_types) # type: Optional[Set[str]]
  3191. else:
  3192. event_types_set = None
  3193.  
  3194. ret = fetch_initial_state_data(user_profile, event_types_set, queue_id)
  3195.  
  3196. # Apply events that came in while we were fetching initial data
  3197. events = get_user_events(user_profile, queue_id, -1)
  3198. apply_events(ret, events, user_profile)
  3199. if events:
  3200. ret['last_event_id'] = events[-1]['id']
  3201. else:
  3202. ret['last_event_id'] = -1
  3203. return ret
  3204.  
  3205. def do_send_confirmation_email(invitee, referrer):
  3206. # type: (PreregistrationUser, UserProfile) -> None
  3207. """
  3208. Send the confirmation/welcome e-mail to an invited user.
  3209.  
  3210. `invitee` is a PreregistrationUser.
  3211. `referrer` is a UserProfile.
  3212. """
  3213. subject_template_path = 'confirmation/invite_email_subject.txt'
  3214. body_template_path = 'confirmation/invite_email_body.txt'
  3215. context = {'referrer': referrer,
  3216. 'support_email': settings.ZULIP_ADMINISTRATOR,
  3217. 'verbose_support_offers': settings.VERBOSE_SUPPORT_OFFERS}
  3218.  
  3219. if referrer.realm.is_zephyr_mirror_realm:
  3220. subject_template_path = 'confirmation/mituser_invite_email_subject.txt'
  3221. body_template_path = 'confirmation/mituser_invite_email_body.txt'
  3222.  
  3223. Confirmation.objects.send_confirmation(
  3224. invitee, invitee.email, additional_context=context,
  3225. subject_template_path=subject_template_path,
  3226. body_template_path=body_template_path, host=referrer.realm.host)
  3227.  
  3228. @statsd_increment("push_notifications")
  3229. def handle_push_notification(user_profile_id, missed_message):
  3230. # type: (int, Dict[str, Any]) -> None
  3231. try:
  3232. user_profile = get_user_profile_by_id(user_profile_id)
  3233. if not (receives_offline_notifications(user_profile) or receives_online_notifications(user_profile)):
  3234. return
  3235.  
  3236. umessage = UserMessage.objects.get(user_profile=user_profile,
  3237. message__id=missed_message['message_id'])
  3238. message = umessage.message
  3239. if umessage.flags.read:
  3240. return
  3241. sender_str = message.sender.full_name
  3242.  
  3243. apple = num_push_devices_for_user(user_profile, kind=PushDeviceToken.APNS)
  3244. android = num_push_devices_for_user(user_profile, kind=PushDeviceToken.GCM)
  3245.  
  3246. if apple or android:
  3247. # TODO: set badge count in a better way
  3248. # Determine what alert string to display based on the missed messages
  3249. if message.recipient.type == Recipient.HUDDLE:
  3250. alert = "New private group message from %s" % (sender_str,)
  3251. elif message.recipient.type == Recipient.PERSONAL:
  3252. alert = "New private message from %s" % (sender_str,)
  3253. elif message.recipient.type == Recipient.STREAM:
  3254. alert = "New mention from %s" % (sender_str,)
  3255. else:
  3256. alert = "New Zulip mentions and private messages from %s" % (sender_str,)
  3257.  
  3258. if apple:
  3259. apple_extra_data = {'message_ids': [message.id]}
  3260. send_apple_push_notification(user_profile, alert, badge=1, zulip=apple_extra_data)
  3261.  
  3262. if android:
  3263. content = message.content
  3264. content_truncated = (len(content) > 200)
  3265. if content_truncated:
  3266. content = content[:200] + "..."
  3267.  
  3268. android_data = {
  3269. 'user': user_profile.email,
  3270. 'event': 'message',
  3271. 'alert': alert,
  3272. 'zulip_message_id': message.id, # message_id is reserved for CCS
  3273. 'time': datetime_to_timestamp(message.pub_date),
  3274. 'content': content,
  3275. 'content_truncated': content_truncated,
  3276. 'sender_email': message.sender.email,
  3277. 'sender_full_name': message.sender.full_name,
  3278. 'sender_avatar_url': get_avatar_url(message.sender.avatar_source, message.sender.email),
  3279. }
  3280.  
  3281. if message.recipient.type == Recipient.STREAM:
  3282. android_data['recipient_type'] = "stream"
  3283. android_data['stream'] = get_display_recipient(message.recipient)
  3284. android_data['topic'] = message.subject
  3285. elif message.recipient.type in (Recipient.HUDDLE, Recipient.PERSONAL):
  3286. android_data['recipient_type'] = "private"
  3287.  
  3288. send_android_push_notification(user_profile, android_data)
  3289.  
  3290. except UserMessage.DoesNotExist:
  3291. logging.error("Could not find UserMessage with message_id %s" %(missed_message['message_id'],))
  3292.  
  3293. def is_inactive(email):
  3294. # type: (text_type) -> None
  3295. try:
  3296. if get_user_profile_by_email(email).is_active:
  3297. raise ValidationError(u'%s is already active' % (email,))
  3298. except UserProfile.DoesNotExist:
  3299. pass
  3300.  
  3301. def user_email_is_unique(email):
  3302. # type: (text_type) -> None
  3303. try:
  3304. get_user_profile_by_email(email)
  3305. raise ValidationError(u'%s is already registered' % (email,))
  3306. except UserProfile.DoesNotExist:
  3307. pass
  3308.  
  3309. def do_invite_users(user_profile, invitee_emails, streams):
  3310. # type: (UserProfile, SizedTextIterable, Iterable[Stream]) -> Tuple[Optional[str], Dict[str, List[Tuple[text_type, str]]]]
  3311. new_prereg_users = [] # type: List[PreregistrationUser]
  3312. errors = [] # type: List[Tuple[text_type, str]]
  3313. skipped = [] # type: List[Tuple[text_type, str]]
  3314.  
  3315. ret_error = None # type: Optional[str]
  3316. ret_error_data = {} # type: Dict[str, List[Tuple[text_type, str]]]
  3317.  
  3318. for email in invitee_emails:
  3319. if email == '':
  3320. continue
  3321.  
  3322. try:
  3323. validators.validate_email(email)
  3324. except ValidationError:
  3325. errors.append((email, _("Invalid address.")))
  3326. continue
  3327.  
  3328. if not email_allowed_for_realm(email, user_profile.realm):
  3329. errors.append((email, _("Outside your domain.")))
  3330. continue
  3331.  
  3332. try:
  3333. existing_user_profile = get_user_profile_by_email(email)
  3334. except UserProfile.DoesNotExist:
  3335. existing_user_profile = None
  3336. try:
  3337. if existing_user_profile is not None and existing_user_profile.is_mirror_dummy:
  3338. # Mirror dummy users to be activated must be inactive
  3339. is_inactive(email)
  3340. else:
  3341. # Other users should not already exist at all.
  3342. user_email_is_unique(email)
  3343. except ValidationError:
  3344. skipped.append((email, _("Already has an account.")))
  3345. continue
  3346.  
  3347. # The logged in user is the referrer.
  3348. prereg_user = PreregistrationUser(email=email, referred_by=user_profile)
  3349.  
  3350. # We save twice because you cannot associate a ManyToMany field
  3351. # on an unsaved object.
  3352. prereg_user.save()
  3353. prereg_user.streams = streams
  3354. prereg_user.save()
  3355.  
  3356. new_prereg_users.append(prereg_user)
  3357.  
  3358. if errors:
  3359. ret_error = _("Some emails did not validate, so we didn't send any invitations.")
  3360. ret_error_data = {'errors': errors}
  3361.  
  3362. if skipped and len(skipped) == len(invitee_emails):
  3363. # All e-mails were skipped, so we didn't actually invite anyone.
  3364. ret_error = _("We weren't able to invite anyone.")
  3365. ret_error_data = {'errors': skipped}
  3366. return ret_error, ret_error_data
  3367.  
  3368. # If we encounter an exception at any point before now, there are no unwanted side-effects,
  3369. # since it is totally fine to have duplicate PreregistrationUsers
  3370. for user in new_prereg_users:
  3371. event = {"email": user.email, "referrer_email": user_profile.email}
  3372. queue_json_publish("invites", event,
  3373. lambda event: do_send_confirmation_email(user, user_profile))
  3374.  
  3375. if skipped:
  3376. ret_error = _("Some of those addresses are already using Zulip, "
  3377. "so we didn't send them an invitation. We did send "
  3378. "invitations to everyone else!")
  3379. ret_error_data = {'errors': skipped}
  3380.  
  3381. return ret_error, ret_error_data
  3382.  
  3383. def send_referral_event(user_profile):
  3384. # type: (UserProfile) -> None
  3385. event = dict(type="referral",
  3386. referrals=dict(granted=user_profile.invites_granted,
  3387. used=user_profile.invites_used))
  3388. send_event(event, [user_profile.id])
  3389.  
  3390. def do_refer_friend(user_profile, email):
  3391. # type: (UserProfile, text_type) -> None
  3392. content = ('Referrer: "%s" <%s>\n'
  3393. 'Realm: %s\n'
  3394. 'Referred: %s') % (user_profile.full_name, user_profile.email,
  3395. user_profile.realm.domain, email)
  3396. subject = "Zulip referral: %s" % (email,)
  3397. from_email = '"%s" <%s>' % (user_profile.full_name, 'referrals@zulip.com')
  3398. to_email = '"Zulip Referrals" <zulip+referrals@zulip.com>'
  3399. headers = {'Reply-To' : '"%s" <%s>' % (user_profile.full_name, user_profile.email,)}
  3400. msg = EmailMessage(subject, content, from_email, [to_email], headers=headers)
  3401. msg.send()
  3402.  
  3403. referral = Referral(user_profile=user_profile, email=email)
  3404. referral.save()
  3405. user_profile.invites_used += 1
  3406. user_profile.save(update_fields=['invites_used'])
  3407.  
  3408. send_referral_event(user_profile)
  3409.  
  3410. def notify_realm_emoji(realm):
  3411. # type: (Realm) -> None
  3412. event = dict(type="realm_emoji", op="update",
  3413. realm_emoji=realm.get_emoji())
  3414. user_ids = [userdict['id'] for userdict in get_active_user_dicts_in_realm(realm)]
  3415. send_event(event, user_ids)
  3416.  
  3417. def check_add_realm_emoji(realm, name, img_url):
  3418. # type: (Realm, text_type, text_type) -> None
  3419. emoji = RealmEmoji(realm=realm, name=name, img_url=img_url)
  3420. emoji.full_clean()
  3421. emoji.save()
  3422. notify_realm_emoji(realm)
  3423.  
  3424. def do_remove_realm_emoji(realm, name):
  3425. # type: (Realm, text_type) -> None
  3426. RealmEmoji.objects.get(realm=realm, name=name).delete()
  3427. notify_realm_emoji(realm)
  3428.  
  3429. def notify_alert_words(user_profile, words):
  3430. # type: (UserProfile, Iterable[text_type]) -> None
  3431. event = dict(type="alert_words", alert_words=words)
  3432. send_event(event, [user_profile.id])
  3433.  
  3434. def do_add_alert_words(user_profile, alert_words):
  3435. # type: (UserProfile, Iterable[text_type]) -> None
  3436. words = add_user_alert_words(user_profile, alert_words)
  3437. notify_alert_words(user_profile, words)
  3438.  
  3439. def do_remove_alert_words(user_profile, alert_words):
  3440. # type: (UserProfile, Iterable[text_type]) -> None
  3441. words = remove_user_alert_words(user_profile, alert_words)
  3442. notify_alert_words(user_profile, words)
  3443.  
  3444. def do_set_alert_words(user_profile, alert_words):
  3445. # type: (UserProfile, List[text_type]) -> None
  3446. set_user_alert_words(user_profile, alert_words)
  3447. notify_alert_words(user_profile, alert_words)
  3448.  
  3449. def do_set_muted_topics(user_profile, muted_topics):
  3450. # type: (UserProfile, Union[List[List[text_type]], List[Tuple[text_type, text_type]]]) -> None
  3451. user_profile.muted_topics = ujson.dumps(muted_topics)
  3452. user_profile.save(update_fields=['muted_topics'])
  3453. event = dict(type="muted_topics", muted_topics=muted_topics)
  3454. send_event(event, [user_profile.id])
  3455.  
  3456. def notify_realm_filters(realm):
  3457. # type: (Realm) -> None
  3458. realm_filters = realm_filters_for_domain(realm.domain)
  3459. user_ids = [userdict['id'] for userdict in get_active_user_dicts_in_realm(realm)]
  3460. event = dict(type="realm_filters", realm_filters=realm_filters)
  3461. send_event(event, user_ids)
  3462.  
  3463. # NOTE: Regexes must be simple enough that they can be easily translated to JavaScript
  3464. # RegExp syntax. In addition to JS-compatible syntax, the following features are available:
  3465. # * Named groups will be converted to numbered groups automatically
  3466. # * Inline-regex flags will be stripped, and where possible translated to RegExp-wide flags
  3467. def do_add_realm_filter(realm, pattern, url_format_string):
  3468. # type: (Realm, text_type, text_type) -> int
  3469. pattern = pattern.strip()
  3470. url_format_string = url_format_string.strip()
  3471. realm_filter = RealmFilter(
  3472. realm=realm, pattern=pattern,
  3473. url_format_string=url_format_string)
  3474. realm_filter.full_clean()
  3475. realm_filter.save()
  3476. notify_realm_filters(realm)
  3477.  
  3478. return realm_filter.id
  3479.  
  3480. def do_remove_realm_filter(realm, pattern=None, id=None):
  3481. # type: (Realm, Optional[text_type], Optional[int]) -> None
  3482. if pattern is not None:
  3483. RealmFilter.objects.get(realm=realm, pattern=pattern).delete()
  3484. else:
  3485. RealmFilter.objects.get(realm=realm, pk=id).delete()
  3486. notify_realm_filters(realm)
  3487.  
  3488. def get_emails_from_user_ids(user_ids):
  3489. # type: (Sequence[int]) -> Dict[int, text_type]
  3490. # We may eventually use memcached to speed this up, but the DB is fast.
  3491. return UserProfile.emails_from_ids(user_ids)
  3492.  
  3493. def realm_aliases(realm):
  3494. # type: (Realm) -> List[text_type]
  3495. return [alias.domain for alias in realm.realmalias_set.all()]
  3496.  
  3497. def get_occupied_streams(realm):
  3498. # type: (Realm) -> QuerySet
  3499. # TODO: Make a generic stub for QuerySet
  3500. """ Get streams with subscribers """
  3501. subs_filter = Subscription.objects.filter(active=True, user_profile__realm=realm,
  3502. user_profile__is_active=True).values('recipient_id')
  3503. stream_ids = Recipient.objects.filter(
  3504. type=Recipient.STREAM, id__in=subs_filter).values('type_id')
  3505.  
  3506. return Stream.objects.filter(id__in=stream_ids, realm=realm, deactivated=False)
  3507.  
  3508. def do_get_streams(user_profile, include_public=True, include_subscribed=True,
  3509. include_all_active=False, include_default=False):
  3510. # type: (UserProfile, bool, bool, bool, bool) -> List[Dict[str, Any]]
  3511. if include_all_active and not user_profile.is_api_super_user:
  3512. raise JsonableError(_("User not authorized for this query"))
  3513.  
  3514. # Listing public streams are disabled for Zephyr mirroring realms.
  3515. include_public = include_public and not user_profile.realm.is_zephyr_mirror_realm
  3516. # Start out with all streams in the realm with subscribers
  3517. query = get_occupied_streams(user_profile.realm)
  3518.  
  3519. if not include_all_active:
  3520. user_subs = Subscription.objects.select_related("recipient").filter(
  3521. active=True, user_profile=user_profile,
  3522. recipient__type=Recipient.STREAM)
  3523.  
  3524. if include_subscribed:
  3525. recipient_check = Q(id__in=[sub.recipient.type_id for sub in user_subs])
  3526. if include_public:
  3527. invite_only_check = Q(invite_only=False)
  3528.  
  3529. if include_subscribed and include_public:
  3530. query = query.filter(recipient_check | invite_only_check)
  3531. elif include_public:
  3532. query = query.filter(invite_only_check)
  3533. elif include_subscribed:
  3534. query = query.filter(recipient_check)
  3535. else:
  3536. # We're including nothing, so don't bother hitting the DB.
  3537. query = []
  3538.  
  3539. streams = [(row.to_dict()) for row in query]
  3540. streams.sort(key=lambda elt: elt["name"])
  3541. if include_default:
  3542. is_default = {}
  3543. default_streams = get_default_streams_for_realm(user_profile.realm)
  3544. for default_stream in default_streams:
  3545. is_default[default_stream.id] = True
  3546. for stream in streams:
  3547. stream['is_default'] = is_default.get(stream["stream_id"], False)
  3548.  
  3549. return streams
  3550.  
  3551. def do_claim_attachments(message):
  3552. # type: (Message) -> List[Tuple[text_type, bool]]
  3553. attachment_url_list = attachment_url_re.findall(message.content)
  3554.  
  3555. results = []
  3556. for url in attachment_url_list:
  3557. path_id = attachment_url_to_path_id(url)
  3558. user_profile = message.sender
  3559. is_message_realm_public = False
  3560. if message.recipient.type == Recipient.STREAM:
  3561. is_message_realm_public = Stream.objects.get(id=message.recipient.type_id).is_public()
  3562.  
  3563. if path_id is not None:
  3564. is_claimed = claim_attachment(user_profile, path_id, message,
  3565. is_message_realm_public)
  3566. results.append((path_id, is_claimed))
  3567.  
  3568. return results
  3569.  
  3570. def do_delete_old_unclaimed_attachments(weeks_ago):
  3571. # type: (int) -> None
  3572. old_unclaimed_attachments = get_old_unclaimed_attachments(weeks_ago)
  3573.  
  3574. for attachment in old_unclaimed_attachments:
  3575. delete_message_image(attachment.path_id)
  3576. attachment.delete()
  3577.  
  3578. def check_attachment_reference_change(prev_content, message):
  3579. # type: (text_type, Message) -> None
  3580. new_content = message.content
  3581. prev_attachments = set(attachment_url_re.findall(prev_content))
  3582. new_attachments = set(attachment_url_re.findall(new_content))
  3583.  
  3584. to_remove = list(prev_attachments - new_attachments)
  3585. path_ids = []
  3586. for url in to_remove:
  3587. path_id = attachment_url_to_path_id(url)
  3588. path_ids.append(path_id)
  3589.  
  3590. attachments_to_update = Attachment.objects.filter(path_id__in=path_ids).select_for_update()
  3591. message.attachment_set.remove(*attachments_to_update)
  3592.  
  3593. to_add = list(new_attachments - prev_attachments)
  3594. if len(to_add) > 0:
  3595. do_claim_attachments(message)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement