models.py 18.6 KB
Newer Older
1 2 3
"""
Models for bulk email
"""
4
import logging
5

6 7
import markupsafe
from config_models.models import ConfigurationModel
8
from django.contrib.auth.models import User
Ned Batchelder committed
9
from django.db import models
10

11 12 13
from course_modes.models import CourseMode
from enrollment.api import validate_course_mode
from enrollment.errors import CourseModeNotFoundError
14 15
from openedx.core.djangoapps.course_groups.cohorts import get_cohort_by_name
from openedx.core.djangoapps.course_groups.models import CourseUserGroup
16
from openedx.core.djangoapps.xmodule_django.models import CourseKeyField
17 18 19
from openedx.core.lib.html_to_text import html_to_text
from openedx.core.lib.mail_utils import wrap_message
from student.roles import CourseInstructorRole, CourseStaffRole
20
from util.keyword_substitution import substitute_keywords_with_data
21
from util.query import use_read_replica_if_available
22

23 24
log = logging.getLogger(__name__)

25 26 27 28 29 30

class Email(models.Model):
    """
    Abstract base class for common information for an email.
    """
    sender = models.ForeignKey(User, default=1, blank=True, null=True)
31
    slug = models.CharField(max_length=128, db_index=True)
32 33
    subject = models.CharField(max_length=128, blank=True)
    html_message = models.TextField(null=True, blank=True)
34
    text_message = models.TextField(null=True, blank=True)
35 36 37
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

38
    class Meta(object):
39
        app_label = "bulk_email"
40 41
        abstract = True

42

43 44 45 46 47
# Bulk email targets - the send to options that users can select from when they send email.
SEND_TO_MYSELF = 'myself'
SEND_TO_STAFF = 'staff'
SEND_TO_LEARNERS = 'learners'
SEND_TO_COHORT = 'cohort'
48
SEND_TO_TRACK = 'track'
49
EMAIL_TARGET_CHOICES = zip(
50 51
    [SEND_TO_MYSELF, SEND_TO_STAFF, SEND_TO_LEARNERS, SEND_TO_COHORT, SEND_TO_TRACK],
    ['Myself', 'Staff and instructors', 'All students', 'Specific cohort', 'Specific course mode']
52 53
)
EMAIL_TARGETS = {target[0] for target in EMAIL_TARGET_CHOICES}
54 55 56 57 58


class Target(models.Model):
    """
    A way to refer to a particular group (within a course) as a "Send to:" target.
59 60 61 62 63 64 65 66

    Django hackery in this class - polymorphism does not work well in django, for reasons relating to how
    each class is represented by its own database table. Due to this, we can't just override
    methods of Target in CohortTarget and get the child method, as one would expect. The
    workaround is to check to see that a given target is a CohortTarget (self.target_type ==
    SEND_TO_COHORT), then explicitly call the method on self.cohorttarget, which is created
    by django as part of this inheritance setup. These calls require pylint disable no-member in
    several locations in this class.
67 68 69 70 71 72 73
    """
    target_type = models.CharField(max_length=64, choices=EMAIL_TARGET_CHOICES)

    class Meta(object):
        app_label = "bulk_email"

    def __unicode__(self):
74 75 76 77 78 79 80 81
        return "CourseEmail Target: {}".format(self.short_display())

    def short_display(self):
        """
        Returns a short display name
        """
        if self.target_type == SEND_TO_COHORT:
            return self.cohorttarget.short_display()  # pylint: disable=no-member
82 83
        elif self.target_type == SEND_TO_TRACK:
            return self.coursemodetarget.short_display()  # pylint: disable=no-member
84 85 86 87 88 89 90 91 92
        else:
            return self.target_type

    def long_display(self):
        """
        Returns a long display name
        """
        if self.target_type == SEND_TO_COHORT:
            return self.cohorttarget.long_display()  # pylint: disable=no-member
93 94
        elif self.target_type == SEND_TO_TRACK:
            return self.coursemodetarget.long_display()  # pylint: disable=no-member
95 96
        else:
            return self.get_target_type_display()
97 98 99 100 101 102 103 104 105 106

    def get_users(self, course_id, user_id=None):
        """
        Gets the users for a given target.

        Result is returned in the form of a queryset, and may contain duplicates.
        """
        staff_qset = CourseStaffRole(course_id).users_with_role()
        instructor_qset = CourseInstructorRole(course_id).users_with_role()
        staff_instructor_qset = (staff_qset | instructor_qset)
107
        enrollment_query = models.Q(
108 109 110 111
            is_active=True,
            courseenrollment__course_id=course_id,
            courseenrollment__is_active=True
        )
