keyword_substitution.py 2.29 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
"""
keyword_substitution.py

Contains utility functions to help substitute keywords in a text body with
the appropriate user / course data.

Supported:
    LMS:
        - %%USER_ID%% => anonymous user id
        - %%USER_FULLNAME%% => User's full name
        - %%COURSE_DISPLAY_NAME%% => display name of the course
        - %%COURSE_END_DATE%% => end date of the course

Usage:
15
    Call substitute_keywords_with_data where substitution is
16 17 18 19 20 21
    needed. Currently called in:
        - LMS: Announcements + Bulk emails
        - CMS: Not called
"""

from django.contrib.auth.models import User
22
from student.models import anonymous_id_for_user
23 24


25
def anonymous_id_from_user_id(user_id):
26
    """
27
    Gets a user's anonymous id from their user id
28
    """
29 30
    user = User.objects.get(id=user_id)
    return anonymous_id_for_user(user, None)
31 32


33
def substitute_keywords(string, user_id, context):
34 35 36 37 38 39 40 41 42
    """
    Replaces all %%-encoded words using KEYWORD_FUNCTION_MAP mapping functions

    Iterates through all keywords that must be substituted and replaces
    them by calling the corresponding functions stored in KEYWORD_FUNCTION_MAP.

    Functions stored in KEYWORD_FUNCTION_MAP must return a replacement string.
    """

43 44 45 46 47 48 49 50 51
    # do this lazily to avoid unneeded database hits
    KEYWORD_FUNCTION_MAP = {
        '%%USER_ID%%': lambda: anonymous_id_from_user_id(user_id),
        '%%USER_FULLNAME%%': lambda: context.get('name'),
        '%%COURSE_DISPLAY_NAME%%': lambda: context.get('course_title'),
        '%%COURSE_END_DATE%%': lambda: context.get('course_end_date'),
    }

    for key in KEYWORD_FUNCTION_MAP.keys():
52
        if key in string:
53 54
            substitutor = KEYWORD_FUNCTION_MAP[key]
            string = string.replace(key, substitutor())
55 56 57 58

    return string


59
def substitute_keywords_with_data(string, context):
60
    """
61 62 63
    Given an email context, replaces all %%-encoded words in the given string
    `context` is a dictionary that should include `user_id` and `course_title`
    keys
64 65 66 67
    """

    # Do not proceed without parameters: Compatibility check with existing tests
    # that do not supply these parameters
68 69
    user_id = context.get('user_id')
    course_title = context.get('course_title')
70

71 72
    if user_id is None or course_title is None:
        return string
73

74
    return substitute_keywords(string, user_id, context)