def get_lang_node(node_id, lang): rel_value = get_relation_value(ObjectId(node_id), "translation_of") for each in rel_value['grel_node']: if each.language[0] == get_language_tuple(lang)[0]: trans_node = each print "in get_lang_node", trans_node._id, "in language", each.language[ 0] return trans_node
def video_edit(request,group_id,_id): # ins_objectid = ObjectId() # if ins_objectid.is_valid(group_id) is False : # group_ins = node_collection.find_one({'_type': "Group","name": group_id}) # auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) # if group_ins: # group_id = str(group_ins._id) # else : # auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) # if auth : # group_id = str(auth._id) # else : # pass try: group_id = ObjectId(group_id) except: group_name, group_id = get_group_name_id(group_id) vid_node = node_collection.one({"_id": ObjectId(_id)}) title = GST_VIDEO.name video_obj=request.GET.get("vid_id","") group_obj = node_collection.one({'_id': ObjectId(group_id)}) ce_id = request.GET.get('course_event_id') course_tab_title = request.POST.get("course_tab_title",'') res = request.GET.get('res') if request.method == "POST": # get_node_common_fields(request, vid_node, group_id, GST_VIDEO) vid_node.save(is_changed=get_node_common_fields(request, vid_node, group_id, GST_VIDEO),groupid=group_id) thread_create_val = request.POST.get("thread_create",'') course_tab_title = request.POST.get("course_tab_title",'') # help_info_page = request.POST.getlist('help_info_page','') help_info_page = request.POST['help_info_page'] if help_info_page: help_info_page = json.loads(help_info_page) discussion_enable_at = node_collection.one({"_type": "AttributeType", "name": "discussion_enable"}) if thread_create_val == "Yes": create_gattribute(vid_node._id, discussion_enable_at, True) return_status = create_thread_for_node(request,group_id, vid_node) else: create_gattribute(vid_node._id, discussion_enable_at, False) # print "\n\n help_info_page ================ ",help_info_page if help_info_page and u"None" not in help_info_page: has_help_rt = node_collection.one({'_type': "RelationType", 'name': "has_help"}) try: help_info_page = map(ObjectId, help_info_page) create_grelation(vid_node._id, has_help_rt,help_info_page) except Exception as invalidobjectid: # print "\n\n ERROR -------- ",invalidobjectid pass else: # Check if node had has_help RT grel_dict = get_relation_value(vid_node._id,"has_help") # print "\n\n grel_dict ==== ", grel_dict if grel_dict: grel_id = grel_dict.get("grel_id","") if grel_id: for each_grel_id in grel_id: del_status, del_status_msg = delete_grelation( subject_id=vid_node._id, node_id=each_grel_id, deletion_type=0 ) # print "\n\n del_status == ",del_status # print "\n\n del_status_msg == ",del_status_msg if "CourseEventGroup" not in group_obj.member_of_names_list: get_node_metadata(request,vid_node) teaches_list = request.POST.get('teaches_list', '') # get the teaches list assesses_list = request.POST.get('assesses_list', '') # get the teaches list if teaches_list !='': teaches_list=teaches_list.split(",") create_grelation_list(vid_node._id,"teaches",teaches_list) if assesses_list !='': assesses_list=assesses_list.split(",") create_grelation_list(vid_node._id,"assesses",assesses_list) return HttpResponseRedirect(reverse('video_detail', kwargs={'group_id': group_id, '_id': vid_node._id})) else: vid_node.status = u"PUBLISHED" vid_node.save() if course_tab_title: if course_tab_title == "raw material": course_tab_title = "raw_material" return HttpResponseRedirect(reverse('course_'+course_tab_title + '_detail', kwargs={'group_id': group_id, 'node_id': str(vid_node._id)})) return HttpResponseRedirect(reverse('course_about', kwargs={'group_id': group_id})) # url = "/"+ str(group_id) +"/?selected="+str(vid_node._id)+"#view_page" # return HttpResponseRedirect(url) else: vid_col = node_collection.find({'member_of': GST_VIDEO._id,'group_set': ObjectId(group_id)}) nodes_list = [] for each in vid_col: nodes_list.append(str((each.name).strip().lower())) return render_to_response("ndf/video_edit.html", { 'node': vid_node, 'title': title, 'group_id': group_id, 'groupid':group_id, 'video_obj':video_obj, 'nodes_list':nodes_list, 'ce_id': ce_id, 'res': res, 'course_tab_title':course_tab_title }, context_instance=RequestContext(request) )
def create_edit_page(request, group_id, node_id=None): """Creates/Modifies details about the given quiz-item. """ # ins_objectid = ObjectId() # if ins_objectid.is_valid(group_id) is False : # group_ins = node_collection.find_one({'_type': "Group", "name": group_id}) # auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) # if group_ins: # group_id = str(group_ins._id) # else : # auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) # if auth : # group_id = str(auth._id) # else : # pass group_name, group_id = get_group_name_id(group_id) ce_id = request.GET.get('course_event_id', '') blog_type = request.GET.get('blog_type', '') res = request.GET.get('res', '') program_res = request.GET.get('program_res', '') context_variables = { 'title': gst_page.name, 'group_id': group_id, 'groupid': group_id, 'ce_id': ce_id, 'res': res, 'program_res': program_res, 'blog_type': blog_type } group_obj = node_collection.one({'_id': ObjectId(group_id)}) available_nodes = node_collection.find({ '_type': u'GSystem', 'member_of': ObjectId(gst_page._id), 'group_set': ObjectId(group_id), '_id': { '$ne': ObjectId(node_id) } }) nodes_list = [] thread = None url_name = "/home" # for each in available_nodes: # nodes_list.append(str((each.name).strip().lower())) # loop replaced by a list comprehension node_list = [str((each.name).strip().lower()) for each in available_nodes] # print "available_nodes: ", node_list if request.method == "POST": # get_node_common_fields(request, page_node, group_id, gst_page) page_name = request.POST.get('name', '') # print "====== page_name: ", page_name if page_name.strip().lower() in node_list and not node_id: new_page = False return render_to_response("error_base.html", { 'message': 'Page with same name already exists in the group!' }, context_instance=RequestContext(request)) elif node_id: new_page = False page_node = node_collection.one({ '_type': u'GSystem', '_id': ObjectId(node_id) }) else: new_page = True page_node = node_collection.collection.GSystem() # page_type = request.POST.getlist("type_of",'') ce_id = request.POST.get("ce_id", '') blog_type = request.POST.get('blog_type', '') res = request.POST.get("res", '') program_res = request.POST.get('program_res', '') # we are fetching the value of release_response flag # if this is set, it means, we can proceed to create a thread node # for the current page node. thread_create_val = request.POST.get("thread_create", '') # print "\n\n thread_create_val", thread_create_val # print "\n\n request.POST === ",request.POST # raise Exception("demo") # help_info_page = request.POST.getlist('help_info_page','') help_info_page = request.POST['help_info_page'] if help_info_page: help_info_page = json.loads(help_info_page) # print "\n\n help_info_page === ",help_info_page #program_res and res are boolean values if program_res: program_res = eval(program_res) if res: res = eval(res) if blog_type: blog_type = eval(blog_type) # if page_type: # objid= page_type[0] # if not ObjectId(objid) in page_node.type_of: # page_type1=[] # page_type1.append(ObjectId(objid)) # page_node.type_of = page_type1 # page_node.type_of page_node.save(is_changed=get_node_common_fields( request, page_node, group_id, gst_page)) # if course event grp's id is passed, it means # its a blog page added in notebook and hence set type_of field as "Blog page" # print "\n\n blog_type---",blog_type if blog_type: blogpage_gst = node_collection.one({ '_type': "GSystemType", 'name': "Blog page" }) page_node.type_of = [blogpage_gst._id] elif GSTUDIO_SITE_NAME == "NROER" and "Author" in group_obj.member_of_names_list: infopage_gst = node_collection.one({ '_type': "GSystemType", 'name': "Info page" }) page_node.type_of = [infopage_gst._id] # if the page created is as a resource in course or program event, # set status to PUBLISHED by default # one major reason for this, ONLY published nodes can be replicated. if res or program_res or ce_id: page_node.status = u"PUBLISHED" page_node.save() # if page is created in program event, add page_node to group's collection set if program_res: group_obj = node_collection.one({'_id': ObjectId(group_id)}) group_obj.collection_set.append(page_node._id) group_obj.save() discussion_enable_at = node_collection.one({ "_type": "AttributeType", "name": "discussion_enable" }) if thread_create_val == "Yes" or blog_type: create_gattribute(page_node._id, discussion_enable_at, True) return_status = create_thread_for_node(request, group_id, page_node) else: create_gattribute(page_node._id, discussion_enable_at, False) # print "\n\n help_info_page ================ ",help_info_page if "None" not in help_info_page: has_help_rt = node_collection.one({ '_type': "RelationType", 'name': "has_help" }) try: help_info_page = map(ObjectId, help_info_page) create_grelation(page_node._id, has_help_rt, help_info_page) page_node.reload() except Exception as invalidobjectid: # print invalidobjectid pass else: # Check if node had has_help RT grel_dict = get_relation_value(page_node._id, "has_help") # print "\n\n grel_dict ==== ", grel_dict if grel_dict: grel_id = grel_dict.get("grel_id", "") if grel_id: for each_grel_id in grel_id: del_status, del_status_msg = delete_grelation( subject_id=page_node._id, node_id=each_grel_id, deletion_type=0) # print "\n\n del_status == ",del_status # print "\n\n del_status_msg == ",del_status_msg # To fill the metadata info while creating and editing page node metadata = request.POST.get("metadata_info", '') if "CourseEventGroup" in group_obj.member_of_names_list and blog_type: if new_page: # counter_obj = Counter.get_counter_obj(request.user.id,ObjectId(group_id)) # # counter_obj.no_notes_written=counter_obj.no_notes_written+1 # counter_obj['page']['blog']['created'] += 1 # # counter_obj.course_score += GSTUDIO_NOTE_CREATE_POINTS # counter_obj['group_points'] += GSTUDIO_NOTE_CREATE_POINTS # counter_obj.last_update = datetime.datetime.now() # counter_obj.save() active_user_ids_list = [request.user.id] if GSTUDIO_BUDDY_LOGIN: active_user_ids_list += Buddy.get_buddy_userids_list_within_datetime( request.user.id, datetime.datetime.now()) # removing redundancy of user ids: active_user_ids_list = dict.fromkeys( active_user_ids_list).keys() counter_objs_cur = Counter.get_counter_objs_cur( active_user_ids_list, group_id) for each_counter_obj in counter_objs_cur: each_counter_obj['page']['blog']['created'] += 1 each_counter_obj[ 'group_points'] += GSTUDIO_NOTE_CREATE_POINTS each_counter_obj.last_update = datetime.datetime.now() each_counter_obj.save() return HttpResponseRedirect( reverse('course_notebook_tab_note', kwargs={ 'group_id': group_id, 'tab': 'my-notes', 'notebook_id': page_node._id })) if ce_id or res or program_res: url_name = "/" + group_name + "/" + str(page_node._id) if ce_id: # url_name = "/" + group_name + "/#journal-tab" url_name = "/" + group_name if res or program_res: url_name = "/" + group_name + "/?selected=" + str( page_node._id) + "#view_page" # print "\n\n url_name---",url_name return HttpResponseRedirect(url_name) if metadata: # Only while metadata editing if metadata == "metadata": if page_node: get_node_metadata(request, page_node, is_changed=True) # End of filling metadata return HttpResponseRedirect( reverse('page_details', kwargs={ 'group_id': group_id, 'app_id': page_node._id })) else: if node_id: page_node = node_collection.one({ '_type': u'GSystem', '_id': ObjectId(node_id) }) #page_node,ver=get_page(request,page_node) page_node.get_neighbourhood(page_node.member_of) context_variables['node'] = page_node context_variables['groupid'] = group_id context_variables['group_id'] = group_id # fetch Page instances # Page_node = node_collection.find_one({'_type':"GSystemType","name":"Page"}) page_instances = node_collection.find({"type_of": gst_page._id}) page_ins_list = [i for i in page_instances] context_variables['page_instance'] = page_ins_list context_variables['nodes_list'] = json.dumps(nodes_list) # print "\n\n context_variables----\n",context_variables return render_to_response("ndf/page_create_edit.html", context_variables, context_instance=RequestContext(request))
def discussion_reply(request, group_id, node_id): try: group_id = ObjectId(group_id) except: group_name, group_id = get_group_name_id(group_id) try: group_object = node_collection.one({'_id': ObjectId(group_id)}) prior_node = request.POST.get("prior_node_id", "") content_org = request.POST.get("reply_text_content", "") # reply content node = node_collection.one({"_id": ObjectId(node_id)}) gs_type_node_id = None if u'Twist' not in node.member_of_names_list: grel_dict = get_relation_value(node_id,'thread_of', True) node = grel_dict['grel_node'] if node.prior_node: gs_type_node_id = node.prior_node[0] # if node and node.relation_set: # for each_rel in node.relation_set: # if each_rel and "thread_of" in each_rel: # gs_type_node_id = each_rel['thread_of'][0] # break # grel_dict = get_relation_value(node_id,'thread_of') # is_cursor = grel_dict.get("cursor",False) # if not is_cursor: # gs_type_node_id = grel_dict.get("grel_node") # # grel_id = grel_dict.get("grel_id") # print "\n\n node.name === ", node.member_of_names_list, node._id, node.name # process and save node if it reply has content if content_org: user_id = int(request.user.id) user_name = unicode(request.user.username) # auth = node_collection.one({'_type': 'Author', 'name': user_name }) # creating empty GST and saving it reply_obj = node_collection.collection.GSystem() reply_obj.name = unicode("Reply of:" + str(prior_node)) reply_obj.status = u"PUBLISHED" reply_obj.created_by = user_id reply_obj.modified_by = user_id reply_obj.contributors.append(user_id) reply_obj.member_of.append(ObjectId(reply_st._id)) reply_obj.prior_node.append(ObjectId(prior_node)) reply_obj.group_set.append(ObjectId(group_id)) reply_obj.content_org = unicode(content_org) filename = slugify(unicode("Reply of:" + str(prior_node))) + "-" + user_name + "-" # reply_obj.content = org2html(content_org, file_prefix=filename) reply_obj.content = content_org if gs_type_node_id: reply_obj.origin.append({'prior_node_id_of_thread': ObjectId(gs_type_node_id)}) if node_id: reply_obj.origin.append({'thread_id': ObjectId(node_id)}) # ============================== # try: upload_files_count=int(request.POST.get("upload_cnt",0)) # print "upfiles=",upload_files_count lst=[] lstobj_collection=[] usrid = int(request.user.id) if upload_files_count > 0: # print "uploaded items",request.FILES.items() try: thread_obj = node_collection.one({'_id': ObjectId(prior_node)}) # print "thread_obj : ", thread_obj if thread_obj.access_policy: access_policy = thread_obj.access_policy else: access_policy = u'PUBLIC' except: access_policy = u'PUBLIC' for key,value in request.FILES.items(): fname=unicode(value.__dict__['_name']) # print "key=",key,"value=",value,"fname=",fname fileobj,fs=save_file(value,fname,usrid,group_id, "", "", username=unicode(request.user.username), access_policy=access_policy, count=0, first_object="", oid=True) if type(fileobj) == list: obid = str(list(fileobj)[1]) else: obid=str(fileobj) try: file_obj=node_collection.find_one({'_id': ObjectId(obid)}) lstobj_collection.append(file_obj._id) except: pass if "CourseEventGroup" not in group_object.member_of_names_list: if group_object.edit_policy == 'EDITABLE_MODERATED': t = create_moderator_task(request, file_obj.group_set[0], file_obj._id,on_upload=True) # print "::: lstobj_collection: ", lstobj_collection # except: # lstobj_collection = [] # ============================== reply_obj.collection_set = lstobj_collection # print "=== lstobj_collection: ", lstobj_collection # saving the reply obj reply_obj.save() #Update Counter Collection # thread_obj = node_collection.one({'_id':ObjectId(node_id)}) if gs_type_node_id: gs_type_node = node_collection.one({'_id':gs_type_node_id}) active_user_ids_list = [request.user.id] if GSTUDIO_BUDDY_LOGIN: active_user_ids_list += Buddy.get_buddy_userids_list_within_datetime(request.user.id, datetime.now()) # removing redundancy of user ids: active_user_ids_list = dict.fromkeys(active_user_ids_list).keys() Counter.add_comment_pt(resource_obj_or_id=gs_type_node, current_group_id=group_id, active_user_id_or_list=active_user_ids_list) # if gs_type_node.if_file.mime_type : # file_creator_id = gs_type_node.created_by # if file_creator_id != request.user.id : # counter_obj = Counter.get_counter_obj(request.user.id, ObjectId(group_id)) # # counter_obj.no_comments_on_others_files += 1 # counter_obj['file']['commented_on_others_res'] += 1 # # counter_obj.no_comments_by_user += 1 # counter_obj['total_comments_by_user'] += 1 # # counter_obj.course_score += GSTUDIO_COMMENT_POINTS # counter_obj['group_points'] += GSTUDIO_COMMENT_POINTS # counter_obj_creator = Counter.get_counter_obj(file_creator_id, ObjectId(group_id)) # # counter_obj_creator.no_comments_received_on_files += 1 # counter_obj_creator['file']['comments_gained'] += 1 # # counter_obj_creator.no_comments_for_user += 1 # if str(counter_obj.user_id) in counter_obj_creator.file['comments_by_others_on_res'].keys(): # # counter_obj_creator.comments_by_others_on_files[str(counter_obj.user_id)] += 1 # counter_obj_creator['file']['comments_by_others_on_res'][str(counter_obj.user_id)] += 1 # else: # # counter_obj_creator.comments_by_others_on_files.update({str(counter_obj.user_id):1}) # counter_obj_creator.file['comments_by_others_on_res'].update({str(counter_obj.user_id):1}) # counter_obj.last_update = datetime.now() # counter_obj_creator.last_update = datetime.now() # counter_obj.save() # counter_obj_creator.save() # else : # note_creator_id = gs_type_node.created_by # if note_creator_id != request.user.id : # counter_obj = Counter.get_counter_obj(request.user.id, ObjectId(group_id)) # # counter_obj.no_comments_by_user += 1 # counter_obj['total_comments_by_user'] += 1 # # counter_obj.no_comments_on_others_notes += 1 # counter_obj['page']['blog']['commented_on_others_res'] += 1 # counter_obj['group_points'] += GSTUDIO_COMMENT_POINTS # counter_obj_creator = Counter.get_counter_obj(note_creator_id, ObjectId(group_id)) # # counter_obj_creator.no_comments_for_user += 1 # # counter_obj_creator.no_comments_received_on_notes += 1 # counter_obj_creator['page']['blog']['comments_gained'] += 1 # # if str(counter_obj.user_id) in counter_obj_creator.comments_by_others_on_notes.keys(): # if str(counter_obj.user_id) in counter_obj_creator.page.blog['comments_by_others_on_res'].keys(): # # counter_obj_creator.comments_by_others_on_notes[str(counter_obj.user_id)] += 1 # counter_obj_creator['page']['blog']['comments_by_others_on_res'][str(counter_obj.user_id)] += 1 # else: # counter_obj_creator.page.blog['comments_by_others_on_res'].update({str(counter_obj.user_id):1}) # counter_obj.last_update = datetime.now() # counter_obj_creator.last_update = datetime.now() # counter_obj.save() # counter_obj_creator.save() formated_time = reply_obj.created_at.strftime("%B %d, %Y, %I:%M %p") files = [] for each_coll_item in reply_obj.collection_set: temp_list = [] temp = node_collection.one({'_id': ObjectId(each_coll_item)}, {'mime_type': 1, 'name': 1}) temp_list.append(str(temp['_id'])) temp_list.append(str(temp['mime_type'])) temp_list.append(str(temp['name'])) files.append(temp_list) # print files user_names = reply_obj.user_details_dict["contributors"] is_grp_admin = False if request.user.id in group_object.group_admin: is_grp_admin = True # ["status_info", "reply_id", "prior_node", "html_content", "org_content", "user_id", "user_name", "created_at" ] reply = json.dumps( [ "reply_saved", str(reply_obj._id), str(reply_obj.prior_node[0]), reply_obj.content, reply_obj.content_org, user_id, user_names, formated_time, files,is_grp_admin], cls=DjangoJSONEncoder ) # print "===========", reply # ---------- mail/notification sending ------- try: node_creator_user_obj = User.objects.get(id=node.created_by) node_creator_user_name = node_creator_user_obj.username if int(request.user.id) not in node.author_set: node.author_set.append(int(request.user.id)) node.save() site = Site.objects.get(pk=1) site = site.name.__str__() from_user = user_name to_user_list = [node_creator_user_obj] msg = "\n\nDear " + node_creator_user_name + ",\n\n" + \ "A reply has been added in discussion under the " + \ node.member_of_names_list[0] + " named: '" + \ node.name + "' by '" + user_name + "'." activity = "Discussion Reply" render_label = render_to_string( "notification/label.html", { # "sender": from_user, "activity": activity, "conjunction": "-", "link": "url_link" } ) notification.create_notice_type(render_label, msg, "notification") notification.send(to_user_list, render_label, {"from_user": from_user}) except Exception as notification_err: print "\n Unable to send notification", notification_err # ---------- END of mail/notification sending --------- return HttpResponse( reply ) else: # no reply content return HttpResponse(json.dumps(["no_content"])) except Exception as e: error_message = "\n DiscussionReplyCreateError: " + str(e) + "\n" raise Exception(error_message) return HttpResponse(json.dumps(["Server Error"]))
def create_moderator_task(request, group_id, node_id, \ task_type_creation='group', task_type='Moderation', task_content_org="", \ created_by_name="",on_upload=False): ''' Method to create task to group admins or moderators of the moderated groups. ''' from gnowsys_ndf.ndf.templatetags.ndf_tags import get_relation_value # def create_task(task_dict, task_type_creation="single"): # task_dict # - Required keys: _id[optional], name, group_set, created_by, modified_by, contributors, content_org, # created_by_name, Status, Priority, start_time, end_time, Assignee, has_type try: task_dict = {} node_obj = node_collection.one({'_id': ObjectId(node_id)}) # task_id_val = get_relation_value(node_obj._id,"has_current_approval_task") grel_dict = get_relation_value(node_obj._id,"has_current_approval_task") is_cursor = grel_dict.get("cursor",False) if not is_cursor: task_node = grel_dict.get("grel_node",None) if task_node: task_dict['_id'] = task_node._id # grel_id = grel_dict.get("grel_id") # if task_id_val != None: # task_dict['_id'] = get_relation_value(node_obj._id,"has_current_approval_task") # if node_obj.relation_set: # for rel in node_obj.relation_set: # if rel and 'has_current_approval_task' in rel: # task_id = rel['has_current_approval_task'][0] # task_dict["_id"] = ObjectId(task_id) # last group is next appended group group_obj = get_group_name_id(group_id, get_obj=True) at_curr_app_task = node_collection.one({'_type': "RelationType", 'name': "has_current_approval_task"}) glist_gst = node_collection.one({'_type': "GSystemType", 'name': "GList"}) task_type_list = [] task_type_list.append(node_collection.one({'member_of': glist_gst._id, 'name':unicode(task_type)})._id) site = Site.objects.get(pk=1) site_domain = site.domain # print "=== site_domain: ", site_domain site = unicode(site.name.__str__()) auth_grp = node_collection.one({'_type': "Author", 'created_by': int(node_obj.created_by)}) if task_type == "Moderation": task_title = u"Resource under moderation: " + node_obj.name if task_content_org: pass else: url = u"http://" + site_domain + "/"+ unicode(group_obj._id) \ + u"/moderation#" + unicode(node_obj._id.__str__()) task_content_org = u'\n\nResource under moderation: "' + unicode(node_obj.name) \ + u'" having id: "' + unicode(node_obj._id.__str__()) + '"' \ task_dict = { "name": task_title, "group_set": [group_obj._id], "created_by": node_obj.created_by, "modified_by": request.user.id, "contributors": [request.user.id], "content_org": unicode(task_content_org), "created_by_name": unicode(request.user.username), # "Status": u"New", "Priority": u"Normal", # "start_time": "", # "end_time": "", "Assignee": list(group_obj.group_admin[:]), "has_type": task_type_list } if on_upload: task_dict['Status'] = u"New" else: task_dict['Status'] = u"In Progress" task_obj = create_task(task_dict, task_type_creation) if task_obj: create_grelation(node_obj._id, at_curr_app_task, task_obj._id) try: url = u"http://" + site_domain + "/" + unicode(auth_grp._id) \ + u"/moderation/status/" + unicode(node_obj._id.__str__()) activ = "Contribution to " + group_obj.name + "." if not on_upload: mail_content = "Moderation status of your contributed file has been updated.\n" \ + "You may visit this link to check the status of Moderation :\t" \ + url elif on_upload: mail_content = "Your contributed file has been sent for Moderation.\n" \ + "You may visit this link to check the status of Moderation :\t" \ + url user_obj = User.objects.get(id=node_obj.created_by) set_notif_val(request, auth_grp._id, mail_content, activ, user_obj) except Exception as notif_err: # print notif_err msg = "Unable to send Notification" else: # on final publish to top group # task_title = u"\n\nResource " + node_obj.name + \ # u" in " + group_obj.name + u" is Approved. " # task_dict = { # "name": task_title, # "modified_by": request.user.id, # "created_by_name": unicode(request.user.username), # "Status": u"Feedback", # "group_set": [group_obj._id], # "created_by": node_obj.created_by, # "content_org": unicode(task_content_org), # "modified_by": request.user.id, # "contributors": [request.user.id], # "Priority": u"Normal", # "Assignee": list(group_obj.group_admin[:] + [node_obj.created_by]), # "has_type": task_type_list # } try: # delete the task associated with the resource list_of_recipients_ids = [] list_of_recipients_ids.extend(group_obj.group_admin) list_of_recipients_ids.append(node_obj.created_by) # Sending notification to all watchers about the updates of the task for each_user_id in list_of_recipients_ids: url = u"http://" + site_domain + "/"+ unicode(group_obj._id) \ + u"/file/" + unicode(node_obj._id.__str__()) activ = "Contribution to " + group_obj.name +"." mail_content = u"\n\n Contribution file "+ node_obj.name +" is moderated " \ + "and successfully published to " + \ group_obj.name + \ u". \n\nVisit this link to view the resource : " \ + url user_obj = User.objects.get(id=int(each_user_id)) set_notif_val(request, auth_grp._id, mail_content, activ, user_obj) if task_id: task_node = node_collection.one({'_id': ObjectId(task_id)}) # del_status, del_status_msg = delete_node( # node_id=task_node._id, deletion_type=0) url = u"http://" + site_domain + "/"+ unicode(group_obj._id) \ + u"/file/" + unicode(node_obj._id.__str__()) task_content_org = u"\n\nThis task is CLOSED.\n " \ "However, you may find the moderated resource at following link: \n" \ + unicode(url) task_dict = { "name": task_node.name, "group_set": [group_obj._id], "created_by": node_obj.created_by, "modified_by": request.user.id, "contributors": [request.user.id], "content_org": unicode(task_content_org), "created_by_name": unicode(request.user.username), "Status": u"CLOSED", "Priority": u"Normal", "Assignee": list(group_obj.group_admin[:]), "has_type": task_type_list } task_obj = create_task(task_dict, task_type_creation) except Exception as e: msg = "Unable to send Notification", str(e) except Exception as e: print "Error in task create moderation --- " + str(e)
def discussion_reply(request, group_id, node_id): try: group_id = ObjectId(group_id) except: group_name, group_id = get_group_name_id(group_id) try: group_object = node_collection.one({'_id': ObjectId(group_id)}) prior_node = request.POST.get("prior_node_id", "") content_org = request.POST.get("reply_text_content", "") # reply content node = node_collection.one({"_id": ObjectId(node_id)}) gs_type_node_id = None if u'Twist' not in node.member_of_names_list: # grel_dict = get_relation_value(node_id,'thread_of', True) grel_dict = get_relation_value(node._id,'has_thread', True) node = grel_dict['grel_node'] if node.prior_node: gs_type_node_id = node.prior_node[0] else: try: has_thread_at = node_collection.one({'_type': 'RelationType', 'name': 'has_thread'}) has_thread_grel = triple_collection.find_one({'_type': 'GRelation', 'relation_type': has_thread_at._id, 'right_subject': node._id, 'status': 'PUBLISHED'}) gs_type_node_id = has_thread_grel.subject except Exception as e: print "\n Node asssociated with Thread node NOT found.", e pass # process and save node if it reply has content if content_org: user_id = int(request.user.id) user_name = unicode(request.user.username) # auth = node_collection.one({'_type': 'Author', 'name': user_name }) # creating empty GST and saving it reply_obj = node_collection.collection.GSystem() reply_obj.name = unicode("Reply of:" + str(prior_node)) reply_obj.status = u"PUBLISHED" reply_obj.created_by = user_id reply_obj.modified_by = user_id reply_obj.contributors.append(user_id) reply_obj.member_of.append(ObjectId(reply_st._id)) reply_obj.prior_node.append(ObjectId(prior_node)) reply_obj.group_set.append(ObjectId(group_id)) reply_obj.content_org = unicode(content_org) filename = slugify(unicode("Reply of:" + str(prior_node))) + "-" + user_name + "-" # reply_obj.content = org2html(content_org, file_prefix=filename) reply_obj.content = content_org if gs_type_node_id: reply_obj.origin.append({'prior_node_id_of_thread': ObjectId(gs_type_node_id)}) if node_id: reply_obj.origin.append({'thread_id': ObjectId(node_id)}) # ============================== # try: upload_files_count=int(request.POST.get("upload_cnt",0)) # print "upfiles=",upload_files_count lst=[] lstobj_collection=[] usrid = int(request.user.id) if upload_files_count > 0: # print "uploaded items",request.FILES.items() try: thread_obj = node_collection.one({'_id': ObjectId(prior_node)}) # print "thread_obj : ", thread_obj if thread_obj.access_policy: access_policy = thread_obj.access_policy else: access_policy = u'PUBLIC' except: access_policy = u'PUBLIC' for key,value in request.FILES.items(): fname=unicode(value.__dict__['_name']) # print "key=",key,"value=",value,"fname=",fname fileobj,fs=save_file(value,fname,usrid,group_id, "", "", username=unicode(request.user.username), access_policy=access_policy, count=0, first_object="", oid=True) if type(fileobj) == list: obid = str(list(fileobj)[1]) else: obid=str(fileobj) try: file_obj=node_collection.find_one({'_id': ObjectId(obid)}) lstobj_collection.append(file_obj._id) except: pass if "CourseEventGroup" not in group_object.member_of_names_list: if group_object.edit_policy == 'EDITABLE_MODERATED': t = create_moderator_task(request, file_obj.group_set[0], file_obj._id,on_upload=True) # print "::: lstobj_collection: ", lstobj_collection # except: # lstobj_collection = [] # ============================== reply_obj.collection_set = lstobj_collection # print "=== lstobj_collection: ", lstobj_collection # saving the reply obj reply_obj.save() #Update Counter Collection # thread_obj = node_collection.one({'_id':ObjectId(node_id)}) if gs_type_node_id: gs_type_node = node_collection.one({'_id':gs_type_node_id}) active_user_ids_list = [request.user.id] if GSTUDIO_BUDDY_LOGIN: active_user_ids_list += Buddy.get_buddy_userids_list_within_datetime(request.user.id, datetime.now()) # removing redundancy of user ids: active_user_ids_list = dict.fromkeys(active_user_ids_list).keys() Counter.add_comment_pt(resource_obj_or_id=gs_type_node, current_group_id=group_id, active_user_id_or_list=active_user_ids_list) # if gs_type_node.if_file.mime_type : # file_creator_id = gs_type_node.created_by # if file_creator_id != request.user.id : # counter_obj = Counter.get_counter_obj(request.user.id, ObjectId(group_id)) # # counter_obj.no_comments_on_others_files += 1 # counter_obj['file']['commented_on_others_res'] += 1 # # counter_obj.no_comments_by_user += 1 # counter_obj['total_comments_by_user'] += 1 # # counter_obj.course_score += GSTUDIO_COMMENT_POINTS # counter_obj['group_points'] += GSTUDIO_COMMENT_POINTS # counter_obj_creator = Counter.get_counter_obj(file_creator_id, ObjectId(group_id)) # # counter_obj_creator.no_comments_received_on_files += 1 # counter_obj_creator['file']['comments_gained'] += 1 # # counter_obj_creator.no_comments_for_user += 1 # if str(counter_obj.user_id) in counter_obj_creator.file['comments_by_others_on_res'].keys(): # # counter_obj_creator.comments_by_others_on_files[str(counter_obj.user_id)] += 1 # counter_obj_creator['file']['comments_by_others_on_res'][str(counter_obj.user_id)] += 1 # else: # # counter_obj_creator.comments_by_others_on_files.update({str(counter_obj.user_id):1}) # counter_obj_creator.file['comments_by_others_on_res'].update({str(counter_obj.user_id):1}) # counter_obj.last_update = datetime.now() # counter_obj_creator.last_update = datetime.now() # counter_obj.save() # counter_obj_creator.save() # else : # note_creator_id = gs_type_node.created_by # if note_creator_id != request.user.id : # counter_obj = Counter.get_counter_obj(request.user.id, ObjectId(group_id)) # # counter_obj.no_comments_by_user += 1 # counter_obj['total_comments_by_user'] += 1 # # counter_obj.no_comments_on_others_notes += 1 # counter_obj['page']['blog']['commented_on_others_res'] += 1 # counter_obj['group_points'] += GSTUDIO_COMMENT_POINTS # counter_obj_creator = Counter.get_counter_obj(note_creator_id, ObjectId(group_id)) # # counter_obj_creator.no_comments_for_user += 1 # # counter_obj_creator.no_comments_received_on_notes += 1 # counter_obj_creator['page']['blog']['comments_gained'] += 1 # # if str(counter_obj.user_id) in counter_obj_creator.comments_by_others_on_notes.keys(): # if str(counter_obj.user_id) in counter_obj_creator.page.blog['comments_by_others_on_res'].keys(): # # counter_obj_creator.comments_by_others_on_notes[str(counter_obj.user_id)] += 1 # counter_obj_creator['page']['blog']['comments_by_others_on_res'][str(counter_obj.user_id)] += 1 # else: # counter_obj_creator.page.blog['comments_by_others_on_res'].update({str(counter_obj.user_id):1}) # counter_obj.last_update = datetime.now() # counter_obj_creator.last_update = datetime.now() # counter_obj.save() # counter_obj_creator.save() formated_time = reply_obj.created_at.strftime("%B %d, %Y, %I:%M %p") files = [] for each_coll_item in reply_obj.collection_set: temp_list = [] temp = node_collection.one({'_id': ObjectId(each_coll_item)}, {'mime_type': 1, 'name': 1}) temp_list.append(str(temp['_id'])) temp_list.append(str(temp['mime_type'])) temp_list.append(str(temp['name'])) files.append(temp_list) # print files user_names = reply_obj.user_details_dict["contributors"] is_grp_admin = False if request.user.id in group_object.group_admin: is_grp_admin = True # ["status_info", "reply_id", "prior_node", "html_content", "org_content", "user_id", "user_name", "created_at" ] reply = json.dumps( [ "reply_saved", str(reply_obj._id), str(reply_obj.prior_node[0]), reply_obj.content, reply_obj.content_org, user_id, user_names, formated_time, files,is_grp_admin], cls=DjangoJSONEncoder ) # print "===========", reply # ---------- mail/notification sending ------- try: node_creator_user_obj = User.objects.get(id=node.created_by) node_creator_user_name = node_creator_user_obj.username if int(request.user.id) not in node.author_set: node.author_set.append(int(request.user.id)) node.save() site = Site.objects.get(pk=1) site = site.name.__str__() from_user = user_name to_user_list = [node_creator_user_obj] msg = "\n\nDear " + node_creator_user_name + ",\n\n" + \ "A reply has been added in discussion under the " + \ node.member_of_names_list[0] + " named: '" + \ node.name + "' by '" + user_name + "'." activity = "Discussion Reply" render_label = render_to_string( "notification/label.html", { # "sender": from_user, "activity": activity, "conjunction": "-", "link": "url_link" } ) notification.create_notice_type(render_label, msg, "notification") notification.send(to_user_list, render_label, {"from_user": from_user}) except Exception as notification_err: print "\n Unable to send notification", notification_err # ---------- END of mail/notification sending --------- return HttpResponse( reply ) else: # no reply content return HttpResponse(json.dumps(["no_content"])) except Exception as e: error_message = "\n DiscussionReplyCreateError: " + str(e) + "\n" raise Exception(error_message) return HttpResponse(json.dumps(["Server Error"]))
def create_edit_page(request, group_id, node_id=None): """Creates/Modifies details about the given quiz-item. """ # ins_objectid = ObjectId() # if ins_objectid.is_valid(group_id) is False : # group_ins = node_collection.find_one({'_type': "Group", "name": group_id}) # auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) # if group_ins: # group_id = str(group_ins._id) # else : # auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) # if auth : # group_id = str(auth._id) # else : # pass group_name, group_id = get_group_name_id(group_id) ce_id = request.GET.get('course_event_id','') blog_type = request.GET.get('blog_type','') res = request.GET.get('res','') program_res = request.GET.get('program_res','') context_variables = { 'title': gst_page.name, 'group_id': group_id, 'groupid': group_id, 'ce_id': ce_id, 'res':res, 'program_res':program_res, 'blog_type': blog_type } group_obj = node_collection.one({'_id': ObjectId(group_id)}) available_nodes = node_collection.find({'_type': u'GSystem', 'member_of': ObjectId(gst_page._id),'group_set': ObjectId(group_id), '_id': {'$ne': ObjectId(node_id)} }) nodes_list = [] thread = None url_name = "/home" # for each in available_nodes: # nodes_list.append(str((each.name).strip().lower())) # loop replaced by a list comprehension node_list = [str((each.name).strip().lower()) for each in available_nodes] # print "available_nodes: ", node_list if request.method == "POST": # get_node_common_fields(request, page_node, group_id, gst_page) page_name = request.POST.get('name', '') # print "====== page_name: ", page_name if page_name.strip().lower() in node_list and not node_id: new_page=False return render_to_response("error_base.html", {'message': 'Page with same name already exists in the group!'}, context_instance=RequestContext(request)) elif node_id: new_page = False page_node = node_collection.one({'_type': u'GSystem', '_id': ObjectId(node_id)}) else: new_page = True page_node = node_collection.collection.GSystem() # page_type = request.POST.getlist("type_of",'') ce_id = request.POST.get("ce_id",'') blog_type = request.POST.get('blog_type','') res = request.POST.get("res",'') program_res = request.POST.get('program_res','') # we are fetching the value of release_response flag # if this is set, it means, we can proceed to create a thread node # for the current page node. thread_create_val = request.POST.get("thread_create",'') # print "\n\n thread_create_val", thread_create_val # print "\n\n request.POST === ",request.POST # raise Exception("demo") # help_info_page = request.POST.getlist('help_info_page','') help_info_page = request.POST['help_info_page'] if help_info_page: help_info_page = json.loads(help_info_page) # print "\n\n help_info_page === ",help_info_page #program_res and res are boolean values if program_res: program_res = eval(program_res) if res: res = eval(res) if blog_type: blog_type = eval(blog_type) # if page_type: # objid= page_type[0] # if not ObjectId(objid) in page_node.type_of: # page_type1=[] # page_type1.append(ObjectId(objid)) # page_node.type_of = page_type1 # page_node.type_of page_node.save(is_changed=get_node_common_fields(request, page_node, group_id, gst_page)) # if course event grp's id is passed, it means # its a blog page added in notebook and hence set type_of field as "Blog page" # print "\n\n blog_type---",blog_type if blog_type: blogpage_gst = node_collection.one({'_type': "GSystemType", 'name': "Blog page"}) page_node.type_of = [blogpage_gst._id] elif GSTUDIO_SITE_NAME == "NROER" and "Author" in group_obj.member_of_names_list: infopage_gst = node_collection.one({'_type': "GSystemType", 'name': "Info page"}) page_node.type_of = [infopage_gst._id] # if the page created is as a resource in course or program event, # set status to PUBLISHED by default # one major reason for this, ONLY published nodes can be replicated. if res or program_res or ce_id: page_node.status = u"PUBLISHED" page_node.save() # if page is created in program event, add page_node to group's collection set if program_res: group_obj = node_collection.one({'_id': ObjectId(group_id)}) group_obj.collection_set.append(page_node._id) group_obj.save() discussion_enable_at = node_collection.one({"_type": "AttributeType", "name": "discussion_enable"}) if thread_create_val == "Yes" or blog_type: create_gattribute(page_node._id, discussion_enable_at, True) return_status = create_thread_for_node(request,group_id, page_node) else: create_gattribute(page_node._id, discussion_enable_at, False) # print "\n\n help_info_page ================ ",help_info_page if "None" not in help_info_page: has_help_rt = node_collection.one({'_type': "RelationType", 'name': "has_help"}) try: help_info_page = map(ObjectId, help_info_page) create_grelation(page_node._id, has_help_rt,help_info_page) page_node.reload() except Exception as invalidobjectid: # print invalidobjectid pass else: # Check if node had has_help RT grel_dict = get_relation_value(page_node._id,"has_help") # print "\n\n grel_dict ==== ", grel_dict if grel_dict: grel_id = grel_dict.get("grel_id","") if grel_id: for each_grel_id in grel_id: del_status, del_status_msg = delete_grelation( subject_id=page_node._id, node_id=each_grel_id, deletion_type=0 ) # print "\n\n del_status == ",del_status # print "\n\n del_status_msg == ",del_status_msg # To fill the metadata info while creating and editing page node metadata = request.POST.get("metadata_info", '') if "CourseEventGroup" in group_obj.member_of_names_list and blog_type: if new_page: # counter_obj = Counter.get_counter_obj(request.user.id,ObjectId(group_id)) # # counter_obj.no_notes_written=counter_obj.no_notes_written+1 # counter_obj['page']['blog']['created'] += 1 # # counter_obj.course_score += GSTUDIO_NOTE_CREATE_POINTS # counter_obj['group_points'] += GSTUDIO_NOTE_CREATE_POINTS # counter_obj.last_update = datetime.datetime.now() # counter_obj.save() active_user_ids_list = [request.user.id] if GSTUDIO_BUDDY_LOGIN: active_user_ids_list += Buddy.get_buddy_userids_list_within_datetime(request.user.id, datetime.datetime.now()) # removing redundancy of user ids: active_user_ids_list = dict.fromkeys(active_user_ids_list).keys() counter_objs_cur = Counter.get_counter_objs_cur(active_user_ids_list, group_id) for each_counter_obj in counter_objs_cur: each_counter_obj['page']['blog']['created'] += 1 each_counter_obj['group_points'] += GSTUDIO_NOTE_CREATE_POINTS each_counter_obj.last_update = datetime.datetime.now() each_counter_obj.save() return HttpResponseRedirect(reverse('course_notebook_tab_note', kwargs={ 'group_id': group_id, 'tab': 'my-notes', 'notebook_id': page_node._id }) ) if ce_id or res or program_res: url_name = "/" + group_name + "/" + str(page_node._id) if ce_id: # url_name = "/" + group_name + "/#journal-tab" url_name = "/" + group_name if res or program_res: url_name = "/" + group_name + "/?selected=" + str(page_node._id) + "#view_page" # print "\n\n url_name---",url_name return HttpResponseRedirect(url_name) if metadata: # Only while metadata editing if metadata == "metadata": if page_node: get_node_metadata(request,page_node,is_changed=True) # End of filling metadata return HttpResponseRedirect(reverse('page_details', kwargs={'group_id': group_id, 'app_id': page_node._id })) else: if node_id: page_node = node_collection.one({'_type': u'GSystem', '_id': ObjectId(node_id)}) #page_node,ver=get_page(request,page_node) page_node.get_neighbourhood(page_node.member_of) context_variables['node'] = page_node context_variables['groupid'] = group_id context_variables['group_id'] = group_id # fetch Page instances # Page_node = node_collection.find_one({'_type':"GSystemType","name":"Page"}) page_instances = node_collection.find({"type_of": gst_page._id}) page_ins_list = [i for i in page_instances] context_variables['page_instance'] = page_ins_list context_variables['nodes_list'] = json.dumps(nodes_list) # print "\n\n context_variables----\n",context_variables return render_to_response("ndf/page_create_edit.html", context_variables, context_instance=RequestContext(request) )
def approve_resource(request, group_id): ''' Method to approve resorce. Means resource will get published by moderator to next moderated or parent group. ''' group_obj = get_group_name_id(group_id, get_obj=True) node_id = request.POST.get('node_oid', '') node_obj = node_collection.one({'_id': ObjectId(node_id)}) approve_or_reject = request.POST.get('app_rej_state', '') flag = 0 # good to check at JS/front-end level if approve_or_reject == "Approve": if node_obj: node_group_set = node_obj.group_set # task_id = get_relation_value(node_obj._id,"has_current_approval_task") # make deep copy of object and not to copy it's reference with [:]. group_set_details_dict = get_moderator_group_set(node_group_set[:], group_id, get_details=True) updated_group_set = group_set_details_dict['updated_group_set'] # print "==== updated_group_set : ", updated_group_set # print "==== node_group_set : ", node_group_set # print "==== group_set_details_dict : ", group_set_details_dict # if set(node_group_set) != set(updated_group_set): if group_set_details_dict['is_group_set_updated']: node_obj.group_set = updated_group_set # ---| checking for top group. \ # If not top group and it's fond to be sub group create task |--- # one way: # group_obj = get_group_name_id(updated_group_set[len(updated_group_set) - 1], get_obj=True) # print "===== group_obj.member_of_names_list : ", group_obj.member_of_names_list # if group_obj.member_of_names_list[0] in ['ProgramEventGroup', 'CourseEventGroup', 'PartnerGroup', 'ModeratingGroup']: # second way: if group_set_details_dict['is_new_group_top_group']: # means, resource is passed through curation flow and \ # therefore change the status from 'MODERATION' to 'PUBLISHED' node_obj.status = u'PUBLISHED' # intimate creator of object/resource and creator of parent group node_creator_username = User.objects.get(id=node_obj.created_by).username task_content_org = u"Congratulations " + unicode(node_creator_username) + \ u",\n\n Your contribution is moderated and it's published to " + \ group_set_details_dict['newly_appended_group_name'] + \ u". \n\nWe appreciate your efforts and thank you for your contribution!" create_moderator_task(request, \ group_set_details_dict['newly_appended_group_id'],\ node_obj._id, task_type_creation='multiple', \ task_type='Other', task_content_org=task_content_org,\ created_by_name=node_creator_username) else: # resource is in curation flow hence, create a task create_moderator_task(request, \ group_set_details_dict['newly_appended_group_id'],\ node_obj._id) # node_obj.modified_by = int(request.user.id) node_obj.save(groupid=group_id) flag = 1 else: flag = 0 elif approve_or_reject == "Reject": reject_reason_msg = request.POST.get('reject_reason', '') # print "reject_reason_msg----", reject_reason_msg # raise Exception("bb") # task_node,task_rt = get_relation_value(node_obj._id,"has_current_approval_task") grel_dict = get_relation_value(node_obj._id,"has_current_approval_task") is_cursor = grel_dict.get("cursor",False) if not is_cursor: task_node = grel_dict.get("grel_node") task_rt = grel_dict.get("grel_id") auth_grp = node_collection.one({'_type': "Author", 'created_by': int(node_obj.created_by)}) node_obj.group_set = [auth_grp._id] node_obj.status = u"DRAFT" node_obj.save() # is_top_group, top_group_obj = get_top_group_of_hierarchy(group_obj._id) mod_group_instance = CreateModeratedGroup(request) # is_top_group, top_group_obj = mod_group_instance.get_top_group_of_hierarchy(curr_group_id) is_top_group, top_group_obj = mod_group_instance.get_top_group_of_hierarchy(group_obj._id) list_of_recipients_ids = [] list_of_recipients_ids.extend(group_obj.group_admin) list_of_recipients_ids.extend(top_group_obj.group_admin) list_of_recipients_ids.append(node_obj.created_by) # print list_of_recipients_ids if task_node: task_content_org = u"\n\nThis task is CLOSED.\n " \ "The resource associated with Moderation Task has been REJECTED. \n" task_dict = { "name": task_node.name, "_id" : ObjectId(task_node._id), "created_by": node_obj.created_by, "modified_by": request.user.id, "contributors": [request.user.id], "content_org": unicode(task_content_org), "created_by_name": unicode(request.user.username), "Status": u"CLOSED", "Priority": u"Normal", "Assignee": list(group_obj.group_admin[:]), # "has_type": task_type_list } task_obj = create_task(task_dict, 'group') # Sending notification to all watchers about the updates of the task try: for each_user_id in list_of_recipients_ids: activ = "Contribution to " + group_obj.name +"." mail_content = u"\n The resource "+ node_obj.name +" is REJECTED by " \ + request.user.username + ". \n" \ + "Reason specified: "+ unicode(reject_reason_msg) user_obj = User.objects.get(id=int(each_user_id)) set_notif_val(request, group_obj._id, mail_content, activ, user_obj) except Exception as e: print "\n Unable to send notifications ",e flag = 1 return HttpResponse(flag)
def get_lang_node(node_id,lang): rel_value = get_relation_value(ObjectId(node_id),"translation_of") for each in rel_value['grel_node']: if each.language[0] == get_language_tuple(lang)[0]: trans_node = each return trans_node
def save_quizitem_answer(request, group_id): response_dict = {"success": False} try: if request.is_ajax() and request.method == "POST": try: group_id = ObjectId(group_id) except: group_name, group_id = get_group_name_id(group_id) import datetime new_list = [] old_submitted_ans = None recent_ans = None is_user_given_ans_not_in_recent_submitted_ans = False recent_submitted_ans_was_correct = False user_given_ans = request.POST.getlist("user_given_ans[]", '') node_id = request.POST.get("node", '') node_obj = node_collection.one({'_id': ObjectId(node_id)}) thread_obj = user_ans = None ''' print "\n\n node_obj::::::::",node_obj.relation_set try: for each_rel in node_obj.relation_set: if each_rel and "has_thread" in each_rel: thread_id = each_rel['has_thread'][0] thread_obj = node_collection.one({'_id': ObjectId(thread_id)}) # print "\n\n thread_obj === ", thread_obj.name , "===" except: pass ''' grel_dict = get_relation_value(node_obj._id,"has_thread", True) is_cursor = grel_dict.get("cursor",False) if not is_cursor: thread_obj = grel_dict.get("grel_node") # print "\n thread_obj: ", thread_obj user_action = request.POST.get("user_action", '') user_id = int(request.user.id) user_name = unicode(request.user.username) qip_gst = node_collection.one({ '_type': 'GSystemType', 'name': 'QuizItemPost'}) qip_user_submitted_ans_AT = node_collection.one({'_type': "AttributeType", 'name': "quizitempost_user_submitted_ans"}) qip_user_checked_ans_AT = node_collection.one({'_type': "AttributeType", 'name': "quizitempost_user_checked_ans"}) already_ans_obj = already_submitted_ans = None # print "\n\n thread_obj == ", thread_obj if thread_obj != None: already_ans_obj = node_collection.find_one({'member_of': qip_gst._id,'created_by': user_id, 'prior_node': thread_obj._id}) if already_ans_obj: already_submitted_ans = get_attribute_value(already_ans_obj._id,"quizitempost_user_submitted_ans") # print "\n already_submitted_ans == ", already_submitted_ans # check whether user has already checked or submitted ans user_ans = already_ans_obj else: user_ans = node_collection.collection.GSystem() user_ans.created_by = user_id user_ans.modified_by = user_id user_ans.contributors.append(user_id) user_ans.member_of.append(qip_gst._id) user_ans.group_set.append(group_id) if node_obj._id not in user_ans.prior_node: user_ans.prior_node.append(node_obj._id) user_ans.origin = [{'thread_id': thread_obj._id, 'prior_node_id_of_thread': node_obj._id}] user_ans.status = u"PUBLISHED" user_ans.name = unicode("Answer_of:" + str(node_obj.name) + "-Answer_by:"+ str(user_name)) user_ans.save() # print "\n\n user_ans== ",user_ans if user_id not in thread_obj.author_set: thread_obj.author_set.append(user_id) thread_obj.save() # print "\n thread_obj.author_set",thread_obj.author_set if thread_obj._id not in user_ans.prior_node: # add user's post/reply obj to thread obj's post_node node_collection.collection.update({'_id': user_ans._id}, {'$push': {'prior_node':thread_obj._id}},upsert=False,multi=False) if user_ans._id not in thread_obj.post_node: # add thread obj to user's post/reply prior_node node_collection.collection.update({'_id': thread_obj._id}, {'$push': {'post_node':user_ans._id}},upsert=False,multi=False) quiz_type_val = get_attribute_value(node_obj._id,"quiz_type") quiz_correct_ans = get_attribute_value(node_obj._id,"correct_answer") # print "\n quiz_type_val: ", quiz_type_val # print "\n quiz_correct_ans: ", quiz_correct_ans # print "\n user_given_ans: ",user_given_ans quiz_correct_ans = (map(unicode,[re.sub(r'[\r]', '', cor_ans) for cor_ans in quiz_correct_ans])) # print "\n get_attribute_value--", get_attribute_value if user_given_ans and user_ans: if quiz_type_val == "Short-Response": create_gattribute(user_ans._id, qip_user_submitted_ans_AT, user_given_ans) else: curr_datetime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") if user_given_ans: if user_action == "check": if already_ans_obj: old_checked_ans = get_attribute_value(user_ans._id,"quizitempost_user_checked_ans") if old_checked_ans != "None" and old_checked_ans != "": new_list = old_checked_ans new_list.append({str(curr_datetime):user_given_ans}) if new_list: create_gattribute(user_ans._id, qip_user_checked_ans_AT, new_list) elif user_action == "submit": if already_ans_obj: old_submitted_ans = get_attribute_value(user_ans._id,"quizitempost_user_submitted_ans") if old_submitted_ans != "None" and old_submitted_ans != "" and old_submitted_ans: new_list = old_submitted_ans new_list.append({str(curr_datetime):user_given_ans}) if new_list: create_gattribute(user_ans._id, qip_user_submitted_ans_AT, new_list) user_ans.reload() # print "\n user_ans.attribute_set",user_ans.attribute_set response_dict['count'] = len(new_list) response_dict['success'] = True active_user_ids_list = [request.user.id] if old_submitted_ans: recent_ans = old_submitted_ans[-1].values() if recent_ans: recent_ans = recent_ans[0] is_user_given_ans_not_in_recent_submitted_ans = all(each_usr_given_ans not in recent_ans for each_usr_given_ans in user_given_ans) recent_submitted_ans_was_correct = any(each_submitted_ans in quiz_correct_ans for each_submitted_ans in recent_ans) # print "\n recent_ans == ", recent_ans # print "\n user_given_ans == ", user_given_ans if GSTUDIO_BUDDY_LOGIN: active_user_ids_list += Buddy.get_buddy_userids_list_within_datetime(request.user.id, datetime.datetime.now()) # removing redundancy of user ids: # active_user_ids_list = dict.fromkeys(active_user_ids_list).keys() counter_objs_cur = Counter.get_counter_objs_cur(active_user_ids_list, group_id) #code to update counter collection # counter_obj = Counter.get_counter_obj(user_id, group_id) if not already_submitted_ans: # This is the first time to attempt this quizitemevent for userr_each_attr in user_ans.attribute_set: if 'quizitempost_user_submitted_ans' in userr_each_attr: if len(userr_each_attr['quizitempost_user_submitted_ans'])!=0: # counter_obj.no_questions_attempted+=1 for each_counter_obj in counter_objs_cur: each_counter_obj['quiz']['attempted'] += 1 each_counter_obj.save() counter_objs_cur.rewind() ''' for each_attr in node_obj.attribute_set: if 'correct_answer' in each_attr: quiz_correct_ans = each_attr['correct_answer'] if 'quiz_type' in each_attr: type_of_quiz = each_attr['quiz_type'] ''' for each_user_ans_attr in user_ans.attribute_set: if 'quizitempost_user_submitted_ans' in each_user_ans_attr: if quiz_type_val=='Single-Choice': if len(each_user_ans_attr['quizitempost_user_submitted_ans'])!=0: for each_counter_obj in counter_objs_cur: if cmp(quiz_correct_ans,user_given_ans)==0: # counter_obj.no_correct_answers+=1 if not already_submitted_ans or is_user_given_ans_not_in_recent_submitted_ans: if is_user_given_ans_not_in_recent_submitted_ans and each_counter_obj['quiz']['incorrect']: each_counter_obj['quiz']['incorrect'] -= 1 if not recent_submitted_ans_was_correct: each_counter_obj['quiz']['correct'] += 1 each_counter_obj['group_points'] += GSTUDIO_QUIZ_CORRECT_POINTS each_counter_obj.save() else: # each_counter_obj.no_incorrect_answers+=1 if not already_submitted_ans or is_user_given_ans_not_in_recent_submitted_ans: if is_user_given_ans_not_in_recent_submitted_ans and each_counter_obj['quiz']['correct']: each_counter_obj['quiz']['correct'] -= 1 if recent_submitted_ans_was_correct: each_counter_obj['quiz']['incorrect'] += 1 each_counter_obj.save() counter_objs_cur.rewind() if quiz_type_val=='Multiple-Choice': if each_user_ans_attr['quizitempost_user_submitted_ans']: search = False user_given_ans = [x.encode('UTF8') for x in user_given_ans] quiz_correct_ans = [x.encode('UTF8') for x in quiz_correct_ans] # print "\n user_given_ans : ", user_given_ans # print "\n quiz_correct_ans: ", quiz_correct_ans # Remove Carriage Return from Python strings ['\r'] in quiz_correct_ans quiz_correct_ans_tmp = [] for each_option in quiz_correct_ans: each_option = each_option.replace('\r','') quiz_correct_ans_tmp.append(each_option) quiz_correct_ans = quiz_correct_ans_tmp for each_user_given_ans in user_given_ans: if each_user_given_ans in quiz_correct_ans: search = True # print "\n search : ", search ''' i=0 while i<len(user_given_ans): try: quiz_correct_ans.index(user_given_ans[i]) search=True i=i+1 except Exception as e1: search=False break ''' for each_counter_obj in counter_objs_cur: if search==True: try: if not already_submitted_ans or is_user_given_ans_not_in_recent_submitted_ans: if is_user_given_ans_not_in_recent_submitted_ans and each_counter_obj['quiz']['incorrect']: each_counter_obj['quiz']['incorrect'] -= 1 if not recent_submitted_ans_was_correct: each_counter_obj['quiz']['correct'] += 1 # each_counter_obj.course_score+=GSTUDIO_QUIZ_CORRECT_POINTS each_counter_obj['group_points'] += GSTUDIO_QUIZ_CORRECT_POINTS each_counter_obj.save() except Exception as rer: print "\n Error ", rer else: # each_counter_obj.no_incorrect_answers+=1 if not already_submitted_ans or is_user_given_ans_not_in_recent_submitted_ans: if is_user_given_ans_not_in_recent_submitted_ans and each_counter_obj['quiz']['correct']: each_counter_obj['quiz']['correct'] -= 1 if recent_submitted_ans_was_correct: each_counter_obj['quiz']['incorrect'] += 1 each_counter_obj.save() counter_objs_cur.rewind() if quiz_type_val=='Short-Response': if len(user_given_ans)!=0: # counter_obj.no_correct_answers+=1 for each_counter_obj in counter_objs_cur: if not already_submitted_ans: each_counter_obj['quiz']['correct'] += 1 # each_counter_obj.course_score += GSTUDIO_QUIZ_CORRECT_POINTS each_counter_obj['group_points'] += GSTUDIO_QUIZ_CORRECT_POINTS each_counter_obj.save() #updated counter collection return HttpResponse(json.dumps(response_dict)) except Exception as e: print "\n Something went wrong while saving quiz answer!!! ", str(e) return response_dict
def create_moderator_task(request, group_id, node_id, \ task_type_creation='group', task_type='Moderation', task_content_org="", \ created_by_name="",on_upload=False): ''' Method to create task to group admins or moderators of the moderated groups. ''' from gnowsys_ndf.ndf.templatetags.ndf_tags import get_relation_value # def create_task(task_dict, task_type_creation="single"): # task_dict # - Required keys: _id[optional], name, group_set, created_by, modified_by, contributors, content_org, # created_by_name, Status, Priority, start_time, end_time, Assignee, has_type try: task_dict = {} node_obj = node_collection.one({'_id': ObjectId(node_id)}) # task_id_val = get_relation_value(node_obj._id,"has_current_approval_task") grel_dict = get_relation_value(node_obj._id,"has_current_approval_task") is_cursor = grel_dict.get("cursor",False) if not is_cursor: task_node = grel_dict.get("grel_node",None) if task_node: task_dict['_id'] = task_node._id # grel_id = grel_dict.get("grel_id") # if task_id_val != None: # task_dict['_id'] = get_relation_value(node_obj._id,"has_current_approval_task") # if node_obj.relation_set: # for rel in node_obj.relation_set: # if rel and 'has_current_approval_task' in rel: # task_id = rel['has_current_approval_task'][0] # task_dict["_id"] = ObjectId(task_id) # last group is next appended group group_obj = get_group_name_id(group_id, get_obj=True) at_curr_app_task = node_collection.one({'_type': "RelationType", 'name': "has_current_approval_task"}) glist_gst = node_collection.one({'_type': "GSystemType", 'name': "GList"}) task_type_list = [] task_type_list.append(node_collection.one({'member_of': glist_gst._id, 'name':unicode(task_type)})._id) site = Site.objects.get(pk=1) site_domain = site.domain # print "=== site_domain: ", site_domain site = unicode(site.name.__str__()) auth_grp = node_collection.one({'_type': "Author", 'created_by': int(node_obj.created_by)}) if task_type == "Moderation": task_title = u"Resource under moderation: " + node_obj.name if task_content_org: pass else: url = u"http://" + site_domain + "/"+ unicode(group_obj._id) \ + u"/moderation#" + unicode(node_obj._id.__str__()) task_content_org = u'\n\nResource under moderation: "' + unicode(node_obj.name) \ + u'" having id: "' + unicode(node_obj._id.__str__()) + '"' \ task_dict = { "name": task_title, "group_set": [group_obj._id], "created_by": node_obj.created_by, "modified_by": request.user.id, "contributors": [request.user.id], "content_org": unicode(task_content_org), "created_by_name": unicode(request.user.username), # "Status": u"New", "Priority": u"Normal", # "start_time": "", # "end_time": "", "Assignee": list(group_obj.group_admin[:]), "has_type": task_type_list } if on_upload: task_dict['Status'] = u"New" else: task_dict['Status'] = u"In Progress" task_obj = create_task(task_dict, task_type_creation) if task_obj: create_grelation(node_obj._id, at_curr_app_task, task_obj._id) try: url = u"http://" + site_domain + "/" + unicode(auth_grp._id) \ + u"/moderation/status/" + unicode(node_obj._id.__str__()) activ = "Contribution to " + group_obj.name + "." if not on_upload: mail_content = "Moderation status of your contributed file has been updated.\n" \ + "You may visit this link to check the status of Moderation :\t" \ + url elif on_upload: mail_content = "Your contributed file has been sent for Moderation.\n" \ + "You may visit this link to check the status of Moderation :\t" \ + url user_obj = User.objects.get(id=node_obj.created_by) set_notif_val(request, auth_grp._id, mail_content, activ, user_obj) except Exception as notif_err: # print notif_err msg = "Unable to send Notification" else: # on final publish to top group # task_title = u"\n\nResource " + node_obj.name + \ # u" in " + group_obj.name + u" is Approved. " # task_dict = { # "name": task_title, # "modified_by": request.user.id, # "created_by_name": unicode(request.user.username), # "Status": u"Feedback", # "group_set": [group_obj._id], # "created_by": node_obj.created_by, # "content_org": unicode(task_content_org), # "modified_by": request.user.id, # "contributors": [request.user.id], # "Priority": u"Normal", # "Assignee": list(group_obj.group_admin[:] + [node_obj.created_by]), # "has_type": task_type_list # } try: # delete the task associated with the resource list_of_recipients_ids = [] list_of_recipients_ids.extend(group_obj.group_admin) list_of_recipients_ids.append(node_obj.created_by) # Sending notification to all watchers about the updates of the task for each_user_id in list_of_recipients_ids: url = u"http://" + site_domain + "/"+ unicode(group_obj._id) \ + u"/file/" + unicode(node_obj._id.__str__()) activ = "Contribution to " + group_obj.name +"." mail_content = u"\n\n Contribution file "+ node_obj.name +" is moderated " \ + "and successfully published to " + \ group_obj.name + \ u". \n\nVisit this link to view the resource : " \ + url user_obj = User.objects.get(id=int(each_user_id)) set_notif_val(request, auth_grp._id, mail_content, activ, user_obj) if task_id: task_node = node_collection.one({'_id': ObjectId(task_id)}) # del_status, del_status_msg = delete_node( # node_id=task_node._id, deletion_type=0) url = u"http://" + site_domain + "/"+ unicode(group_obj._id) \ + u"/file/" + unicode(node_obj._id.__str__()) task_content_org = u"\n\nThis task is CLOSED.\n " \ "However, you may find the moderated resource at following link: \n" \ + unicode(url) task_dict = { "name": task_node.name, "group_set": [group_obj._id], "created_by": node_obj.created_by, "modified_by": request.user.id, "contributors": [request.user.id], "content_org": unicode(task_content_org), "created_by_name": unicode(request.user.username), "Status": u"CLOSED", "Priority": u"Normal", "Assignee": list(group_obj.group_admin[:]), "has_type": task_type_list } task_obj = create_task(task_dict, task_type_creation) except Exception as e: msg = "Unable to send Notification", str(e) except Exception as e: print "Error in task create moderation --- " + str(e)
def approve_resource(request, group_id): ''' Method to approve resorce. Means resource will get published by moderator to next moderated or parent group. ''' group_obj = get_group_name_id(group_id, get_obj=True) node_id = request.POST.get('node_oid', '') node_obj = node_collection.one({'_id': ObjectId(node_id)}) approve_or_reject = request.POST.get('app_rej_state', '') flag = 0 # good to check at JS/front-end level if approve_or_reject == "Approve": if node_obj: node_group_set = node_obj.group_set # task_id = get_relation_value(node_obj._id,"has_current_approval_task") # make deep copy of object and not to copy it's reference with [:]. group_set_details_dict = get_moderator_group_set(node_group_set[:], group_id, get_details=True) updated_group_set = group_set_details_dict['updated_group_set'] # print "==== updated_group_set : ", updated_group_set # print "==== node_group_set : ", node_group_set # print "==== group_set_details_dict : ", group_set_details_dict # if set(node_group_set) != set(updated_group_set): if group_set_details_dict['is_group_set_updated']: node_obj.group_set = updated_group_set # ---| checking for top group. \ # If not top group and it's fond to be sub group create task |--- # one way: # group_obj = get_group_name_id(updated_group_set[len(updated_group_set) - 1], get_obj=True) # print "===== group_obj.member_of_names_list : ", group_obj.member_of_names_list # if group_obj.member_of_names_list[0] in ['ProgramEventGroup', 'CourseEventGroup', 'PartnerGroup', 'ModeratingGroup']: # second way: if group_set_details_dict['is_new_group_top_group']: # means, resource is passed through curation flow and \ # therefore change the status from 'MODERATION' to 'PUBLISHED' node_obj.status = u'PUBLISHED' # intimate creator of object/resource and creator of parent group node_creator_username = User.objects.get(id=node_obj.created_by).username task_content_org = u"Congratulations " + unicode(node_creator_username) + \ u",\n\n Your contribution is moderated and it's published to " + \ group_set_details_dict['newly_appended_group_name'] + \ u". \n\nWe appreciate your efforts and thank you for your contribution!" create_moderator_task(request, \ group_set_details_dict['newly_appended_group_id'],\ node_obj._id, task_type_creation='multiple', \ task_type='Other', task_content_org=task_content_org,\ created_by_name=node_creator_username) else: # resource is in curation flow hence, create a task create_moderator_task(request, \ group_set_details_dict['newly_appended_group_id'],\ node_obj._id) # node_obj.modified_by = int(request.user.id) node_obj.save(groupid=group_id) flag = 1 else: flag = 0 elif approve_or_reject == "Reject": reject_reason_msg = request.POST.get('reject_reason', '') # print "reject_reason_msg----", reject_reason_msg # raise Exception("bb") # task_node,task_rt = get_relation_value(node_obj._id,"has_current_approval_task") grel_dict = get_relation_value(node_obj._id,"has_current_approval_task") is_cursor = grel_dict.get("cursor",False) if not is_cursor: task_node = grel_dict.get("grel_node") task_rt = grel_dict.get("grel_id") auth_grp = node_collection.one({'_type': "Author", 'created_by': int(node_obj.created_by)}) node_obj.group_set = [auth_grp._id] node_obj.status = u"DRAFT" node_obj.save() # is_top_group, top_group_obj = get_top_group_of_hierarchy(group_obj._id) mod_group_instance = CreateModeratedGroup(request) # is_top_group, top_group_obj = mod_group_instance.get_top_group_of_hierarchy(curr_group_id) is_top_group, top_group_obj = mod_group_instance.get_top_group_of_hierarchy(group_obj._id) list_of_recipients_ids = [] list_of_recipients_ids.extend(group_obj.group_admin) list_of_recipients_ids.extend(top_group_obj.group_admin) list_of_recipients_ids.append(node_obj.created_by) # print list_of_recipients_ids if task_node: task_content_org = u"\n\nThis task is CLOSED.\n " \ "The resource associated with Moderation Task has been REJECTED. \n" task_dict = { "name": task_node.name, "_id" : ObjectId(task_node._id), "created_by": node_obj.created_by, "modified_by": request.user.id, "contributors": [request.user.id], "content_org": unicode(task_content_org), "created_by_name": unicode(request.user.username), "Status": u"CLOSED", "Priority": u"Normal", "Assignee": list(group_obj.group_admin[:]), # "has_type": task_type_list } task_obj = create_task(task_dict, 'group') # Sending notification to all watchers about the updates of the task try: for each_user_id in list_of_recipients_ids: activ = "Contribution to " + group_obj.name +"." mail_content = u"\n The resource "+ node_obj.name +" is REJECTED by " \ + request.user.username + ". \n" \ + "Reason specified: "+ unicode(reject_reason_msg) user_obj = User.objects.get(id=int(each_user_id)) set_notif_val(request, group_obj._id, mail_content, activ, user_obj) except Exception as e: print "\n Unable to send notifications ",e flag = 1 return HttpResponse(flag)
def save_quizitem_answer(request, group_id): response_dict = {"success": False} try: if request.is_ajax() and request.method == "POST": try: group_id = ObjectId(group_id) except: group_name, group_id = get_group_name_id(group_id) import datetime new_list = [] old_submitted_ans = None recent_ans = None is_user_given_ans_not_in_recent_submitted_ans = False recent_submitted_ans_was_correct = False user_given_ans = request.POST.getlist("user_given_ans[]", '') node_id = request.POST.get("node", '') node_obj = node_collection.one({'_id': ObjectId(node_id)}) thread_obj = user_ans = None ''' print "\n\n node_obj::::::::",node_obj.relation_set try: for each_rel in node_obj.relation_set: if each_rel and "has_thread" in each_rel: thread_id = each_rel['has_thread'][0] thread_obj = node_collection.one({'_id': ObjectId(thread_id)}) # print "\n\n thread_obj === ", thread_obj.name , "===" except: pass ''' grel_dict = get_relation_value(node_obj._id, "has_thread", True) is_cursor = grel_dict.get("cursor", False) if not is_cursor: thread_obj = grel_dict.get("grel_node") # print "\n thread_obj: ", thread_obj user_action = request.POST.get("user_action", '') user_id = int(request.user.id) user_name = unicode(request.user.username) qip_gst = node_collection.one({ '_type': 'GSystemType', 'name': 'QuizItemPost' }) qip_user_submitted_ans_AT = node_collection.one({ '_type': "AttributeType", 'name': "quizitempost_user_submitted_ans" }) qip_user_checked_ans_AT = node_collection.one({ '_type': "AttributeType", 'name': "quizitempost_user_checked_ans" }) already_ans_obj = already_submitted_ans = None # print "\n\n thread_obj == ", thread_obj if thread_obj != None: already_ans_obj = node_collection.find_one({ 'member_of': qip_gst._id, 'created_by': user_id, 'prior_node': thread_obj._id }) if already_ans_obj: already_submitted_ans = get_attribute_value( already_ans_obj._id, "quizitempost_user_submitted_ans") # print "\n already_submitted_ans == ", already_submitted_ans # check whether user has already checked or submitted ans user_ans = already_ans_obj else: user_ans = node_collection.collection.GSystem() user_ans.created_by = user_id user_ans.modified_by = user_id user_ans.contributors.append(user_id) user_ans.member_of.append(qip_gst._id) user_ans.group_set.append(group_id) if node_obj._id not in user_ans.prior_node: user_ans.prior_node.append(node_obj._id) user_ans.origin = [{ 'thread_id': thread_obj._id, 'prior_node_id_of_thread': node_obj._id }] user_ans.status = u"PUBLISHED" user_ans.name = unicode("Answer_of:" + str(node_obj.name) + "-Answer_by:" + str(user_name)) user_ans.save() # print "\n\n user_ans== ",user_ans if user_id not in thread_obj.author_set: thread_obj.author_set.append(user_id) thread_obj.save() # print "\n thread_obj.author_set",thread_obj.author_set if thread_obj._id not in user_ans.prior_node: # add user's post/reply obj to thread obj's post_node node_collection.collection.update( {'_id': user_ans._id}, {'$push': { 'prior_node': thread_obj._id }}, upsert=False, multi=False) if user_ans._id not in thread_obj.post_node: # add thread obj to user's post/reply prior_node node_collection.collection.update( {'_id': thread_obj._id}, {'$push': { 'post_node': user_ans._id }}, upsert=False, multi=False) quiz_type_val = get_attribute_value(node_obj._id, "quiz_type") quiz_correct_ans = get_attribute_value(node_obj._id, "correct_answer") # print "\n quiz_type_val: ", quiz_type_val # print "\n quiz_correct_ans: ", quiz_correct_ans # print "\n user_given_ans: ",user_given_ans quiz_correct_ans = (map(unicode, [ re.sub(r'[\r]', '', cor_ans) for cor_ans in quiz_correct_ans ])) # print "\n get_attribute_value--", get_attribute_value if user_given_ans and user_ans: if quiz_type_val == "Short-Response": create_gattribute(user_ans._id, qip_user_submitted_ans_AT, user_given_ans) else: curr_datetime = datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S") if user_given_ans: if user_action == "check": if already_ans_obj: old_checked_ans = get_attribute_value( user_ans._id, "quizitempost_user_checked_ans") if old_checked_ans != "None" and old_checked_ans != "": new_list = old_checked_ans new_list.append( {str(curr_datetime): user_given_ans}) if new_list: create_gattribute(user_ans._id, qip_user_checked_ans_AT, new_list) elif user_action == "submit": if already_ans_obj: old_submitted_ans = get_attribute_value( user_ans._id, "quizitempost_user_submitted_ans") if old_submitted_ans != "None" and old_submitted_ans != "" and old_submitted_ans: new_list = old_submitted_ans new_list.append( {str(curr_datetime): user_given_ans}) if new_list: create_gattribute( user_ans._id, qip_user_submitted_ans_AT, new_list) user_ans.reload() # print "\n user_ans.attribute_set",user_ans.attribute_set response_dict['count'] = len(new_list) response_dict['success'] = True active_user_ids_list = [request.user.id] if old_submitted_ans: recent_ans = old_submitted_ans[-1].values() if recent_ans: recent_ans = recent_ans[0] is_user_given_ans_not_in_recent_submitted_ans = all( each_usr_given_ans not in recent_ans for each_usr_given_ans in user_given_ans) recent_submitted_ans_was_correct = any( each_submitted_ans in quiz_correct_ans for each_submitted_ans in recent_ans) # print "\n recent_ans == ", recent_ans # print "\n user_given_ans == ", user_given_ans if GSTUDIO_BUDDY_LOGIN: active_user_ids_list += Buddy.get_buddy_userids_list_within_datetime( request.user.id, datetime.datetime.now()) # removing redundancy of user ids: # active_user_ids_list = dict.fromkeys(active_user_ids_list).keys() counter_objs_cur = Counter.get_counter_objs_cur( active_user_ids_list, group_id) #code to update counter collection # counter_obj = Counter.get_counter_obj(user_id, group_id) if not already_submitted_ans: # This is the first time to attempt this quizitemevent for userr_each_attr in user_ans.attribute_set: if 'quizitempost_user_submitted_ans' in userr_each_attr: if len(userr_each_attr[ 'quizitempost_user_submitted_ans']) != 0: # counter_obj.no_questions_attempted+=1 for each_counter_obj in counter_objs_cur: each_counter_obj['quiz']['attempted'] += 1 each_counter_obj.save() counter_objs_cur.rewind() ''' for each_attr in node_obj.attribute_set: if 'correct_answer' in each_attr: quiz_correct_ans = each_attr['correct_answer'] if 'quiz_type' in each_attr: type_of_quiz = each_attr['quiz_type'] ''' for each_user_ans_attr in user_ans.attribute_set: if 'quizitempost_user_submitted_ans' in each_user_ans_attr: if quiz_type_val == 'Single-Choice': if len(each_user_ans_attr[ 'quizitempost_user_submitted_ans']) != 0: for each_counter_obj in counter_objs_cur: if cmp(quiz_correct_ans, user_given_ans) == 0: # counter_obj.no_correct_answers+=1 if not already_submitted_ans or is_user_given_ans_not_in_recent_submitted_ans: if is_user_given_ans_not_in_recent_submitted_ans and each_counter_obj[ 'quiz']['incorrect']: each_counter_obj['quiz'][ 'incorrect'] -= 1 if not recent_submitted_ans_was_correct: each_counter_obj['quiz'][ 'correct'] += 1 each_counter_obj[ 'group_points'] += GSTUDIO_QUIZ_CORRECT_POINTS each_counter_obj.save() else: # each_counter_obj.no_incorrect_answers+=1 if not already_submitted_ans or is_user_given_ans_not_in_recent_submitted_ans: if is_user_given_ans_not_in_recent_submitted_ans and each_counter_obj[ 'quiz']['correct']: each_counter_obj['quiz'][ 'correct'] -= 1 if recent_submitted_ans_was_correct: each_counter_obj['quiz'][ 'incorrect'] += 1 each_counter_obj.save() counter_objs_cur.rewind() if quiz_type_val == 'Multiple-Choice': if each_user_ans_attr[ 'quizitempost_user_submitted_ans']: search = False user_given_ans = [ x.encode('UTF8') for x in user_given_ans ] quiz_correct_ans = [ x.encode('UTF8') for x in quiz_correct_ans ] # print "\n user_given_ans : ", user_given_ans # print "\n quiz_correct_ans: ", quiz_correct_ans # Remove Carriage Return from Python strings ['\r'] in quiz_correct_ans quiz_correct_ans_tmp = [] for each_option in quiz_correct_ans: each_option = each_option.replace('\r', '') quiz_correct_ans_tmp.append(each_option) quiz_correct_ans = quiz_correct_ans_tmp for each_user_given_ans in user_given_ans: if each_user_given_ans in quiz_correct_ans: search = True # print "\n search : ", search ''' i=0 while i<len(user_given_ans): try: quiz_correct_ans.index(user_given_ans[i]) search=True i=i+1 except Exception as e1: search=False break ''' for each_counter_obj in counter_objs_cur: if search == True: try: if not already_submitted_ans or is_user_given_ans_not_in_recent_submitted_ans: if is_user_given_ans_not_in_recent_submitted_ans and each_counter_obj[ 'quiz']['incorrect']: each_counter_obj['quiz'][ 'incorrect'] -= 1 if not recent_submitted_ans_was_correct: each_counter_obj['quiz'][ 'correct'] += 1 # each_counter_obj.course_score+=GSTUDIO_QUIZ_CORRECT_POINTS each_counter_obj[ 'group_points'] += GSTUDIO_QUIZ_CORRECT_POINTS each_counter_obj.save() except Exception as rer: print "\n Error ", rer else: # each_counter_obj.no_incorrect_answers+=1 if not already_submitted_ans or is_user_given_ans_not_in_recent_submitted_ans: if is_user_given_ans_not_in_recent_submitted_ans and each_counter_obj[ 'quiz']['correct']: each_counter_obj['quiz'][ 'correct'] -= 1 if recent_submitted_ans_was_correct: each_counter_obj['quiz'][ 'incorrect'] += 1 each_counter_obj.save() counter_objs_cur.rewind() if quiz_type_val == 'Short-Response': if len(user_given_ans) != 0: # counter_obj.no_correct_answers+=1 for each_counter_obj in counter_objs_cur: if not already_submitted_ans: each_counter_obj['quiz'][ 'correct'] += 1 # each_counter_obj.course_score += GSTUDIO_QUIZ_CORRECT_POINTS each_counter_obj[ 'group_points'] += GSTUDIO_QUIZ_CORRECT_POINTS each_counter_obj.save() #updated counter collection return HttpResponse(json.dumps(response_dict)) except Exception as e: print "\n Something went wrong while saving quiz answer!!! ", str(e) return response_dict
def save_quizitem_answer(request, group_id): response_dict = {"success": False} try: if request.is_ajax() and request.method == "POST": try: group_id = ObjectId(group_id) except: group_name, group_id = get_group_name_id(group_id) import datetime # group_obj = node_collection.one({'_id': ObjectId(group_id)}) new_list = [] user_given_ans = request.POST.getlist("user_given_ans[]", '') node_id = request.POST.get("node", '') # print "\n\n user_give_ans",user_given_ans node_obj = node_collection.one({'_id': ObjectId(node_id)}) thread_obj = user_ans = None ''' print "\n\n node_obj::::::::",node_obj.relation_set try: for each_rel in node_obj.relation_set: if each_rel and "has_thread" in each_rel: thread_id = each_rel['has_thread'][0] thread_obj = node_collection.one({'_id': ObjectId(thread_id)}) # print "\n\n thread_obj === ", thread_obj.name , "===" except: pass ''' grel_dict = get_relation_value(node_obj._id,"has_thread", True) is_cursor = grel_dict.get("cursor",False) if not is_cursor: thread_obj = grel_dict.get("grel_node") # print "\n thread_obj: ", thread_obj user_action = request.POST.get("user_action", '') user_id = int(request.user.id) user_name = unicode(request.user.username) qip_gst = node_collection.one({ '_type': 'GSystemType', 'name': 'QuizItemPost'}) qip_user_submitted_ans_AT = node_collection.one({'_type': "AttributeType", 'name': "quizitempost_user_submitted_ans"}) qip_user_checked_ans_AT = node_collection.one({'_type': "AttributeType", 'name': "quizitempost_user_checked_ans"}) already_ans_obj = None # print "\n\n thread_obj == ", thread_obj if thread_obj != None: already_ans_obj = node_collection.find_one({'member_of': qip_gst._id,'created_by': user_id, 'prior_node': thread_obj._id}) if already_ans_obj: # check whether user has already checked or submitted ans user_ans = already_ans_obj else: user_ans = node_collection.collection.GSystem() user_ans.created_by = user_id user_ans.modified_by = user_id user_ans.contributors.append(user_id) user_ans.member_of.append(qip_gst._id) user_ans.group_set.append(group_id) if node_obj._id not in user_ans.prior_node: user_ans.prior_node.append(node_obj._id) user_ans.origin = [{'thread_id': thread_obj._id, 'prior_node_id_of_thread': node_obj._id}] user_ans.status = u"PUBLISHED" user_ans.name = unicode("Answer_of:" + str(node_obj.name) + "-Answer_by:"+ str(user_name)) user_ans.save() # print "\n\n user_ans== ",user_ans if user_id not in thread_obj.author_set: thread_obj.author_set.append(user_id) thread_obj.save() # print "\n thread_obj.author_set",thread_obj.author_set if thread_obj._id not in user_ans.prior_node: # add user's post/reply obj to thread obj's post_node node_collection.collection.update({'_id': user_ans._id}, {'$push': {'prior_node':thread_obj._id}},upsert=False,multi=False) if user_ans._id not in thread_obj.post_node: # add thread obj to user's post/reply prior_node node_collection.collection.update({'_id': thread_obj._id}, {'$push': {'post_node':user_ans._id}},upsert=False,multi=False) quiz_type_val = get_attribute_value(node_obj._id,"quiz_type") # print "\n get_attribute_value--", get_attribute_value if user_given_ans and user_ans: if quiz_type_val == "Short-Response": create_gattribute(user_ans._id, qip_user_submitted_ans_AT, user_given_ans) else: curr_datetime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") if user_given_ans: if user_action == "check": if already_ans_obj: old_checked_ans = get_attribute_value(user_ans._id,"quizitempost_user_checked_ans") if old_checked_ans != "None" and old_checked_ans != "": new_list = old_checked_ans new_list.append({str(curr_datetime):user_given_ans}) if new_list: create_gattribute(user_ans._id, qip_user_checked_ans_AT, new_list) elif user_action == "submit": if already_ans_obj: old_submitted_ans = get_attribute_value(user_ans._id,"quizitempost_user_submitted_ans") if old_submitted_ans != "None" and old_submitted_ans != "": new_list = old_submitted_ans new_list.append({str(curr_datetime):user_given_ans}) if new_list: create_gattribute(user_ans._id, qip_user_submitted_ans_AT, new_list) user_ans.reload() # print "\n user_ans.attribute_set",user_ans.attribute_set response_dict['count'] = len(new_list) response_dict['success'] = True return HttpResponse(json.dumps(response_dict)) except Exception as e: print "\n Something went wrong while saving quiz answer!!! ", str(e) return response_dict
def save_quizitem_answer(request, group_id): response_dict = {"success": False} try: if request.is_ajax() and request.method == "POST": try: group_id = ObjectId(group_id) except: group_name, group_id = get_group_name_id(group_id) import datetime # group_obj = node_collection.one({'_id': ObjectId(group_id)}) new_list = [] user_given_ans = request.POST.getlist("user_given_ans[]", '') node_id = request.POST.get("node", '') # print "\n\n user_give_ans",user_given_ans node_obj = node_collection.one({'_id': ObjectId(node_id)}) thread_obj = user_ans = None ''' print "\n\n node_obj::::::::",node_obj.relation_set try: for each_rel in node_obj.relation_set: if each_rel and "has_thread" in each_rel: thread_id = each_rel['has_thread'][0] thread_obj = node_collection.one({'_id': ObjectId(thread_id)}) # print "\n\n thread_obj === ", thread_obj.name , "===" except: pass ''' grel_dict = get_relation_value(node_obj._id, "has_thread", True) is_cursor = grel_dict.get("cursor", False) if not is_cursor: thread_obj = grel_dict.get("grel_node") # print "\n thread_obj: ", thread_obj user_action = request.POST.get("user_action", '') user_id = int(request.user.id) user_name = unicode(request.user.username) qip_gst = node_collection.one({ '_type': 'GSystemType', 'name': 'QuizItemPost' }) qip_user_submitted_ans_AT = node_collection.one({ '_type': "AttributeType", 'name': "quizitempost_user_submitted_ans" }) qip_user_checked_ans_AT = node_collection.one({ '_type': "AttributeType", 'name': "quizitempost_user_checked_ans" }) already_ans_obj = None # print "\n\n thread_obj == ", thread_obj if thread_obj != None: already_ans_obj = node_collection.find_one({ 'member_of': qip_gst._id, 'created_by': user_id, 'prior_node': thread_obj._id }) if already_ans_obj: # check whether user has already checked or submitted ans user_ans = already_ans_obj else: user_ans = node_collection.collection.GSystem() user_ans.created_by = user_id user_ans.modified_by = user_id user_ans.contributors.append(user_id) user_ans.member_of.append(qip_gst._id) user_ans.group_set.append(group_id) if node_obj._id not in user_ans.prior_node: user_ans.prior_node.append(node_obj._id) user_ans.origin = [{ 'thread_id': thread_obj._id, 'prior_node_id_of_thread': node_obj._id }] user_ans.status = u"PUBLISHED" user_ans.name = unicode("Answer_of:" + str(node_obj.name) + "-Answer_by:" + str(user_name)) user_ans.save() # print "\n\n user_ans== ",user_ans if user_id not in thread_obj.author_set: thread_obj.author_set.append(user_id) thread_obj.save() # print "\n thread_obj.author_set",thread_obj.author_set if thread_obj._id not in user_ans.prior_node: # add user's post/reply obj to thread obj's post_node node_collection.collection.update( {'_id': user_ans._id}, {'$push': { 'prior_node': thread_obj._id }}, upsert=False, multi=False) if user_ans._id not in thread_obj.post_node: # add thread obj to user's post/reply prior_node node_collection.collection.update( {'_id': thread_obj._id}, {'$push': { 'post_node': user_ans._id }}, upsert=False, multi=False) quiz_type_val = get_attribute_value(node_obj._id, "quiz_type") # print "\n get_attribute_value--", get_attribute_value if user_given_ans and user_ans: if quiz_type_val == "Short-Response": create_gattribute(user_ans._id, qip_user_submitted_ans_AT, user_given_ans) else: curr_datetime = datetime.datetime.now().strftime( "%Y-%m-%d %H:%M:%S") if user_given_ans: if user_action == "check": if already_ans_obj: old_checked_ans = get_attribute_value( user_ans._id, "quizitempost_user_checked_ans") if old_checked_ans != "None" and old_checked_ans != "": new_list = old_checked_ans new_list.append( {str(curr_datetime): user_given_ans}) if new_list: create_gattribute(user_ans._id, qip_user_checked_ans_AT, new_list) elif user_action == "submit": if already_ans_obj: old_submitted_ans = get_attribute_value( user_ans._id, "quizitempost_user_submitted_ans") if old_submitted_ans != "None" and old_submitted_ans != "": new_list = old_submitted_ans new_list.append( {str(curr_datetime): user_given_ans}) if new_list: create_gattribute( user_ans._id, qip_user_submitted_ans_AT, new_list) user_ans.reload() # print "\n user_ans.attribute_set",user_ans.attribute_set response_dict['count'] = len(new_list) response_dict['success'] = True return HttpResponse(json.dumps(response_dict)) except Exception as e: print "\n Something went wrong while saving quiz answer!!! ", str(e) return response_dict