112
        enrollment_qset = User.objects.filter(enrollment_query)
113 114 115 116 117 118 119 120
        if self.target_type == SEND_TO_MYSELF:
            if user_id is None:
                raise ValueError("Must define self user to send email to self.")
            user = User.objects.filter(id=user_id)
            return use_read_replica_if_available(user)
        elif self.target_type == SEND_TO_STAFF:
            return use_read_replica_if_available(staff_instructor_qset)
        elif self.target_type == SEND_TO_LEARNERS:
121 122 123
            return use_read_replica_if_available(
                enrollment_qset.exclude(id__in=staff_instructor_qset)
            )
124
        elif self.target_type == SEND_TO_COHORT:
125
            return self.cohorttarget.cohort.users.filter(id__in=enrollment_qset)  # pylint: disable=no-member
126 127
        elif self.target_type == SEND_TO_TRACK:
            return use_read_replica_if_available(
128 129 130
                User.objects.filter(
                    models.Q(courseenrollment__mode=self.coursemodetarget.track.mode_slug)
                    & enrollment_query
131 132
                )
            )
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
        else:
            raise ValueError("Unrecognized target type {}".format(self.target_type))


class CohortTarget(Target):
    """
    Subclass of Target, specifically referring to a cohort.
    """
    cohort = models.ForeignKey('course_groups.CourseUserGroup')

    class Meta:
        app_label = "bulk_email"

    def __init__(self, *args, **kwargs):
        kwargs['target_type'] = SEND_TO_COHORT
        super(CohortTarget, self).__init__(*args, **kwargs)

150 151 152
    def __unicode__(self):
        return self.short_display()

153 154 155 156 157
    def short_display(self):
        return "{}-{}".format(self.target_type, self.cohort.name)

    def long_display(self):
        return "Cohort: {}".format(self.cohort.name)
158 159 160 161 162 163 164 165 166 167 168

    @classmethod
    def ensure_valid_cohort(cls, cohort_name, course_id):
        """
        Ensures cohort_name is a valid cohort for course_id.

        Returns the cohort if valid, raises an error otherwise.
        """
        if cohort_name is None:
            raise ValueError("Cannot create a CohortTarget without specifying a cohort_name.")
        try:
169
            cohort = get_cohort_by_name(name=cohort_name, course_key=course_id)
170 171 172 173 174 175 176 177 178 179
        except CourseUserGroup.DoesNotExist:
            raise ValueError(
                "Cohort {cohort} does not exist in course {course_id}".format(
                    cohort=cohort_name,
                    course_id=course_id
                )
            )
        return cohort


180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
class CourseModeTarget(Target):
    """
    Subclass of Target, specifically for course modes.
    """
    track = models.ForeignKey('course_modes.CourseMode')

    class Meta:
        app_label = "bulk_email"

    def __init__(self, *args, **kwargs):
        kwargs['target_type'] = SEND_TO_TRACK
        super(CourseModeTarget, self).__init__(*args, **kwargs)

    def __unicode__(self):
        return self.short_display()

    def short_display(self):
        return "{}-{}".format(self.target_type, self.track.mode_slug)  # pylint: disable=no-member

    def long_display(self):
        all_modes = CourseMode.objects.filter(
            course_id=self.track.course_id,
            mode_slug=self.track.mode_slug,  # pylint: disable=no-member
        )
        return "Course mode: {}, Currencies: {}".format(
            self.track.mode_display_name,  # pylint: disable=no-member
            ", ".join([mode.currency for mode in all_modes])
        )

    @classmethod
    def ensure_valid_mode(cls, mode_slug, course_id):
        """
        Ensures mode_slug is a valid mode for course_id. Will raise an error if invalid.
        """
        if mode_slug is None:
            raise ValueError("Cannot create a CourseModeTarget without specifying a mode_slug.")
        try:
217
            validate_course_mode(unicode(course_id), mode_slug, include_expired=True)
218 219 220 221 222 223 224 225 226
        except CourseModeNotFoundError:
            raise ValueError(
                "Track {track} does not exist in course {course_id}".format(
                    track=mode_slug,
                    course_id=course_id
                )
            )


227
class CourseEmail(Email):
228 229 230
    """
    Stores information for an email to a course.
    """
231 232 233
    class Meta(object):
        app_label = "bulk_email"

234
    course_id = CourseKeyField(max_length=255, db_index=True)
235 236 237
    # to_option is deprecated and unused, but dropping db columns is hard so it's still here for legacy reasons
    to_option = models.CharField(max_length=64, choices=[("deprecated", "deprecated")])
    targets = models.ManyToManyField(Target)
