Merge branch 'master' of github.com:MITx/mitx into fix/cdodge/dangling-discussion-modules

Conflicts:
	lms/djangoapps/django_comment_client/utils.py
This commit is contained in:
Chris Dodge
2013-02-06 14:05:56 -05:00
279 changed files with 3232 additions and 2526 deletions

View File

@@ -26,21 +26,27 @@ log = logging.getLogger(__name__)
_FULLMODULES = None
_DISCUSSIONINFO = defaultdict(dict)
def extract(dic, keys):
return {k: dic.get(k) for k in keys}
def strip_none(dic):
return dict([(k, v) for k, v in dic.iteritems() if v is not None])
def strip_blank(dic):
def _is_blank(v):
return isinstance(v, str) and len(v.strip()) == 0
return dict([(k, v) for k, v in dic.iteritems() if not _is_blank(v)])
# TODO should we be checking if d1 and d2 have the same keys with different values?
def merge_dict(dic1, dic2):
return dict(dic1.items() + dic2.items())
def get_role_ids(course_id):
roles = Role.objects.filter(course_id=course_id)
staff = list(User.objects.filter(is_staff=True).values_list('id', flat=True))
@@ -49,6 +55,7 @@ def get_role_ids(course_id):
roles_with_ids[role.name] = list(role.users.values_list('id', flat=True))
return roles_with_ids
def has_forum_access(uname, course_id, rolename):
try:
role = Role.objects.get(name=rolename, course_id=course_id)
@@ -56,12 +63,14 @@ def has_forum_access(uname, course_id, rolename):
return False
return role.users.filter(username=uname).exists()
def get_full_modules():
global _FULLMODULES
if not _FULLMODULES:
_FULLMODULES = modulestore().modules
return _FULLMODULES
def get_discussion_id_map(course):
"""
return a dict of the form {category: modules}
@@ -70,18 +79,21 @@ def get_discussion_id_map(course):
initialize_discussion_info(course)
return _DISCUSSIONINFO[course.id]['id_map']
def get_discussion_title(course, discussion_id):
global _DISCUSSIONINFO
initialize_discussion_info(course)
title = _DISCUSSIONINFO[course.id]['id_map'].get(discussion_id, {}).get('title', '(no title)')
return title
def get_discussion_category_map(course):
global _DISCUSSIONINFO
initialize_discussion_info(course)
return filter_unstarted_categories(_DISCUSSIONINFO[course.id]['category_map'])
def filter_unstarted_categories(category_map):
now = time.gmtime()
@@ -119,6 +131,7 @@ def filter_unstarted_categories(category_map):
return result_map
def sort_map_entries(category_map):
things = []
for title, entry in category_map["entries"].items():
@@ -221,7 +234,7 @@ def initialize_discussion_info(course):
# TODO. BUG! : course location is not unique across multiple course runs!
# (I think Kevin already noticed this) Need to send course_id with requests, store it
# in the backend.
default_topics = {'General': {'id' :course.location.html_id()}}
default_topics = {'General': {'id': course.location.html_id()}}
discussion_topics = course.metadata.get('discussion_topics', default_topics)
for topic, entry in discussion_topics.items():
category_map['entries'][topic] = {"id": entry["id"],
@@ -233,12 +246,14 @@ def initialize_discussion_info(course):
_DISCUSSIONINFO[course.id]['category_map'] = category_map
_DISCUSSIONINFO[course.id]['timestamp'] = datetime.now()
class JsonResponse(HttpResponse):
def __init__(self, data=None):
content = simplejson.dumps(data)
super(JsonResponse, self).__init__(content,
mimetype='application/json; charset=utf-8')
class JsonError(HttpResponse):
def __init__(self, error_messages=[], status=400):
if isinstance(error_messages, str):
@@ -249,14 +264,17 @@ class JsonError(HttpResponse):
super(JsonError, self).__init__(content,
mimetype='application/json; charset=utf-8', status=status)
class HtmlResponse(HttpResponse):
def __init__(self, html=''):
super(HtmlResponse, self).__init__(html, content_type='text/plain')
class ViewNameMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
request.view_name = view_func.__name__
class QueryCountDebugMiddleware(object):
"""
This middleware will log the number of queries run
@@ -282,6 +300,7 @@ class QueryCountDebugMiddleware(object):
log.info('%s queries run, total %s seconds' % (len(connection.queries), total_time))
return response
def get_ability(course_id, content, user):
return {
'editable': check_permissions_by_view(user, course_id, content, "update_thread" if content['type'] == 'thread' else "update_comment"),
@@ -293,6 +312,8 @@ def get_ability(course_id, content, user):
}
#TODO: RENAME
def get_annotated_content_info(course_id, content, user, user_info):
"""
Get metadata for an individual content (thread or comment)
@@ -309,6 +330,8 @@ def get_annotated_content_info(course_id, content, user, user_info):
}
#TODO: RENAME
def get_annotated_content_infos(course_id, thread, user, user_info):
"""
Get metadata for a thread and its children
@@ -321,6 +344,7 @@ def get_annotated_content_infos(course_id, thread, user, user_info):
annotate(thread)
return infos
def get_metadata_for_threads(course_id, threads, user, user_info):
def infogetter(thread):
return get_annotated_content_infos(course_id, thread, user, user_info)
@@ -329,13 +353,17 @@ def get_metadata_for_threads(course_id, threads, user, user_info):
return metadata
# put this method in utils.py to avoid circular import dependency between helpers and mustache_helpers
def url_for_tags(course_id, tags):
return reverse('django_comment_client.forum.views.forum_form_discussion', args=[course_id]) + '?' + urllib.urlencode({'tags': tags})
def render_mustache(template_name, dictionary, *args, **kwargs):
template = middleware.lookup['main'].get_template(template_name).source
return pystache.render(template, dictionary)
def permalink(content):
if content['type'] == 'thread':
return reverse('django_comment_client.forum.views.single_thread',
@@ -344,6 +372,7 @@ def permalink(content):
return reverse('django_comment_client.forum.views.single_thread',
args=[content['course_id'], content['commentable_id'], content['thread_id']]) + '#' + content['id']
def extend_content(content):
roles = {}
if content.get('user_id'):
@@ -359,10 +388,11 @@ def extend_content(content):
'raw_tags': ','.join(content.get('tags', [])),
'permalink': permalink(content),
'roles': roles,
'updated': content['created_at']!=content['updated_at'],
'updated': content['created_at'] != content['updated_at'],
}
return merge_dict(content, content_info)
def get_courseware_context(content, course):
id_map = get_discussion_id_map(course)
id = content['commentable_id']
@@ -381,9 +411,11 @@ def get_courseware_context(content, course):
"chapter":chapter,
"section":section,
"position":position})
content_info = {"courseware_url": url, "courseware_title": title}
return content_info
def safe_content(content):
fields = [
'id', 'title', 'body', 'course_id', 'anonymous', 'anonymous_to_peers',