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

7
from django.contrib.auth.models import User
Ned Batchelder committed
8
from django.db import models
9

10
from openedx.core.djangoapps.course_groups.models import CourseUserGroup
11
from openedx.core.djangoapps.course_groups.cohorts import get_cohort_by_name
12 13
from openedx.core.lib.html_to_text import html_to_text
from openedx.core.lib.mail_utils import wrap_message
14

15
from config_models.models import ConfigurationModel
16 17 18
from course_modes.models import CourseMode
from enrollment.api import validate_course_mode
from enrollment.errors import CourseModeNotFoundError
19
from student.roles import CourseStaffRole, CourseInstructorRole
20

21
from openedx.core.djangoapps.xmodule_django.models import CourseKeyField
22

23
from util.keyword_substitution import substitute_keywords_with_data
24
from util.query import use_read_replica_if_available
25

26 27
log = logging.getLogger(__name__)

28 29 30 31 32 33

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

41
    class Meta(object):
42
        app_label = "bulk_email"
43 44
        abstract = True

45

46 47 48 49 50
# 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'
51
SEND_TO_TRACK = 'track'
52
EMAIL_TARGET_CHOICES = zip(
53 54
    [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']
55 56
)
EMAIL_TARGETS = {target[0] for target in EMAIL_TARGET_CHOICES}
57 58 59 60 61


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

    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.
70 71 72 73 74 75 76
    """
    target_type = models.CharField(max_length=64, choices=EMAIL_TARGET_CHOICES)

    class Meta(object):
        app_label = "bulk_email"

    def __unicode__(self):
77 78 79 80 81 82 83 84
        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
85 86
        elif self.target_type == SEND_TO_TRACK:
            return self.coursemodetarget.short_display()  # pylint: disable=no-member
87 88 89 90 91 92 93 94 95
        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
96 97
        elif self.target_type == SEND_TO_TRACK:
            return self.coursemodetarget.long_display()  # pylint: disable=no-member
98 99
        else:
            return self.get_target_type_display()
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124

    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)
        enrollment_qset = User.objects.filter(
            is_active=True,
            courseenrollment__course_id=course_id,
            courseenrollment__is_active=True
        )
        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:
            return use_read_replica_if_available(enrollment_qset.exclude(id__in=staff_instructor_qset))
        elif self.target_type == SEND_TO_COHORT:
125
            return self.cohorttarget.cohort.users.filter(id__in=enrollment_qset)  # pylint: disable=no-member
126 127 128 129 130 131
        elif self.target_type == SEND_TO_TRACK:
            return use_read_replica_if_available(
                enrollment_qset.filter(
                    courseenrollment__mode=self.coursemodetarget.track.mode_slug
                )
            )
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
        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)

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

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

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

    @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:
168
            cohort = get_cohort_by_name(name=cohort_name, course_key=course_id)
169 170 171 172 173 174 175 176 177 178
        except CourseUserGroup.DoesNotExist:
            raise ValueError(
                "Cohort {cohort} does not exist in course {course_id}".format(
                    cohort=cohort_name,
                    course_id=course_id
                )
            )
        return cohort


179 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 217 218 219 220 221 222 223 224 225
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:
            validate_course_mode(unicode(course_id), mode_slug)
        except CourseModeNotFoundError:
            raise ValueError(
                "Track {track} does not exist in course {course_id}".format(
                    track=mode_slug,
                    course_id=course_id
                )
            )


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

233
    course_id = CourseKeyField(max_length=255, db_index=True)
234 235 236
    # 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)
237 238
    template_name = models.CharField(null=True, max_length=255)
    from_addr = models.CharField(null=True, max_length=255)
239 240 241 242

    def __unicode__(self):
        return self.subject

243
    @classmethod
244
    def create(
245
            cls, course_id, sender, targets, subject, html_message,
246
            text_message=None, template_name=None, from_addr=None):
247 248 249 250 251 252 253
        """
        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)

254 255
        new_targets = []
        for target in targets:
256
            # split target, to handle cohort:cohort_name and track:mode_slug
257
            target_split = target.split(':', 1)
258
            # Ensure our desired target exists
259
            if target_split[0] not in EMAIL_TARGETS:
260 261 262
                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)
263 264 265 266
            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)
267 268 269 270 271 272 273 274
            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)
275
            else:
276
                new_target, _ = Target.objects.get_or_create(target_type=target_split[0])
277
            new_targets.append(new_target)
278 279 280 281 282 283 284 285

        # 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,
286 287
            template_name=template_name,
            from_addr=from_addr,
288
        )
289 290
        course_email.save()  # Must exist in db before setting M2M relationship values
        course_email.targets.add(*new_targets)
291
        course_email.save()
292 293 294

        return course_email

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

301

302 303
class Optout(models.Model):
    """
304
    Stores users that have opted out of receiving emails from a course.
305
    """
306 307 308
    # 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.
309
    user = models.ForeignKey(User, db_index=True, null=True)
310
    course_id = CourseKeyField(max_length=255, db_index=True)
311

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


# 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.
    """
331 332 333
    class Meta(object):
        app_label = "bulk_email"

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

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

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

    @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.

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

        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.
        """
368 369 370

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

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

375 376 377 378 379 380
        # 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)

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

    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.
        """
400 401 402 403
        # 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)
404
        return CourseEmailTemplate._render(self.html_template, htmltext, context)
405 406 407 408 409 410


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

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

    # 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 = ""
435 436
        # pylint: disable=no-member
        return u"Course '{}': Instructor Email {}Enabled".format(self.course_id.to_deprecated_string(), not_en)
437 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


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()
477
        return u"BulkEmailFlag: enabled {}, require_course_email_auth: {}".format(
478 479 480
            current_model.is_enabled(),
            current_model.require_course_email_auth
        )