238 239
    template_name = models.CharField(null=True, max_length=255)
    from_addr = models.CharField(null=True, max_length=255)
240 241 242 243

    def __unicode__(self):
        return self.subject

244
    @classmethod
245
    def create(
246
            cls, course_id, sender, targets, subject, html_message,
247
            text_message=None, template_name=None, from_addr=None):
248 249 250 251 252 253 254
        """
        Create an instance of CourseEmail.
        """
        # automatically generate the stripped version of the text from the HTML markup:
        if text_message is None:
            text_message = html_to_text(html_message)

255 256
        new_targets = []
        for target in targets:
257
            # split target, to handle cohort:cohort_name and track:mode_slug
258
            target_split = target.split(':', 1)
259
            # Ensure our desired target exists
260
            if target_split[0] not in EMAIL_TARGETS:
261 262 263
                fmt = 'Course email being sent to unrecognized target: "{target}" for "{course}", subject "{subject}"'
                msg = fmt.format(target=target, course=course_id, subject=subject)
                raise ValueError(msg)
264 265 266 267
            elif target_split[0] == SEND_TO_COHORT:
                # target_split[1] will contain the cohort name
                cohort = CohortTarget.ensure_valid_cohort(target_split[1], course_id)
                new_target, _ = CohortTarget.objects.get_or_create(target_type=target_split[0], cohort=cohort)
268 269 270 271 272 273 274 275
            elif target_split[0] == SEND_TO_TRACK:
                # target_split[1] contains the desired mode slug
                CourseModeTarget.ensure_valid_mode(target_split[1], course_id)

                # There could exist multiple CourseModes that match this query, due to differing currency types.
                # The currencies do not affect user lookup though, so we can just use the first result.
                mode = CourseMode.objects.filter(course_id=course_id, mode_slug=target_split[1])[0]
                new_target, _ = CourseModeTarget.objects.get_or_create(target_type=target_split[0], track=mode)
276
            else:
277
                new_target, _ = Target.objects.get_or_create(target_type=target_split[0])
278
            new_targets.append(new_target)
279 280 281 282 283 284 285 286

        # create the task, then save it immediately:
        course_email = cls(
            course_id=course_id,
            sender=sender,
            subject=subject,
            html_message=html_message,
            text_message=text_message,
287 288
            template_name=template_name,
            from_addr=from_addr,
289
        )
290 291
        course_email.save()  # Must exist in db before setting M2M relationship values
        course_email.targets.add(*new_targets)
292
        course_email.save()
293 294 295

        return course_email

296 297 298 299 300
    def get_template(self):
        """
        Returns the corresponding CourseEmailTemplate for this CourseEmail.
        """
        return CourseEmailTemplate.get_template(name=self.template_name)
301

302

303 304
class Optout(models.Model):
    """
305
    Stores users that have opted out of receiving emails from a course.
306
    """
307 308 309
    # Allowing null=True to support data migration from email->user.
    # We need to first create the 'user' column with some sort of default in order to run the data migration,
    # and given the unique index, 'null' is the best default value.
310
    user = models.ForeignKey(User, db_index=True, null=True)
311
    course_id = CourseKeyField(max_length=255, db_index=True)
312

313
    class Meta(object):
314
        app_label = "bulk_email"
315
        unique_together = ('user', 'course_id')
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331


# Defines the tag that must appear in a template, to indicate
# the location where the email message body is to be inserted.
COURSE_EMAIL_MESSAGE_BODY_TAG = '{{message_body}}'


class CourseEmailTemplate(models.Model):
    """
    Stores templates for all emails to a course to use.

    This is expected to be a singleton, to be shared across all courses.
    Initialization takes place in a migration that in turn loads a fixture.
    The admin console interface disables add and delete operations.
    Validation is handled in the CourseEmailTemplateForm class.
    """
332 333 334
    class Meta(object):
        app_label = "bulk_email"

335 336
    html_template = models.TextField(null=True, blank=True)
    plain_template = models.TextField(null=True, blank=True)
337
    name = models.CharField(null=True, max_length=255, unique=True, blank=True)
338 339

    @staticmethod
340
    def get_template(name=None):
341 342 343 344 345
        """
        Fetch the current template

        If one isn't stored, an exception is thrown.
        """
346
        try:
347
            return CourseEmailTemplate.objects.get(name=name)
348 349 350
        except CourseEmailTemplate.DoesNotExist:
            log.exception("Attempting to fetch a non-existent course email template")
            raise
351 352 353 354 355 356 357 358 359 360

    @staticmethod
    def _render(format_string, message_body, context):
        """
        Create a text message using a template, message body and context.

        Convert message body (`message_body`) into an email message
        using the provided template.  The template is a format string,
        which is rendered using format() with the provided `context` dict.

361
        Any keywords encoded in the form %%KEYWORD%% found in the message
362
        body are substituted with user data before the body is inserted into
363
        the template.
364 365 366 367 368

        Output is returned as a unicode string.  It is not encoded as utf-8.
        Such encoding is left to the email code, which will use the value
        of settings.DEFAULT_CHARSET to encode the message.
        """
369 370 371

        # Substitute all %%-encoded keywords in the message body
        if 'user_id' in context and 'course_id' in context:
372
            message_body = substitute_keywords_with_data(message_body, context)
373

374
        result = format_string.format(**context)
375

376 377 378 379 380 381
        # Note that the body tag in the template will now have been
        # "formatted", so we need to do the same to the tag being
        # searched for.
        message_body_tag = COURSE_EMAIL_MESSAGE_BODY_TAG.format()
        result = result.replace(message_body_tag, message_body, 1)

382 383
        # finally, return the result, after wrapping long lines and without converting to an encoded byte array.
        return wrap_message(result)
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400

    def render_plaintext(self, plaintext, context):
        """
        Create plain text message.

        Convert plain text body (`plaintext`) into plaintext email message using the
        stored plain template and the provided `context` dict.
        """
        return CourseEmailTemplate._render(self.plain_template, plaintext, context)

    def render_htmltext(self, htmltext, context):
        """
        Create HTML text message.

        Convert HTML text body (`htmltext`) into HTML email message using the
        stored HTML template and the provided `context` dict.
        """
401 402 403 404
        # HTML-escape string values in the context (used for keyword substitution).
        for key, value in context.iteritems():
            if isinstance(value, basestring):
                context[key] = markupsafe.escape(value)
405
        return CourseEmailTemplate._render(self.html_template, htmltext, context)
406 407 408 409 410 411


class CourseAuthorization(models.Model):
    """
    Enable the course email feature on a course-by-course basis.
    """
412 413 414
    class Meta(object):
        app_label = "bulk_email"

415
    # The course that these features are attached to.
416
    course_id = CourseKeyField(max_length=255, db_index=True, unique=True)
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435

    # Whether or not to enable instructor email
    email_enabled = models.BooleanField(default=False)

    @classmethod
    def instructor_email_enabled(cls, course_id):
        """
        Returns whether or not email is enabled for the given course id.
        """
        try:
            record = cls.objects.get(course_id=course_id)
            return record.email_enabled
        except cls.DoesNotExist:
            return False

    def __unicode__(self):
        not_en = "Not "
        if self.email_enabled:
            not_en = ""
436 437
        # pylint: disable=no-member
        return u"Course '{}': Instructor Email {}Enabled".format(self.course_id.to_deprecated_string(), not_en)
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477


class BulkEmailFlag(ConfigurationModel):
    """
    Enables site-wide configuration for the bulk_email feature.

    Staff can only send bulk email for a course if all the following conditions are true:
    1. BulkEmailFlag is enabled.
    2. Course-specific authorization not required, or course authorized to use bulk email.
    """
    # boolean field 'enabled' inherited from parent ConfigurationModel
    require_course_email_auth = models.BooleanField(default=True)

    @classmethod
    def feature_enabled(cls, course_id=None):
        """
        Looks at the currently active configuration model to determine whether the bulk email feature is available.

        If the flag is not enabled, the feature is not available.
        If the flag is enabled, course-specific authorization is required, and the course_id is either not provided
            or not authorixed, the feature is not available.
        If the flag is enabled, course-specific authorization is required, and the provided course_id is authorized,
            the feature is available.
        If the flag is enabled and course-specific authorization is not required, the feature is available.
        """
        if not BulkEmailFlag.is_enabled():
            return False
        elif BulkEmailFlag.current().require_course_email_auth:
            if course_id is None:
                return False
            else:
                return CourseAuthorization.instructor_email_enabled(course_id)
        else:  # implies enabled == True and require_course_email == False, so email is globally enabled
            return True

    class Meta(object):
        app_label = "bulk_email"

    def __unicode__(self):
        current_model = BulkEmailFlag.current()
478
        return u"BulkEmailFlag: enabled {}, require_course_email_auth: {}".format(
479 480 481
            current_model.is_enabled(),
            current_model.require_course_email_auth
        )