def update_teaches(file_name, teaches): # print file_name, teaches,"\n" changed = "" file_obj = collection.Node.one({'_type': 'File', 'group_set': ObjectId(group_id) ,'name':unicode(file_name), 'created_by': auth_id}) if file_obj: rel_objs = collection.Triple.find({'_type':'GRelation','subject': ObjectId(file_obj._id), 'relation_type': RT_teaches._id}) if rel_objs.count() > 0: for rel_obj in rel_objs: rel_obj.delete() print "\n Relation ",rel_obj.name," deleted !!!\n" topic = teaches[len(teaches) - 1] topic_obj = collection.Node.find({'name':unicode(topic), 'group_set': ObjectId(group_id),'member_of': topic_GST._id }) if topic_obj.count() > 0: for k in topic_obj: if k.prior_node: for each in k.prior_node: obj = collection.Node.one({'_id': ObjectId(each) }) if obj.name == teaches[len(teaches) - 2]: create_grelation(file_obj._id, RT_teaches, k._id) print "\n Grelation created for ",file_obj.name,"\n"
def upload_prof_pic(request, group_id): if request.method == "POST" : user = request.POST.get('user','') if_module = request.POST.get('if_module','') if if_module == "True": group_id_for_module = request.POST.get('group_id_for_module','') url_name = request.POST.get('url_name','') # used for reverse # print "\n\n url_name", url_name group_obj = node_collection.one({'_id': ObjectId(group_id)}) file_uploaded = request.FILES.get("filehive", "") pic_rt = request.POST.get("pic_rt", "") node_id = request.POST.get("node_id", "") # print "\n\n pic_rt === ", pic_rt has_profile_or_banner_rt = None if pic_rt == "is_banner": has_profile_or_banner_rt = node_collection.one({'_type': 'RelationType', 'name': unicode('has_banner_pic') }) elif pic_rt == "is_profile": has_profile_or_banner_rt = node_collection.one({'_type': 'RelationType', 'name': unicode('has_profile_pic') }) if pic_rt == "is_thumbnail": # print "================================" has_profile_or_banner_rt = node_collection.one({'_type': 'RelationType', 'name': unicode('has_thumbnail') }) choose_from_existing_pic = request.POST.get("old_pic_ele","") warehouse_grp_obj = node_collection.one({'_type': "Group", 'name': "warehouse"}) if file_uploaded: fileobj = write_files(request,group_id) gs_obj_id = fileobj[0]['_id'] # print "\n\n\nfileobj",gs_obj_id if fileobj: profile_pic_image = node_collection.one({'_id': ObjectId(gs_obj_id)}) # The 'if' below is required in case file node is deleted but exists in grid_fs if profile_pic_image and not node_id: gr_node = create_grelation(group_obj._id, has_profile_or_banner_rt, profile_pic_image._id) # Move fileobj to "Warehouse" group node_collection.collection.update({'_id': profile_pic_image._id}, {'$set': {'group_set': [warehouse_grp_obj._id] }}, upsert=False, multi=False) elif node_id: # print "-----------------------------------------------------------------",node_id gr_node = create_grelation(ObjectId(node_id), has_profile_or_banner_rt, profile_pic_image._id) # Move fileobj to "Warehouse" group node_collection.collection.update({'_id': profile_pic_image._id}, {'$set': {'group_set': [warehouse_grp_obj._id] }}, upsert=False, multi=False) else: success_state = False elif choose_from_existing_pic: # update status of old GRelation profile_pic_image = node_collection.one({'_id': ObjectId(choose_from_existing_pic)}) gr_node = create_grelation(group_obj._id,has_profile_or_banner_rt,profile_pic_image._id) # Move fileobj to "Warehouse" group if warehouse_grp_obj._id not in profile_pic_image.group_set: node_collection.collection.update({'_id': profile_pic_image._id}, {'$set': {'group_set': [warehouse_grp_obj._id] }}, upsert=False, multi=False) group_obj.reload() if user: group_id = user if if_module == "True": return HttpResponseRedirect(reverse(str(url_name), kwargs={'group_id': ObjectId(group_id_for_module),'node_id':group_obj._id })) else: return HttpResponseRedirect(reverse(str(url_name), kwargs={'group_id': group_id}))
def attach_resource_thumbnail(thumbnail_url, node_id, resource_data, row_no): updated_res_data = resource_data.copy() updated_res_data['resource_link'] = thumbnail_url updated_res_data['name'] = u'Thumbnail: ' + thumbnail_url.split('/')[-1] # updated_res_data['content_org'] = '' # updated_res_data['tags'] = [] # th_id: thumbnail id th_obj = create_resource_gsystem(updated_res_data, row_no, group_set_id=warehouse_group._id) th_id = th_obj._id # th_obj = node_collection.one({'_id': ObjectId(th_id)}) # # tring to keep mid-size image otherwise thumbnail # try: # th_gridfs_id = th_obj.fs_file_ids[2] # except: # th_gridfs_id = th_obj.fs_file_ids[1] # # print "th_gridfs_id: ", th_gridfs_id # node_obj = node_collection.one({'_id': ObjectId(node_id)}) # print "~~~~~~~~~~", ObjectId(node_id), " : ", has_thumbnail_rt, " : ", ObjectId(th_id) info_message = "\n- Creating GRelation ("+ str(node_id)+ " -- has_thumbnail -- "+ str(th_id)+") ..." log_print(info_message) print '\n Created/Updated GRelation Object:\n' create_grelation(ObjectId(node_id), has_thumbnail_rt, ObjectId(th_id)) print '\n\n' info_message = "\n- Grelation processing done for has_thumbnail.\n" log_print(info_message) # # print "node_obj.fs_file_ids: ", node_obj.fs_file_ids # node_fs_file_ids = node_obj.fs_file_ids # if len(node_fs_file_ids) == 1: th_obj.group_set.append(ObjectId(warehouse_group._id)) if ObjectId(home_group._id) in th_obj.group_set: th_obj.group_set.remove(ObjectId(home_group._id)) # print "**********************************",th_obj.group_set th_obj.save()
def attach_user_icon(username, auth_node): if username and auth_node: icon_file_name = username[:username.rfind('-')] + '.png' file_obj_in_str = open(user_icons_dir_path + icon_file_name) img_file = io.BytesIO(file_obj_in_str.read()) img_file.seek(0) fh_obj = filehive_collection.collection.Filehive() filehive_obj_exists = fh_obj.check_if_file_exists(img_file) file_gs_obj = None if not filehive_obj_exists: file_gs_obj = node_collection.collection.GSystem() file_gs_obj.fill_gstystem_values( request=HttpRequest(), name=unicode(icon_file_name), group_set=[warehouse_grp._id], # language=language, uploaded_file=img_file, created_by=1, member_of=file_gst._id, origin={'script': 'sync_users.py'}, unique_gs_per_file=True) file_gs_obj.save(groupid=warehouse_grp._id) else: file_gs_obj = node_collection.one({ '_type': "GSystem", '$or': [{ 'if_file.original.id': filehive_obj_exists._id }, { 'if_file.mid.id': filehive_obj_exists._id }, { 'if_file.thumbnail.id': filehive_obj_exists._id }] }) # create GRelation 'has_profile_pic' with respective Author nodes if file_gs_obj: gr_node = create_grelation(auth_node._id, has_profile_pic_rt, file_gs_obj._id) print '+ Created new GRelation "has_profile_pic" with file "%s"' % file_gs_obj.name # log_filewrite("\n File : " + str(file_gs_obj.name) + " -- linked -- "+ str(each_auth.name)) else: print "!!! Either User or Author does NOT exist."
def link_login_ac(): """This function links Author GSystem and Respecive Person's Sub-type GSystem. """ users = User.objects.all() has_login_rt = node_collection.one({'_type': "RelationType", 'name': "has_login"}) for each in users: person_node = node_collection.find({'attribute_set.email_id': each.email}) auth_node = node_collection.one({'_type': "Author", 'email': each.email}) if person_node.count() <= 0 or auth_node is None: error_message = "\n Either person_node or auth_node doesn't exists for given email (" + each.email + ") !!!" log_list.append(error_message) continue for pn in person_node: gr_node = create_grelation(pn._id, has_login_rt, auth_node._id) info_message = "\n This GRelation created for " + str(gr_node.name) + "." log_list.append(info_message)
def attach_user_icon(username, auth_node): if username and auth_node: icon_file_name = username[:username.rfind('-')] + '.png' file_obj_in_str = open(user_icons_dir_path + icon_file_name) img_file = io.BytesIO(file_obj_in_str.read()) img_file.seek(0) fh_obj = filehive_collection.collection.Filehive() filehive_obj_exists = fh_obj.check_if_file_exists(img_file) file_gs_obj = None if not filehive_obj_exists: file_gs_obj = node_collection.collection.GSystem() file_gs_obj.fill_gstystem_values( request=HttpRequest(), name=unicode(icon_file_name), group_set=[warehouse_grp._id], # language=language, uploaded_file=img_file, created_by=1, member_of=file_gst._id, origin={'script': 'sync_users.py'}, unique_gs_per_file=True ) file_gs_obj.save(groupid=warehouse_grp._id) else: file_gs_obj = node_collection.one({'_type':"GSystem", '$or': [ {'if_file.original.id':filehive_obj_exists._id}, {'if_file.mid.id':filehive_obj_exists._id}, {'if_file.thumbnail.id':filehive_obj_exists._id} ]}) # create GRelation 'has_profile_pic' with respective Author nodes if file_gs_obj: gr_node = create_grelation(auth_node._id, has_profile_pic_rt, file_gs_obj._id) print '+ Created new GRelation "has_profile_pic" with file "%s"'%file_gs_obj.name # log_filewrite("\n File : " + str(file_gs_obj.name) + " -- linked -- "+ str(each_auth.name)) else: print "!!! Either User or Author does NOT exist."
def save_batch(request, group_id): # def save_batch(batch_name, user_list, group_id, request, ac_id): group_name, group_id = get_group_name_id(group_id) response_dict = {"success": False} # new_batch_node = None rt_has_batch_member = node_collection.one({'_type': 'RelationType', 'name': 'has_batch_member'}) if request.is_ajax() and request.method == "POST": ac_id = request.POST.get("ac_id", '') batch_name = request.POST.get("batch_name", '') batch_id = request.POST.get("batch_id", '') user_list = request.POST.getlist("user_list[]", '') # create_new_batch = request.POST.get("create_new_batch", '') # response_dict["old_batches"] = find_batches_of_ac(ac_id) user_list = [ObjectId(each) for each in user_list] all_batches_in_grp = [] if not batch_id: # b_node = node_collection.one({'member_of':GST_BATCH._id,'name':unicode(batch_name)}) b_node = node_collection.collection.GSystem() b_node.member_of.append(GST_BATCH._id) b_node.created_by = int(request.user.id) b_node.group_set.append(ObjectId(group_id)) b_node.name = batch_name b_node['altnames'] = batch_name.replace('_', ' ') b_node.contributors.append(int(request.user.id)) b_node.modified_by = int(request.user.id) b_node.save(groupid=group_id) all_batches_in_grp.append(b_node._id) rt_group_has_batch = node_collection.one({'_type': 'RelationType', 'name': 'group_has_batch'}) relation_coll = triple_collection.find({'_type': 'GRelation', 'relation_type.$id': rt_group_has_batch._id,'subject':ObjectId(group_id)}) for each in relation_coll: all_batches_in_grp.append(each.right_subject) # to get all batches of the group rt_has_course = node_collection.one({'_type': 'RelationType', 'name': 'has_course'}) create_grelation(ObjectId(group_id), rt_group_has_batch, all_batches_in_grp) create_grelation(b_node._id, rt_has_course, ObjectId(ac_id)) response_dict['new_batch_created'] = True response_dict['new_batch_node_name'] = b_node.name response_dict['new_batch_node_id'] = str(b_node._id) else: response_dict['new_batch_created'] = False b_node = node_collection.one({'_id': ObjectId(batch_id)}) if user_list: create_grelation(b_node._id, rt_has_batch_member, user_list) response_dict['success'] = True return HttpResponse(json.dumps(response_dict, cls=NodeJSONEncoder))
def create_thread_obj(node_id): ''' Creates thread object. RT : has_thread AT : release_response, thread_interaction_type ''' try: node_obj = node_collection.one({'_id': ObjectId(node_id)}) release_response_val = True interaction_type_val = unicode('Comment') thread_obj = None thread_obj = node_collection.one({"_type": "GSystem", "member_of": ObjectId(twist_gst._id),"relation_set.thread_of": ObjectId(node_obj._id)}) if thread_obj == None: # print "\n\n Creating new thread node" thread_obj = node_collection.collection.GSystem() thread_obj.name = u"Thread_of_" + unicode(node_obj.name) thread_obj.status = u"PUBLISHED" thread_obj.created_by = int(nroer_team_id) thread_obj.modified_by = int(nroer_team_id) thread_obj.contributors.append(int(nroer_team_id)) thread_obj.member_of.append(ObjectId(twist_gst._id)) thread_obj.group_set.append(home_group._id) thread_obj.save() # creating GRelation gr = create_grelation(node_obj._id, has_thread_rt, thread_obj._id) create_gattribute(thread_obj._id, rel_resp_at, release_response_val) create_gattribute(thread_obj._id, thr_inter_type_at, interaction_type_val) create_gattribute(node_obj._id, discussion_enable_at, True) thread_obj.reload() node_obj.reload() # print "\n\n thread_obj", thread_obj.attribute_set, "\n---\n" info_message = "\n- Successfully created thread obj - " + thread_obj._id.__str__() +" for - " + node_obj._id.__str__() log_print(info_message) except Exception as e: info_message = "\n- Error occurred while creating thread obj for - " + node_obj._id.__str__() +" - " + str(e) log_print(info_message)
def translate_node(request, group_id, node_id=None): """ translate the node content""" # 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) context_variables = { 'title': gst_page.name, 'group_id': group_id, 'groupid': group_id } if request.method == "POST": get_type = get_resource_type(request, node_id) # get_type can be GSystem/File/Author/Group page_node = eval("node_collection.collection" + "." + get_type)() get_translate_common_fields(request, get_type, page_node, group_id, gst_page, node_id) page_node.save(groupid=group_id) # add triple to the GRelation # then append this ObjectId of GRelation instance in respective subject and object Nodes' relation_set field. relation_type = node_collection.one({ '_type': 'RelationType', 'name': 'translation_of' }) gr_node = create_grelation(ObjectId(node_id), relation_type, page_node._id) # grelation = node_collection.collection.GRelation() # grelation.relation_type=relation_type # grelation.subject=ObjectId(node_id) # grelation.right_subject=page_node._id # grelation.name=u"" # grelation.save() return HttpResponseRedirect( reverse('page_details', kwargs={ 'group_id': group_id, 'app_id': page_node._id })) node = node_collection.one({"_id": ObjectId(node_id)}) fp = history_manager.get_file_path(node) # Retrieve rcs-file for a given version-number rcs.checkout(fp) # Copy content from rcs-version-file data = None with open(fp, 'r') as sf: data = sf.read() # Used json.loads(x) -- to covert string to dictionary object # If want to use key from this converted dictionay, use array notation because dot notation doesn't works! data = json.loads(data) # Remove retrieved rcs-file belonging to the given version-number rcs.checkin(fp) content = data node_details = [] for k, v in content.items(): node_name = content['name'] node_content_org = content['content_org'] node_tags = content['tags'] return render_to_response("ndf/translation_page.html", { 'content': content, 'appId': app._id, 'node': node, 'node_name': node_name, 'groupid': group_id, 'group_id': group_id }, context_instance=RequestContext(request))
def event_create_edit(request, group_id, app_set_id=None, app_set_instance_id=None): """ View for handling Event and it's sub-types create-edit-view """ auth = None try: group_id = ObjectId(group_id) #group_id is a valid ObjectId except: group_name, group_id = get_group_name_id( group_id ) #instead of group_id the name of the object is passed via URL to the function app_set = "" title = "" #Stores the name of the type of event such as Meeting, Inauguration, etc. session_of = "" module = "" Add = "" announced_course = "" batch = "" event_gst = None event_gs = None property_order_list = [] template_prefix = "mis" group_inverse_rel_id = [] Group_type = node_collection.one( {'_id': ObjectId(group_id)} ) #instance of the group object in which the event is created e.g. "home" is a group for i in Group_type.relation_set: if unicode("group_of") in i.keys(): group_inverse_rel_id = i['group_of'] Group_name = node_collection.one({ '_type': 'GSystem', '_id': { '$in': group_inverse_rel_id } }) Eventtype = 'Eventtype' if Group_name: if (any(unicode('has_group') in d for d in Group_name.relation_set)) == True: Eventtype = 'CollegeEvents' else: Eventtype = 'Eventtype' Glisttype = node_collection.find({"_type": "GSystemType", "name": "GList"}) Event_Types = node_collection.one( { "member_of": ObjectId(Glisttype[0]["_id"]), "name": Eventtype }, {'collection_set': 1} ) #Stores the object ids of all the types of events e.g. Meeting, Inauguration, ... app_collection_set = [ ] #stores the id, name and type_of for all event types (Meeting, Inauguration, etc.) as a list if Event_Types: for eachset in Event_Types.collection_set: app_collection_set.append( node_collection.one({"_id": eachset}, { '_id': 1, 'name': 1, 'type_of': 1 })) iteration = request.POST.get("iteration", "") if iteration == "": iteration = 1 for i in range(int(iteration)): if app_set_id: event_gst = node_collection.one( { '_type': "GSystemType", '_id': ObjectId(app_set_id) }, { 'name': 1, 'type_of': 1 } ) #GSystemType Object for the event corresponding to app_set_id e.g. Meeting title = event_gst.name event_gs = node_collection.collection.GSystem( ) #create a new GSystem Object for the Event event_gs.member_of.append( event_gst._id) #event_gs is a member_of event_gst if app_set_instance_id: #app_set_instance_id is the objectid of the event object which is already created event_gs = node_collection.one({ '_type': "GSystem", '_id': ObjectId(app_set_instance_id) }) property_order_list = get_property_order_with_value( event_gs ) #.property_order #stores the properties defining a particular event in a list e.g. name, start_time, attendees, etc.. if request.method == "POST": print "#####################" print request.POST.getlist(u'event_coordinator') print "#####################" # [A] Save event-node's base-field(s) # print "\n Going before....", type(event_gs), "\n event_gs.keys(): ", event_gs.keys() # get_node_common_fields(request, event_gs, group_id, event_gst) # print "\n Going after....", type(event_gs), "\n event_gs.keys(): ", event_gs.keys() # print "\n event_gs: \n", event_gs.keys() # for k, v in event_gs.items(): # print "\n ", k, " -- ", v is_changed = get_node_common_fields(request, event_gs, group_id, event_gst) if is_changed: # Remove this when publish button is setup on interface event_gs.status = u"PUBLISHED" if (request.POST.get("name", "")) == "": if i > 0: field_value = request.POST.get('start_time' + "_" + str(i), '') else: field_value = request.POST.get('start_time', '') # print "----------------Field Value-----------" # print field_value if event_gst.name == "Exam": name = "Exam" + "--" + slugify( request.POST.get("batch_name", "")) + "--" + field_value else: name = "Class" + "--" + slugify( request.POST.get("course_name", "")) + "--" + field_value # print "-----------------Name------------------" # print name event_gs.name = name event_gs.save(is_changed=is_changed, groupid=group_id) # print "\n Event: ", event_gs._id, " -- ", event_gs.name, "\n" # [B] Store AT and/or RT field(s) of given event-node (i.e., event_gs) for tab_details in property_order_list: for field_set in tab_details[1]: print "##########################" print "field_set:" print field_set print "##########################s" # field_set pattern -- {[field_set[0]:node_structure, field_set[1]:field_base/AT/RT_instance{'_id':, 'name':, 'altnames':}, field_set[2]:node_value]} # field_set pattern -- {'_id', 'data_type', 'name', 'altnames', 'value'} # print " ", field_set["name"] # * Fetch only Attribute field(s) / Relation field(s) if field_set.has_key( '_id' ): #Implies field_set is not a basefield but is an AT/RT field_instance = node_collection.one( {'_id': field_set['_id']} ) #field_instance is an instance for AT or RT e.g. start_time field_instance_type = type(field_instance) if field_instance_type in [ AttributeType, RelationType ]: if field_instance["name"] == "attendees": continue field_data_type = field_set[ 'data_type'] #data type of AT/RT e.g. datetime.datetime for start_time # Fetch field's value depending upon AT/RT and Parse fetched-value depending upon that field's data-type if field_instance_type == AttributeType: if "File" in field_instance["validators"]: # Special case: AttributeTypes that require file instance as it's value in which case file document's ObjectId is used if field_instance["name"] in request.FILES: field_value = request.FILES[ field_instance["name"]] else: field_value = "" # Below 0th index is used because that function returns tuple(ObjectId, bool-value) if field_value != '' and field_value != u'': file_name = event_gs.name + " -- " + field_instance[ "altnames"] content_org = "" tags = "" field_value = save_file( field_value, file_name, request.user.id, group_id, content_org, tags, access_policy="PRIVATE", count=0, first_object="", oid=True)[0] if "date_month_day_year" in field_instance[ "validators"]: if i > 0: field_value = request.POST.get( field_instance["name"] + "_" + str(i)) else: field_value = request.POST[ field_instance["name"]] else: # Other AttributeTypes field_value = request.POST[ field_instance["name"]] # field_instance_type = "GAttribute" # print "\n Parsing data for: ", field_instance["name"] if field_instance["name"] in [ "12_passing_year", "degree_passing_year" ]: #, "registration_year"]: field_value = parse_template_data( field_data_type, field_value, date_format_string="%Y") elif field_instance["name"] in [ "dob", "registration_date" ]: field_value = parse_template_data( field_data_type, field_value, date_format_string="%d/%m/%Y") else: field_value = parse_template_data( field_data_type, field_value, date_format_string="%d/%m/%Y %H:%M") if field_value: event_gs_triple_instance = create_gattribute( event_gs._id, node_collection.collection. AttributeType(field_instance), field_value) # print "--------------------------------------------------------------------------------------------------" # print "\n event_gs_triple_instance: ", event_gs_triple_instance._id, " -- ", event_gs_triple_instance.name else: #field_instance_type == RelationType field_value_list = request.POST.getlist( field_instance["name"]) # print "#######################" # print field_value_list # print "#######################" # field_instance_type = "GRelation" #code for creation of relation Session of for i, field_value in enumerate( field_value_list): print "#######" print field_value print "#######" field_value = parse_template_data( ObjectId, field_value, field_instance=field_instance, date_format_string="%d/%m/%Y %H:%M") field_value_list[i] = field_value if field_value_list: event_gs_triple_instance = create_grelation( event_gs._id, node_collection.collection. RelationType(field_instance), field_value_list) # if isinstance(event_gs_triple_instance, list): # print "\n" # for each in event_gs_triple_instance: # print " event_gs_triple_instance: ", each._id, " -- ", each.name # print "\n" # else: # print "\n event_gs_triple_instance: ", event_gs_triple_instance._id, " -- ", event_gs_triple_instance.name #End of for loop on property_order_list # return HttpResponseRedirect(reverse('page_details', kwargs={'group_id': group_id, 'app_id': page_node._id })) '''return HttpResponseRedirect(reverse(app_name.lower()+":"+template_prefix+'_app_detail', kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id}))''' if event_gst.name == u'Classroom Session' or event_gst.name == u'Exam': if i == ((int(iteration)) - 1): #code to send mail to every one return HttpResponseRedirect( reverse('event_app_instance_detail', kwargs={ 'group_id': group_id, "app_set_id": app_set_id, "app_set_instance_id": event_gs._id })) else: to_user_list = [] event_organizer_str = "" event_coordinator_str = "" event_organized_by = [] event_attendees = [] event_coordinator = [] event_node = node_collection.one( {'_id': ObjectId(event_gs._id)}) for i in event_node.relation_set: if unicode('event_organised_by') in i.keys(): event_organized_by = i['event_organised_by'] if unicode('has_attendees') in i.keys(): event_attendees = i['has_attendees'] if unicode('event_coordinator') in i.keys(): event_coordinator = i['event_coordinator'] event_url = "/" + str(group_id) + "/event/" + str( app_set_id) + "/" + str(event_node._id) site = Site.objects.get(pk=1) site = site.name.__str__() event_link = "http://" + site + event_url event_organized_by_cur = node_collection.find( {"_id": { '$in': event_organized_by }}) event_coordinator_cur = node_collection.find( {"_id": { '$in': event_coordinator }}) for i in event_coordinator_cur: event_coordinator_str = event_coordinator_str + i.name + " " for i in event_organized_by_cur: event_organizer_str = event_coordinator_str + i.name + " " for j in event_attendees: auth = node_collection.one({"_id": ObjectId(j)}) user_obj = User.objects.get(id=auth.created_by) if user_obj not in to_user_list: to_user_list.append(user_obj) render_label = render_to_string( "notification/label.html", { "sender": "metaStudio", "activity": "Event Created", "conjunction": "-" }) if event_organized_by: msg_string = "\n Event is organized by " + str( event_organizer_str) else: msg_string = "" print "--------------------------" print event_node.name print event_node._id print "--------------------------" SALT = '8cd8ef52e8e101574e400365b55e11a6' URL = 'http://test-install.blindsidenetworks.com/bigbluebutton/' createMeeting(event_node.name, event_node._id, 'welcome', 'mPW', 'aPW', SALT, URL, 'www.google.com') url = joinURL(event_node._id, 'user', 'mPW', SALT, URL) event_node.url = unicode(url) event_node.save() # url_create = createMeetingURL(event_node.name, event_node._id, 'aPW', 'mPW', 'welcome', 'www.google.com', SALT , URL); print "##########" print event_node.url print "##########" # bbb_start(event_node.name, event_node._id) message_string = "Invitation for Event" + " " + str( event_node.name ) + msg_string + "\n Event will be co-ordinated by " + str( event_coordinator_str ) + "\n- Please click [[" + event_link + "][here]] to view the details of the event" message_string = "Hello World" notification.create_notice_type( render_label, message_string, "notification" ) ##This is sent via email to all attendees in the group notification.send(to_user_list, render_label, {"from_user": "******"}) return HttpResponseRedirect( reverse('event_app_instance_detail', kwargs={ 'group_id': group_id, "app_set_id": app_set_id, "app_set_instance_id": event_node._id })) event_attendees = request.POST.getlist('has_attendees', '') event_gs.get_neighbourhood(event_gs.member_of) course = [] val = False for i in event_gs.relation_set: if unicode('event_has_batch') in i.keys(): batch = node_collection.one({ '_type': "GSystem", '_id': ObjectId(i['event_has_batch'][0]) }) batch_relation = node_collection.one( { '_type': "GSystem", '_id': ObjectId(batch._id) }, {'relation_set': 1}) for i in batch_relation['relation_set']: if unicode('has_course') in i.keys(): announced_course = node_collection.one({ "_type": "GSystem", '_id': ObjectId(i['has_course'][0]) }) for i in announced_course.relation_set: if unicode('announced_for') in i.keys(): course = node_collection.one({ "_type": "GSystem", '_id': ObjectId(i['announced_for'][0]) }) if unicode('session_of') in i.keys(): session_of = node_collection.one({ '_type': "GSystem", '_id': ObjectId(i['session_of'][0]) }) module = node_collection.one({ '_type': "GSystem", '_id': { '$in': session_of.prior_node } }) event_gs.event_coordinator Mis_admin = node_collection.one({"_type": "Group", "name": "MIS_admin"}) if Mis_admin: Mis_admin_list = Mis_admin.group_admin Mis_admin_list.append(Mis_admin.created_by) if request.user.id in Mis_admin_list: Add = "Allow" else: Add = "Stop" else: Add = "Stop" if event_gst.name == u'Classroom Session' or event_gst.name == u'Exam': template = "ndf/Nussd_event_Schedule.html" else: template = "ndf/event_create_edit.html" # default_template = "ndf/"+template_prefix+"_create_edit.html" context_variables = { 'group_id': group_id, 'groupid': group_id, 'app_collection_set': app_collection_set, 'app_set_id': app_set_id, 'title': title, 'property_order_list': property_order_list, 'Add': Add } if app_set_instance_id: event_detail = {} events = {} if event_gs.event_coordinator: event_detail["cordinatorname"] = str( event_gs.event_coordinator[0].name) event_detail["cordinatorid"] = str( event_gs.event_coordinator[0]._id) events["cordinator"] = event_detail if announced_course: event_detail["course"] = str(announced_course.name) event_detail["course_id"] = str(announced_course._id) events["course"] = event_detail event_detail = {} if batch: event_detail["batchname"] = str(batch.name) event_detail["batchid"] = str(batch._id) events["batch"] = event_detail event_detail = {} if session_of: event_detail["sessionname"] = str(session_of.name) event_detail["sessionid"] = str(session_of._id) for i in session_of.attribute_set: if unicode('course_structure_minutes') in i.keys(): event_detail["sessionminutes"] = str( i['course_structure_minutes']) events["session"] = event_detail event_detail = {} if module: event_detail["Modulename"] = str(module.name) event_detail["Moduleid"] = str(module._id) events["Module"] = event_detail context_variables['node'] = event_gs context_variables['edit_details'] = events # print "\n template-list: ", [template, default_template] # template = "ndf/fgh.html" # default_template = "ndf/dsfjhk.html" # return render_to_response([template, default_template], return render_to_response(template, context_variables, context_instance=RequestContext(request))
from gnowsys_ndf.ndf.models import * from gnowsys_ndf.ndf.views.methods import create_grelation twist_gst = node_collection.one({'_type':"GSystemType", 'name': "Twist"}) twist_cur = node_collection.find({'member_of': twist_gst._id, 'relation_set.thread_of':{'$exists': False}}) print "\n Total threads found without thread_of -- ", twist_cur.count() has_thread_rt = node_collection.one({"_type": "RelationType", "name": u"has_thread"}) for eachtw in twist_cur: if eachtw.prior_node: for eachprior_node_id in eachtw.prior_node: prior_node_id = eachprior_node_id prior_node_obj = node_collection.one({'_id': ObjectId(prior_node_id)}) if "Forum" in prior_node_obj.member_of_names_list: gr = create_grelation(prior_node_obj._id, has_thread_rt, eachtw._id) break
def translate(request, group_id, node_id, lang, translated_node_id=None, **kwargs): ''' for EDIT: translate provided node to provided LANG CODE lang could be either proper/full language-name/language-code `node_id` is _id of source node. ''' group_name, group_id = Group.get_group_name_id(group_id) language = get_language_tuple(lang) source_obj = Node.get_node_by_id(node_id) existing_grel = translate_grel = translated_node = None if translated_node_id: translated_node = Node.get_node_by_id(translated_node_id) else: # get translated_node existing_grel = triple_collection.one({ '_type': 'GRelation', 'subject': ObjectId(node_id), 'relation_type': rt_translation_of._id, 'language': language }) if existing_grel: # get existing translated_node translated_node = Node.get_node_by_id(existing_grel.right_subject) translate_grel = existing_grel if request.method == 'GET': return render_to_response("ndf/translate_form.html", { 'group_id': group_id, 'node_obj': translated_node, 'source_obj': source_obj, 'post_url': reverse('translate', kwargs={ 'group_id': group_id, 'node_id': node_id, 'lang': lang, }) }, context_instance=RequestContext(request)) elif request.method == 'POST': # explicit `if` check for `POST` if not translated_node: # create a new translated new # translated_node = node_collection.collection.GSystem() # copy source_obj's data into a new if source_obj._type == "Group": translated_node = node_collection.collection.GSystem() exclude_fields = ['_id','member_of','_type','type_of','modified_by','prior_node','post_node'] for each in translated_node: if each not in exclude_fields: translated_node[each] = source_obj[each] translated_node.group_set.append(source_obj._id) else: translated_node = source_obj.__deepcopy__() translated_node['_id'] = ObjectId() translated_node.fill_gstystem_values(request=request, language=language, **kwargs) trans_alt_name = request.POST.get('altnames', None) translated_node.altnames = unicode(trans_alt_name) translated_node.member_of = [ObjectId(trans_node_gst_id)] translated_node.save(group_id=group_id) if not existing_grel: trans_grel_list = [ObjectId(translated_node._id)] trans_grels = triple_collection.find({'_type': 'GRelation', \ 'relation_type': rt_translation_of._id,'subject': ObjectId(node_id)},{'_id': 0, 'right_subject': 1}) for each_rel in trans_grels: trans_grel_list.append(each_rel['right_subject']) translate_grel = create_grelation(node_id, rt_translation_of, trans_grel_list, language=language) # page_gst_name, page_gst_id = Node.get_name_id_from_type('Page', 'GSystemType') # return HttpResponseRedirect(reverse('page_details', kwargs={'group_id': group_id, 'app_id': page_gst_id })) # return HttpResponseRedirect(reverse('all_translations', kwargs={'group_id': group_id, 'node_id': node_id })) return HttpResponseRedirect(reverse('show_translation', kwargs={'group_id': group_id, 'node_id': node_id, 'lang': lang }))
def parse_data_create_gsystem(json_file_path, file_name): json_file_content = "" try: print "\n file_name == ",file_name with open(json_file_path) as json_file: json_file_content = json_file.read() json_documents_list = json.loads(json_file_content) # Process data in proper format node = node_collection.collection.GSystem() node_keys = node.keys() node_structure = node.structure json_documents_list_spaces = json_documents_list json_documents_list = [] # Removes leading and trailing spaces from keys as well as values for json_document_spaces in json_documents_list_spaces: json_document = {} for key_spaces, value_spaces in json_document_spaces.iteritems(): json_document[key_spaces.strip().lower()] = value_spaces.strip() json_documents_list.append(json_document) except Exception as e: error_message = "\n While parsing the file ("+json_file_path+") got following error...\n " + str(e) log_list.append(error_message) print error_message raise error_message for i, json_document in enumerate(json_documents_list): try: global node_repeated node_repeated = False info_message = "\n ============ #"+ str(i+1) +" : Start of "+gsystem_type_name+"'s GSystem ("+json_document['name']+") creation/updation ============\n" log_list.append(info_message) parsed_json_document = {} attribute_relation_list = [] for key in json_document.iterkeys(): # print "\n key ",key parsed_key = key.lower() parsed_key = parsed_key.replace(" ", "_") if parsed_key in node_keys: if node_structure[parsed_key] == unicode: parsed_json_document[parsed_key] = unicode(json_document[key]) elif node_structure[parsed_key] == datetime.datetime: parsed_json_document[parsed_key] = datetime.datetime.strptime(json_document[key], "%d/%m/%Y") else: parsed_json_document[parsed_key] = json_document[key] else: parsed_json_document[key] = json_document[key] attribute_relation_list.append(key) print "\nparsed_json_document: ", parsed_json_document info_message = "\n Creating "+gsystem_type_name+" ("+parsed_json_document["name"]+")..." log_list.append(info_message) print "\n HERE == " node = create_edit_gsystem(gsystem_type_id, gsystem_type_name, parsed_json_document, user_id) #print "\n node created === ", node._id, " === ", node.name, node.altnames # print "attribute_relation_list == ",attribute_relation_list #print node if node: if not attribute_relation_list: # Neither possible attribute fields, nor possible relations defined for this node info_message = "\n "+gsystem_type_name+" ("+node.name+"): Neither possible attribute fields, nor possible relations defined for this node !\n" log_list.append(info_message) continue #print "bfr possible attrbs" gst_possible_attributes_dict = node.get_possible_attributes(gsystem_type_id) print "\n gsystem_type_id ===",gst_possible_attributes_dict relation_list = [] json_document['name'] = node.name # Write code for setting atrributes for key in attribute_relation_list: is_relation = True for attr_key, attr_value in gst_possible_attributes_dict.iteritems(): #print "\n\n attr_key === ", attr_key #print "\n\n altnames -- === ", attr_value['altnames'] if attr_value['altnames'] and key == attr_value['altnames'].lower() or key == attr_key.lower(): is_relation = False if json_document[key]: try: if attr_value['data_type'] == basestring: if u"\u2013" in json_document[key]: json_document[key] = json_document[key].replace(u"\u2013", "-") info_message = "\n For GAttribute parsing content | key: " + attr_key + " -- " + json_document[key] log_list.append(info_message) if attr_value['data_type'] == unicode: print unicode(json_document[key]) json_document[key] = unicode(json_document[key]) elif attr_value['data_type'] == bool: if json_document[key].lower() == "yes": json_document[key] = True elif json_document[key].lower() == "no": json_document[key] = False else: json_document[key] = None elif attr_value['data_type'] == datetime.datetime: # Use small-case altnames if key in ["dob", "date of birth", "date of registration"]: if json_document[key]: json_document[key] = datetime.datetime.strptime(json_document[key], "%d/%m/%Y") else: if json_document[key]: json_document[key] = datetime.datetime.strptime(json_document[key], "%Y") elif attr_value['data_type'] in [int, float, long]: if not json_document[key]: json_document[key] = 0 else: if attr_value['data_type'] == int: json_document[key] = int(json_document[key]) elif attr_value['data_type'] == float: json_document[key] = float(json_document[key]) else: json_document[key] = long(json_document[key]) elif type(attr_value['data_type']) == IS: for op in attr_value['data_type']._operands: if op.lower() == json_document[key].lower(): json_document[key] = op elif (attr_value['data_type'] in [list, dict]) or (type(attr_value['data_type']) in [list, dict]): if "," not in json_document[key]: # Necessary to inform perform_eval_type() that handle this value as list json_document[key] = "\"" + json_document[key] + "\", " else: formatted_value = "" for v in json_document[key].split(","): formatted_value += "\""+v.strip(" ")+"\", " json_document[key] = formatted_value perform_eval_type(key, json_document, "GSystem") subject_id = node._id attribute_type_node = None if attr_key in attr_type_dict: attribute_type_node = attr_type_dict[attr_key] else: attribute_type_node = node_collection.one({ '_type': "AttributeType", '$or': [{ 'name': {'$regex': "^" + attr_key + "$", '$options': 'i'} }, { 'altnames': {'$regex': "^" + attr_key + "$", '$options': 'i'} }] }) attr_type_dict[attr_key] = attribute_type_node object_value = json_document[key] ga_node = None info_message = "\n Creating GAttribute (" + node.name + " -- " + attribute_type_node.name + " -- " + str(json_document[key]) + ") ...\n" log_list.append(info_message) ga_node = create_gattribute(subject_id, attribute_type_node, object_value) except Exception as e: error_message = "\n While creating GAttribute (" + attr_key + ") for "+gsystem_type_name+"'s GSystem ("+json_document['name']+") got following error...\n " + str(e) + "\n" log_list.append(error_message) print error_message # Keep it! # To break outer for loop as key found break else: error_message = "\n DataNotFound: No data found for field ("+attr_key+") while creating GSystem (" + gsystem_type_name + " -- " + node.name + ") !!!\n" log_list.append(error_message) if is_relation: relation_list.append(key) if not relation_list: # No possible relations defined for this node info_message = "\n "+gsystem_type_name+" ("+node.name+"): No possible relations defined for this node !!!\n" log_list.append(info_message) else: gst_possible_relations_dict = node.get_possible_relations(gsystem_type_id) # Write code for setting relations for key in relation_list: is_relation = True for rel_key, rel_value in gst_possible_relations_dict.iteritems(): if key == rel_value['altnames'].lower() or key == rel_key.lower(): is_relation = False if json_document[key]: # Here semi-colon(';') is used instead of comma(',') # Beacuse one of the value may contain comma(',') which causes problem in finding required value in database try: if ";" not in json_document[key]: # Necessary to inform perform_eval_type() that handle this value as list json_document[key] = "\""+json_document[key]+"\", " else: formatted_value = "" for v in json_document[key].split(";"): formatted_value += "\""+v.strip(" ")+"\", " json_document[key] = formatted_value info_message = "\n For GRelation parsing content | key: " + rel_key + " -- " + json_document[key] log_list.append(info_message) perform_eval_type(key, json_document, "GSystem", "GSystem") # for right_subject_id in json_document[key]: subject_id = node._id # Here we are appending list of ObjectIds of GSystemType's type_of field # along with the ObjectId of GSystemType's itself (whose GSystem is getting created) # This is because some of the RelationType's are holding Base class's ObjectId # and not that of the Derived one's # Delibrately keeping GSystemType's ObjectId first in the list # And hence, used $in operator in the query! rel_subject_type = [] rel_subject_type.append(gsystem_type_id) if gsystem_type_node.type_of: rel_subject_type.extend(gsystem_type_node.type_of) relation_type_node = None if rel_key in rel_type_dict: relation_type_node = rel_type_dict[rel_key] else: relation_type_node = node_collection.one({ '_type': "RelationType", '$or': [{ 'name': {'$regex': "^" + rel_key + "$", '$options': 'i'} }, { 'altnames': {'$regex': "^" + rel_key + "$", '$options': 'i'} }], 'subject_type': {'$in': rel_subject_type} }) rel_type_dict[rel_key] = relation_type_node info_message = "\n Creating GRelation ("+node.name+" -- "+rel_key+" -- "+str(json_document[key])+") ...\n" log_list.append(info_message) gr_node = create_grelation(subject_id, relation_type_node, json_document_spaces[key]) except Exception as e: error_message = "\n While creating GRelation (" + rel_key + ") for "+gsystem_type_name+"'s GSystem ("+json_document['name']+") got following error...\n" + str(e) + "\n" log_list.append(error_message) pass if college_gst._id in relation_type_node.object_type: # Fetch college node's group id # Append it to node's group_set node_group_set = node.group_set is_group_set_changed = False # Iterate through each college # Find it's corresponding group's ObjectId # Append it to node's group_set for each in json_document[key]: each = ObjectId(each) each_str = str(each) # Update node's group_set with updated list # if changed if is_group_set_changed: node_collection.collection.update({ "_id": subject_id }, { "$set": {"group_set": node_group_set} }, upsert=False, multi=False ) # To break outer for loop if key found break else: error_message = "\n DataNotFound: No data found for relation ("+rel_key+") while creating GSystem ("+gsystem_type_name+" -- "+node.name+") !!!\n" log_list.append(error_message) # print error_message break except Exception as e: error_message = "\n While creating "+gsystem_type_name+"'s GSystem ("+json_document['name']+") got following error...\n " + str(e) log_list.append(error_message) print error_message # Keep it! import sys print "\n ****\n" print 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno)
def create_thread(request, group_id, forum_id): ''' Method to create thread ''' forum = node_collection.one({'_id': ObjectId(forum_id)}) # forum_data = { # 'name':forum.name, # 'content':forum.content, # 'created_by':User.objects.get(id=forum.created_by).username # } # print forum_data forum_threads = [] exstng_reply = node_collection.find({'$and':[{'_type':'GSystem'},{'prior_node':ObjectId(forum._id)}],'status':{'$nin':['HIDDEN']}}) exstng_reply.sort('created_at') for each in exstng_reply: forum_threads.append((each.name).strip().lower()) if request.method == "POST": colg = node_collection.one({'_id':ObjectId(group_id)}) name = unicode(request.POST.get('thread_name',"")) content_org = request.POST.get('content_org',"") # ------------------- colrep = node_collection.collection.GSystem() colrep.member_of.append(twist_gst._id) # ADDED ON 14th July colrep.access_policy = u"PUBLIC" colrep.url = set_all_urls(colrep.member_of) colrep.prior_node.append(forum._id) colrep.name = name if content_org: colrep.content_org = unicode(content_org) # Required to link temporary files with the current user who is modifying this document usrname = request.user.username filename = slugify(name) + "-" + usrname + "-" colrep.content = content_org usrid = int(request.user.id) colrep.created_by = usrid colrep.modified_by = usrid if usrid not in colrep.contributors: colrep.contributors.append(usrid) colrep.group_set.append(colg._id) colrep.save(groupid=group_id) has_thread_rt = node_collection.one({"_type": "RelationType", "name": u"has_thread"}) gr = create_grelation(forum._id, has_thread_rt, colrep._id) '''Code to send notification to all members of the group except those whose notification preference is turned OFF''' link="http://"+sitename+"/"+str(colg._id)+"/forum/thread/"+str(colrep._id) for each in colg.author_set: bx=User.objects.filter(id=each) if bx: bx=User.objects.get(id=each) else: continue activity="Added thread" msg=request.user.username+" has added a thread in the forum " + forum.name + " in the group -'" + colg.name+"'\n"+"Please visit "+link+" to see the thread." if bx: auth = node_collection.one({'_type': 'Author', 'name': unicode(bx.username) }) if colg._id and auth: no_check=forum_notification_status(colg._id,auth._id) else: no_check=True if no_check: ret = set_notif_val(request,colg._id,msg,activity,bx) url_name = "/" + group_id + "/forum/thread/" + str(colrep._id) return HttpResponseRedirect(url_name) # variables = RequestContext(request, # { 'forum':forum, # 'thread':colrep, # 'eachrep':colrep, # 'groupid':group_id, # 'group_id':group_id, # 'user': request.user, # 'reply_count':0, # 'forum_threads': json.dumps(forum_threads), # 'forum_created_by':User.objects.get(id=forum.created_by).username # }) # print "\n\n renedering to thread_details" # return render_to_response("ndf/thread_details.html",variables) else: return render_to_response("ndf/create_thread.html", { 'group_id':group_id, 'groupid':group_id, 'forum': forum, 'forum_threads': json.dumps(forum_threads), 'forum_created_by':User.objects.get(id=forum.created_by).username }, RequestContext(request))
def lesson_create_edit(request, group_id, unit_group_id=None): ''' creation as well as edit of lessons returns following: { 'success': <BOOL: 0 or 1>, 'unit_hierarchy': <unit hierarchy json>, 'msg': <error msg or objectid of newly created obj> } ''' # parent_group_name, parent_group_id = Group.get_group_name_id(group_id) # parent unit id lesson_id = request.POST.get('lesson_id', None) lesson_language = request.POST.get('sel_lesson_lang','') unit_id_post = request.POST.get('unit_id', '') lesson_content = request.POST.get('lesson_desc', '') # print "lesson_id: ", lesson_id # print "lesson_language: ", lesson_language # print "unit_id_post: ", unit_id_post unit_group_id = unit_id_post if unit_id_post else unit_group_id # getting parent unit object unit_group_obj = Group.get_group_name_id(unit_group_id, get_obj=True) result_dict = {'success': 0, 'unit_hierarchy': [], 'msg': ''} if request.method == "POST": # lesson name lesson_name = request.POST.get('name', '').strip() if not lesson_name: msg = 'Name can not be empty.' result_dict = {'success': 0, 'unit_hierarchy': [], 'msg': msg} # return HttpResponse(0) # check for uniqueness of name # unit_cs: unit collection_set unit_cs_list = unit_group_obj.collection_set unit_cs_objs_cur = Node.get_nodes_by_ids_list(unit_cs_list) if unit_cs_objs_cur: unit_cs_names_list = [u.name for u in unit_cs_objs_cur] if not lesson_id and unit_cs_objs_cur and lesson_name in unit_cs_names_list: # same name activity # currently following logic was only for "en" nodes. # commented and expecting following in future: # check for uniqueness w.r.t language selected within all sibling lessons's translated nodes # lesson_obj = Node.get_node_by_id(lesson_id) # if lesson_language != lesson_obj.language[0]: # if lesson_language: # language = get_language_tuple(lesson_language) # lesson_obj.language = language # lesson_obj.save() msg = u'Activity with same name exists in lesson: ' + unit_group_obj.name result_dict = {'success': 0, 'unit_hierarchy': [], 'msg': msg} elif lesson_id and ObjectId.is_valid(lesson_id): # Update # getting default, "en" node: if lesson_language != "en": node = translated_node_id = None grel_node = triple_collection.one({ '_type': 'GRelation', 'subject': ObjectId(lesson_id), 'relation_type': rt_translation_of._id, 'language': get_language_tuple(lesson_language), # 'status': 'PUBLISHED' }) if grel_node: # grelation found. # transalated node exists. # edit of existing translated node. # node = Node.get_node_by_id(grel_node.right_subject) # translated_node_id = node._id lesson_id = grel_node.right_subject else: # grelation NOT found. # create transalated node. user_id = request.user.id new_lesson_obj = node_collection.collection.GSystem() new_lesson_obj.fill_gstystem_values(name=lesson_name, content=lesson_content, member_of=gst_lesson_id, group_set=unit_group_obj._id, created_by=user_id, status=u'PUBLISHED') # print new_lesson_obj if lesson_language: language = get_language_tuple(lesson_language) new_lesson_obj.language = language new_lesson_obj.save(groupid=group_id) trans_grel_list = [ObjectId(new_lesson_obj._id)] trans_grels = triple_collection.find({'_type': 'GRelation', \ 'relation_type': rt_translation_of._id,'subject': ObjectId(lesson_id)},{'_id': 0, 'right_subject': 1}) for each_rel in trans_grels: trans_grel_list.append(each_rel['right_subject']) # translate_grel = create_grelation(node_id, rt_translation_of, trans_grel_list, language=language) create_grelation(lesson_id, rt_translation_of, trans_grel_list, language=language) lesson_obj = Node.get_node_by_id(lesson_id) if lesson_obj and (lesson_obj.name != lesson_name): trans_lesson = get_lang_node(lesson_obj._id,lesson_language) if trans_lesson: trans_lesson.name = lesson_name else: lesson_obj.name = lesson_name # if lesson_language: # language = get_language_tuple(lesson_language) # lesson_obj.language = language lesson_obj.save(group_id=group_id) unit_structure = get_unit_hierarchy(unit_group_obj, request.LANGUAGE_CODE) msg = u'Lesson name updated.' result_dict = {'success': 1, 'unit_hierarchy': unit_structure, 'msg': str(lesson_obj._id)} else: unit_structure = get_unit_hierarchy(unit_group_obj, request.LANGUAGE_CODE) msg = u'Nothing to update.' result_dict = {'success': 1, 'unit_hierarchy': unit_structure, 'msg': msg} else: # creating a fresh lesson object user_id = request.user.id new_lesson_obj = node_collection.collection.GSystem() new_lesson_obj.fill_gstystem_values(name=lesson_name, content=lesson_content, member_of=gst_lesson_id, group_set=unit_group_obj._id, created_by=user_id, status=u'PUBLISHED') # print new_lesson_obj if lesson_language: language = get_language_tuple(lesson_language) new_lesson_obj.language = language new_lesson_obj.save(groupid=group_id) unit_group_obj.collection_set.append(new_lesson_obj._id) unit_group_obj.save(groupid=group_id) unit_structure = get_unit_hierarchy(unit_group_obj, request.LANGUAGE_CODE) msg = u'Added lesson under lesson: ' + unit_group_obj.name result_dict = {'success': 1, 'unit_hierarchy': unit_structure, 'msg': str(new_lesson_obj._id)} # return HttpResponse(json.dumps(unit_structure)) # return HttpResponse(1) return HttpResponse(json.dumps(result_dict))
asset_content_obj = node_collection.collection.GSystem() asset_content_obj.fill_gstystem_values(request=request, uploaded_file=files[0], **kwargs) asset_content_obj.fill_node_values(**kwargs) asset_content_obj.save(groupid=group_id) asset_contents_list = [asset_content_obj._id] rt_has_asset_content = node_collection.one({'_type': 'RelationType', 'name': 'has_assetcontent'}) asset_grels = triple_collection.find({'_type': 'GRelation', \ 'relation_type': rt_has_asset_content._id,'subject': asset_obj._id}, {'_id': 0, 'right_subject': 1}) for each_asset in asset_grels: asset_contents_list.append(each_asset['right_subject']) create_grelation(asset_obj._id, rt_has_asset_content, asset_contents_list) 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) # counter_obj = Counter.get_counter_obj(request.user.id, group_id) for each_counter_obj in counter_objs_cur: each_counter_obj['file']['created'] += 1 each_counter_obj['group_points'] += GSTUDIO_FILE_UPLOAD_POINTS each_counter_obj.last_update = datetime.datetime.now() each_counter_obj.save() return asset_content_obj
def parse_data_create_gsystem(json_file_path): json_file_content = "" try: with open(json_file_path) as json_file: json_file_content = json_file.read() json_documents_list = json.loads(json_file_content) # Initiating empty node obj and other related data variables node = node_collection.collection.GSystem() node_keys = node.keys() node_structure = node.structure # print "\n\n---------------", node_keys json_documents_list_spaces = json_documents_list json_documents_list = [] # Removes leading and trailing spaces from keys as well as values for json_document_spaces in json_documents_list_spaces: json_document = {} for key_spaces, value_spaces in json_document_spaces.iteritems(): json_document[key_spaces.strip().lower()] = value_spaces.strip() json_documents_list.append(json_document) except Exception as e: error_message = "\n!! While parsing the file ("+json_file_path+") got following error...\n " + str(e) log_print(error_message) raise error_message for i, json_document in enumerate(json_documents_list): info_message = "\n\n\n********** Processing row number : ["+ str(i + 2) + "] **********" log_print(info_message) try: parsed_json_document = {} attribute_relation_list = [] for key in json_document.iterkeys(): parsed_key = key.lower() if parsed_key in node_keys: # print parsed_key # adding the default field values e.g: created_by, member_of # created_by: if parsed_key == "created_by": if json_document[key]: temp_user_id = get_user_id(json_document[key].strip()) if temp_user_id: parsed_json_document[parsed_key] = temp_user_id else: parsed_json_document[parsed_key] = nroer_team_id else: parsed_json_document[parsed_key] = nroer_team_id # print "---", parsed_json_document[parsed_key] # contributors: elif parsed_key == "contributors": if json_document[key]: contrib_list = json_document[key].split(",") temp_contributors = [] for each_user in contrib_list: user_id = get_user_id(each_user.strip()) if user_id: temp_contributors.append(user_id) parsed_json_document[parsed_key] = temp_contributors else: parsed_json_document[parsed_key] = [nroer_team_id] # print "===", parsed_json_document[parsed_key] # tags: elif (parsed_key == "tags") and json_document[key]: parsed_json_document[parsed_key] = cast_to_data_type(json_document[key], node_structure.get(parsed_key)) # print parsed_json_document[parsed_key] # member_of: elif parsed_key == "member_of": parsed_json_document[parsed_key] = [file_gst._id] # print parsed_json_document[parsed_key] # --- END of adding the default field values else: # parsed_json_document[parsed_key] = json_document[key] parsed_json_document[parsed_key] = cast_to_data_type(json_document[key], node_structure.get(parsed_key)) # print parsed_json_document[parsed_key] # --- END of processing for remaining fields else: # key is not in the node_keys parsed_json_document[key] = json_document[key] attribute_relation_list.append(key) # print "key : ", key # --END of for loop --- # calling method to create File GSystems node_obj = create_resource_gsystem(parsed_json_document, i) nodeid = node_obj._id if node_obj else None # print "nodeid : ", nodeid # ----- for updating language ----- # node_lang = get_language_tuple(eval(parsed_json_document['language'])) # print "============= :", node_lang # print "============= lang :", node_obj.language # if node_obj and node_obj.language != node_lang: # update_res = node_collection.collection.update( # {'_id': ObjectId(nodeid), 'language': {'$ne': node_lang}}, # {'$set': {'language': node_lang}}, # upsert=False, # multi=False # ) # if update_res['updatedExisting']: # node_obj.reload() # info_message = "\n\n- Update to language of resource: " + str(update_res) # log_print(info_message) # info_message = "\n\n- Now language of resource updates to: " + str(node_obj.language) # log_print(info_message) # print "============= lang :", node_obj.language # ----- END of updating language ----- collection_name = parsed_json_document.get('collection', '') if collection_name and nodeid: collection_node = node_collection.find_one({ # '_type': 'File', 'member_of': {'$in': [file_gst._id]}, 'group_set': {'$in': [home_group._id]}, 'name': unicode(collection_name) }) if collection_node: add_to_collection_set(collection_node, nodeid) thumbnail_url = parsed_json_document.get('thumbnail') # print "thumbnail_url : ", thumbnail_url if (thumbnail_url and nodeid) and (thumbnail_url != parsed_json_document.get('thumbnail') ): try: info_message = "\n\n- Attaching thumbnail to resource\n" log_print(info_message) attach_resource_thumbnail(thumbnail_url, nodeid, parsed_json_document, i) except Exception, e: print e # print type(nodeid), "-------", nodeid, "\n" if (thumbnail_url == parsed_json_document.get('resource_link')) and (warehouse_group._id in node_obj.group_set) : for i,each_groupid in enumerate(node_obj.group_set): if each_groupid == warehouse_group._id: node_obj.group_set.pop(i) if home_group._id not in node_obj.group_set: node_obj.group_set.append(home_group._id) node_obj.save() # create thread node if isinstance(nodeid, ObjectId): thread_result = create_thread_obj(nodeid) # starting processing for the attributes and relations saving if isinstance(nodeid, ObjectId) and attribute_relation_list: node = node_collection.one({ "_id": ObjectId(nodeid) }) gst_possible_attributes_dict = node.get_possible_attributes(file_gst._id) # print gst_possible_attributes_dict relation_list = [] json_document['name'] = node.name # Write code for setting atrributes for key in attribute_relation_list: is_relation = True # print "\n", key, "----------\n" for attr_key, attr_value in gst_possible_attributes_dict.iteritems(): # print "\n", attr_key,"======", attr_value if key == attr_key: # print key is_relation = False # setting value to "0" for int, float, long (to avoid casting error) # if (attr_value['data_type'] in [int, float, long]) and (not json_document[key]): # json_document[key] = 0 if json_document[key]: # print "key : ", key, "\nvalue : ",json_document[key] info_message = "\n- For GAttribute parsing content | key: '" + attr_key + "' having value: '" + json_document[key] + "'" log_print(info_message) cast_to_data_type(json_document[key], attr_value['data_type']) if attr_value['data_type'] == "curricular": # setting int values for CR/XCR if json_document[key] == "CR": json_document[key] = 1 elif json_document[key] == "XCR": json_document[key] = 0 else: # needs to be confirm json_document[key] = 0 # json_document[key] = bool(int(json_document[key])) # print attr_value['data_type'], "@@@@@@@@@ : ", json_document[key] json_document[key] = cast_to_data_type(json_document[key], attr_value['data_type']) # print key, " !!!!!!!!! : ", json_document[key] subject_id = node._id # print "\n-----\nsubject_id: ", subject_id attribute_type_node = node_collection.one({ '_type': "AttributeType", '$or': [ {'name': {'$regex': "^"+attr_key+"$", '$options': 'i'} }, {'altnames': {'$regex': "^"+attr_key+"$", '$options': 'i'} } ] }) # print "\nattribute_type_node: ", attribute_type_node.name object_value = json_document[key] # print "\nobject_value: ", object_value ga_node = None info_message = "\n- Creating GAttribute ("+node.name+" -- "+attribute_type_node.name+" -- "+str(json_document[key])+") ...\n" log_print(info_message) ga_node = create_gattribute(subject_id, attribute_type_node, object_value) info_message = "- Created ga_node : "+ str(ga_node.name) + "\n" log_print(info_message) # To break outer for loop as key found break else: error_message = "\n!! DataNotFound: No data found for field ("+str(attr_key)+") while creating GSystem ( -- "+str(node.name)+")\n" log_print(error_message) # ---END of if (key == attr_key) if is_relation: relation_list.append(key) if not relation_list: # No possible relations defined for this node info_message = "\n!! ("+str(node.name)+"): No possible relations defined for this node.\n" log_print(info_message) return gst_possible_relations_dict = node.get_possible_relations(file_gst._id) # processing each entry in relation_list # print "=== relation_list : ", relation_list for key in relation_list: is_relation = True for rel_key, rel_value in gst_possible_relations_dict.iteritems(): if key == rel_key: # if key == "teaches": is_relation = False if json_document[key]: # most often the data is hierarchy sep by ":" if ":" in json_document[key]: formatted_list = [] temp_teaches_list = json_document[key].replace("\n", "").split(":") # print "\n temp_teaches", temp_teaches for v in temp_teaches_list: formatted_list.append(v.strip()) right_subject_id = [] # print "~~~~~~~~~~~", formatted_list # rsub_id = _get_id_from_hierarchy(formatted_list) rsub_id = get_id_from_hierarchy(formatted_list) # print "=== rsub_id : ", rsub_id hierarchy_output = None # checking every item in hierarchy exist and leaf node's _id found if rsub_id: right_subject_id.append(rsub_id) json_document[key] = right_subject_id # print json_document[key] else: error_message = "\n!! While creating teaches rel: Any one of the item in hierarchy"+ str(json_document[key]) +"does not exist in Db. \n!! So relation: " + str(key) + " cannot be created.\n" log_print(error_message) break # sometimes direct leaf-node may be present without hierarchy and ":" else: formatted_list = list(json_document[key].strip()) right_subject_id = [] right_subject_id.append(_get_id_from_hierarchy(formatted_list)) json_document[key] = right_subject_id # print "\n----------", json_document[key] info_message = "\n- For GRelation parsing content | key: " + str(rel_key) + " -- " + str(json_document[key]) log_print(info_message) # print list(json_document[key]) # perform_eval_type(key, json_document, "GSystem", "GSystem") for right_subject_id in json_document[key]: # print "\njson_document[key]: ", json_document[key] subject_id = node._id # print "subject_id : ", subject_id # print "node.name: ", node.name # Here we are appending list of ObjectIds of GSystemType's type_of field # along with the ObjectId of GSystemType's itself (whose GSystem is getting created) # This is because some of the RelationType's are holding Base class's ObjectId # and not that of the Derived one's # Delibrately keeping GSystemType's ObjectId first in the list # And hence, used $in operator in the query! rel_subject_type = [] rel_subject_type.append(file_gst._id) if file_gst.type_of: rel_subject_type.extend(file_gst.type_of) relation_type_node = node_collection.one({'_type': "RelationType", '$or': [{'name': {'$regex': "^"+rel_key+"$", '$options': 'i'}}, {'altnames': {'$regex': "^"+rel_key+"$", '$options': 'i'}}], 'subject_type': {'$in': rel_subject_type} }) right_subject_id_or_list = [] right_subject_id_or_list.append(ObjectId(right_subject_id)) nodes = triple_collection.find({'_type': "GRelation", 'subject': subject_id, 'relation_type': relation_type_node._id }) # sending list of all the possible right subject to relation for n in nodes: if not n.right_subject in right_subject_id_or_list: right_subject_id_or_list.append(n.right_subject) info_message = "\n- Creating GRelation ("+ str(node.name)+ " -- "+ str(rel_key)+ " -- "+ str(right_subject_id_or_list)+") ..." log_print(info_message) gr_node = create_grelation(subject_id, relation_type_node, right_subject_id_or_list) info_message = "\n- Grelation processing done.\n" log_print(info_message) # To break outer for loop if key found break else: error_message = "\n!! DataNotFound: No data found for relation ("+ str(rel_key)+ ") while creating GSystem (" + str(file_gst.name) + " -- " + str(node.name) + ")\n" log_print(error_message) break # print relation_list else: info_message = "\n!! Either resource is already created or file is already saved into filehive/DB or file not found" log_print(info_message) continue except Exception as e: error_message = "\n While creating ("+str(json_document['name'])+") got following error...\n " + str(e) print "!!!!!!!!!!!!EEEEEEEERRRRRRRRRRRRRROOOOOOORRRRRRRRRRRRR......................" # file_error_msg = "\nFile with following details got an error: \n" file_error_msg = "\n========================" + " Row No : " + str(i + 2) + " ========================\n" # file_error_msg += "- Row No : " + str(i + 2) + "\n" file_error_msg += "- Name : " + json_document["name"] + "\n" file_error_msg += "- File Name: " + json_document["file_name"] + "\n" file_error_msg += "- ERROR : " + str(e) + "\n\n" file_error_msg += "- Following are the row details : \n\n" + unicode(json.dumps(json_document, sort_keys=True, indent=4, ensure_ascii=False)) + "\n" file_error_msg += "============================================================\n\n\n" log_error_rows.append(file_error_msg) log_print(error_message)
uploaded_file=files[0], **kwargs) asset_content_obj.fill_node_values(**kwargs) asset_content_obj.save(groupid=group_id) asset_contents_list = [asset_content_obj._id] rt_has_asset_content = node_collection.one({ '_type': 'RelationType', 'name': 'has_assetcontent' }) asset_grels = triple_collection.find({'_type': 'GRelation', \ 'relation_type': rt_has_asset_content._id,'subject': asset_obj._id}, {'_id': 0, 'right_subject': 1}) for each_asset in asset_grels: asset_contents_list.append(each_asset['right_subject']) create_grelation(asset_obj._id, rt_has_asset_content, asset_contents_list) 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) # counter_obj = Counter.get_counter_obj(request.user.id, group_id) for each_counter_obj in counter_objs_cur: each_counter_obj['file']['created'] += 1 each_counter_obj['group_points'] += GSTUDIO_FILE_UPLOAD_POINTS each_counter_obj.last_update = datetime.datetime.now() each_counter_obj.save()
def check_folder_exists(resource_link, base_folder_name): resource_code = resource_link[:5] ebook_zip_file = EBOOKS_ROOT + resource_code + "dd.zip" # print "ebook_zip_file : ", ebook_zip_file if (os.path.exists(ebook_zip_file)): # check if .zip exists ebook_unzip_folder = EBOOKS_ROOT + resource_code + "dd" # print "ebook_unzip_folder", ebook_unzip_folder if (not (os.path.isdir(ebook_unzip_folder))) and zipfile.is_zipfile(ebook_zip_file): # creating the folder for the first time info_message = "- Folder does NOT exists. So extracting and creating a new one" print info_message log_list.append(str(info_message)) # calling method to unzip the zip file unzip(ebook_zip_file, ebook_unzip_folder) # ----------------------- for cover page ----------------------- files_subfolder = ebook_unzip_folder + "/" + os.walk(ebook_unzip_folder).next()[1][0] files_list = os.listdir(files_subfolder) # print "files_list : ", files_list # gathering the cover page with .jpg/.png format cover_page_list = [i for i in files_list if i.lower().endswith(('.jpg', '.png'))] # print "cover_page_list : ", cover_page_list if cover_page_list: cover_page_name = cover_page_list[0] # print "cover_page_name : ", cover_page_name cover_page_path = files_subfolder + "/" + cover_page_name # print "cover_page_path : ", cover_page_path if os.path.exists(cover_page_path): info_message = "\n- Cover page found for : '" + str(base_folder_name) + "' found. Having name : '" + cover_page_name + "'." print info_message log_list.append(str(info_message)) cover_pg_link = "file://" + cover_page_path files = urllib2.urlopen(cover_pg_link) files = io.BytesIO(files.read()) files.name = cover_page_name # as per requirements in save_file() filemd5 = hashlib.md5(files.read()).hexdigest() fileobj = node_collection.collection.File() if fileobj.fs.files.exists({"md5": filemd5}): info_message = "\n- Cover page resource exists in DB: '" + str(cur_oid._id) + "'" print info_message log_list.append(str(info_message)) else: files.seek(0) content_org = "" tags = [] img_type = None language = "" cover_page_oid, video = save_file(files, cover_page_name, nroer_team_id, home_group._id, content_org, tags, img_type, language, "nroer_team", u"PUBLIC", count=0, first_object="") cover_page_url = update_url_field(cover_page_oid, cover_page_name) # cover_page_in_content_org = "[[http://" + current_site.domain + "/" + os.getlogin() + "/file/readDoc/" + cover_page_oid.__str__() + "/" + cover_page_name + "]]" # print "cover_page_in_content_org : ", cover_page_in_content_org else: cover_page_url = None cover_page_oid = None info_message = "\n- NO cover page found for : '" + str(base_folder_name) + "'" print info_message log_list.append(str(info_message)) # ----------------------- END cover page processing ----------------------- # overwritting resource link resource_link = ebook_zip_file # print "resource_link : ", resource_link name = base_folder_name content_org = cover_page_url if cover_page_url else "" resource_link = "file://" + resource_link files = urllib2.urlopen(resource_link) files = io.BytesIO(files.read()) files.name = resource_code + "dd.zip" # as per requirements in save_file() filemd5 = hashlib.md5(files.read()).hexdigest() fileobj = node_collection.collection.File() if fileobj.fs.files.exists({"md5": filemd5}): gridfs_obj_by_md5 = gridfs_collection.find_one({"md5":filemd5}) check_obj_by_name_n_fs_ids = collection.File.find_one({ "_type":"File", 'member_of': {'$all': [ObjectId(file_gst._id)]}, 'group_set': {'$all': [ObjectId(home_group._id)]}, "name": unicode(base_folder_name), "fs_file_ids": {"$in":[ gridfs_obj_by_md5["_id"] ]} }) if check_obj_by_name_n_fs_ids: # printing appropriate error message info_message = "\n- Resource with same name of '"+ str(base_folder_name) +"' and _type 'File' exist in the group. Ref _id: "+ str(check_obj_by_name_n_fs_ids._id) print info_message log_list.append(str(info_message)) return None # else process for saving/creating new object files.seek(0) language = "" fileobj_oid, video = save_file(files, name, nroer_team_id, home_group._id, content_org, [], None, language, "nroer_team", u"PUBLIC", count=0, first_object="") # creating grelation "has_cover_page" if fileobj_oid and cover_page_oid: update_url_field(fileobj_oid, resource_code + "dd.zip") relation_type_node = node_collection.one({'_type': "RelationType", 'name': "has_cover_page", 'subject_type': {'$in': [file_gst._id]} }) gr_node = create_grelation(fileobj_oid, relation_type_node, cover_page_oid) if gr_node: info_message = "\n- GRelation 'has_cover_page' processing done." print info_message log_list.append(str(info_message)) else: info_message = "\n!! GRelation 'has_cover_page' could not be created successfully." print info_message log_list.append(str(info_message)) return fileobj_oid elif os.path.isdir(ebook_unzip_folder): # Folder already created. # print "----------- folder already exists" return None else: # otherwise return None and break the flow errror_message = "\n!! Resource with name of : '"+ str(base_folder_name) +"' cannot be created. \n\t - Because resource file containing ZIP : '" + ebook_zip_file + "' does not exists." print errror_message log_list.append(str(errror_message)) return None
def parse_data_create_gsystem(json_file_path): json_file_content = "" try: with open(json_file_path) as json_file: json_file_content = json_file.read() json_documents_list = json.loads(json_file_content) # Process data in proper format node = node_collection.collection.File() node_keys = node.keys() node_structure = node.structure json_documents_list_spaces = json_documents_list json_documents_list = [] # Removes leading and trailing spaces from keys as well as values for json_document_spaces in json_documents_list_spaces: json_document = {} for key_spaces, value_spaces in json_document_spaces.iteritems(): json_document[key_spaces.strip().lower()] = value_spaces.strip() json_documents_list.append(json_document) except Exception as e: error_message = "\n!! While parsing the file ("+json_file_path+") got following error...\n " + str(e) log_list.append(str(error_message)) raise error_message for i, json_document in enumerate(json_documents_list): info_message = "\n\n\n******************** Processing row number : ["+ str(i)+ "] ********************" print info_message log_list.append(str(info_message)) try: # print "base_folder : ", json_document["base_folder"] # print "file_name : ", json_document["file_name"] is_base_folder = check_folder_exists(json_document["file_name"], json_document["base_folder"]) # print "is_base_folder : ", is_base_folder if is_base_folder: info_message = "- File gsystem holding collection is created. Having name : '" + str(json_document["base_folder"]) + "' and ObjectId : '" + str(is_base_folder) + "'" print info_message log_list.append(info_message) parsed_json_document = {} attribute_relation_list = [] for key in json_document.iterkeys(): parsed_key = key.lower() if parsed_key in node_keys: # print parsed_key # adding the default field values like: created_by, member_of, ... # created_by: if parsed_key == "created_by": if json_document[key]: temp_user_id = get_user_id(json_document[key].strip()) if temp_user_id: parsed_json_document[parsed_key] = temp_user_id else: parsed_json_document[parsed_key] = nroer_team_id else: # parsed_json_document[parsed_key] = get_user_id("nroer_team") parsed_json_document[parsed_key] = nroer_team_id # print "---", parsed_json_document[parsed_key] # contributors: elif parsed_key == "contributors": if json_document[key]: contrib_list = json_document[key].split(",") temp_contributors = [] for each_user in contrib_list: user_id = get_user_id(each_user.strip()) if user_id: temp_contributors.append(user_id) parsed_json_document[parsed_key] = temp_contributors else: parsed_json_document[parsed_key] = [nroer_team_id] # print "===", parsed_json_document[parsed_key] # tags: elif (parsed_key == "tags") and json_document[key]: parsed_json_document[parsed_key] = cast_to_data_type(json_document[key], node_structure.get(parsed_key)) # tag_list = json_document[key].replace("\n", "").split(",") # temp_tag_list = [] # for each_tag in tag_list: # if each_tag: # temp_tag_list.append(each_tag.strip()) # parsed_json_document[parsed_key] = temp_tag_list # print parsed_json_document[parsed_key] # member_of: elif parsed_key == "member_of": parsed_json_document[parsed_key] = [file_gst._id] # print parsed_json_document[parsed_key] else: # parsed_json_document[parsed_key] = json_document[key] parsed_json_document[parsed_key] = cast_to_data_type(json_document[key], node_structure.get(parsed_key)) # --- END of processing for remaining fields else: parsed_json_document[key] = json_document[key] attribute_relation_list.append(key) # calling method to create File GSystems nodeid = create_resource_gsystem(parsed_json_document) # print type(nodeid), "nodeid ------- : ", nodeid, "\n" # starting processing for the attributes and relations saving if isinstance(nodeid, ObjectId) and attribute_relation_list: node = node_collection.one({ "_id": ObjectId(nodeid) }) gst_possible_attributes_dict = node.get_possible_attributes(file_gst._id) # print gst_possible_attributes_dict relation_list = [] json_document['name'] = node.name # Write code for setting atrributes for key in attribute_relation_list: is_relation = True # print "\n", key, "----------\n" for attr_key, attr_value in gst_possible_attributes_dict.iteritems(): # print "\n", attr_key,"======", attr_value if key == attr_key: # print key is_relation = False # setting value to "0" for int, float, long (to avoid casting error) # if (attr_value['data_type'] in [int, float, long]) and (not json_document[key]): # json_document[key] = 0 if json_document[key]: info_message = "\n- For GAttribute parsing content | key: '" + attr_key + "' having value: '" + json_document[key] + "'" print info_message log_list.append(str(info_message)) cast_to_data_type(json_document[key], attr_value['data_type']) if attr_value['data_type'] == "curricular": # setting int values for CR/XCR if json_document[key] == "CR": json_document[key] = 1 elif json_document[key] == "XCR": json_document[key] = 0 else: # needs to be confirm json_document[key] = 0 json_document[key] = cast_to_data_type(json_document[key], attr_value['data_type']) # if attr_value['data_type'] == basestring: # info_message = "\n- For GAttribute parsing content | key: " + attr_key + " -- value: " + json_document[key] # print info_message # log_list.append(str(info_message)) # elif attr_value['data_type'] == unicode: # json_document[key] = unicode(json_document[key]) # elif attr_value['data_type'] == bool: # # setting int values for CR/XCR # if json_document[key] == "CR": # json_document[key] = 1 # elif json_document[key] == "XCR": # json_document[key] = 0 # json_document[key] = bool(int(json_document[key])) # elif attr_value['data_type'] == datetime.datetime: # json_document[key] = datetime.datetime.strptime(json_document[key], "%d/%m/%Y") # elif attr_value['data_type'] == int: # json_document[key] = int(json_document[key]) # elif attr_value['data_type'] == float: # json_document[key] = float(json_document[key]) # elif attr_value['data_type'] == long: # json_document[key] = long(json_document[key]) # elif type(attr_value['data_type']) == IS: # for op in attr_value['data_type']._operands: # if op.lower() == json_document[key].lower(): # json_document[key] = op # elif (attr_value['data_type'] in [list, dict]) or (type(attr_value['data_type']) in [list, dict]): # if "," not in json_document[key]: # # Necessary to inform perform_eval_type() that handle this value as list # json_document[key] = "\"" + json_document[key] + "\", " # else: # formatted_value = "" # for v in json_document[key].split(","): # formatted_value += "\""+v.strip(" ")+"\", " # json_document[key] = formatted_value # perform_eval_type(key, json_document, "GSystem") subject_id = node._id # print "\n-----\nsubject_id: ", subject_id attribute_type_node = node_collection.one({'_type': "AttributeType", '$or': [{'name': {'$regex': "^"+attr_key+"$", '$options': 'i'}}, {'altnames': {'$regex': "^"+attr_key+"$", '$options': 'i'}}] }) # print "\nattribute_type_node: ", attribute_type_node.name object_value = json_document[key] # print "\nobject_value: ", object_value ga_node = None info_message = "\n- Creating GAttribute ("+node.name+" -- "+attribute_type_node.name+" -- "+str(json_document[key])+") ...\n" print info_message log_list.append(str(info_message)) ga_node = create_gattribute(subject_id, attribute_type_node, object_value) info_message = "- Created ga_node : "+ str(ga_node.name) + "\n" print info_message log_list.append(str(info_message)) # To break outer for loop as key found break else: error_message = "\n!! DataNotFound: No data found for field ("+str(attr_key)+") while creating GSystem ( -- "+str(node.name)+")\n" print error_message log_list.append(str(error_message)) # ---END of if (key == attr_key) if is_relation: relation_list.append(key) # print "relation_list : ", relation_list if not relation_list: # No possible relations defined for this node info_message = "\n!! ("+str(node.name)+"): No possible relations defined for this node.\n" print info_message log_list.append(str(info_message)) return gst_possible_relations_dict = node.get_possible_relations(file_gst._id) # processing each entry in relation_list for key in relation_list: is_relation = True for rel_key, rel_value in gst_possible_relations_dict.iteritems(): if key == rel_key: # commented because teaches is only relation being used for time being # if key == "teaches": is_relation = False if json_document[key]: # ----------------------------- hierarchy_output = None def _get_id_from_hierarchy(hier_list, oid=None): ''' Returns the last hierarchical element's ObjectId. Arguments to be passes is list of unicode names. e.g. hier_list = [u'NCF', u'Science', u'Physical world', u'Materials', u'States of matter', u'Liquids'] ''' if len(hier_list) >= 2: # print hier_list, "len(hier_list) : ", len(hier_list) try: if oid: curr_oid = node_collection.one({ "_id": oid }) # print "curr_oid._id", curr_oid._id else: curr_oid = node_collection.one({ "name": hier_list[0], 'group_set': {'$all': [ObjectId(home_group._id)]}, 'member_of': {'$in': [ObjectId(theme_gst._id), ObjectId(theme_item_gst._id), ObjectId(topic_gst._id)]} }) if curr_oid: next_oid = node_collection.one({ "name": hier_list[1], 'group_set': {'$all': [ObjectId(home_group._id)]}, 'member_of': {'$in': [ObjectId(theme_item_gst._id), ObjectId(topic_gst._id)]}, '_id': {'$in': curr_oid.collection_set } }) # print "||||||", next_oid.name hier_list.remove(hier_list[0]) # print "calling _get_id_from_hierarchy(", hier_list,", ", next_oid._id,")" _get_id_from_hierarchy(hier_list, next_oid._id) else: error_message = "!! ObjectId of curr_oid does not found." print error_message log_list.append(error_message) except Exception as e: error_message = "\n!! Error in getting _id from teaches hierarchy. " + str(e) print error_message log_list.append(error_message) else: global hierarchy_output hierarchy_output = oid if oid else None return hierarchy_output # ----------------------------- # most often the data is hierarchy sep by ":" if ":" in json_document[key]: formatted_list = [] temp_teaches_list = json_document[key].replace("\n", "").split(":") # print "\n temp_teaches", temp_teaches for v in temp_teaches_list: formatted_list.append(v.strip()) right_subject_id = [] rsub_id = _get_id_from_hierarchy(formatted_list) if formatted_list else None # print hierarchy_output," |||||||||||||||||||", rsub_id # checking every item in hierarchy exist and leaf node's _id found if rsub_id: right_subject_id.append(rsub_id) json_document[key] = right_subject_id # print json_document[key] else: error_message = "\n!! While creating teaches rel: Any one of the item in hierarchy"+ str(json_document[key]) +"does not exist in Db. \n!! So relation: " + str(key) + "cannot be created.\n" log_list.append(error_message) break # sometimes direct leaf-node may be present without hierarchy and ":" else: formatted_list = list(json_document[key].strip()) right_subject_id = [] right_subject_id.append(_get_id_from_hierarchy(formatted_list)) json_document[key] = right_subject_id # print "\n----------", json_document[key] info_message = "\n- For GRelation parsing content | key: " + str(rel_key) + " -- " + str(json_document[key]) print info_message log_list.append(str(info_message)) # print list(json_document[key]) # perform_eval_type(key, json_document, "GSystem", "GSystem") for right_subject_id in json_document[key]: # print "\njson_document[key]: ", json_document[key] subject_id = node._id rel_subject_type = [] rel_subject_type.append(file_gst._id) if file_gst.type_of: rel_subject_type.extend(file_gst.type_of) relation_type_node = node_collection.one({'_type': "RelationType", '$or': [{'name': {'$regex': "^"+rel_key+"$", '$options': 'i'}}, {'altnames': {'$regex': "^"+rel_key+"$", '$options': 'i'}}], 'subject_type': {'$in': rel_subject_type} }) right_subject_id_or_list = [] right_subject_id_or_list.append(ObjectId(right_subject_id)) nodes = triple_collection.find({'_type': "GRelation", 'subject': subject_id, 'relation_type.$id': relation_type_node._id }) # sending list of all the possible right subject to relation for n in nodes: if not n.right_subject in right_subject_id_or_list: right_subject_id_or_list.append(n.right_subject) info_message = "\n- Creating GRelation ("+ str(node.name)+ " -- "+ str(rel_key)+ " -- "+ str(right_subject_id_or_list)+") ..." print info_message log_list.append(str(info_message)) gr_node = create_grelation(subject_id, relation_type_node, right_subject_id_or_list) info_message = "\n- Grelation processing done.\n" print info_message log_list.append(str(info_message)) # To break outer for loop if key found break else: error_message = "\n!! DataNotFound: No data found for relation ("+ str(rel_key)+ ") while creating GSystem (" + str(file_gst.name) + " -- " + str(node.name) + ")\n" print error_message log_list.append(str(error_message)) break # print relation_list else: # node object or attribute_relation_list does not exist. info_message = "\n!! Either resource is already created -- OR -- file is already saved into gridfs/DB -- OR -- file does not exists." print info_message log_list.append(str(info_message)) continue except Exception as e: error_message = "\n While creating ("+str(json_document['name'])+") got following error...\n " + str(e) print error_message # Keep it! log_list.append(str(error_message))
# language=language, uploaded_file=img_file, created_by=1, member_of=file_gst._id, origin={'user-icon-list-path':str(path)}, unique_gs_per_file=True ) file_gs_obj.save(groupid=warehouse_grp._id) else: file_gs_obj = node_collection.one({'_type':"GSystem", '$or': [ {'if_file.original.id':filehive_obj_exists._id}, {'if_file.mid.id':filehive_obj_exists._id}, {'if_file.thumbnail.id':filehive_obj_exists._id}]}) # create GRelation 'has_profile_pic' with respective Author nodes if file_gs_obj: for each_auth in auth_nodes: gr_node = create_grelation(each_auth._id, has_profile_pic_rt, file_gs_obj._id) print "\n File : ", file_gs_obj.name , " -- linked -- ", each_auth.name log_file.write("\n File : " + str(file_gs_obj.name) + " -- linked -- "+ str(each_auth.name)) else: print "\n Either Users or Authors with file name : ", str(each_img_name_wo_ext), "does NOT exist." else: print "\n No such path exists." except Exception as user_icon_err: print "\n Error occurred!!!" + str(user_icon_err)
def theme_topic_create_edit(request, group_id, app_set_id=None): ##################### # 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) ###################### nodes_dict = [] create_edit = True themes_hierarchy = False themes_list_items = "" themes_cards = "" title = "" node = "" theme_topic_node = "" drawers = None drawer = None app_id = None nodes_list = [] parent_nodes_collection = "" translate=request.GET.get('translate','') app_GST = node_collection.find_one({"_id":ObjectId(app_set_id)}) if app_GST._id != theme_GST._id: app_obj = node_collection.one({'_id': ObjectId(app_GST.member_of[0])}) else: app_obj = theme_GST if app_obj: app_id = app_obj._id shelves = [] shelf_list = {} auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) if auth: has_shelf_RT = node_collection.one({'_type': 'RelationType', 'name': u'has_shelf' }) shelf = triple_collection.find({'_type': 'GRelation', 'subject': ObjectId(auth._id), 'relation_type.$id': has_shelf_RT._id}) shelf_list = {} if shelf: for each in shelf: shelf_name = node_collection.one({'_id': ObjectId(each.right_subject)}) shelves.append(shelf_name) shelf_list[shelf_name.name] = [] for ID in shelf_name.collection_set: shelf_item = node_collection.one({'_id': ObjectId(ID) }) shelf_list[shelf_name.name].append(shelf_item.name) else: shelves = [] if request.method == "POST": if app_GST: create_edit = True themes_list_items = "" root_themes = [] root_themes_id = [] nodes_list = [] name = request.POST.get('name') collection_list = request.POST.get('collection_list','') prior_node_list = request.POST.get('prior_node_list','') teaches_list = request.POST.get('teaches_list','') assesses_list = request.POST.get('assesses_list','') # To find the root nodes to maintain the uniquness while creating and editing themes nodes = node_collection.find({'member_of': {'$all': [theme_GST._id]},'group_set':{'$all': [ObjectId(group_id)]}}) for each in nodes: if each.collection_set: for k in each.collection_set: nodes_list.append(k) nodes.rewind() for each in nodes: if each._id not in nodes_list: root_themes.append(each.name) root_themes_id.append(each._id) if app_GST.name == "Theme" or app_GST.name == "Topic" or translate == "true": # For creating new themes & Topics themes_list_items = False create_edit = False themes_hierarchy = False themes_cards = True if name or translate == "true": if not name.upper() in (theme_name.upper() for theme_name in root_themes) or translate == "true": if translate != "true": theme_topic_node = node_collection.collection.GSystem() # get_node_common_fields(request, theme_topic_node, group_id, app_GST) theme_topic_node.save(is_changed=get_node_common_fields(request, theme_topic_node, group_id, app_GST),groupid=group_id) if translate == "true": global list_trans_coll list_trans_coll = [] coll_set1=get_coll_set(app_GST._id) for each in coll_set1: theme_topic_node = node_collection.collection.GSystem() if "Theme" in each.member_of_names_list: app_obj = theme_GST if "theme_item" in each.member_of_names_list: app_obj = theme_item_GST if "topic" in each.member_of_names_list: app_obj = topic_GST theme_topic_node.save(is_changed=get_node_common_fields(request, theme_topic_node, group_id, app_obj, each),groupid=group_id) coll_set_dict[each._id]=theme_topic_node._id relation_type = node_collection.one({'_type':'RelationType', 'name':'translation_of'}) # grelation=collection.GRelation() # grelation.relation_type=relation_type # grelation.subject=each._id # grelation.right_subject=theme_topic_node._id # grelation.name=u"" # grelation.save() gr_node = create_grelation(each._id, relation_type, theme_topic_node._id) for each in coll_set1: #if "Theme" in each.member_of_names_list: if each.collection_set: for collset in each.collection_set: p=coll_set_dict[each._id] parent_node = node_collection.one({'_id':ObjectId(str(p))}) n= coll_set_dict[collset] sub_node = node_collection.one({'_id':ObjectId(str(n))}) parent_node.collection_set.append(sub_node._id) parent_node.save(groupid=group_id) # To return themes card view for listing theme nodes after creating new Themes nodes.rewind() nodes_dict = nodes else: themes_list_items = False create_edit = False themes_hierarchy = True theme_topic_node = node_collection.one({'_id': ObjectId(app_GST._id)}) # For edititng themes if theme_GST._id in app_GST.member_of and translate != "true": # To find themes uniqueness within the context of its parent Theme collection, while editing theme name root_themes = [] nodes = node_collection.find({'member_of': {'$all': [theme_GST._id]},'group_set':{'$all': [ObjectId(group_id)]}}) for each in nodes: root_themes.append(each.name) if name: if name.upper() != theme_topic_node.name.upper(): if not name.upper() in (theme_name.upper() for theme_name in root_themes): # get_node_common_fields(request, theme_topic_node, group_id, theme_GST) theme_topic_node.save(is_changed=get_node_common_fields(request, theme_topic_node, group_id, theme_GST),groupid=group_id) else: theme_topic_node.save(is_changed=get_node_common_fields(request, theme_topic_node, group_id, theme_GST),groupid=group_id) if translate != "true": # For storing and maintaning collection order if collection_list != '': theme_topic_node.collection_set = [] collection_list = collection_list.split(",") i = 0 while (i < len(collection_list)): node_id = ObjectId(collection_list[i]) if node_collection.one({"_id": node_id}): theme_topic_node.collection_set.append(node_id) i = i+1 theme_topic_node.save(groupid=group_id) # End of storing collection title = theme_GST.name nodes.rewind() nodes_dict = nodes # This will return to Themes Hierarchy themes_list_items = False create_edit = False themes_hierarchy = False themes_cards = True elif theme_item_GST._id in app_GST.member_of and translate != "true": title = "Theme Item" dict_drawer = {} dict2 = [] node = app_GST prior_theme_collection = [] parent_nodes_collection = "" # To display the theme-topic drawer while create or edit theme checked = "theme_item" # drawers = get_drawers(group_id, node._id, node.collection_set, checked) # Code for fetching drawer2 for k in node.collection_set: obj = node_collection.one({'_id': ObjectId(k) }) dict2.append(obj) dict_drawer['2'] = dict2 # drawers = dict_drawer # End of code for drawer2 drawer = dict_drawer['2'] # To find themes uniqueness within the context of its parent Theme collection, while editing theme item nodes = node_collection.find({'member_of': {'$all': [theme_item_GST._id]},'group_set':{'$all': [ObjectId(group_id)]}}) for each in nodes: if app_GST._id in each.collection_set: for k in each.collection_set: prior_theme = node_collection.one({'_id': ObjectId(k) }) prior_theme_collection.append(prior_theme.name) parent_nodes_collection = json.dumps(prior_theme_collection) if not prior_theme_collection: root_nodes = node_collection.find({'member_of': {'$all': [theme_GST._id]},'group_set':{'$all': [ObjectId(group_id)]}}) for k in root_nodes: if app_GST._id in k.collection_set: root_themes = [] root_themes_id = [] for l in k.collection_set: objs = node_collection.one({'_id': ObjectId(l)}) root_themes.append(objs.name) root_themes_id.append(objs._id) # End of finding unique theme names for editing name # For adding a sub-theme-items and maintianing their uniqueness within their context nodes_list = [] for each in app_GST.collection_set: sub_theme = node_collection.one({'_id': ObjectId(each) }) nodes_list.append(sub_theme.name) nodes_list = json.dumps(nodes_list) # End of finding unique sub themes if name: if name.upper() != theme_topic_node.name.upper(): # If "Name" has changed if theme_topic_node._id in root_themes_id: # If editing node in root theme items if not name.upper() in (theme_name.upper() for theme_name in root_themes): # get_node_common_fields(request, theme_topic_node, group_id, theme_GST) theme_topic_node.save(is_changed=get_node_common_fields(request, theme_topic_node, group_id, theme_item_GST),groupid=group_id) else: # If editing theme item in prior_theme_collection hierarchy if not name.upper() in (theme_name.upper() for theme_name in prior_theme_collection): # get_node_common_fields(request, theme_topic_node, group_id, theme_GST) theme_topic_node.save(is_changed=get_node_common_fields(request, theme_topic_node, group_id, theme_item_GST),groupid=group_id) else: # If name not changed but other fields has changed theme_topic_node.save(is_changed=get_node_common_fields(request, theme_topic_node, group_id, theme_item_GST),groupid=group_id) if translate != "true" and collection_list: # For storing and maintaning collection order if collection_list != '': theme_topic_node.collection_set = [] collection_list = collection_list.split(",") i = 0 while (i < len(collection_list)): node_id = ObjectId(collection_list[i]) if node_collection.one({"_id": node_id}): theme_topic_node.collection_set.append(node_id) i = i+1 theme_topic_node.save(groupid=group_id) # End of storing collection # This will return to Themes items edit if theme_topic_node: theme_topic_node.reload() node = theme_topic_node create_edit = True themes_hierarchy = False # For editing topics elif topic_GST._id in app_GST.member_of: root_topics = [] nodes_list = [] # To find the root nodes to maintain the uniquness while creating and editing topics nodes = node_collection.find({'member_of': {'$all': [topic_GST._id]},'group_set':{'$all': [ObjectId(group_id)]}}) for each in nodes: if each.collection_set: for k in each.collection_set: nodes_list.append(k) nodes.rewind() for each in nodes: if each._id not in nodes_list: root_topics.append(each.name) # End of finding the root nodes if name: if theme_topic_node.name != name: topic_name = theme_topic_node.name if not name.upper() in (theme_name.upper() for theme_name in root_topics): theme_topic_node.save(is_changed=get_node_common_fields(request, theme_topic_node, group_id, topic_GST),groupid=group_id) elif topic_name.upper() == name.upper(): theme_topic_node.save(is_changed=get_node_common_fields(request, theme_topic_node, group_id, topic_GST),groupid=group_id) else: theme_topic_node.save(is_changed=get_node_common_fields(request, theme_topic_node, group_id, topic_GST),groupid=group_id) if collection_list: # For storing and maintaning collection order if collection_list != '': theme_topic_node.collection_set = [] collection_list = collection_list.split(",") i = 0 while (i < len(collection_list)): node_id = ObjectId(collection_list[i]) if node_collection.one({"_id": node_id}): theme_topic_node.collection_set.append(node_id) i = i+1 theme_topic_node.save(groupid=group_id) title = topic_GST.name # To fill the metadata info while creating and editing topic node metadata = request.POST.get("metadata_info", '') if metadata: # Only while metadata editing if metadata == "metadata": if theme_topic_node: get_node_metadata(request,theme_topic_node) # End of filling metadata if prior_node_list != '': theme_topic_node.prior_node = [] prior_node_list = prior_node_list.split(",") i = 0 while (i < len(prior_node_list)): node_id = ObjectId(prior_node_list[i]) if node_collection.one({"_id": node_id}): theme_topic_node.prior_node.append(node_id) i = i+1 theme_topic_node.save(groupid=group_id) if teaches_list !='': teaches_list=teaches_list.split(",") create_grelation_list(theme_topic_node._id,"teaches",teaches_list) if assesses_list !='': assesses_list=assesses_list.split(",") create_grelation_list(theme_topic_node._id,"assesses",assesses_list) # This will return to edit topic if theme_topic_node: theme_topic_node.reload() node = theme_topic_node create_edit = True themes_hierarchy = False else: app_node = None nodes_list = [] app_GST = node_collection.find_one({"_id":ObjectId(app_set_id)}) # print "\napp_GST in else: ",app_GST.name,"\n" if app_GST: # For adding new Theme & Topic if app_GST.name == "Theme" or app_GST.name == "Topic" or translate == True: print "22222" title = app_GST.name node = "" root_themes = [] # To find the root nodes to maintain the uniquness while creating new themes nodes = node_collection.find({'member_of': {'$all': [app_GST._id]},'group_set':{'$all': [ObjectId(group_id)]}}) for each in nodes: if each.collection_set: for k in each.collection_set: nodes_list.append(k) nodes.rewind() for each in nodes: if each._id not in nodes_list: root_themes.append(each.name) root_themes = json.dumps(root_themes) nodes_list = root_themes # End of finding unique root level Themes else: if theme_GST._id in app_GST.member_of: title = "Theme" node = app_GST prior_theme_collection = [] parent_nodes_collection = "" drawer = [] # End of editing Themes # For editing theme item if theme_item_GST._id in app_GST.member_of: title = "Theme Item" dict_drawer = {} dict2 = [] node = app_GST prior_theme_collection = [] parent_nodes_collection = "" # To display the theme-topic drawer while create or edit theme checked = "theme_item" # drawers = get_drawers(group_id, node._id, node.collection_set, checked) for k in node.collection_set: obj = node_collection.one({'_id': ObjectId(k) }) dict2.append(obj) dict_drawer['2'] = dict2 drawer = dict_drawer['2'] # To find themes uniqueness within the context of its parent Theme collection, while editing theme name nodes = node_collection.find({'member_of': {'$all': [theme_item_GST._id]},'group_set':{'$all': [ObjectId(group_id)]}}) for each in nodes: if app_GST._id in each.collection_set: for k in each.collection_set: prior_theme = node_collection.one({'_id': ObjectId(k) }) prior_theme_collection.append(prior_theme.name) parent_nodes_collection = json.dumps(prior_theme_collection) # End of finding unique theme names for editing name # For adding a sub-themes and maintianing their uniqueness within their context for each in app_GST.collection_set: sub_theme = node_collection.one({'_id': ObjectId(each) }) nodes_list.append(sub_theme.name) nodes_list = json.dumps(nodes_list) # End of finding unique sub themes # for editing topic elif topic_GST._id in app_GST.member_of: title = topic_GST.name node = app_GST prior_theme_collection = [] parent_nodes_collection = "" node.get_neighbourhood(node.member_of) # To find topics uniqueness within the context of its parent Theme item collection, while editing topic name nodes = node_collection.find({'member_of': {'$all': [theme_item_GST._id]},'group_set':{'$all': [ObjectId(group_id)]}}) for each in nodes: if app_GST._id in each.collection_set: for k in each.collection_set: prior_theme = node_collection.one({'_id': ObjectId(k) }) prior_theme_collection.append(prior_theme.name) parent_nodes_collection = json.dumps(prior_theme_collection) # End of finding unique theme names for editing name if translate: global list_trans_coll list_trans_coll = [] trans_coll_list = get_coll_set(str(app_GST._id)) print LANGUAGES return render_to_response("ndf/translation_page.html", {'group_id': group_id,'groupid': group_id,'title': title, 'node': app_GST, 'lan':LANGUAGES, 'list1':trans_coll_list },context_instance = RequestContext(request) ) if title == "Topic": return render_to_response("ndf/node_edit_base.html", {'group_id': group_id,'groupid': group_id, 'drawer': drawer, 'themes_cards': themes_cards, 'shelf_list': shelf_list,'shelves': shelves, 'create_edit': create_edit, 'themes_hierarchy': themes_hierarchy,'app_id': app_id,'appId':app._id, 'nodes_list': nodes_list,'title': title,'node': node, 'parent_nodes_collection': parent_nodes_collection, 'theme_GST_id': theme_GST._id,'theme_item_GST_id': theme_item_GST._id, 'topic_GST_id': topic_GST._id, 'themes_list_items': themes_list_items,'nodes':nodes_dict,'lan':LANGUAGES },context_instance = RequestContext(request) ) return render_to_response("ndf/theme.html", {'group_id': group_id,'groupid': group_id, 'drawer': drawer, 'themes_cards': themes_cards, 'theme_GST':theme_GST, 'theme_GST':theme_GST, 'shelf_list': shelf_list,'shelves': shelves, 'create_edit': create_edit, 'themes_hierarchy': themes_hierarchy,'app_id': app_id,'appId':app._id, 'nodes_list': nodes_list,'title': title,'node': node, 'parent_nodes_collection': parent_nodes_collection, 'theme_GST_id': theme_GST._id,'theme_item_GST_id': theme_item_GST._id, 'topic_GST_id': topic_GST._id, 'themes_list_items': themes_list_items,'nodes':nodes_dict,'lan':LANGUAGES },context_instance = RequestContext(request) )
def organization_create_edit(request, group_id, app_id, app_set_id=None, app_set_instance_id=None, app_name=None): """ Creates/Modifies document of given organization-type. """ auth = None # if ObjectId.is_valid(group_id) is False : # group_ins = node_collection.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) app = None if app_id is None: app = node_collection.one({'_type': "GSystemType", 'name': app_name}) if app: app_id = str(app._id) else: app = node_collection.one({'_id': ObjectId(app_id)},{'_id':1, 'name':1}) app_name = app.name # app_name = "mis" app_set = "" app_collection_set = [] title = "" organization_gst = None organization_gs = None property_order_list = [] template = "" template_prefix = "mis" if request.user: if auth is None: auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username)}) agency_type = auth.agency_type agency_type_node = node_collection.one({'_type': "GSystemType", 'name': agency_type}, {'collection_set': 1}) if agency_type_node: for eachset in agency_type_node.collection_set: app_collection_set.append(node_collection.one({"_id": eachset}, {'_id': 1, 'name': 1, 'type_of': 1})) # for eachset in app.collection_set: # app_collection_set.append(node_collection.one({"_id":eachset}, {'_id': 1, 'name': 1, 'type_of': 1})) if app_set_id: organization_gst = node_collection.one({'_type': "GSystemType", '_id': ObjectId(app_set_id)}, {'name': 1, 'type_of': 1}) template = "ndf/organization_create_edit.html" title = organization_gst.name organization_gs = node_collection.collection.GSystem() organization_gs.member_of.append(organization_gst._id) if app_set_instance_id: organization_gs = node_collection.one({'_type': "GSystem", '_id': ObjectId(app_set_instance_id)}) property_order_list = get_property_order_with_value(organization_gs)#.property_order if request.method == "POST": # [A] Save organization-node's base-field(s) is_changed = get_node_common_fields(request, organization_gs, group_id, organization_gst) if is_changed: # Remove this when publish button is setup on interface organization_gs.status = u"PUBLISHED" organization_gs.save(is_changed=is_changed,groupid=group_id) # [B] Store AT and/or RT field(s) of given organization-node (i.e., organization_gs) for tab_details in property_order_list: for field_set in tab_details[1]: # Fetch only Attribute field(s) / Relation field(s) if '_id' in field_set: field_instance = node_collection.one({'_id': field_set['_id']}) field_instance_type = type(field_instance) if field_instance_type in [AttributeType, RelationType]: if field_instance["name"] == "attendees": continue field_data_type = field_set['data_type'] # Fetch field's value depending upon AT/RT and Parse fetched-value depending upon that field's data-type if field_instance_type == AttributeType: if "File" in field_instance["validators"]: # Special case: AttributeTypes that require file instance as it's value in which case file document's ObjectId is used if field_instance["name"] in request.FILES: field_value = request.FILES[field_instance["name"]] else: field_value = "" # Below 0th index is used because that function returns tuple(ObjectId, bool-value) if field_value != '' and field_value != u'': file_name = organization_gs.name + " -- " + field_instance["altnames"] content_org = "" tags = "" field_value = save_file(field_value, file_name, request.user.id, group_id, content_org, tags, access_policy="PRIVATE", count=0, first_object="", oid=True)[0] else: # Other AttributeTypes field_value = request.POST[field_instance["name"]] # field_instance_type = "GAttribute" if field_instance["name"] in ["12_passing_year", "degree_passing_year"]: #, "registration_year"]: field_value = parse_template_data(field_data_type, field_value, date_format_string="%Y") elif field_instance["name"] in ["dob", "registration_date"]: field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y") else: field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y %H:%M") if field_value: organization_gs_triple_instance = create_gattribute(organization_gs._id, node_collection.collection.AttributeType(field_instance), field_value) else: if field_instance["object_cardinality"] > 1: field_value_list = request.POST.get(field_instance["name"], "") if "[" in field_value_list and "]" in field_value_list: field_value_list = json.loads(field_value_list) else: field_value_list = request.POST.getlist(field_instance["name"]) else: field_value_list = request.POST.getlist(field_instance["name"]) # field_instance_type = "GRelation" for i, field_value in enumerate(field_value_list): field_value = parse_template_data(field_data_type, field_value, field_instance=field_instance, date_format_string="%m/%d/%Y %H:%M") field_value_list[i] = field_value organization_gs_triple_instance = create_grelation(organization_gs._id, node_collection.collection.RelationType(field_instance), field_value_list) # [C] Create private group only for College GSystems if "College" in organization_gs.member_of_names_list: # Create a group for respective college node college_group, college_group_gr = create_college_group_and_setup_data(organization_gs) return HttpResponseRedirect( reverse( app_name.lower()+":"+template_prefix+'_app_detail', kwargs={'group_id': group_id, "app_id": app_id, "app_set_id": app_set_id} ) ) # default_template = "ndf/"+template_prefix+"_create_edit.html" context_variables = { 'groupid': group_id, 'group_id': group_id, 'app_id': app_id, 'app_name': app_name, 'app_collection_set': app_collection_set, 'app_set_id': app_set_id, 'title': title, 'property_order_list': property_order_list } if app_set_instance_id: # organization_gs.get_neighbourhood(organization_gs.member_of) # context_variables['node'] = organization_gs context_variables['node_id'] = organization_gs._id context_variables['node_name'] = organization_gs.name try: return render_to_response(template, context_variables, context_instance = RequestContext(request) ) except TemplateDoesNotExist as tde: error_message = "\n OrganizationCreateEditViewError: This html template (" + str(tde) + ") does not exists !!!\n" raise Http404(error_message) except Exception as e: error_message = "\n OrganizationCreateEditViewError: " + str(e) + " !!!\n" raise Exception(error_message)
def event_create_edit(request, group_id, app_set_id=None, app_set_instance_id=None): """ View for handling Event and it's sub-types create-edit-view """ auth = None # if ObjectId.is_valid(group_id) is False : # group_ins = node_collection.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) ''' app = None if app_id is None: app = node_collection.one({'_type': "GSystemType", 'name': app_name}) if app: app_id = str(app._id) else: app = node_collection.one({'_id': ObjectId(app_id)}) app_name = app.name ''' app_set = "" app_collection_set = [] title = "" session_of="" module="" Add="" announced_course ="" batch ="" event_gst = None event_gs = None property_order_list = [] template_prefix = "mis" '''if request.user: if auth is None: auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username)}) agency_type = auth.agency_type Event_Types = node_collection.one({'_type': "GSystemType", 'name': agency_type}, {'collection_set': 1}) if Event_Types: for eachset in Event_Types.collection_set: app_collection_set.append(node_collection.one({"_id": eachset}, {'_id': 1, 'name': 1, 'type_of': 1})) ''' group_inverse_rel_id = [] Group_type=node_collection.one({'_id':ObjectId(group_id)}) for i in Group_type.relation_set: if unicode("group_of") in i.keys(): group_inverse_rel_id = i['group_of'] Group_name = node_collection.one({'_type':'GSystem','_id':{'$in':group_inverse_rel_id}}) Eventtype='Eventtype' if Group_name: if (any( unicode('has_group') in d for d in Group_name.relation_set)) == True: Eventtype='CollegeEvents' else: Eventtype='Eventtype' Glisttype=node_collection.find({"_type": "GSystemType", "name":"GList"}) Event_Types = node_collection.one({"member_of":ObjectId(Glisttype[0]["_id"]),"name":Eventtype},{'collection_set': 1}) app_collection_set=[] if Event_Types: for eachset in Event_Types.collection_set: app_collection_set.append(node_collection.one({"_id": eachset}, {'_id': 1, 'name': 1, 'type_of': 1})) # for eachset in app.collection_set: # app_collection_set.append(node_collection.one({"_id":eachset}, {'_id': 1, 'name': 1, 'type_of': 1})) iteration=request.POST.get("iteration","") if iteration == "": iteration=1 for i in range(int(iteration)): if app_set_id: event_gst = node_collection.one({'_type': "GSystemType", '_id': ObjectId(app_set_id)}, {'name': 1, 'type_of': 1}) title = event_gst.name event_gs = node_collection.collection.GSystem() event_gs.member_of.append(event_gst._id) if app_set_instance_id: event_gs = node_collection.one({'_type': "GSystem", '_id': ObjectId(app_set_instance_id)}) property_order_list = get_property_order_with_value(event_gs)#.property_order if request.method == "POST": # [A] Save event-node's base-field(s) # print "\n Going before....", type(event_gs), "\n event_gs.keys(): ", event_gs.keys() # get_node_common_fields(request, event_gs, group_id, event_gst) # print "\n Going after....", type(event_gs), "\n event_gs.keys(): ", event_gs.keys() # print "\n event_gs: \n", event_gs.keys() # for k, v in event_gs.items(): # print "\n ", k, " -- ", v is_changed = get_node_common_fields(request, event_gs, group_id, event_gst) if is_changed: # Remove this when publish button is setup on interface event_gs.status = u"PUBLISHED" if (request.POST.get("name","")) == "": if i>0: field_value=request.POST.get('start_time'+"_"+str(i),'') else: field_value = request.POST.get('start_time','') if event_gst.name == "Exam": name = "Exam" + "--" + slugify(request.POST.get("batch_name","")) + "--" + field_value else: name= "Class" + "--"+ slugify(request.POST.get("course_name","")) + "--" + field_value event_gs.name=name event_gs.save(is_changed=is_changed,groupid=group_id) # print "\n Event: ", event_gs._id, " -- ", event_gs.name, "\n" # [B] Store AT and/or RT field(s) of given event-node (i.e., event_gs) for tab_details in property_order_list: for field_set in tab_details[1]: # field_set pattern -- {[field_set[0]:node_structure, field_set[1]:field_base/AT/RT_instance{'_id':, 'name':, 'altnames':}, field_set[2]:node_value]} # field_set pattern -- {'_id', 'data_type', 'name', 'altnames', 'value'} # print " ", field_set["name"] # * Fetch only Attribute field(s) / Relation field(s) if field_set.has_key('_id'): field_instance = node_collection.one({'_id': field_set['_id']}) field_instance_type = type(field_instance) if field_instance_type in [AttributeType, RelationType]: if field_instance["name"] == "attendees": continue field_data_type = field_set['data_type'] # Fetch field's value depending upon AT/RT and Parse fetched-value depending upon that field's data-type if field_instance_type == AttributeType: if "File" in field_instance["validators"]: # Special case: AttributeTypes that require file instance as it's value in which case file document's ObjectId is used if field_instance["name"] in request.FILES: field_value = request.FILES[field_instance["name"]] else: field_value = "" # Below 0th index is used because that function returns tuple(ObjectId, bool-value) if field_value != '' and field_value != u'': file_name = event_gs.name + " -- " + field_instance["altnames"] content_org = "" tags = "" field_value = save_file(field_value, file_name, request.user.id, group_id, content_org, tags, access_policy="PRIVATE", count=0, first_object="", oid=True)[0] if "date_month_day_year" in field_instance["validators"]: if i>0: field_value=request.POST.get(field_instance["name"]+"_"+str(i)) else: field_value = request.POST[field_instance["name"]] else: # Other AttributeTypes field_value = request.POST[field_instance["name"]] # field_instance_type = "GAttribute" # print "\n Parsing data for: ", field_instance["name"] if field_instance["name"] in ["12_passing_year", "degree_passing_year"]: #, "registration_year"]: field_value = parse_template_data(field_data_type, field_value, date_format_string="%Y") elif field_instance["name"] in ["dob", "registration_date"]: field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y") else: field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y %H:%M") if field_value: event_gs_triple_instance = create_gattribute(event_gs._id, node_collection.collection.AttributeType(field_instance), field_value) # print "\n event_gs_triple_instance: ", event_gs_triple_instance._id, " -- ", event_gs_triple_instance.name else: field_value_list = request.POST.getlist(field_instance["name"]) # field_instance_type = "GRelation" #code for creation of relation Session of for i, field_value in enumerate(field_value_list): field_value = parse_template_data(field_data_type, field_value, field_instance=field_instance, date_format_string="%d/%m/%Y %H:%M") field_value_list[i] = field_value if field_value_list: event_gs_triple_instance = create_grelation(event_gs._id, node_collection.collection.RelationType(field_instance), field_value_list) # if isinstance(event_gs_triple_instance, list): # print "\n" # for each in event_gs_triple_instance: # print " event_gs_triple_instance: ", each._id, " -- ", each.name # print "\n" # else: # print "\n event_gs_triple_instance: ", event_gs_triple_instance._id, " -- ", event_gs_triple_instance.name # return HttpResponseRedirect(reverse('page_details', kwargs={'group_id': group_id, 'app_id': page_node._id })) '''return HttpResponseRedirect(reverse(app_name.lower()+":"+template_prefix+'_app_detail', kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id}))''' if event_gst.name == u'Classroom Session' or event_gst.name == u'Exam': if i==( (int(iteration))-1): #code to send mail to every one return HttpResponseRedirect(reverse('event_app_instance_detail', kwargs={'group_id': group_id,"app_set_id":app_set_id,"app_set_instance_id":event_gs._id})) else: to_user_list = [] event_organizer_str = "" event_coordinator_str = "" event_organized_by = [] event_coordinator = [] event_node = node_collection.one({'_id':ObjectId(event_gs._id)}) for i in event_node.relation_set: if unicode('event_organised_by') in i.keys(): event_organized_by = i['event_organised_by'] if unicode('has_attendees') in i.keys(): event_attendees = i['has_attendees'] if unicode('event_coordinator') in i.keys(): event_coordinator = i['event_coordinator'] event_url = "/"+str(group_id)+"/event/"+str(app_set_id) +"/"+str(event_node._id) site = Site.objects.get(pk=1) site = site.name.__str__() event_link = "http://" + site + event_url event_organized_by_cur = node_collection.find({"_id":{'$in':event_organized_by}}) event_coordinator_cur = node_collection.find({"_id":{'$in':event_coordinator}}) for i in event_coordinator_cur: event_coordinator_str = event_coordinator_str + i.name + " " for i in event_organized_by_cur: event_organizer_str = event_coordinator_str + i.name + " " for j in event_attendees: auth = node_collection.one({"_id":ObjectId(j)}) user_obj = User.objects.get(id=auth.created_by) if user_obj not in to_user_list: to_user_list.append(user_obj) render_label = render_to_string( "notification/label.html", { "sender": "metaStudio", "activity": "Event Created", "conjunction": "-" }) if event_organized_by: msg_string = "\n Event is organized by " + str ( event_organizer_str ) else: msg_string = "" notification.create_notice_type(render_label,"Invitation for Event"+ " " + str(event_node.name) + msg_string + "\n Event will be co-ordinated by " +str (event_coordinator_str) + "\n- Please click [[" + event_link + "][here]] to view the details of the event" , "notification") notification.send(to_user_list, render_label, {"from_user":"******"}) return HttpResponseRedirect(reverse('event_app_instance_detail', kwargs={'group_id': group_id,"app_set_id":app_set_id,"app_set_instance_id":event_node._id})) event_attendees = request.POST.getlist('has_attendees','') event_gs.get_neighbourhood(event_gs.member_of) course=[] val=False for i in event_gs.relation_set: if unicode('event_has_batch') in i.keys(): batch=node_collection.one({'_type':"GSystem",'_id':ObjectId(i['event_has_batch'][0])}) batch_relation=node_collection.one({'_type':"GSystem",'_id':ObjectId(batch._id)},{'relation_set':1}) for i in batch_relation['relation_set']: if unicode('has_course') in i.keys(): announced_course =node_collection.one({"_type":"GSystem",'_id':ObjectId(i['has_course'][0])}) for i in announced_course.relation_set: if unicode('announced_for') in i.keys(): course=node_collection.one({"_type":"GSystem",'_id':ObjectId(i['announced_for'][0])}) if unicode('session_of') in i.keys(): session_of=node_collection.one({'_type':"GSystem",'_id':ObjectId(i['session_of'][0])}) module=node_collection.one({'_type':"GSystem",'_id':{'$in':session_of.prior_node}}) event_gs.event_coordinator Mis_admin=node_collection.one({"_type":"Group","name":"MIS_admin"}) if Mis_admin: Mis_admin_list=Mis_admin.group_admin Mis_admin_list.append(Mis_admin.created_by) if request.user.id in Mis_admin_list: Add="Allow" else: Add= "Stop" else: Add="Stop" if event_gst.name == u'Classroom Session' or event_gst.name == u'Exam': template="ndf/Nussd_event_Schedule.html" else: template = "ndf/event_create_edit.html" # default_template = "ndf/"+template_prefix+"_create_edit.html" context_variables = { 'group_id': group_id, 'groupid': group_id, 'app_collection_set': app_collection_set, 'app_set_id': app_set_id, 'title':title, 'property_order_list': property_order_list, 'Add':Add } if app_set_instance_id: event_detail={} events={} if event_gs.event_coordinator: event_detail["cordinatorname"]=str(event_gs.event_coordinator[0].name) event_detail["cordinatorid"]=str(event_gs.event_coordinator[0]._id) events["cordinator"]=event_detail if announced_course: event_detail["course"]=str(announced_course.name) event_detail["course_id"]=str(announced_course._id) events["course"]=event_detail event_detail={} if batch: event_detail["batchname"]=str(batch.name) event_detail["batchid"]=str(batch._id) events["batch"]=event_detail event_detail={} if session_of: event_detail["sessionname"]=str(session_of.name) event_detail["sessionid"]=str(session_of._id) for i in session_of.attribute_set: if unicode('course_structure_minutes') in i.keys(): event_detail["sessionminutes"] = str(i['course_structure_minutes']) events["session"]=event_detail event_detail={} if module: event_detail["Modulename"]=str(module.name) event_detail["Moduleid"]=str(module._id) events["Module"]=event_detail context_variables['node'] = event_gs context_variables['edit_details']=events # print "\n template-list: ", [template, default_template] # template = "ndf/fgh.html" # default_template = "ndf/dsfjhk.html" # return render_to_response([template, default_template], return render_to_response(template, context_variables, context_instance = RequestContext(request) )
def theme_topic_create_edit(request, group_id, app_set_id=None): ##################### # 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) ###################### nodes_dict = [] create_edit = True themes_hierarchy = False themes_list_items = "" themes_cards = "" title = "" node = "" theme_topic_node = "" drawers = None drawer = None app_id = None nodes_list = [] parent_nodes_collection = "" translate = request.GET.get('translate', '') app_GST = node_collection.find_one({"_id": ObjectId(app_set_id)}) if app_GST._id != theme_GST._id: app_obj = node_collection.one({'_id': ObjectId(app_GST.member_of[0])}) else: app_obj = theme_GST if app_obj: app_id = app_obj._id shelves = [] shelf_list = {} auth = node_collection.one({ '_type': 'Author', 'name': unicode(request.user.username) }) if auth: has_shelf_RT = node_collection.one({ '_type': 'RelationType', 'name': u'has_shelf' }) shelf = triple_collection.find({ '_type': 'GRelation', 'subject': ObjectId(auth._id), 'relation_type': has_shelf_RT._id }) shelf_list = {} if shelf: for each in shelf: shelf_name = node_collection.one( {'_id': ObjectId(each.right_subject)}) shelves.append(shelf_name) shelf_list[shelf_name.name] = [] for ID in shelf_name.collection_set: shelf_item = node_collection.one({'_id': ObjectId(ID)}) shelf_list[shelf_name.name].append(shelf_item.name) else: shelves = [] if request.method == "POST": if app_GST: create_edit = True themes_list_items = "" root_themes = [] root_themes_id = [] nodes_list = [] name = request.POST.get('name') collection_list = request.POST.get('collection_list', '') prior_node_list = request.POST.get('prior_node_list', '') teaches_list = request.POST.get('teaches_list', '') assesses_list = request.POST.get('assesses_list', '') # To find the root nodes to maintain the uniquness while creating and editing themes nodes = node_collection.find({ 'member_of': { '$all': [theme_GST._id] }, 'group_set': { '$all': [ObjectId(group_id)] } }) for each in nodes: if each.collection_set: for k in each.collection_set: nodes_list.append(k) nodes.rewind() for each in nodes: if each._id not in nodes_list: root_themes.append(each.name) root_themes_id.append(each._id) if app_GST.name == "Theme" or app_GST.name == "Topic" or translate == "true": # For creating new themes & Topics themes_list_items = False create_edit = False themes_hierarchy = False themes_cards = True if name or translate == "true": if not name.upper() in (theme_name.upper() for theme_name in root_themes ) or translate == "true": if translate != "true": theme_topic_node = node_collection.collection.GSystem( ) # get_node_common_fields(request, theme_topic_node, group_id, app_GST) theme_topic_node.save( is_changed=get_node_common_fields( request, theme_topic_node, group_id, app_GST), groupid=group_id) if translate == "true": global list_trans_coll list_trans_coll = [] coll_set1 = get_coll_set(app_GST._id) for each in coll_set1: theme_topic_node = node_collection.collection.GSystem( ) if "Theme" in each.member_of_names_list: app_obj = theme_GST if "theme_item" in each.member_of_names_list: app_obj = theme_item_GST if "topic" in each.member_of_names_list: app_obj = topic_GST theme_topic_node.save( is_changed=get_node_common_fields( request, theme_topic_node, group_id, app_obj, each), groupid=group_id) coll_set_dict[each._id] = theme_topic_node._id relation_type = node_collection.one({ '_type': 'RelationType', 'name': 'translation_of' }) # grelation=collection.GRelation() # grelation.relation_type=relation_type # grelation.subject=each._id # grelation.right_subject=theme_topic_node._id # grelation.name=u"" # grelation.save() gr_node = create_grelation( each._id, relation_type, theme_topic_node._id) for each in coll_set1: #if "Theme" in each.member_of_names_list: if each.collection_set: for collset in each.collection_set: p = coll_set_dict[each._id] parent_node = node_collection.one( {'_id': ObjectId(str(p))}) n = coll_set_dict[collset] sub_node = node_collection.one( {'_id': ObjectId(str(n))}) parent_node.collection_set.append( sub_node._id) parent_node.save(groupid=group_id) # To return themes card view for listing theme nodes after creating new Themes nodes.rewind() nodes_dict = nodes else: themes_list_items = False create_edit = False themes_hierarchy = True theme_topic_node = node_collection.one( {'_id': ObjectId(app_GST._id)}) # For edititng themes if theme_GST._id in app_GST.member_of and translate != "true": # To find themes uniqueness within the context of its parent Theme collection, while editing theme name root_themes = [] nodes = node_collection.find({ 'member_of': { '$all': [theme_GST._id] }, 'group_set': { '$all': [ObjectId(group_id)] } }) for each in nodes: root_themes.append(each.name) if name: if name.upper() != theme_topic_node.name.upper(): if not name.upper() in ( theme_name.upper() for theme_name in root_themes): # get_node_common_fields(request, theme_topic_node, group_id, theme_GST) theme_topic_node.save( is_changed=get_node_common_fields( request, theme_topic_node, group_id, theme_GST), groupid=group_id) else: theme_topic_node.save( is_changed=get_node_common_fields( request, theme_topic_node, group_id, theme_GST), groupid=group_id) if translate != "true": # For storing and maintaning collection order if collection_list != '': theme_topic_node.collection_set = [] collection_list = collection_list.split(",") i = 0 while (i < len(collection_list)): node_id = ObjectId(collection_list[i]) if node_collection.one({"_id": node_id}): theme_topic_node.collection_set.append(node_id) i = i + 1 theme_topic_node.save(groupid=group_id) # End of storing collection title = theme_GST.name nodes.rewind() nodes_dict = nodes # This will return to Themes Hierarchy themes_list_items = False create_edit = False themes_hierarchy = False themes_cards = True elif theme_item_GST._id in app_GST.member_of and translate != "true": title = "Theme Item" dict_drawer = {} dict2 = [] node = app_GST prior_theme_collection = [] parent_nodes_collection = "" # To display the theme-topic drawer while create or edit theme checked = "theme_item" # drawers = get_drawers(group_id, node._id, node.collection_set, checked) # Code for fetching drawer2 for k in node.collection_set: obj = node_collection.one({'_id': ObjectId(k)}) dict2.append(obj) dict_drawer['2'] = dict2 # drawers = dict_drawer # End of code for drawer2 drawer = dict_drawer['2'] # To find themes uniqueness within the context of its parent Theme collection, while editing theme item nodes = node_collection.find({ 'member_of': { '$all': [theme_item_GST._id] }, 'group_set': { '$all': [ObjectId(group_id)] } }) for each in nodes: if app_GST._id in each.collection_set: for k in each.collection_set: prior_theme = node_collection.one( {'_id': ObjectId(k)}) prior_theme_collection.append(prior_theme.name) parent_nodes_collection = json.dumps( prior_theme_collection) if not prior_theme_collection: root_nodes = node_collection.find({ 'member_of': { '$all': [theme_GST._id] }, 'group_set': { '$all': [ObjectId(group_id)] } }) for k in root_nodes: if app_GST._id in k.collection_set: root_themes = [] root_themes_id = [] for l in k.collection_set: objs = node_collection.one( {'_id': ObjectId(l)}) root_themes.append(objs.name) root_themes_id.append(objs._id) # End of finding unique theme names for editing name # For adding a sub-theme-items and maintianing their uniqueness within their context nodes_list = [] for each in app_GST.collection_set: sub_theme = node_collection.one( {'_id': ObjectId(each)}) nodes_list.append(sub_theme.name) nodes_list = json.dumps(nodes_list) # End of finding unique sub themes if name: if name.upper() != theme_topic_node.name.upper(): # If "Name" has changed if theme_topic_node._id in root_themes_id: # If editing node in root theme items if not name.upper() in ( theme_name.upper() for theme_name in root_themes): # get_node_common_fields(request, theme_topic_node, group_id, theme_GST) theme_topic_node.save( is_changed=get_node_common_fields( request, theme_topic_node, group_id, theme_item_GST), groupid=group_id) else: # If editing theme item in prior_theme_collection hierarchy if not name.upper() in (theme_name.upper( ) for theme_name in prior_theme_collection): # get_node_common_fields(request, theme_topic_node, group_id, theme_GST) theme_topic_node.save( is_changed=get_node_common_fields( request, theme_topic_node, group_id, theme_item_GST), groupid=group_id) else: # If name not changed but other fields has changed theme_topic_node.save( is_changed=get_node_common_fields( request, theme_topic_node, group_id, theme_item_GST), groupid=group_id) if translate != "true" and collection_list: # For storing and maintaning collection order if collection_list != '': theme_topic_node.collection_set = [] collection_list = collection_list.split(",") i = 0 while (i < len(collection_list)): node_id = ObjectId(collection_list[i]) if node_collection.one({"_id": node_id}): theme_topic_node.collection_set.append(node_id) i = i + 1 theme_topic_node.save(groupid=group_id) # End of storing collection # This will return to Themes items edit if theme_topic_node: theme_topic_node.reload() node = theme_topic_node create_edit = True themes_hierarchy = False # For editing topics elif topic_GST._id in app_GST.member_of: root_topics = [] nodes_list = [] # To find the root nodes to maintain the uniquness while creating and editing topics nodes = node_collection.find({ 'member_of': { '$all': [topic_GST._id] }, 'group_set': { '$all': [ObjectId(group_id)] } }) for each in nodes: if each.collection_set: for k in each.collection_set: nodes_list.append(k) nodes.rewind() for each in nodes: if each._id not in nodes_list: root_topics.append(each.name) # End of finding the root nodes if name: if theme_topic_node.name != name: topic_name = theme_topic_node.name if not name.upper() in ( theme_name.upper() for theme_name in root_topics): theme_topic_node.save( is_changed=get_node_common_fields( request, theme_topic_node, group_id, topic_GST), groupid=group_id) elif topic_name.upper() == name.upper(): theme_topic_node.save( is_changed=get_node_common_fields( request, theme_topic_node, group_id, topic_GST), groupid=group_id) else: theme_topic_node.save( is_changed=get_node_common_fields( request, theme_topic_node, group_id, topic_GST), groupid=group_id) if collection_list: # For storing and maintaning collection order if collection_list != '': theme_topic_node.collection_set = [] collection_list = collection_list.split(",") i = 0 while (i < len(collection_list)): node_id = ObjectId(collection_list[i]) if node_collection.one({"_id": node_id}): theme_topic_node.collection_set.append( node_id) i = i + 1 theme_topic_node.save(groupid=group_id) title = topic_GST.name # To fill the metadata info while creating and editing topic node metadata = request.POST.get("metadata_info", '') if metadata: # Only while metadata editing if metadata == "metadata": if theme_topic_node: get_node_metadata(request, theme_topic_node) # End of filling metadata if prior_node_list != '': theme_topic_node.prior_node = [] prior_node_list = prior_node_list.split(",") i = 0 while (i < len(prior_node_list)): node_id = ObjectId(prior_node_list[i]) if node_collection.one({"_id": node_id}): theme_topic_node.prior_node.append(node_id) i = i + 1 theme_topic_node.save(groupid=group_id) if teaches_list != '': teaches_list = teaches_list.split(",") create_grelation_list(theme_topic_node._id, "teaches", teaches_list) if assesses_list != '': assesses_list = assesses_list.split(",") create_grelation_list(theme_topic_node._id, "assesses", assesses_list) # This will return to edit topic if theme_topic_node: theme_topic_node.reload() node = theme_topic_node create_edit = True themes_hierarchy = False else: app_node = None nodes_list = [] app_GST = node_collection.find_one({"_id": ObjectId(app_set_id)}) # print "\napp_GST in else: ",app_GST.name,"\n" if app_GST: # For adding new Theme & Topic if app_GST.name == "Theme" or app_GST.name == "Topic" or translate == True: print "22222" title = app_GST.name node = "" root_themes = [] # To find the root nodes to maintain the uniquness while creating new themes nodes = node_collection.find({ 'member_of': { '$all': [app_GST._id] }, 'group_set': { '$all': [ObjectId(group_id)] } }) for each in nodes: if each.collection_set: for k in each.collection_set: nodes_list.append(k) nodes.rewind() for each in nodes: if each._id not in nodes_list: root_themes.append(each.name) root_themes = json.dumps(root_themes) nodes_list = root_themes # End of finding unique root level Themes else: if theme_GST._id in app_GST.member_of: title = "Theme" node = app_GST prior_theme_collection = [] parent_nodes_collection = "" drawer = [] # End of editing Themes # For editing theme item if theme_item_GST._id in app_GST.member_of: title = "Theme Item" dict_drawer = {} dict2 = [] node = app_GST prior_theme_collection = [] parent_nodes_collection = "" # To display the theme-topic drawer while create or edit theme checked = "theme_item" # drawers = get_drawers(group_id, node._id, node.collection_set, checked) for k in node.collection_set: obj = node_collection.one({'_id': ObjectId(k)}) dict2.append(obj) dict_drawer['2'] = dict2 drawer = dict_drawer['2'] # To find themes uniqueness within the context of its parent Theme collection, while editing theme name nodes = node_collection.find({ 'member_of': { '$all': [theme_item_GST._id] }, 'group_set': { '$all': [ObjectId(group_id)] } }) for each in nodes: if app_GST._id in each.collection_set: for k in each.collection_set: prior_theme = node_collection.one( {'_id': ObjectId(k)}) prior_theme_collection.append(prior_theme.name) parent_nodes_collection = json.dumps( prior_theme_collection) # End of finding unique theme names for editing name # For adding a sub-themes and maintianing their uniqueness within their context for each in app_GST.collection_set: sub_theme = node_collection.one( {'_id': ObjectId(each)}) nodes_list.append(sub_theme.name) nodes_list = json.dumps(nodes_list) # End of finding unique sub themes # for editing topic elif topic_GST._id in app_GST.member_of: title = topic_GST.name node = app_GST prior_theme_collection = [] parent_nodes_collection = "" node.get_neighbourhood(node.member_of) # To find topics uniqueness within the context of its parent Theme item collection, while editing topic name nodes = node_collection.find({ 'member_of': { '$all': [theme_item_GST._id] }, 'group_set': { '$all': [ObjectId(group_id)] } }) for each in nodes: if app_GST._id in each.collection_set: for k in each.collection_set: prior_theme = node_collection.one( {'_id': ObjectId(k)}) prior_theme_collection.append(prior_theme.name) parent_nodes_collection = json.dumps( prior_theme_collection) # End of finding unique theme names for editing name if translate: global list_trans_coll list_trans_coll = [] trans_coll_list = get_coll_set(str(app_GST._id)) print LANGUAGES return render_to_response( "ndf/translation_page.html", { 'group_id': group_id, 'groupid': group_id, 'title': title, 'node': app_GST, 'lan': LANGUAGES, 'list1': trans_coll_list }, context_instance=RequestContext(request)) if title == "Topic": return render_to_response("ndf/node_edit_base.html", { 'group_id': group_id, 'groupid': group_id, 'drawer': drawer, 'themes_cards': themes_cards, 'shelf_list': shelf_list, 'shelves': shelves, 'create_edit': create_edit, 'themes_hierarchy': themes_hierarchy, 'app_id': app_id, 'appId': app._id, 'nodes_list': nodes_list, 'title': title, 'node': node, 'parent_nodes_collection': parent_nodes_collection, 'theme_GST_id': theme_GST._id, 'theme_item_GST_id': theme_item_GST._id, 'topic_GST_id': topic_GST._id, 'themes_list_items': themes_list_items, 'nodes': nodes_dict, 'lan': LANGUAGES }, context_instance=RequestContext(request)) return render_to_response("ndf/theme.html", { 'group_id': group_id, 'groupid': group_id, 'drawer': drawer, 'themes_cards': themes_cards, 'theme_GST': theme_GST, 'theme_GST': theme_GST, 'shelf_list': shelf_list, 'shelves': shelves, 'create_edit': create_edit, 'themes_hierarchy': themes_hierarchy, 'app_id': app_id, 'appId': app._id, 'nodes_list': nodes_list, 'title': title, 'node': node, 'parent_nodes_collection': parent_nodes_collection, 'theme_GST_id': theme_GST._id, 'theme_item_GST_id': theme_item_GST._id, 'topic_GST_id': topic_GST._id, 'themes_list_items': themes_list_items, 'nodes': nodes_dict, 'lan': LANGUAGES }, context_instance=RequestContext(request))
def data_review_save(request, group_id): ''' Method to save each and every data-row edit of data review app ''' userid = request.user.pk try: group_id = ObjectId(group_id) except: group_name, group_id = get_group_name_id(group_id) group_obj = node_collection.one({"_id": ObjectId(group_id)}) node_oid = request.POST.get("node_oid", "") node_details = request.POST.get("node_details", "") node_details = json.loads(node_details) # print "node_details : ", node_details # updating some key names of dictionary as per get_node_common_fields. node_details["lan"] = node_details.pop("language") node_details["prior_node_list"] = node_details.pop("prior_node") node_details["login-mode"] = node_details.pop("access_policy") status = node_details.pop("status") # node_details["collection_list"] = node_details.pop("collection") for future use # Making copy of POST QueryDict instance. # To make it mutable and fill in node_details value/s. post_req = request.POST.copy() # removing node_details dict from req post_req.pop('node_details') # adding values to post req post_req.update(node_details) # overwriting request.POST with newly created QueryDict instance post_req request.POST = post_req # print "\n---\n", request.POST, "\n---\n" license = request.POST.get('license', '') file_node = node_collection.one({"_id": ObjectId(node_oid)}) if request.method == "POST": edit_summary = [] file_node_before = file_node.copy( ) # copying before it is getting modified is_changed = get_node_common_fields(request, file_node, group_id, GST_FILE) for key, val in file_node_before.iteritems(): if file_node_before[key] != file_node[key]: temp_edit_summ = {} temp_edit_summ["name"] = "Field: " + key temp_edit_summ["before"] = file_node_before[key] temp_edit_summ["after"] = file_node[key] edit_summary.append(temp_edit_summ) # to fill/update attributes of the node and get updated attrs as return ga_nodes = get_node_metadata(request, file_node, is_changed=True) if len(ga_nodes): is_changed = True # adding the edit attribute name in summary for each_ga in ga_nodes: temp_edit_summ = {} temp_edit_summ["name"] = "Attribute: " + each_ga["node"][ "attribute_type"]["name"] temp_edit_summ["before"] = each_ga["before_obj_value"] temp_edit_summ["after"] = each_ga["node"]["object_value"] edit_summary.append(temp_edit_summ) teaches_list = request.POST.get('teaches', '') # get the teaches list prev_teaches_list = request.POST.get( "teaches_prev", "") # get the before-edit teaches list # check if teaches list exist means nodes added/removed for teaches relation_type # also check for if previous teaches list made empty with prev_teaches_list if (teaches_list != '') or prev_teaches_list: teaches_list = teaches_list.split(",") if teaches_list else [] teaches_list = [ObjectId(each_oid) for each_oid in teaches_list] relation_type_node = node_collection.one({ '_type': "RelationType", 'name': 'teaches' }) gr_nodes = create_grelation(file_node._id, relation_type_node, teaches_list) gr_nodes_oid_list = [ ObjectId(each_oid["right_subject"]) for each_oid in gr_nodes ] if gr_nodes else [] prev_teaches_list = prev_teaches_list.split( ",") if prev_teaches_list else [] prev_teaches_list = [ ObjectId(each_oid) for each_oid in prev_teaches_list ] if len(gr_nodes_oid_list) == len(prev_teaches_list) and set( gr_nodes_oid_list) == set(prev_teaches_list): pass else: rel_nodes = triple_collection.find({ '_type': "GRelation", 'subject': file_node._id, 'relation_type': relation_type_node._id }) rel_oid_name = {} for each in rel_nodes: temp = {} temp[each.right_subject] = each.name rel_oid_name.update(temp) is_changed = True temp_edit_summ = {} temp_edit_summ["name"] = "Relation: Teaches" temp_edit_summ["before"] = [ rel_oid_name[each_oid].split(" -- ")[2] for each_oid in prev_teaches_list ] temp_edit_summ["after"] = [ rel_oid_name[each_oid].split(" -- ")[2] for each_oid in gr_nodes_oid_list ] edit_summary.append(temp_edit_summ) assesses_list = request.POST.get('assesses_list', '') if assesses_list != '': assesses_list = assesses_list.split(",") assesses_list = [ObjectId(each_oid) for each_oid in assesses_list] relation_type_node = node_collection.one({ '_type': "RelationType", 'name': 'assesses' }) gr_nodes = create_grelation(file_node._id, relation_type_node, teaches_list) gr_nodes_oid_list = [ ObjectId(each_oid["right_subject"]) for each_oid in gr_nodes ] if len(gr_nodes_oid_list) == len(teaches_list) and set( gr_nodes_oid_list) == set(teaches_list): pass else: is_changed = True # changing status to draft even if attributes/relations are changed if is_changed: file_node.status = unicode("DRAFT") file_node.modified_by = userid if userid not in file_node.contributors: file_node.contributors.append(userid) # checking if user is authenticated to change the status of node if status and ((group_obj.is_gstaff(request.user)) or (userid in group_obj.author_set)): if file_node.status != status: file_node.status = unicode(status) file_node.modified_by = userid if userid not in file_node.contributors: file_node.contributors.append(userid) is_changed = True if is_changed: file_node.save(groupid=group_id) # print edit_summary return HttpResponse(file_node.status)
def event_create_edit(request, group_id, app_set_id=None, app_set_instance_id=None): """ View for handling Event and it's sub-types create-edit-view """ auth = None try: group_id = ObjectId(group_id) #group_id is a valid ObjectId except: group_name, group_id = get_group_name_id(group_id) #instead of group_id the name of the object is passed via URL to the function group_obj = node_collection.one({'_id': group_id}) app_set = "" title = "" #Stores the name of the type of event such as Meeting, Inauguration, etc. session_of="" module="" Add="" announced_course ="" batch ="" event_gst = None event_gs = None property_order_list = [] template_prefix = "mis" group_inverse_rel_id = [] Group_type=node_collection.one({'_id':ObjectId(group_id)}) #instance of the group object in which the event is created e.g. "home" is a group for i in Group_type.relation_set: if unicode("group_of") in i.keys(): group_inverse_rel_id = i['group_of'] Group_name = node_collection.one({'_type':'GSystem','_id':{'$in':group_inverse_rel_id}}) Eventtype='Eventtype' if Group_name: if (any( unicode('has_group') in d for d in Group_name.relation_set)) == True: Eventtype='CollegeEvents' else: Eventtype='Eventtype' Glisttype=node_collection.find({"_type": "GSystemType", "name":"GList"}) Event_Types = node_collection.one({"member_of":ObjectId(Glisttype[0]["_id"]),"name":Eventtype},{'collection_set': 1}) #Stores the object ids of all the types of events e.g. Meeting, Inauguration, ... app_collection_set=[] #stores the id, name and type_of for all event types (Meeting, Inauguration, etc.) as a list if Event_Types: for eachset in Event_Types.collection_set: app_collection_set.append(node_collection.one({"_id": eachset}, {'_id': 1, 'name': 1, 'type_of': 1})) iteration=request.POST.get("iteration","") if iteration == "": iteration=1 for i in range(int(iteration)): if app_set_id: event_gst = node_collection.one({'_type': "GSystemType", '_id': ObjectId(app_set_id)}, {'name': 1, 'type_of': 1}) #GSystemType Object for the event corresponding to app_set_id e.g. Meeting title = event_gst.name event_gs = node_collection.collection.GSystem() #create a new GSystem Object for the Event event_gs.member_of.append(event_gst._id) #event_gs is a member_of event_gst if app_set_instance_id: #app_set_instance_id is the objectid of the event object which is already created event_gs = node_collection.one({'_type': "GSystem", '_id': ObjectId(app_set_instance_id)}) property_order_list = get_property_order_with_value(event_gs) #.property_order #stores the properties defining a particular event in a list e.g. name, start_time, attendees, etc.. if request.method == "POST": # [A] Save event-node's base-field(s) # print "\n Going before....", type(event_gs), "\n event_gs.keys(): ", event_gs.keys() # get_node_common_fields(request, event_gs, group_id, event_gst) # print "\n Going after....", type(event_gs), "\n event_gs.keys(): ", event_gs.keys() # print "\n event_gs: \n", event_gs.keys() # for k, v in event_gs.items(): # print "\n ", k, " -- ", v is_changed = get_node_common_fields(request, event_gs, group_id, event_gst) if is_changed: # Remove this when publish button is setup on interface event_gs.status = u"PUBLISHED" if (request.POST.get("name","")) == "": if i>0: field_value=request.POST.get('start_time'+"_"+str(i),'') else: field_value = request.POST.get('start_time','') # print "----------------Field Value-----------" # print field_value if event_gst.name == "Exam": name = "Exam" + "--" + slugify(request.POST.get("batch_name","")) + "--" + field_value else: name= "Class" + "--"+ slugify(request.POST.get("course_name","")) + "--" + field_value # print "-----------------Name------------------" # print name event_gs.name=name # if request.POST.get("is_bigbluebutton") == unicode("Yes"): # event_gs.is_bigbluebutton = True # else: # event_gs.is_bigbluebutton = False event_gs.save(is_changed=is_changed,groupid=group_id) # print "\n Event: ", event_gs._id, " -- ", event_gs.name, "\n" check_attendee = True # [B] Store AT and/or RT field(s) of given event-node (i.e., event_gs) for tab_details in property_order_list: for field_set in tab_details[1]: # field_set pattern -- {[field_set[0]:node_structure, field_set[1]:field_base/AT/RT_instance{'_id':, 'name':, 'altnames':}, field_set[2]:node_value]} # field_set pattern -- {'_id', 'data_type', 'name', 'altnames', 'value'} # print " ", field_set["name"] # * Fetch only Attribute field(s) / Relation field(s) if field_set.has_key('_id'): #Implies field_set is not a basefield but is an AT/RT field_instance = node_collection.one({'_id': field_set['_id']})#field_instance is an instance for AT or RT e.g. start_time field_instance_type = type(field_instance) if field_instance_type in [AttributeType, RelationType]: if field_instance["name"] == "attendees": continue field_data_type = field_set['data_type'] #data type of AT/RT e.g. datetime.datetime for start_time # Fetch field's value depending upon AT/RT and Parse fetched-value depending upon that field's data-type open_event = False if field_instance_type == AttributeType: if "File" in field_instance["validators"]: # Special case: AttributeTypes that require file instance as it's value in which case file document's ObjectId is used if field_instance["name"] in request.FILES: field_value = request.FILES[field_instance["name"]] else: field_value = "" # Below 0th index is used because that function returns tuple(ObjectId, bool-value) if field_value != '' and field_value != u'': file_name = event_gs.name + " -- " + field_instance["altnames"] content_org = "" tags = "" field_value = save_file(field_value, file_name, request.user.id, group_id, content_org, tags, access_policy="PRIVATE", count=0, first_object="", oid=True)[0] if "date_month_day_year" in field_instance["validators"]: if i>0: field_value=request.POST.get(field_instance["name"]+"_"+str(i)) else: field_value = request.POST[field_instance["name"]] else: # Other AttributeTypes field_value = request.POST[field_instance["name"]] # field_instance_type = "GAttribute" # print "\n Parsing data for: ", field_instance["name"] if field_instance["name"] in ["12_passing_year", "degree_passing_year"]: #, "registration_year"]: field_value = parse_template_data(field_data_type, field_value, date_format_string="%Y") elif field_instance["name"] in ["dob", "registration_date"]: field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y") else: field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y %H:%M") if field_value: event_gs_triple_instance = create_gattribute(event_gs._id, node_collection.collection.AttributeType(field_instance), field_value) # print "--------------------------------------------------------------------------------------------------" # print "\n event_gs_triple_instance: ", event_gs_triple_instance._id, " -- ", event_gs_triple_instance.name if field_instance["name"] == 'open_event': open_event = field_value else: #field_instance_type == RelationType field_value_list = request.POST.getlist(field_instance["name"]) # field_instance_type = "GRelation" #code for creation of relation Session of for i, field_value in enumerate(field_value_list): try: field_value = parse_template_data(field_data_type, field_value, field_instance=field_instance, date_format_string="%d/%m/%Y %H:%M") except: field_value = parse_template_data(ObjectId, field_value, field_instance=field_instance, date_format_string="%d/%m/%Y %H:%M") field_value_list[i] = field_value if field_value_list: if field_instance["name"] == "has_attendees" and open_event == "False": send_event_notif_to_all_grp_members(group_obj, app_set_id, event_gs) else: event_gs_triple_instance = create_grelation(event_gs._id, node_collection.collection.RelationType(field_instance), field_value_list) # End of for loop on property_order_list # return HttpResponseRedirect(reverse('page_details', kwargs={'group_id': group_id, 'app_id': page_node._id })) '''return HttpResponseRedirect(reverse(app_name.lower()+":"+template_prefix+'_app_detail', kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id}))''' if event_gst.name == u'Classroom Session' or event_gst.name == u'Exam': if i==( (int(iteration))-1): #code to send mail to every one return HttpResponseRedirect(reverse('event_app_instance_detail', kwargs={'group_id': group_id,"app_set_id":app_set_id,"app_set_instance_id":event_gs._id})) else: event_attendees = [] event_node = node_collection.one({'_id':ObjectId(event_gs._id)}) for i in event_node.relation_set: if unicode('has_attendees') in i.keys(): event_attendees = i['has_attendees'] send_event_notif_to_all_grp_members(group_obj, app_set_id, event_gs, event_attendees) return HttpResponseRedirect(reverse('event_app_instance_detail', kwargs={'group_id': group_id,"app_set_id":app_set_id,"app_set_instance_id":event_node._id})) event_attendees = request.POST.getlist('has_attendees','') event_gs.get_neighbourhood(event_gs.member_of) course=[] val=False for i in event_gs.relation_set: if unicode('event_has_batch') in i.keys(): batch=node_collection.one({'_type':"GSystem",'_id':ObjectId(i['event_has_batch'][0])}) batch_relation=node_collection.one({'_type':"GSystem",'_id':ObjectId(batch._id)},{'relation_set':1}) for i in batch_relation['relation_set']: if unicode('has_course') in i.keys(): announced_course =node_collection.one({"_type":"GSystem",'_id':ObjectId(i['has_course'][0])}) for i in announced_course.relation_set: if unicode('announced_for') in i.keys(): course=node_collection.one({"_type":"GSystem",'_id':ObjectId(i['announced_for'][0])}) if unicode('session_of') in i.keys(): session_of=node_collection.one({'_type':"GSystem",'_id':ObjectId(i['session_of'][0])}) module=node_collection.one({'_type':"GSystem",'_id':{'$in':session_of.prior_node}}) event_gs.event_coordinator Mis_admin=node_collection.one({"_type":"Group","name":"MIS_admin"}) if Mis_admin: Mis_admin_list=Mis_admin.group_admin Mis_admin_list.append(Mis_admin.created_by) if request.user.id in Mis_admin_list: Add="Allow" else: Add= "Stop" else: Add="Stop" if event_gst.name == u'Classroom Session' or event_gst.name == u'Exam': template="ndf/Nussd_event_Schedule.html" else: template = "ndf/event_create_edit.html" # default_template = "ndf/"+template_prefix+"_create_edit.html" context_variables = { 'group_id': group_id, 'groupid': group_id, 'app_collection_set': app_collection_set, 'app_set_id': app_set_id, 'title':title, 'property_order_list': property_order_list, 'Add':Add } if app_set_instance_id: event_detail={} events={} if event_gs.event_coordinator: event_detail["cordinatorname"]=str(event_gs.event_coordinator[0].name) event_detail["cordinatorid"]=str(event_gs.event_coordinator[0]._id) events["cordinator"]=event_detail if announced_course: event_detail["course"]=str(announced_course.name) event_detail["course_id"]=str(announced_course._id) events["course"]=event_detail event_detail={} if batch: event_detail["batchname"]=str(batch.name) event_detail["batchid"]=str(batch._id) events["batch"]=event_detail event_detail={} if session_of: event_detail["sessionname"]=str(session_of.name) event_detail["sessionid"]=str(session_of._id) for i in session_of.attribute_set: if unicode('course_structure_minutes') in i.keys(): event_detail["sessionminutes"] = str(i['course_structure_minutes']) events["session"]=event_detail event_detail={} if module: event_detail["Modulename"]=str(module.name) event_detail["Moduleid"]=str(module._id) events["Module"]=event_detail context_variables['node'] = event_gs context_variables['edit_details']=events # print "\n template-list: ", [template, default_template] # template = "ndf/fgh.html" # default_template = "ndf/dsfjhk.html" # return render_to_response([template, default_template], return render_to_response(template, context_variables, context_instance = RequestContext(request) )
def update(request, rt_list, at_list, task_node, group_id, group_name): file_id = (request.POST.get("files")) file_name = (request.POST.get("files_name")) user_to_be_notified = [] assignee_list = [] change_list = [] for each in rt_list: rel_type_node = node_collection.one({ '_type': "RelationType", 'name': each }) field_value_list = None if rel_type_node["object_cardinality"] > 1: field_value_list = request.POST.get(rel_type_node["name"], "") if "[" in field_value_list and "]" in field_value_list: field_value_list = json.loads(field_value_list) else: field_value_list = request.POST.getlist(rel_type_node["name"]) else: field_value_list = request.POST.getlist(rel_type_node["name"]) for i, field_value in enumerate(field_value_list): field_value = parse_template_data(rel_type_node.object_type, field_value, field_instance=rel_type_node) field_value_list[i] = field_value old_value = [] for rel in task_node.relation_set: for k in rel: if rel_type_node.name == k: vals_cur = node_collection.find({'_id': { '$in': rel[k] }}, {'name': 1}) for v_node in vals_cur: old_value.append(v_node.name) break new_value = [] vals_cur = node_collection.find({'_id': { '$in': field_value_list }}, {'name': 1}) for v_node in vals_cur: new_value.append(v_node.name) break if old_value != new_value: change_list.append( each.encode('utf8') + ' changed from ' + ", ".join(old_value) + ' to ' + ", ".join(new_value)) # updated details task_gs_triple_instance = create_grelation( task_node._id, node_collection.collection.RelationType(rel_type_node), field_value_list) task_node.reload() for each in at_list: if request.POST.get(each, ""): attributetype_key = node_collection.find_one({ "_type": 'AttributeType', 'name': each }) attr = triple_collection.find_one({ "_type": "GAttribute", "subject": task_node._id, "attribute_type": attributetype_key._id }) if each == "Assignee": field_value = request.POST.getlist(each, "") for i, val in enumerate(field_value): field_value[i] = int(val) assignee_list_id = field_value for eachuser in assignee_list_id: bx = User.objects.get(id=int(eachuser)) if bx: if bx.username not in assignee_list: assignee_list.append(bx.username) # Adding to list which holds user's to be notified about the task if bx not in user_to_be_notified: user_to_be_notified.append(bx) else: field_value = request.POST.get(each, "") date_format_string = "" if each in ["start_time", "end_time"]: date_format_string = "%d/%m/%Y" field_value = parse_template_data( eval(attributetype_key["data_type"]), field_value, date_format_string=date_format_string) if attr: # already attribute exist if not attr.object_value == field_value: # change_list.append(each.encode('utf8')+' changed from '+attr.object_value.encode('utf8')+' to '+request.POST.get(each,"").encode('utf8')) # updated details if attributetype_key["data_type"] == "datetime.datetime": change_list.append( each.encode('utf8') + ' changed from ' + attr.object_value.strftime("%d/%m/%Y") + ' to ' + field_value.strftime("%d/%m/%Y") ) # updated details else: change_list.append( each.encode('utf8') + ' changed from ' + str(attr.object_value) + ' to ' + str(field_value)) # updated details attr.object_value = field_value attr.save(groupid=group_id) else: # attributetype_key = node_collection.find_one({"_type":'AttributeType', 'name':each}) # newattribute = triple_collection.collection.GAttribute() # newattribute.subject = task_node._id # newattribute.attribute_type = attributetype_key # newattribute.object_value = request.POST.get(each,"") # newattribute.object_value = field_value # newattribute.save() ga_node = create_gattribute(task_node._id, attributetype_key, field_value) # change_list.append(each.encode('utf8')+' set to '+request.POST.get(each,"").encode('utf8')) # updated details change_list.append( each.encode('utf8') + ' set to ' + str(field_value)) # updated details elif each == 'Upload_Task': attributetype_key = node_collection.find_one({ "_type": 'AttributeType', 'name': 'Upload_Task' }) attr = triple_collection.find_one({ "_type": "GAttribute", "subject": task_node._id, "attribute_type": attributetype_key._id }) if attr: value = get_file_node(attr.object_value) change_list.append( each.encode('utf8') + ' changed from ' + str(value).strip('[]') + ' to ' + str(file_name)) # attr.object_value=file_id # attr.save() ga_node = create_gattribute(attr.subject, attributetype_key, file_id) else: # newattribute = node_collection.collection.GAttribute() # newattribute.subject = task_node._id # newattribute.attribute_type = attributetype_key # newattribute.object_value = file_id # newattribute.save() ga_node = create_gattribute(task_node._id, attributetype_key, file_id) change_list.append( each.encode('utf8') + ' set to ' + file_name.encode('utf8')) # updated details # userobj = User.objects.get(id=task_node.created_by) # if userobj and userobj not in user_to_be_notified: # user_to_be_notified.append(userobj) for each_author in task_node.author_set: each_author = User.objects.get(id=each_author) if each_author and each_author not in user_to_be_notified: user_to_be_notified.append(each_author) # Sending notification to all watchers about the updates of the task for eachuser in user_to_be_notified: activ = "task updated" msg = "Task '" + task_node.name + \ "' has been updated by " + request.user.username + \ "\n - Changes: " + str(change_list).strip('[]') + \ "\n - Status: " + request.POST.get('Status','') + \ "\n - Assignee: " + ", ".join(assignee_list) + \ "\n - Url: http://" + site_domain + "/" + group_name.replace(" ","%20").encode('utf8') + "/task/" + str(task_node._id) bx = User.objects.get(username=eachuser) set_notif_val(request, group_id, msg, activ, bx) if change_list or content_org: GST_task_update_history = node_collection.one({ '_type': "GSystemType", 'name': 'task_update_history' }) update_node = node_collection.collection.GSystem() get_node_common_fields(request, update_node, group_id, GST_task_update_history) if change_list: update_node.altnames = unicode(str(change_list)) else: update_node.altnames = unicode('[]') update_node.prior_node = [task_node._id] update_node.name = unicode(task_node.name + "-update_history") update_node.save(groupid=group_id) update_node.name = unicode(task_node.name + "-update_history-" + str(update_node._id)) update_node.save(groupid=group_id) task_node.post_node.append(update_node._id) task_node.save(groupid=group_id) # patch GST_TASK = node_collection.one({ '_type': "GSystemType", 'name': 'Task' }) get_node_common_fields(request, task_node, group_id, GST_TASK) task_node.save(groupid=group_id)
def save_batch(request, group_id): # def save_batch(batch_name, user_list, group_id, request, ac_id): group_name, group_id = get_group_name_id(group_id) response_dict = {"success": False} # new_batch_node = None rt_has_batch_member = node_collection.one({ '_type': 'RelationType', 'name': 'has_batch_member' }) if request.is_ajax() and request.method == "POST": ac_id = request.POST.get("ac_id", '') batch_name = request.POST.get("batch_name", '') batch_id = request.POST.get("batch_id", '') user_list = request.POST.getlist("user_list[]", '') # create_new_batch = request.POST.get("create_new_batch", '') # response_dict["old_batches"] = find_batches_of_ac(ac_id) user_list = [ObjectId(each) for each in user_list] all_batches_in_grp = [] if not batch_id: # b_node = node_collection.one({'member_of':GST_BATCH._id,'name':unicode(batch_name)}) b_node = node_collection.collection.GSystem() b_node.member_of.append(GST_BATCH._id) b_node.created_by = int(request.user.id) b_node.group_set.append(ObjectId(group_id)) b_node.name = batch_name b_node['altnames'] = batch_name.replace('_', ' ') b_node.contributors.append(int(request.user.id)) b_node.modified_by = int(request.user.id) b_node.save(groupid=group_id) all_batches_in_grp.append(b_node._id) rt_group_has_batch = node_collection.one({ '_type': 'RelationType', 'name': 'group_has_batch' }) relation_coll = triple_collection.find({ '_type': 'GRelation', 'relation_type': rt_group_has_batch._id, 'subject': ObjectId(group_id) }) for each in relation_coll: all_batches_in_grp.append(each.right_subject) # to get all batches of the group rt_has_course = node_collection.one({ '_type': 'RelationType', 'name': 'has_course' }) create_grelation(ObjectId(group_id), rt_group_has_batch, all_batches_in_grp) create_grelation(b_node._id, rt_has_course, ObjectId(ac_id)) response_dict['new_batch_created'] = True response_dict['new_batch_node_name'] = b_node.name response_dict['new_batch_node_id'] = str(b_node._id) else: response_dict['new_batch_created'] = False b_node = node_collection.one({'_id': ObjectId(batch_id)}) if user_list: create_grelation(b_node._id, rt_has_batch_member, user_list) response_dict['success'] = True return HttpResponse(json.dumps(response_dict, cls=NodeJSONEncoder))
def data_review_save(request, group_id): ''' Method to save each and every data-row edit of data review app ''' userid = request.user.pk try: group_id = ObjectId(group_id) except: group_name, group_id = get_group_name_id(group_id) group_obj = node_collection.one({"_id": ObjectId(group_id)}) node_oid = request.POST.get("node_oid", "") node_details = request.POST.get("node_details", "") node_details = json.loads(node_details) # print "node_details : ", node_details # updating some key names of dictionary as per get_node_common_fields. node_details["lan"] = node_details.pop("language") node_details["prior_node_list"] = node_details.pop("prior_node") node_details["login-mode"] = node_details.pop("access_policy") status = node_details.pop("status") # node_details["collection_list"] = node_details.pop("collection") for future use # Making copy of POST QueryDict instance. # To make it mutable and fill in node_details value/s. post_req = request.POST.copy() # removing node_details dict from req post_req.pop('node_details') # adding values to post req post_req.update(node_details) # overwriting request.POST with newly created QueryDict instance post_req request.POST = post_req # print "\n---\n", request.POST, "\n---\n" copyright = request.POST.get('copyright', '') file_node = node_collection.one({"_id": ObjectId(node_oid)}) if request.method == "POST": edit_summary = [] file_node_before = file_node.copy() # copying before it is getting modified is_changed = get_node_common_fields(request, file_node, group_id, GST_FILE) for key, val in file_node_before.iteritems(): if file_node_before[key] != file_node[key]: temp_edit_summ = {} temp_edit_summ["name"] = "Field: " + key temp_edit_summ["before"] = file_node_before[key] temp_edit_summ["after"] = file_node[key] edit_summary.append(temp_edit_summ) # to fill/update attributes of the node and get updated attrs as return ga_nodes = get_node_metadata(request, file_node, is_changed=True) if len(ga_nodes): is_changed = True # adding the edit attribute name in summary for each_ga in ga_nodes: temp_edit_summ = {} temp_edit_summ["name"] = "Attribute: " + each_ga["node"]["attribute_type"]["name"] temp_edit_summ["before"] = each_ga["before_obj_value"] temp_edit_summ["after"] = each_ga["node"]["object_value"] edit_summary.append(temp_edit_summ) teaches_list = request.POST.get('teaches', '') # get the teaches list prev_teaches_list = request.POST.get("teaches_prev", "") # get the before-edit teaches list # check if teaches list exist means nodes added/removed for teaches relation_type # also check for if previous teaches list made empty with prev_teaches_list if (teaches_list != '') or prev_teaches_list: teaches_list = teaches_list.split(",") if teaches_list else [] teaches_list = [ObjectId(each_oid) for each_oid in teaches_list] relation_type_node = node_collection.one({'_type': "RelationType", 'name':'teaches'}) gr_nodes = create_grelation(file_node._id, relation_type_node, teaches_list) gr_nodes_oid_list = [ObjectId(each_oid["right_subject"]) for each_oid in gr_nodes] if gr_nodes else [] prev_teaches_list = prev_teaches_list.split(",") if prev_teaches_list else [] prev_teaches_list = [ObjectId(each_oid) for each_oid in prev_teaches_list] if len(gr_nodes_oid_list) == len(prev_teaches_list) and set(gr_nodes_oid_list) == set(prev_teaches_list): pass else: rel_nodes = triple_collection.find({'_type': "GRelation", 'subject': file_node._id, 'relation_type': relation_type_node._id }) rel_oid_name = {} for each in rel_nodes: temp = {} temp[each.right_subject] = each.name rel_oid_name.update(temp) is_changed = True temp_edit_summ = {} temp_edit_summ["name"] = "Relation: Teaches" temp_edit_summ["before"] = [rel_oid_name[each_oid].split(" -- ")[2] for each_oid in prev_teaches_list] temp_edit_summ["after"] = [rel_oid_name[each_oid].split(" -- ")[2] for each_oid in gr_nodes_oid_list] edit_summary.append(temp_edit_summ) assesses_list = request.POST.get('assesses_list','') if assesses_list != '': assesses_list = assesses_list.split(",") assesses_list = [ObjectId(each_oid) for each_oid in assesses_list] relation_type_node = node_collection.one({'_type': "RelationType", 'name':'assesses'}) gr_nodes = create_grelation(file_node._id, relation_type_node, teaches_list) gr_nodes_oid_list = [ObjectId(each_oid["right_subject"]) for each_oid in gr_nodes] if len(gr_nodes_oid_list) == len(teaches_list) and set(gr_nodes_oid_list) == set(teaches_list): pass else: is_changed = True # changing status to draft even if attributes/relations are changed if is_changed: file_node.status = unicode("DRAFT") file_node.modified_by = userid if userid not in file_node.contributors: file_node.contributors.append(userid) # checking if user is authenticated to change the status of node if status and ((group_obj.is_gstaff(request.user)) or (userid in group_obj.author_set)): if file_node.status != status: file_node.status = unicode(status) file_node.modified_by = userid if userid not in file_node.contributors: file_node.contributors.append(userid) is_changed = True if is_changed: file_node.save(groupid=group_id) # print edit_summary return HttpResponse(file_node.status)
def upload_prof_pic(request, group_id): if request.method == "POST": user = request.POST.get('user', '') if_module = request.POST.get('if_module', '') if if_module == "True": group_id_for_module = request.POST.get('group_id_for_module', '') url_name = request.POST.get('url_name', '') # used for reverse # print "\n\n url_name", url_name group_obj = node_collection.one({'_id': ObjectId(group_id)}) file_uploaded = request.FILES.get("filehive", "") pic_rt = request.POST.get("pic_rt", "") node_id = request.POST.get("node_id", "") # print "\n\n pic_rt === ", pic_rt has_profile_or_banner_rt = None if pic_rt == "is_banner": has_profile_or_banner_rt = node_collection.one({ '_type': 'RelationType', 'name': unicode('has_banner_pic') }) elif pic_rt == "is_profile": has_profile_or_banner_rt = node_collection.one({ '_type': 'RelationType', 'name': unicode('has_profile_pic') }) if pic_rt == "is_thumbnail": # print "================================" has_profile_or_banner_rt = node_collection.one({ '_type': 'RelationType', 'name': unicode('has_thumbnail') }) choose_from_existing_pic = request.POST.get("old_pic_ele", "") warehouse_grp_obj = node_collection.one({ '_type': "Group", 'name': "warehouse" }) if file_uploaded: fileobj = write_files(request, group_id) gs_obj_id = fileobj[0]['_id'] # print "\n\n\nfileobj",gs_obj_id if fileobj: profile_pic_image = node_collection.one( {'_id': ObjectId(gs_obj_id)}) # The 'if' below is required in case file node is deleted but exists in grid_fs if profile_pic_image and not node_id: gr_node = create_grelation(group_obj._id, has_profile_or_banner_rt, profile_pic_image._id) # Move fileobj to "Warehouse" group node_collection.collection.update( {'_id': profile_pic_image._id}, {'$set': { 'group_set': [warehouse_grp_obj._id] }}, upsert=False, multi=False) elif node_id: # print "-----------------------------------------------------------------",node_id gr_node = create_grelation(ObjectId(node_id), has_profile_or_banner_rt, profile_pic_image._id) # Move fileobj to "Warehouse" group node_collection.collection.update( {'_id': profile_pic_image._id}, {'$set': { 'group_set': [warehouse_grp_obj._id] }}, upsert=False, multi=False) else: success_state = False elif choose_from_existing_pic: # update status of old GRelation profile_pic_image = node_collection.one( {'_id': ObjectId(choose_from_existing_pic)}) gr_node = create_grelation(group_obj._id, has_profile_or_banner_rt, profile_pic_image._id) # Move fileobj to "Warehouse" group if warehouse_grp_obj._id not in profile_pic_image.group_set: node_collection.collection.update( {'_id': profile_pic_image._id}, {'$set': { 'group_set': [warehouse_grp_obj._id] }}, upsert=False, multi=False) group_obj.reload() if user: group_id = user if if_module == "True": return HttpResponseRedirect( reverse(str(url_name), kwargs={ 'group_id': ObjectId(group_id_for_module), 'node_id': group_obj._id })) else: return HttpResponseRedirect( reverse(str(url_name), kwargs={'group_id': group_id}))
def parse_data_create_gsystem(json_file_path, file_name): json_file_content = "" try: print "\n file_name == ",file_name with open(json_file_path) as json_file: json_file_content = json_file.read() json_documents_list = json.loads(json_file_content) # Process data in proper format node = node_collection.collection.GSystem() node_keys = node.keys() node_structure = node.structure json_documents_list_spaces = json_documents_list json_documents_list = [] # Removes leading and trailing spaces from keys as well as values for json_document_spaces in json_documents_list_spaces: json_document = {} for key_spaces, value_spaces in json_document_spaces.iteritems(): json_document[key_spaces.strip().lower()] = value_spaces.strip() json_documents_list.append(json_document) except Exception as e: error_message = "\n While parsing the file ("+json_file_path+") got following error...\n " + str(e) log_list.append(error_message) print error_message raise error_message for i, json_document in enumerate(json_documents_list): try: if file_name == "QuizItem.csv": print "\n\n *******************" question_content = json_document['content'] question_content = question_content.split(' ') question_content = question_content[:4] question_content = ' '.join(question_content) json_document['name'] = question_content json_document['altnames'] = json_document['content'] group_id = ObjectId(json_document['group_id']) group_obj = node_collection.one({'_id': group_id}) if group_obj: group_id = group_obj._id else: group_id = home_grp._id user_id = int(json_document['user_id']) print "\n\n NAME ======= ", json_document['name'], group_id, user_id global node_repeated node_repeated = False n_name = "" if "first name" in json_document: n_name = json_document["first name"] + " " if json_document["middle name"]: n_name += json_document["middle name"] if json_document["last name"]: n_name += " " n_name += json_document["last name"] json_document["name"] = n_name.title() info_message = "\n ============ #"+ str(i+1) +" : Start of "+gsystem_type_name+"'s GSystem ("+json_document['name']+") creation/updation ============\n" log_list.append(info_message) parsed_json_document = {} attribute_relation_list = [] for key in json_document.iterkeys(): # print "\n key ",key parsed_key = key.lower() parsed_key = parsed_key.replace(" ", "_") if parsed_key in node_keys: if node_structure[parsed_key] == unicode: parsed_json_document[parsed_key] = unicode(json_document[key]) elif node_structure[parsed_key] == datetime.datetime: parsed_json_document[parsed_key] = datetime.datetime.strptime(json_document[key], "%d/%m/%Y") else: parsed_json_document[parsed_key] = json_document[key] else: parsed_json_document[key] = json_document[key] attribute_relation_list.append(key) info_message = "\n Creating "+gsystem_type_name+" ("+parsed_json_document["name"]+")..." log_list.append(info_message) print "\n HERE == " node = create_edit_gsystem(gsystem_type_id, gsystem_type_name, parsed_json_document, user_id) print "\n node created === ", node._id, " === ", node.name, node.altnames # print "attribute_relation_list == ",attribute_relation_list if node: if not attribute_relation_list: # Neither possible attribute fields, nor possible relations defined for this node info_message = "\n "+gsystem_type_name+" ("+node.name+"): Neither possible attribute fields, nor possible relations defined for this node !\n" log_list.append(info_message) continue gst_possible_attributes_dict = node.get_possible_attributes(gsystem_type_id) print "\n gsystem_type_id ===",gst_possible_attributes_dict relation_list = [] json_document['name'] = node.name # Write code for setting atrributes for key in attribute_relation_list: is_relation = True for attr_key, attr_value in gst_possible_attributes_dict.iteritems(): # print "\n\n attr_key === ", attr_key # print "\n\n altnames -- === ", attr_value['altnames'] if attr_value['altnames'] and key == attr_value['altnames'].lower() or key == attr_key.lower(): is_relation = False if json_document[key]: try: if attr_value['data_type'] == basestring: if u"\u2013" in json_document[key]: json_document[key] = json_document[key].replace(u"\u2013", "-") info_message = "\n For GAttribute parsing content | key: " + attr_key + " -- " + json_document[key] log_list.append(info_message) if attr_value['data_type'] == unicode: json_document[key] = unicode(json_document[key]) elif attr_value['data_type'] == bool: if json_document[key].lower() == "yes": json_document[key] = True elif json_document[key].lower() == "no": json_document[key] = False else: json_document[key] = None elif attr_value['data_type'] == datetime.datetime: # Use small-case altnames if key in ["dob", "date of birth", "date of registration"]: if json_document[key]: json_document[key] = datetime.datetime.strptime(json_document[key], "%d/%m/%Y") else: if json_document[key]: json_document[key] = datetime.datetime.strptime(json_document[key], "%Y") elif attr_value['data_type'] in [int, float, long]: if not json_document[key]: json_document[key] = 0 else: if attr_value['data_type'] == int: json_document[key] = int(json_document[key]) elif attr_value['data_type'] == float: json_document[key] = float(json_document[key]) else: json_document[key] = long(json_document[key]) elif type(attr_value['data_type']) == IS: for op in attr_value['data_type']._operands: if op.lower() == json_document[key].lower(): json_document[key] = op elif (attr_value['data_type'] in [list, dict]) or (type(attr_value['data_type']) in [list, dict]): if "," not in json_document[key]: # Necessary to inform perform_eval_type() that handle this value as list json_document[key] = "\"" + json_document[key] + "\", " else: formatted_value = "" for v in json_document[key].split(","): formatted_value += "\""+v.strip(" ")+"\", " json_document[key] = formatted_value perform_eval_type(key, json_document, "GSystem") subject_id = node._id attribute_type_node = None if attr_key in attr_type_dict: attribute_type_node = attr_type_dict[attr_key] else: attribute_type_node = node_collection.one({ '_type': "AttributeType", '$or': [{ 'name': {'$regex': "^" + attr_key + "$", '$options': 'i'} }, { 'altnames': {'$regex': "^" + attr_key + "$", '$options': 'i'} }] }) attr_type_dict[attr_key] = attribute_type_node object_value = json_document[key] ga_node = None info_message = "\n Creating GAttribute (" + node.name + " -- " + attribute_type_node.name + " -- " + str(json_document[key]) + ") ...\n" log_list.append(info_message) ga_node = create_gattribute(subject_id, attribute_type_node, object_value) except Exception as e: error_message = "\n While creating GAttribute (" + attr_key + ") for "+gsystem_type_name+"'s GSystem ("+json_document['name']+") got following error...\n " + str(e) + "\n" log_list.append(error_message) print error_message # Keep it! # To break outer for loop as key found break else: error_message = "\n DataNotFound: No data found for field ("+attr_key+") while creating GSystem (" + gsystem_type_name + " -- " + node.name + ") !!!\n" log_list.append(error_message) if is_relation: relation_list.append(key) if not relation_list: # No possible relations defined for this node info_message = "\n "+gsystem_type_name+" ("+node.name+"): No possible relations defined for this node !!!\n" log_list.append(info_message) else: gst_possible_relations_dict = node.get_possible_relations(gsystem_type_id) # Write code for setting relations for key in relation_list: is_relation = True for rel_key, rel_value in gst_possible_relations_dict.iteritems(): if key == rel_value['altnames'].lower() or key == rel_key.lower(): is_relation = False if json_document[key]: # Here semi-colon(';') is used instead of comma(',') # Beacuse one of the value may contain comma(',') which causes problem in finding required value in database try: if ";" not in json_document[key]: # Necessary to inform perform_eval_type() that handle this value as list json_document[key] = "\""+json_document[key]+"\", " else: formatted_value = "" for v in json_document[key].split(";"): formatted_value += "\""+v.strip(" ")+"\", " json_document[key] = formatted_value info_message = "\n For GRelation parsing content | key: " + rel_key + " -- " + json_document[key] log_list.append(info_message) perform_eval_type(key, json_document, "GSystem", "GSystem") # for right_subject_id in json_document[key]: subject_id = node._id # Here we are appending list of ObjectIds of GSystemType's type_of field # along with the ObjectId of GSystemType's itself (whose GSystem is getting created) # This is because some of the RelationType's are holding Base class's ObjectId # and not that of the Derived one's # Delibrately keeping GSystemType's ObjectId first in the list # And hence, used $in operator in the query! rel_subject_type = [] rel_subject_type.append(gsystem_type_id) if gsystem_type_node.type_of: rel_subject_type.extend(gsystem_type_node.type_of) relation_type_node = None if rel_key in rel_type_dict: relation_type_node = rel_type_dict[rel_key] else: relation_type_node = node_collection.one({ '_type': "RelationType", '$or': [{ 'name': {'$regex': "^" + rel_key + "$", '$options': 'i'} }, { 'altnames': {'$regex': "^" + rel_key + "$", '$options': 'i'} }], 'subject_type': {'$in': rel_subject_type} }) rel_type_dict[rel_key] = relation_type_node info_message = "\n Creating GRelation ("+node.name+" -- "+rel_key+" -- "+str(json_document[key])+") ...\n" log_list.append(info_message) gr_node = create_grelation(subject_id, relation_type_node, json_document[key]) except Exception as e: error_message = "\n While creating GRelation (" + rel_key + ") for "+gsystem_type_name+"'s GSystem ("+json_document['name']+") got following error...\n" + str(e) + "\n" log_list.append(error_message) pass if college_gst._id in relation_type_node.object_type: # Fetch college node's group id # Append it to node's group_set node_group_set = node.group_set is_group_set_changed = False # Iterate through each college # Find it's corresponding group's ObjectId # Append it to node's group_set for each in json_document[key]: each = ObjectId(each) each_str = str(each) if each_str in college_dict: college_group_id = college_dict[each_str] if college_group_id not in node_group_set: node_group_set.append(college_group_id) is_group_set_changed = True else: # If not found in college_dict # Then find and update college_dict college_node = node_collection.collection.aggregate([{ "$match": {"_id": each} }, { "$project": {"group_id": "$relation_set.has_group"} }]) college_node = college_node["result"] if college_node: college_node = college_node[0] college_group_id = college_node["group_id"] if college_group_id: college_group_id = college_group_id[0][0] college_dict[each_str] = college_group_id node_group_set.append(college_group_id) is_group_set_changed = True # Update node's group_set with updated list # if changed if is_group_set_changed: node_collection.collection.update({ "_id": subject_id }, { "$set": {"group_set": node_group_set} }, upsert=False, multi=False ) # To break outer for loop if key found break else: error_message = "\n DataNotFound: No data found for relation ("+rel_key+") while creating GSystem ("+gsystem_type_name+" -- "+node.name+") !!!\n" log_list.append(error_message) # print error_message break # Create enrollment code (Only for Student) if create_student_enrollment_code and not node_repeated: enrollment_code_at = node_collection.one({ "_type": "AttributeType", "name": "enrollment_code" }) node_exist = node_collection.one({"_id": node._id, "attribute_set.enrollment_code": {"$exists": True}}) if not node_exist: # It means enrollment_code is not set for given student node # Then set it try: college_id = None group_id = None for k, v in college_dict.items(): college_id = ObjectId(k) group_id = ObjectId(v) student_enrollment_code = get_student_enrollment_code(college_id, node._id, json_document["date of registration"], group_id) info_message = "\n Creating GAttribute (" + node.name + " -- " + enrollment_code_at.name + " -- " + str(student_enrollment_code) + ") ...\n" log_list.append(info_message) ga_node = create_gattribute(node._id, enrollment_code_at, student_enrollment_code) except Exception as e: error_message = "\n StudentEnrollmentCreateError: " + str(e) + "!!!" log_list.append(error_message) elif create_private_college_group: # Create a private group for respective college node node_exist = node_collection.one({"_id": node._id, "relation_set.has_group": {"$exists": True}}) if not node_exist: try: info_message = "\n Creating private group for given college (" + node.name + ") via RelationType (has_group)...\n" log_list.append(info_message) college_group, college_group_gr = create_college_group_and_setup_data(node) except Exception as e: error_message = "\n CollegeGroupCreateError: " + str(e) + "!!!" log_list.append(error_message) except Exception as e: error_message = "\n While creating "+gsystem_type_name+"'s GSystem ("+json_document['name']+") got following error...\n " + str(e) log_list.append(error_message) print error_message # Keep it! import sys print "\n ****\n" print 'Error on line {}'.format(sys.exc_info()[-1].tb_lineno)
def lesson_create_edit(request, group_id, unit_group_id=None): ''' creation as well as edit of lessons returns following: { 'success': <BOOL: 0 or 1>, 'unit_hierarchy': <unit hierarchy json>, 'msg': <error msg or objectid of newly created obj> } ''' # parent_group_name, parent_group_id = Group.get_group_name_id(group_id) # parent unit id lesson_id = request.POST.get('lesson_id', None) lesson_language = request.POST.get('sel_lesson_lang', '') unit_id_post = request.POST.get('unit_id', '') lesson_content = request.POST.get('lesson_desc', '') # print "lesson_id: ", lesson_id # print "lesson_language: ", lesson_language # print "unit_id_post: ", unit_id_post unit_group_id = unit_id_post if unit_id_post else unit_group_id # getting parent unit object unit_group_obj = Group.get_group_name_id(unit_group_id, get_obj=True) result_dict = {'success': 0, 'unit_hierarchy': [], 'msg': ''} if request.method == "POST": # lesson name lesson_name = request.POST.get('name', '').strip() if not lesson_name: msg = 'Name can not be empty.' result_dict = {'success': 0, 'unit_hierarchy': [], 'msg': msg} # return HttpResponse(0) # check for uniqueness of name # unit_cs: unit collection_set unit_cs_list = unit_group_obj.collection_set unit_cs_objs_cur = Node.get_nodes_by_ids_list(unit_cs_list) if unit_cs_objs_cur: unit_cs_names_list = [u.name for u in unit_cs_objs_cur] if not lesson_id and unit_cs_objs_cur and lesson_name in unit_cs_names_list: # same name activity # currently following logic was only for "en" nodes. # commented and expecting following in future: # check for uniqueness w.r.t language selected within all sibling lessons's translated nodes # lesson_obj = Node.get_node_by_id(lesson_id) # if lesson_language != lesson_obj.language[0]: # if lesson_language: # language = get_language_tuple(lesson_language) # lesson_obj.language = language # lesson_obj.save() msg = u'Activity with same name exists in lesson: ' + unit_group_obj.name result_dict = {'success': 0, 'unit_hierarchy': [], 'msg': msg} elif lesson_id and ObjectId.is_valid(lesson_id): # Update # getting default, "en" node: if lesson_language != "en": node = translated_node_id = None grel_node = triple_collection.one({ '_type': 'GRelation', 'subject': ObjectId(lesson_id), 'relation_type': rt_translation_of._id, 'language': get_language_tuple(lesson_language), # 'status': 'PUBLISHED' }) if grel_node: # grelation found. # transalated node exists. # edit of existing translated node. # node = Node.get_node_by_id(grel_node.right_subject) # translated_node_id = node._id lesson_id = grel_node.right_subject else: # grelation NOT found. # create transalated node. user_id = request.user.id new_lesson_obj = node_collection.collection.GSystem() new_lesson_obj.fill_gstystem_values( name=lesson_name, content=lesson_content, member_of=gst_lesson_id, group_set=unit_group_obj._id, created_by=user_id, status=u'PUBLISHED') # print new_lesson_obj if lesson_language: language = get_language_tuple(lesson_language) new_lesson_obj.language = language new_lesson_obj.save(groupid=group_id) trans_grel_list = [ObjectId(new_lesson_obj._id)] trans_grels = triple_collection.find({'_type': 'GRelation', \ 'relation_type': rt_translation_of._id,'subject': ObjectId(lesson_id)},{'_id': 0, 'right_subject': 1}) for each_rel in trans_grels: trans_grel_list.append(each_rel['right_subject']) # translate_grel = create_grelation(node_id, rt_translation_of, trans_grel_list, language=language) create_grelation(lesson_id, rt_translation_of, trans_grel_list, language=language) lesson_obj = Node.get_node_by_id(lesson_id) if lesson_obj and (lesson_obj.name != lesson_name): trans_lesson = get_lang_node(lesson_obj._id, lesson_language) if trans_lesson: trans_lesson.name = lesson_name else: lesson_obj.name = lesson_name # if lesson_language: # language = get_language_tuple(lesson_language) # lesson_obj.language = language lesson_obj.save(group_id=group_id) unit_structure = get_unit_hierarchy(unit_group_obj, request.LANGUAGE_CODE) msg = u'Lesson name updated.' result_dict = { 'success': 1, 'unit_hierarchy': unit_structure, 'msg': str(lesson_obj._id) } else: unit_structure = get_unit_hierarchy(unit_group_obj, request.LANGUAGE_CODE) msg = u'Nothing to update.' result_dict = { 'success': 1, 'unit_hierarchy': unit_structure, 'msg': msg } else: # creating a fresh lesson object user_id = request.user.id new_lesson_obj = node_collection.collection.GSystem() new_lesson_obj.fill_gstystem_values(name=lesson_name, content=lesson_content, member_of=gst_lesson_id, group_set=unit_group_obj._id, created_by=user_id, status=u'PUBLISHED') # print new_lesson_obj if lesson_language: language = get_language_tuple(lesson_language) new_lesson_obj.language = language new_lesson_obj.save(groupid=group_id) unit_group_obj.collection_set.append(new_lesson_obj._id) unit_group_obj.save(groupid=group_id) unit_structure = get_unit_hierarchy(unit_group_obj, request.LANGUAGE_CODE) msg = u'Added lesson under lesson: ' + unit_group_obj.name result_dict = { 'success': 1, 'unit_hierarchy': unit_structure, 'msg': str(new_lesson_obj._id) } # return HttpResponse(json.dumps(unit_structure)) # return HttpResponse(1) return HttpResponse(json.dumps(result_dict))
def create_thread(request, group_id, forum_id): ''' Method to create thread ''' forum = node_collection.one({'_id': ObjectId(forum_id)}) # forum_data = { # 'name':forum.name, # 'content':forum.content, # 'created_by':User.objects.get(id=forum.created_by).username # } # print forum_data forum_threads = [] exstng_reply = node_collection.find({ '$and': [{ '_type': 'GSystem' }, { 'prior_node': ObjectId(forum._id) }], 'status': { '$nin': ['HIDDEN'] } }) exstng_reply.sort('created_at') for each in exstng_reply: forum_threads.append((each.name).strip().lower()) if request.method == "POST": colg = node_collection.one({'_id': ObjectId(group_id)}) name = unicode(request.POST.get('thread_name', "")) content_org = request.POST.get('content_org', "") # ------------------- colrep = node_collection.collection.GSystem() colrep.member_of.append(twist_gst._id) # ADDED ON 14th July colrep.access_policy = u"PUBLIC" colrep.url = set_all_urls(colrep.member_of) colrep.prior_node.append(forum._id) colrep.name = name if content_org: colrep.content_org = unicode(content_org) # Required to link temporary files with the current user who is modifying this document usrname = request.user.username filename = slugify(name) + "-" + usrname + "-" colrep.content = content_org usrid = int(request.user.id) colrep.created_by = usrid colrep.modified_by = usrid if usrid not in colrep.contributors: colrep.contributors.append(usrid) colrep.group_set.append(colg._id) colrep.save(groupid=group_id) has_thread_rt = node_collection.one({ "_type": "RelationType", "name": u"has_thread" }) gr = create_grelation(forum._id, has_thread_rt, [colrep._id]) try: '''Code to send notification to all members of the group except those whose notification preference is turned OFF''' link = "http://" + sitename + "/" + str( colg._id) + "/forum/thread/" + str(colrep._id) for each in colg.author_set: bx = User.objects.filter(id=each) if bx: bx = User.objects.get(id=each) else: continue activity = "Added thread" msg = request.user.username + " has added a thread in the forum " + forum.name + " in the group -'" + colg.name + "'\n" + "Please visit " + link + " to see the thread." if bx: auth = node_collection.one({ '_type': 'Author', 'name': unicode(bx.username) }) if colg._id and auth: no_check = forum_notification_status( colg._id, auth._id) else: no_check = True if no_check: ret = set_notif_val(request, colg._id, msg, activity, bx) except Exception, e: print e url_name = "/" + group_id + "/forum/thread/" + str(colrep._id) return HttpResponseRedirect(url_name)
def create_task_at_rt(request, rt_list, at_list, task_node, assign, group_name, group_id): file_id = (request.POST.get("files")) file_name = (request.POST.get("files_name")) for each in rt_list: rel_type_node = node_collection.one({ '_type': "RelationType", 'name': each }) field_value_list = None if rel_type_node["object_cardinality"] > 1: field_value_list = request.POST.get(rel_type_node["name"], "") if "[" in field_value_list and "]" in field_value_list: field_value_list = json.loads(field_value_list) else: field_value_list = request.POST.getlist(rel_type_node["name"]) else: field_value_list = request.POST.getlist(rel_type_node["name"]) # rel_type_node_type = "GRelation" for i, field_value in enumerate(field_value_list): field_value = parse_template_data(rel_type_node.object_type, field_value, field_instance=rel_type_node) field_value_list[i] = field_value task_gs_triple_instance = create_grelation( task_node._id, node_collection.collection.RelationType(rel_type_node), field_value_list) for each in at_list: field_value = [] if request.POST.get(each, ""): attributetype_key = node_collection.find_one({ "_type": 'AttributeType', 'name': each }) subject = task_node._id object_value = "" if each == 'Assignee': if type(assign) == list: object_value = assign else: field_value.append(assign) object_value = field_value else: field_value = request.POST.get(each, "") date_format_string = "" if each in ["start_time", "end_time"]: date_format_string = "%d/%m/%Y" field_value = parse_template_data( eval(attributetype_key["data_type"]), field_value, date_format_string=date_format_string) # newattribute.object_value = field_value object_value = field_value # newattribute.save() ga_node = create_gattribute(subject, attributetype_key, object_value) if request.FILES.getlist('UploadTask'): attributetype_key = node_collection.find_one({ "_type": 'AttributeType', 'name': 'Upload_Task' }) ga_node = create_gattribute(task_node._id, attributetype_key, file_id) assignee_list = [] assignee_list_id = [] if type(assign) == list: assignee_list_id = assign else: assignee_list_id.append(assign) user_to_be_notified = [] if assignee_list_id: for eachuser in assignee_list_id: if eachuser: bx = User.objects.get(id=int(eachuser)) assignee_list.append(bx.username) user_to_be_notified.append(bx) for eachuser in user_to_be_notified: activ = "Task reported" msg = "Task '" + task_node.name + \ "' has been reported by " + request.user.username + \ "\n - Status: " + request.POST.get('Status', '') + \ "\n - Assignee: " + ", ".join(assignee_list) + \ "\n - Url: http://" + site_domain + "/" + group_name.replace(" ","%20").encode('utf8') + "/task/" + str(task_node._id) set_notif_val(request, group_id, msg, activ, eachuser)
def person_create_edit(request, group_id, app_id, app_set_id=None, app_set_instance_id=None, app_name=None): """ Creates/Modifies document of given person-type. """ auth = None if ObjectId.is_valid(group_id) is False : group_ins = node_collection.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 app = None if app_id is None: app = node_collection.one({'_type': "GSystemType", 'name': app_name}) if app: app_id = str(app._id) else: app = node_collection.one({'_id': ObjectId(app_id)}) app_name = app.name # app_name = "mis" app_set = "" app_collection_set = [] title = "" person_gst = None person_gs = None college_node = None college_id = None student_enrollment_code = u"" create_student_enrollment_code = False existing_colg = [] registration_date = None property_order_list = [] template = "" template_prefix = "mis" if request.user: if auth is None: auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username)}) agency_type = auth.agency_type agency_type_node = node_collection.one({'_type': "GSystemType", 'name': agency_type}, {'collection_set': 1}) if agency_type_node: for eachset in agency_type_node.collection_set: app_collection_set.append(node_collection.one({"_id": eachset}, {'_id': 1, 'name': 1, 'type_of': 1})) # for eachset in app.collection_set: # app_collection_set.append(node_collection.one({"_id":eachset}, {'_id': 1, 'name': 1, 'type_of': 1})) college_node = node_collection.one({ "_id": ObjectId(group_id), "relation_set.group_of": {"$exists": True} }, { "relation_set.group_of": 1 }) if app_set_id: person_gst = node_collection.one({'_type': "GSystemType", '_id': ObjectId(app_set_id)}, {'name': 1, 'type_of': 1}) template = "ndf/" + person_gst.name.strip().lower().replace(' ', '_') + "_create_edit.html" title = person_gst.name person_gs = node_collection.collection.GSystem() person_gs.member_of.append(person_gst._id) if app_set_instance_id: person_gs = node_collection.one({'_type': "GSystem", '_id': ObjectId(app_set_instance_id)}) property_order_list = get_property_order_with_value(person_gs)#.property_order if request.method == "POST": if person_gst.name == "Student" and "_id" not in person_gs: create_student_enrollment_code = True # [A] Save person-node's base-field(s) is_changed = get_node_common_fields(request, person_gs, group_id, person_gst) if is_changed: # Remove this when publish button is setup on interface person_gs.status = u"PUBLISHED" person_gs.save(is_changed=is_changed,groupid=group_id) for each_rel in person_gs.relation_set: if each_rel and "officer_incharge_of" in each_rel: existing_colg = each_rel["officer_incharge_of"] if college_node: mis_admin = node_collection.one({ "_type": "Group", "name": "MIS_admin" }, { "_id": 1 } ) node_collection.collection.update({ "_id": person_gs._id }, { "$addToSet": {"group_set": mis_admin._id} }, upsert=False, multi=False ) # [B] Store AT and/or RT field(s) of given person-node (i.e., person_gs) for tab_details in property_order_list: for field_set in tab_details[1]: # Fetch only Attribute field(s) / Relation field(s) if '_id' in field_set: field_instance = node_collection.one({'_id': field_set['_id']}) fi_name = field_instance["name"] field_instance_type = type(field_instance) if field_instance_type in [AttributeType, RelationType]: field_data_type = field_set['data_type'] # Fetch field's value depending upon AT/RT and Parse fetched-value depending upon that field's data-type if field_instance_type == AttributeType: if "File" in field_instance["validators"]: # Special case: AttributeTypes that require file instance as it's value in which case file document's ObjectId is used user_id = request.user.id if fi_name in request.FILES: field_value = request.FILES[fi_name] else: field_value = "" # Below 0th index is used because that function returns tuple(ObjectId, bool-value) if field_value != '' and field_value != u'': file_name = person_gs.name + " -- " + field_instance["altnames"] content_org = "" tags = "" field_value = save_file(field_value, file_name, user_id, group_id, content_org, tags, access_policy="PRIVATE", count=0, first_object="", oid=True)[0] else: # Other AttributeTypes if fi_name in request.POST: field_value = request.POST[fi_name] # field_instance_type = "GAttribute" if fi_name in ["12_passing_year", "degree_passing_year"]: #, "registration_year"]: field_value = parse_template_data(field_data_type, field_value, date_format_string="%Y") elif fi_name in ["dob", "registration_date"]: field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y") registration_date = field_value else: field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y %H:%M") if field_value: person_gs_triple_instance = create_gattribute(person_gs._id, node_collection.collection.AttributeType(field_instance), field_value) else: if field_instance["object_cardinality"] > 1: field_value_list = request.POST.get(fi_name, "") if "[" in field_value_list and "]" in field_value_list: field_value_list = json.loads(field_value_list) else: field_value_list = request.POST.getlist(fi_name) else: field_value_list = request.POST.getlist(fi_name) if META_TYPE[3] in field_instance.member_of_names_list: # If Binary relationship found # [id, id, ...] # field_instance_type = "GRelation" for i, field_value in enumerate(field_value_list): field_value = parse_template_data(field_data_type, field_value, field_instance=field_instance, date_format_string="%m/%d/%Y %H:%M") field_value_list[i] = field_value else: # Relationship Other than Binary one found; e.g, Triadic # [[id, id, ...], [id, id, ...], ...] # field_instance_type = "GRelation" for i, field_value_inner_list in enumerate(field_value_list): for j, field_value in enumerate(field_value_inner_list): field_value = parse_template_data(field_data_type, field_value, field_instance=field_instance, date_format_string="%m/%d/%Y %H:%M") field_value_list[i][j] = field_value person_gs_triple_instance = create_grelation(person_gs._id, node_collection.collection.RelationType(field_instance), field_value_list) # Setting enrollment code for student node only while creating it if create_student_enrollment_code: # Create enrollment code for student node only while registering a new node for rel in college_node.relation_set: if rel and "group_of" in rel: college_id = rel["group_of"][0] student_enrollment_code = get_student_enrollment_code(college_id, person_gs._id, registration_date, ObjectId(group_id)) enrollment_code_at = node_collection.one({ "_type": "AttributeType", "name": "enrollment_code" }) try: ga_node = create_gattribute(person_gs._id, enrollment_code_at, student_enrollment_code) except Exception as e: print "\n StudentEnrollmentCreateError: " + str(e) + "!!!" # [C] Code to link GSystem Node and Author node via "has_login" relationship; # and Subscribe the Author node to College group if user "Program Officer" person_gs.reload() auth_node = None for attr in person_gs.attribute_set: if "email_id" in attr: if attr["email_id"]: auth_node = node_collection.one({'_type': "Author", 'email': attr["email_id"].lower()}) break if auth_node: has_login_rt = node_collection.one({'_type': "RelationType", 'name': "has_login"}) if has_login_rt: # Linking GSystem Node and Author node via "has_login" relationship; gr_node = create_grelation(person_gs._id, has_login_rt, auth_node._id) # Set author_agency field's value of author node as "Program Officer" # Required to identify at time of log-in in order to display # required modules defined for Program Officers under MIS GApp if auth_node.agency_type != u"Program Officer": auth_node.agency_type = u"Program Officer" auth_node.save(groupid=group_id) if "Program Officer" in person_gs.member_of_names_list: # If Person node (GSystem) is of Program Officer type # then only go for subscription college_id_list = [] # Fetch College's ObjectId to which Program Officer is assigned (via "officer_incharge_of") for rel in person_gs.relation_set: if "officer_incharge_of" in rel: if rel["officer_incharge_of"]: for college_id in rel["officer_incharge_of"]: if college_id not in college_id_list: college_id_list.append(college_id) break # break outer-loop (of relation_set) if college_id_list: # If College's ObjectId exists (list as PO might be assigned to more than one college) # Then prepare a list of their corresponding private group(s) (via "has_group") college_cur = node_collection.find( {'_id': {'$in': college_id_list}}, {'relation_set.has_group': 1} ) college_group_id_list = [] for college in college_cur: for rel in college.relation_set: if rel and "has_group" in rel: if rel["has_group"]: if rel["has_group"][0] not in college_group_id_list: college_group_id_list.append(rel["has_group"][0]) break # break inner-loop (college.relation_set) if college_group_id_list: # If college-group list exists # Then update their group_admin field (append PO's created_by) res = node_collection.collection.update( {'_id': {'$in': college_group_id_list}}, {'$addToSet': {'group_admin': auth_node.created_by}}, upsert=False, multi=True ) old_college_id_list = [] if existing_colg: if len(existing_colg) > len(college_id_list): for each_colg_id in existing_colg: if each_colg_id not in college_id_list: old_college_id_list.append(each_colg_id) old_college_cur = node_collection.find( {'_id': {'$in': old_college_id_list}}, {'relation_set.has_group': 1} ) old_college_group_id_list = [] for college in old_college_cur: for rel in college.relation_set: if rel and "has_group" in rel: if rel["has_group"]: if rel["has_group"][0] not in old_college_group_id_list: old_college_group_id_list.append(rel["has_group"][0]) break # break inner-loop (college.relation_set) if old_college_group_id_list: # If college-group list exists # Then update their group_admin field (remove PO's created_by) res = node_collection.collection.update( {'_id': {'$in': old_college_group_id_list}, '$or': [{'group_admin': auth_node.created_by}, {'author_set': auth_node.created_by}]}, {'$pull': {'group_admin': auth_node.created_by, 'author_set': auth_node.created_by}}, upsert=False, multi=True ) # The code below is commented as the college groups are PRIVATE. # for rel in person_gs.relation_set: # if rel and "officer_incharge_of" in rel: # pass # else: # node_collection.collection.update({'_id': auth_node._id}, # {'$set': {'agency_type': u"Other"}}, # upsert=False, multi=False # ) # Its purpose is to change the agency type back to Other auth_node.reload() # if person_gst.name != "Student": # return HttpResponseRedirect(reverse(app_name.lower()+":"+template_prefix+'_app_detail', kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id})) # else: return HttpResponseRedirect(reverse('mis:mis_app_instance_detail',kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id, "app_set_instance_id":unicode(person_gs._id)})) # return HttpResponseRedirect(reverse(app_name.lower()+":"+template_prefix+'_app_detail', kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id})) default_template = "ndf/person_create_edit.html" # default_template = "ndf/"+template_prefix+"_create_edit.html" context_variables = { 'groupid': group_id, 'group_id': group_id, 'app_id': app_id, 'app_name': app_name, 'app_collection_set': app_collection_set, 'app_set_id': app_set_id, 'title':title, 'property_order_list': property_order_list } if person_gst and person_gst.name in ["Voluntary Teacher", "Master Trainer"]: nussd_course_type = node_collection.one({'_type': "AttributeType", 'name': "nussd_course_type"}, {'_type': 1, '_id': 1, 'data_type': 1, 'complex_data_type': 1, 'name': 1, 'altnames': 1}) if nussd_course_type["data_type"] == "IS()": # Below code does little formatting, for example: # data_type: "IS()" complex_value: [u"ab", u"cd"] dt: # "IS(u'ab', u'cd')" dt = "IS(" for v in nussd_course_type.complex_data_type: dt = dt + "u'" + v + "'" + ", " dt = dt[:(dt.rfind(", "))] + ")" nussd_course_type["data_type"] = dt nussd_course_type["data_type"] = eval(nussd_course_type["data_type"]) nussd_course_type["value"] = None context_variables['nussd_course_type'] = nussd_course_type if app_set_instance_id: person_gs.get_neighbourhood(person_gs.member_of) if "trainer_teaches_course_in_college" in person_gs: l = [] for each_course_college in person_gs.trainer_teaches_course_in_college: # Fetch Course Type (i.e. nussd_course_type) ct = "" for each_attr in each_course_college[0].attribute_set: if "nussd_course_type" in each_attr and each_attr: ct = each_attr["nussd_course_type"] break univ_name = "" for each_rel in each_course_college[1].relation_set: if "college_affiliated_to" in each_rel and each_rel: univ = node_collection.find_one({"_id": {"$in": each_rel["college_affiliated_to"]}}) univ_name = univ.name if univ else "" l.append(( ct, each_course_college[0].name, each_course_college[1].name, each_course_college[0]._id.__str__(), each_course_college[1]._id.__str__(), univ_name )) if l: person_gs.trainer_teaches_course_in_college = l context_variables['node'] = person_gs try: return render_to_response([template, default_template], context_variables, context_instance = RequestContext(request) ) except TemplateDoesNotExist as tde: error_message = "\n PersonCreateEditViewError: This html template (" + str(tde) + ") does not exists !!!\n" raise Http404(error_message) except Exception as e: error_message = "\n PersonCreateEditViewError: " + str(e) + " !!!\n" raise Exception(error_message)
def parse_data_create_gsystem(json_file_path): json_file_content = "" try: with open(json_file_path) as json_file: json_file_content = json_file.read() json_documents_list = json.loads(json_file_content) # Initiating empty node obj and other related data variables node = node_collection.collection.File() node_keys = node.keys() node_structure = node.structure # print "\n\n---------------", node_keys json_documents_list_spaces = json_documents_list json_documents_list = [] # Removes leading and trailing spaces from keys as well as values for json_document_spaces in json_documents_list_spaces: json_document = {} for key_spaces, value_spaces in json_document_spaces.iteritems(): json_document[key_spaces.strip().lower()] = value_spaces.strip() json_documents_list.append(json_document) except Exception as e: error_message = "\n!! While parsing the file ("+json_file_path+") got following error...\n " + str(e) log_print(error_message) raise error_message for i, json_document in enumerate(json_documents_list): info_message = "\n\n\n********** Processing row number : ["+ str(i + 2) + "] **********" log_print(info_message) try: parsed_json_document = {} attribute_relation_list = [] for key in json_document.iterkeys(): parsed_key = key.lower() if parsed_key in node_keys: # print parsed_key # adding the default field values e.g: created_by, member_of # created_by: if parsed_key == "created_by": if json_document[key]: temp_user_id = get_user_id(json_document[key].strip()) if temp_user_id: parsed_json_document[parsed_key] = temp_user_id else: parsed_json_document[parsed_key] = nroer_team_id else: parsed_json_document[parsed_key] = nroer_team_id # print "---", parsed_json_document[parsed_key] # contributors: elif parsed_key == "contributors": if json_document[key]: contrib_list = json_document[key].split(",") temp_contributors = [] for each_user in contrib_list: user_id = get_user_id(each_user.strip()) if user_id: temp_contributors.append(user_id) parsed_json_document[parsed_key] = temp_contributors else: parsed_json_document[parsed_key] = [nroer_team_id] # print "===", parsed_json_document[parsed_key] # tags: elif (parsed_key == "tags") and json_document[key]: parsed_json_document[parsed_key] = cast_to_data_type(json_document[key], node_structure.get(parsed_key)) # print parsed_json_document[parsed_key] # member_of: elif parsed_key == "member_of": parsed_json_document[parsed_key] = [file_gst._id] # print parsed_json_document[parsed_key] # --- END of adding the default field values else: # parsed_json_document[parsed_key] = json_document[key] parsed_json_document[parsed_key] = cast_to_data_type(json_document[key], node_structure.get(parsed_key)) # print parsed_json_document[parsed_key] # --- END of processing for remaining fields else: # key is not in the node_keys parsed_json_document[key] = json_document[key] attribute_relation_list.append(key) # print "key : ", key # --END of for loop --- # calling method to create File GSystems node_obj = create_resource_gsystem(parsed_json_document, i) nodeid = node_obj._id if node_obj else None # print "nodeid : ", nodeid # ----- for updating language ----- node_lang = get_language_tuple(eval(parsed_json_document['language'])) # print "============= :", node_lang # print "============= lang :", node_obj.language if node_obj and node_obj.language != node_lang: update_res = node_collection.collection.update( {'_id': ObjectId(nodeid), 'language': {'$ne': node_lang}}, {'$set': {'language': node_lang}}, upsert=False, multi=False ) if update_res['updatedExisting']: node_obj.reload() info_message = "\n\n- Update to language of resource: " + str(update_res) log_print(info_message) info_message = "\n\n- Now language of resource updates to: " + str(node_obj.language) log_print(info_message) # print "============= lang :", node_obj.language # ----- END of updating language ----- collection_name = parsed_json_document.get('collection', '') if collection_name and nodeid: collection_node = node_collection.find_one({ # '_type': 'File', 'member_of': {'$in': [file_gst._id]}, 'group_set': {'$in': [home_group._id]}, 'name': unicode(collection_name) }) if collection_node: add_to_collection_set(collection_node, nodeid) thumbnail_url = parsed_json_document.get('thumbnail') # print "thumbnail_url : ", thumbnail_url if thumbnail_url and nodeid: try: info_message = "\n\n- Attaching thumbnail to resource\n" log_print(info_message) attach_resource_thumbnail(thumbnail_url, nodeid, parsed_json_document, i) except Exception, e: print e # print type(nodeid), "-------", nodeid, "\n" # create thread node if isinstance(nodeid, ObjectId): thread_result = create_thread_obj(nodeid) # starting processing for the attributes and relations saving if isinstance(nodeid, ObjectId) and attribute_relation_list: node = node_collection.one({ "_id": ObjectId(nodeid) }) gst_possible_attributes_dict = node.get_possible_attributes(file_gst._id) # print gst_possible_attributes_dict relation_list = [] json_document['name'] = node.name # Write code for setting atrributes for key in attribute_relation_list: is_relation = True # print "\n", key, "----------\n" for attr_key, attr_value in gst_possible_attributes_dict.iteritems(): # print "\n", attr_key,"======", attr_value if key == attr_key: # print key is_relation = False # setting value to "0" for int, float, long (to avoid casting error) # if (attr_value['data_type'] in [int, float, long]) and (not json_document[key]): # json_document[key] = 0 if json_document[key]: # print "key : ", key, "\nvalue : ",json_document[key] info_message = "\n- For GAttribute parsing content | key: '" + attr_key + "' having value: '" + json_document[key] + "'" log_print(info_message) cast_to_data_type(json_document[key], attr_value['data_type']) if attr_value['data_type'] == "curricular": # setting int values for CR/XCR if json_document[key] == "CR": json_document[key] = 1 elif json_document[key] == "XCR": json_document[key] = 0 else: # needs to be confirm json_document[key] = 0 # json_document[key] = bool(int(json_document[key])) # print attr_value['data_type'], "@@@@@@@@@ : ", json_document[key] json_document[key] = cast_to_data_type(json_document[key], attr_value['data_type']) # print key, " !!!!!!!!! : ", json_document[key] subject_id = node._id # print "\n-----\nsubject_id: ", subject_id attribute_type_node = node_collection.one({ '_type': "AttributeType", '$or': [ {'name': {'$regex': "^"+attr_key+"$", '$options': 'i'} }, {'altnames': {'$regex': "^"+attr_key+"$", '$options': 'i'} } ] }) # print "\nattribute_type_node: ", attribute_type_node.name object_value = json_document[key] # print "\nobject_value: ", object_value ga_node = None info_message = "\n- Creating GAttribute ("+node.name+" -- "+attribute_type_node.name+" -- "+str(json_document[key])+") ...\n" log_print(info_message) ga_node = create_gattribute(subject_id, attribute_type_node, object_value) info_message = "- Created ga_node : "+ str(ga_node.name) + "\n" log_print(info_message) # To break outer for loop as key found break else: error_message = "\n!! DataNotFound: No data found for field ("+str(attr_key)+") while creating GSystem ( -- "+str(node.name)+")\n" log_print(error_message) # ---END of if (key == attr_key) if is_relation: relation_list.append(key) if not relation_list: # No possible relations defined for this node info_message = "\n!! ("+str(node.name)+"): No possible relations defined for this node.\n" log_print(info_message) return gst_possible_relations_dict = node.get_possible_relations(file_gst._id) # processing each entry in relation_list # print "=== relation_list : ", relation_list for key in relation_list: is_relation = True for rel_key, rel_value in gst_possible_relations_dict.iteritems(): if key == rel_key: # if key == "teaches": is_relation = False if json_document[key]: # most often the data is hierarchy sep by ":" if ":" in json_document[key]: formatted_list = [] temp_teaches_list = json_document[key].replace("\n", "").split(":") # print "\n temp_teaches", temp_teaches for v in temp_teaches_list: formatted_list.append(v.strip()) right_subject_id = [] # print "~~~~~~~~~~~", formatted_list # rsub_id = _get_id_from_hierarchy(formatted_list) rsub_id = get_id_from_hierarchy(formatted_list) # print "=== rsub_id : ", rsub_id hierarchy_output = None # checking every item in hierarchy exist and leaf node's _id found if rsub_id: right_subject_id.append(rsub_id) json_document[key] = right_subject_id # print json_document[key] else: error_message = "\n!! While creating teaches rel: Any one of the item in hierarchy"+ str(json_document[key]) +"does not exist in Db. \n!! So relation: " + str(key) + " cannot be created.\n" log_print(error_message) break # sometimes direct leaf-node may be present without hierarchy and ":" else: formatted_list = list(json_document[key].strip()) right_subject_id = [] right_subject_id.append(_get_id_from_hierarchy(formatted_list)) json_document[key] = right_subject_id # print "\n----------", json_document[key] info_message = "\n- For GRelation parsing content | key: " + str(rel_key) + " -- " + str(json_document[key]) log_print(info_message) # print list(json_document[key]) # perform_eval_type(key, json_document, "GSystem", "GSystem") for right_subject_id in json_document[key]: # print "\njson_document[key]: ", json_document[key] subject_id = node._id # print "subject_id : ", subject_id # print "node.name: ", node.name # Here we are appending list of ObjectIds of GSystemType's type_of field # along with the ObjectId of GSystemType's itself (whose GSystem is getting created) # This is because some of the RelationType's are holding Base class's ObjectId # and not that of the Derived one's # Delibrately keeping GSystemType's ObjectId first in the list # And hence, used $in operator in the query! rel_subject_type = [] rel_subject_type.append(file_gst._id) if file_gst.type_of: rel_subject_type.extend(file_gst.type_of) relation_type_node = node_collection.one({'_type': "RelationType", '$or': [{'name': {'$regex': "^"+rel_key+"$", '$options': 'i'}}, {'altnames': {'$regex': "^"+rel_key+"$", '$options': 'i'}}], 'subject_type': {'$in': rel_subject_type} }) right_subject_id_or_list = [] right_subject_id_or_list.append(ObjectId(right_subject_id)) nodes = triple_collection.find({'_type': "GRelation", 'subject': subject_id, 'relation_type.$id': relation_type_node._id }) # sending list of all the possible right subject to relation for n in nodes: if not n.right_subject in right_subject_id_or_list: right_subject_id_or_list.append(n.right_subject) info_message = "\n- Creating GRelation ("+ str(node.name)+ " -- "+ str(rel_key)+ " -- "+ str(right_subject_id_or_list)+") ..." log_print(info_message) gr_node = create_grelation(subject_id, relation_type_node, right_subject_id_or_list) info_message = "\n- Grelation processing done.\n" log_print(info_message) # To break outer for loop if key found break else: error_message = "\n!! DataNotFound: No data found for relation ("+ str(rel_key)+ ") while creating GSystem (" + str(file_gst.name) + " -- " + str(node.name) + ")\n" log_print(error_message) break # print relation_list else: info_message = "\n!! Either resource is already created or file is already saved into filehive/DB or file not found" log_print(info_message) continue except Exception as e: error_message = "\n While creating ("+str(json_document['name'])+") got following error...\n " + str(e) print "!!!!!!!!!!!!EEEEEEEERRRRRRRRRRRRRROOOOOOORRRRRRRRRRRRR......................" # file_error_msg = "\nFile with following details got an error: \n" file_error_msg = "\n========================" + " Row No : " + str(i + 2) + " ========================\n" # file_error_msg += "- Row No : " + str(i + 2) + "\n" file_error_msg += "- Name : " + json_document["name"] + "\n" file_error_msg += "- File Name: " + json_document["file_name"] + "\n" file_error_msg += "- ERROR : " + str(e) + "\n\n" file_error_msg += "- Following are the row details : \n\n" + unicode(json.dumps(json_document, sort_keys=True, indent=4, ensure_ascii=False)) + "\n" file_error_msg += "============================================================\n\n\n" log_error_rows.append(file_error_msg) log_print(error_message)
def translate(request, group_id, node_id, lang, translated_node_id=None, **kwargs): ''' for EDIT: translate provided node to provided LANG CODE lang could be either proper/full language-name/language-code `node_id` is _id of source node. ''' group_name, group_id = Group.get_group_name_id(group_id) language = get_language_tuple(lang) source_obj = Node.get_node_by_id(node_id) existing_grel = translate_grel = translated_node = None if translated_node_id: translated_node = Node.get_node_by_id(translated_node_id) else: # get translated_node existing_grel = triple_collection.one({ '_type': 'GRelation', 'subject': ObjectId(node_id), 'relation_type': rt_translation_of._id, 'language': language }) if existing_grel: # get existing translated_node translated_node = Node.get_node_by_id(existing_grel.right_subject) translate_grel = existing_grel if request.method == 'GET': return render_to_response("ndf/translate_form.html", { 'group_id': group_id, 'node_obj': translated_node, 'source_obj': source_obj, 'post_url': reverse('translate', kwargs={ 'group_id': group_id, 'node_id': node_id, 'lang': lang, }), 'cancel_url': reverse('show_translation', kwargs={ 'group_id': group_id, 'node_id': node_id, 'lang': lang, }) }, context_instance=RequestContext(request)) elif request.method == 'POST': # explicit `if` check for `POST` if not translated_node: # create a new translated new # translated_node = node_collection.collection.GSystem() # copy source_obj's data into a new if source_obj._type == "Group": translated_node = node_collection.collection.GSystem() exclude_fields = [ '_id', 'member_of', '_type', 'type_of', 'modified_by', 'prior_node', 'post_node' ] for each in translated_node: if each not in exclude_fields: translated_node[each] = source_obj[each] translated_node.group_set.append(source_obj._id) else: translated_node = source_obj.__deepcopy__() translated_node['_id'] = ObjectId() translated_node.fill_gstystem_values(request=request, language=language, **kwargs) trans_alt_name = request.POST.get('altnames', None) translated_node.altnames = unicode(trans_alt_name) translated_node.member_of = [ObjectId(trans_node_gst_id)] translated_node.save(group_id=group_id) if not existing_grel: trans_grel_list = [ObjectId(translated_node._id)] trans_grels = triple_collection.find({'_type': 'GRelation', \ 'relation_type': rt_translation_of._id,'subject': ObjectId(node_id)},{'_id': 0, 'right_subject': 1}) for each_rel in trans_grels: trans_grel_list.append(each_rel['right_subject']) translate_grel = create_grelation(node_id, rt_translation_of, trans_grel_list, language=language) # page_gst_name, page_gst_id = Node.get_name_id_from_type('Page', 'GSystemType') # return HttpResponseRedirect(reverse('page_details', kwargs={'group_id': group_id, 'app_id': page_gst_id })) # return HttpResponseRedirect(reverse('all_translations', kwargs={'group_id': group_id, 'node_id': node_id })) return HttpResponseRedirect( reverse('show_translation', kwargs={ 'group_id': group_id, 'node_id': node_id, 'lang': lang }))
def update(request,rt_list,at_list,task_node,group_id,group_name): file_id=(request.POST.get("files")) file_name=(request.POST.get("files_name")) user_to_be_notified = [] assignee_list = [] change_list = [] for each in rt_list: rel_type_node = node_collection.one({'_type': "RelationType", 'name': each}) field_value_list = None if rel_type_node["object_cardinality"] > 1: field_value_list = request.POST.get(rel_type_node["name"], "") if "[" in field_value_list and "]" in field_value_list: field_value_list = json.loads(field_value_list) else: field_value_list = request.POST.getlist(rel_type_node["name"]) else: field_value_list = request.POST.getlist(rel_type_node["name"]) for i, field_value in enumerate(field_value_list): field_value = parse_template_data(rel_type_node.object_type, field_value, field_instance=rel_type_node) field_value_list[i] = field_value old_value = [] for rel in task_node.relation_set: for k in rel: if rel_type_node.name == k: vals_cur = node_collection.find({'_id': {'$in': rel[k]}}, {'name': 1}) for v_node in vals_cur: old_value.append(v_node.name) break new_value = [] vals_cur = node_collection.find({'_id': {'$in': field_value_list}}, {'name': 1}) for v_node in vals_cur: new_value.append(v_node.name) break if old_value != new_value: change_list.append(each.encode('utf8') + ' changed from ' + ", ".join(old_value) + ' to ' + ", ".join(new_value)) # updated details task_gs_triple_instance = create_grelation(task_node._id, node_collection.collection.RelationType(rel_type_node), field_value_list) task_node.reload() for each in at_list: if request.POST.get(each, ""): attributetype_key = node_collection.find_one({"_type": 'AttributeType', 'name': each}) attr = triple_collection.find_one({"_type": "GAttribute", "subject": task_node._id, "attribute_type": attributetype_key._id}) if each == "Assignee": field_value = request.POST.getlist(each, "") for i, val in enumerate(field_value): field_value[i] = int(val) assignee_list_id = field_value for eachuser in assignee_list_id: bx = User.objects.get(id=int(eachuser)) if bx: if bx.username not in assignee_list: assignee_list.append(bx.username) # Adding to list which holds user's to be notified about the task if bx not in user_to_be_notified: user_to_be_notified.append(bx) else: field_value = request.POST.get(each, "") date_format_string = "" if each in ["start_time", "end_time"]: date_format_string = "%d/%m/%Y" field_value = parse_template_data(eval(attributetype_key["data_type"]), field_value, date_format_string=date_format_string) if attr: # already attribute exist if not attr.object_value == field_value: # change_list.append(each.encode('utf8')+' changed from '+attr.object_value.encode('utf8')+' to '+request.POST.get(each,"").encode('utf8')) # updated details if attributetype_key["data_type"] == "datetime.datetime": change_list.append(each.encode('utf8')+' changed from ' + attr.object_value.strftime("%d/%m/%Y") + ' to ' + field_value.strftime("%d/%m/%Y")) # updated details else: change_list.append(each.encode('utf8')+' changed from ' + str(attr.object_value) + ' to ' + str(field_value)) # updated details attr.object_value = field_value attr.save(groupid=group_id) else: # attributetype_key = node_collection.find_one({"_type":'AttributeType', 'name':each}) # newattribute = triple_collection.collection.GAttribute() # newattribute.subject = task_node._id # newattribute.attribute_type = attributetype_key # newattribute.object_value = request.POST.get(each,"") # newattribute.object_value = field_value # newattribute.save() ga_node = create_gattribute(task_node._id, attributetype_key, field_value) # change_list.append(each.encode('utf8')+' set to '+request.POST.get(each,"").encode('utf8')) # updated details change_list.append(each.encode('utf8')+' set to '+str(field_value)) # updated details elif each == 'Upload_Task': attributetype_key = node_collection.find_one({"_type": 'AttributeType', 'name': 'Upload_Task'}) attr = triple_collection.find_one({"_type": "GAttribute", "subject": task_node._id, "attribute_type": attributetype_key._id}) if attr: value=get_file_node(attr.object_value) change_list.append(each.encode('utf8')+' changed from '+str(value).strip('[]')+' to '+str(file_name)) # attr.object_value=file_id # attr.save() ga_node = create_gattribute(attr.subject, attributetype_key, file_id) else: # newattribute = node_collection.collection.GAttribute() # newattribute.subject = task_node._id # newattribute.attribute_type = attributetype_key # newattribute.object_value = file_id # newattribute.save() ga_node = create_gattribute(task_node._id, attributetype_key, file_id) change_list.append(each.encode('utf8')+' set to '+file_name.encode('utf8')) # updated details # userobj = User.objects.get(id=task_node.created_by) # if userobj and userobj not in user_to_be_notified: # user_to_be_notified.append(userobj) for each_author in task_node.author_set: each_author = User.objects.get(id=each_author) if each_author and each_author not in user_to_be_notified: user_to_be_notified.append(each_author) # Sending notification to all watchers about the updates of the task for eachuser in user_to_be_notified: activ="task updated" msg = "Task '" + task_node.name + \ "' has been updated by " + request.user.username + \ "\n - Changes: " + str(change_list).strip('[]') + \ "\n - Status: " + request.POST.get('Status','') + \ "\n - Assignee: " + ", ".join(assignee_list) + \ "\n - Url: http://" + site_domain + "/" + group_name.replace(" ","%20").encode('utf8') + "/task/" + str(task_node._id) bx=User.objects.get(username=eachuser) set_notif_val(request,group_id,msg,activ,bx) if change_list or content_org: GST_task_update_history = node_collection.one({'_type': "GSystemType", 'name': 'task_update_history'}) update_node = node_collection.collection.GSystem() get_node_common_fields(request, update_node, group_id, GST_task_update_history) if change_list: update_node.altnames = unicode(str(change_list)) else: update_node.altnames = unicode('[]') update_node.prior_node = [task_node._id] update_node.name = unicode(task_node.name+"-update_history") update_node.save(groupid=group_id) update_node.name = unicode(task_node.name+"-update_history-"+str(update_node._id)) update_node.save(groupid=group_id) task_node.post_node.append(update_node._id) task_node.save(groupid=group_id) # patch GST_TASK = node_collection.one({'_type': "GSystemType", 'name': 'Task'}) get_node_common_fields(request, task_node, group_id, GST_TASK) task_node.save(groupid=group_id)
def person_create_edit(request, group_id, app_id, app_set_id=None, app_set_instance_id=None, app_name=None): """ Creates/Modifies document of given person-type. """ auth = None if ObjectId.is_valid(group_id) is False: group_ins = node_collection.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 app = None if app_id is None: app = node_collection.one({'_type': "GSystemType", 'name': app_name}) if app: app_id = str(app._id) else: app = node_collection.one({'_id': ObjectId(app_id)}) app_name = app.name # app_name = "mis" app_set = "" app_collection_set = [] title = "" person_gst = None person_gs = None college_node = None college_id = None student_enrollment_code = u"" create_student_enrollment_code = False existing_colg = [] registration_date = None property_order_list = [] template = "" template_prefix = "mis" if request.user: if auth is None: auth = node_collection.one({ '_type': 'Author', 'name': unicode(request.user.username) }) agency_type = auth.agency_type agency_type_node = node_collection.one( { '_type': "GSystemType", 'name': agency_type }, {'collection_set': 1}) if agency_type_node: for eachset in agency_type_node.collection_set: app_collection_set.append( node_collection.one({"_id": eachset}, { '_id': 1, 'name': 1, 'type_of': 1 })) # for eachset in app.collection_set: # app_collection_set.append(node_collection.one({"_id":eachset}, {'_id': 1, 'name': 1, 'type_of': 1})) college_node = node_collection.one( { "_id": ObjectId(group_id), "relation_set.group_of": { "$exists": True } }, {"relation_set.group_of": 1}) if app_set_id: person_gst = node_collection.one( { '_type': "GSystemType", '_id': ObjectId(app_set_id) }, { 'name': 1, 'type_of': 1 }) template = "ndf/" + person_gst.name.strip().lower().replace( ' ', '_') + "_create_edit.html" title = person_gst.name person_gs = node_collection.collection.GSystem() person_gs.member_of.append(person_gst._id) if app_set_instance_id: person_gs = node_collection.one({ '_type': "GSystem", '_id': ObjectId(app_set_instance_id) }) property_order_list = get_property_order_with_value( person_gs) #.property_order if request.method == "POST": if person_gst.name == "Student" and "_id" not in person_gs: create_student_enrollment_code = True # [A] Save person-node's base-field(s) is_changed = get_node_common_fields(request, person_gs, group_id, person_gst) if is_changed: # Remove this when publish button is setup on interface person_gs.status = u"PUBLISHED" person_gs.save(is_changed=is_changed, groupid=group_id) for each_rel in person_gs.relation_set: if each_rel and "officer_incharge_of" in each_rel: existing_colg = each_rel["officer_incharge_of"] if college_node: mis_admin = node_collection.one( { "_type": "Group", "name": "MIS_admin" }, {"_id": 1}) node_collection.collection.update( {"_id": person_gs._id}, {"$addToSet": { "group_set": mis_admin._id }}, upsert=False, multi=False) # [B] Store AT and/or RT field(s) of given person-node (i.e., person_gs) for tab_details in property_order_list: for field_set in tab_details[1]: # Fetch only Attribute field(s) / Relation field(s) if '_id' in field_set: field_instance = node_collection.one( {'_id': field_set['_id']}) fi_name = field_instance["name"] field_instance_type = type(field_instance) if field_instance_type in [AttributeType, RelationType]: field_data_type = field_set['data_type'] # Fetch field's value depending upon AT/RT and Parse fetched-value depending upon that field's data-type if field_instance_type == AttributeType: if "File" in field_instance["validators"]: # Special case: AttributeTypes that require file instance as it's value in which case file document's ObjectId is used user_id = request.user.id if fi_name in request.FILES: field_value = request.FILES[fi_name] else: field_value = "" # Below 0th index is used because that function returns tuple(ObjectId, bool-value) if field_value != '' and field_value != u'': file_name = person_gs.name + " -- " + field_instance[ "altnames"] content_org = "" tags = "" field_value = save_file( field_value, file_name, user_id, group_id, content_org, tags, access_policy="PRIVATE", count=0, first_object="", oid=True)[0] else: # Other AttributeTypes if fi_name in request.POST: field_value = request.POST[fi_name] # field_instance_type = "GAttribute" if fi_name in [ "12_passing_year", "degree_passing_year" ]: #, "registration_year"]: field_value = parse_template_data( field_data_type, field_value, date_format_string="%Y") elif fi_name in ["dob", "registration_date"]: field_value = parse_template_data( field_data_type, field_value, date_format_string="%d/%m/%Y") registration_date = field_value else: field_value = parse_template_data( field_data_type, field_value, date_format_string="%d/%m/%Y %H:%M") if field_value: person_gs_triple_instance = create_gattribute( person_gs._id, node_collection.collection.AttributeType( field_instance), field_value) else: if field_instance["object_cardinality"] > 1: field_value_list = request.POST.get( fi_name, "") if "[" in field_value_list and "]" in field_value_list: field_value_list = json.loads( field_value_list) else: field_value_list = request.POST.getlist( fi_name) else: field_value_list = request.POST.getlist( fi_name) if META_TYPE[ 3] in field_instance.member_of_names_list: # If Binary relationship found # [id, id, ...] # field_instance_type = "GRelation" for i, field_value in enumerate( field_value_list): field_value = parse_template_data( field_data_type, field_value, field_instance=field_instance, date_format_string="%m/%d/%Y %H:%M") field_value_list[i] = field_value else: # Relationship Other than Binary one found; e.g, Triadic # [[id, id, ...], [id, id, ...], ...] # field_instance_type = "GRelation" for i, field_value_inner_list in enumerate( field_value_list): for j, field_value in enumerate( field_value_inner_list): field_value = parse_template_data( field_data_type, field_value, field_instance=field_instance, date_format_string="%m/%d/%Y %H:%M" ) field_value_list[i][j] = field_value person_gs_triple_instance = create_grelation( person_gs._id, node_collection.collection.RelationType( field_instance), field_value_list) # Setting enrollment code for student node only while creating it if create_student_enrollment_code: # Create enrollment code for student node only while registering a new node for rel in college_node.relation_set: if rel and "group_of" in rel: college_id = rel["group_of"][0] student_enrollment_code = get_student_enrollment_code( college_id, person_gs._id, registration_date, ObjectId(group_id)) enrollment_code_at = node_collection.one({ "_type": "AttributeType", "name": "enrollment_code" }) try: ga_node = create_gattribute(person_gs._id, enrollment_code_at, student_enrollment_code) except Exception as e: print "\n StudentEnrollmentCreateError: " + str(e) + "!!!" # [C] Code to link GSystem Node and Author node via "has_login" relationship; # and Subscribe the Author node to College group if user "Program Officer" person_gs.reload() auth_node = None for attr in person_gs.attribute_set: if "email_id" in attr: if attr["email_id"]: auth_node = node_collection.one({ '_type': "Author", 'email': attr["email_id"].lower() }) break if auth_node: has_login_rt = node_collection.one({ '_type': "RelationType", 'name': "has_login" }) if has_login_rt: # Linking GSystem Node and Author node via "has_login" relationship; gr_node = create_grelation(person_gs._id, has_login_rt, auth_node._id) # Set author_agency field's value of author node as "Program Officer" # Required to identify at time of log-in in order to display # required modules defined for Program Officers under MIS GApp if auth_node.agency_type != u"Program Officer": auth_node.agency_type = u"Program Officer" auth_node.save(groupid=group_id) if "Program Officer" in person_gs.member_of_names_list: # If Person node (GSystem) is of Program Officer type # then only go for subscription college_id_list = [] # Fetch College's ObjectId to which Program Officer is assigned (via "officer_incharge_of") for rel in person_gs.relation_set: if "officer_incharge_of" in rel: if rel["officer_incharge_of"]: for college_id in rel["officer_incharge_of"]: if college_id not in college_id_list: college_id_list.append(college_id) break # break outer-loop (of relation_set) if college_id_list: # If College's ObjectId exists (list as PO might be assigned to more than one college) # Then prepare a list of their corresponding private group(s) (via "has_group") college_cur = node_collection.find( {'_id': { '$in': college_id_list }}, {'relation_set.has_group': 1}) college_group_id_list = [] for college in college_cur: for rel in college.relation_set: if rel and "has_group" in rel: if rel["has_group"]: if rel["has_group"][ 0] not in college_group_id_list: college_group_id_list.append( rel["has_group"][0]) break # break inner-loop (college.relation_set) if college_group_id_list: # If college-group list exists # Then update their group_admin field (append PO's created_by) res = node_collection.collection.update( {'_id': { '$in': college_group_id_list }}, { '$addToSet': { 'group_admin': auth_node.created_by } }, upsert=False, multi=True) old_college_id_list = [] if existing_colg: if len(existing_colg) > len(college_id_list): for each_colg_id in existing_colg: if each_colg_id not in college_id_list: old_college_id_list.append(each_colg_id) old_college_cur = node_collection.find( {'_id': { '$in': old_college_id_list }}, {'relation_set.has_group': 1}) old_college_group_id_list = [] for college in old_college_cur: for rel in college.relation_set: if rel and "has_group" in rel: if rel["has_group"]: if rel["has_group"][ 0] not in old_college_group_id_list: old_college_group_id_list.append( rel["has_group"][0]) break # break inner-loop (college.relation_set) if old_college_group_id_list: # If college-group list exists # Then update their group_admin field (remove PO's created_by) res = node_collection.collection.update( { '_id': { '$in': old_college_group_id_list }, '$or': [{ 'group_admin': auth_node.created_by }, { 'author_set': auth_node.created_by }] }, { '$pull': { 'group_admin': auth_node.created_by, 'author_set': auth_node.created_by } }, upsert=False, multi=True) # The code below is commented as the college groups are PRIVATE. # for rel in person_gs.relation_set: # if rel and "officer_incharge_of" in rel: # pass # else: # node_collection.collection.update({'_id': auth_node._id}, # {'$set': {'agency_type': u"Other"}}, # upsert=False, multi=False # ) # Its purpose is to change the agency type back to Other auth_node.reload() # if person_gst.name != "Student": # return HttpResponseRedirect(reverse(app_name.lower()+":"+template_prefix+'_app_detail', kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id})) # else: return HttpResponseRedirect( reverse('mis:mis_app_instance_detail', kwargs={ 'group_id': group_id, "app_id": app_id, "app_set_id": app_set_id, "app_set_instance_id": unicode(person_gs._id) })) # return HttpResponseRedirect(reverse(app_name.lower()+":"+template_prefix+'_app_detail', kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id})) default_template = "ndf/person_create_edit.html" # default_template = "ndf/"+template_prefix+"_create_edit.html" context_variables = { 'groupid': group_id, 'group_id': group_id, 'app_id': app_id, 'app_name': app_name, 'app_collection_set': app_collection_set, 'app_set_id': app_set_id, 'title': title, 'property_order_list': property_order_list } if person_gst and person_gst.name in [ "Voluntary Teacher", "Master Trainer" ]: nussd_course_type = node_collection.one( { '_type': "AttributeType", 'name': "nussd_course_type" }, { '_type': 1, '_id': 1, 'data_type': 1, 'complex_data_type': 1, 'name': 1, 'altnames': 1 }) if nussd_course_type["data_type"] == "IS()": # Below code does little formatting, for example: # data_type: "IS()" complex_value: [u"ab", u"cd"] dt: # "IS(u'ab', u'cd')" dt = "IS(" for v in nussd_course_type.complex_data_type: dt = dt + "u'" + v + "'" + ", " dt = dt[:(dt.rfind(", "))] + ")" nussd_course_type["data_type"] = dt nussd_course_type["data_type"] = eval(nussd_course_type["data_type"]) nussd_course_type["value"] = None context_variables['nussd_course_type'] = nussd_course_type if app_set_instance_id: person_gs.get_neighbourhood(person_gs.member_of) if "trainer_teaches_course_in_college" in person_gs: l = [] for each_course_college in person_gs.trainer_teaches_course_in_college: # Fetch Course Type (i.e. nussd_course_type) ct = "" for each_attr in each_course_college[0].attribute_set: if "nussd_course_type" in each_attr and each_attr: ct = each_attr["nussd_course_type"] break univ_name = "" for each_rel in each_course_college[1].relation_set: if "college_affiliated_to" in each_rel and each_rel: univ = node_collection.find_one({ "_id": { "$in": each_rel["college_affiliated_to"] } }) univ_name = univ.name if univ else "" l.append((ct, each_course_college[0].name, each_course_college[1].name, each_course_college[0]._id.__str__(), each_course_college[1]._id.__str__(), univ_name)) if l: person_gs.trainer_teaches_course_in_college = l context_variables['node'] = person_gs try: return render_to_response([template, default_template], context_variables, context_instance=RequestContext(request)) except TemplateDoesNotExist as tde: error_message = "\n PersonCreateEditViewError: This html template (" + str( tde) + ") does not exists !!!\n" raise Http404(error_message) except Exception as e: error_message = "\n PersonCreateEditViewError: " + str(e) + " !!!\n" raise Exception(error_message)
def create_task_at_rt(request,rt_list,at_list,task_node,assign,group_name,group_id): file_id=(request.POST.get("files")) file_name=(request.POST.get("files_name")) for each in rt_list: rel_type_node = node_collection.one({'_type': "RelationType", 'name': each}) field_value_list = None if rel_type_node["object_cardinality"] > 1: field_value_list = request.POST.get(rel_type_node["name"], "") if "[" in field_value_list and "]" in field_value_list: field_value_list = json.loads(field_value_list) else: field_value_list = request.POST.getlist(rel_type_node["name"]) else: field_value_list = request.POST.getlist(rel_type_node["name"]) # rel_type_node_type = "GRelation" for i, field_value in enumerate(field_value_list): field_value = parse_template_data(rel_type_node.object_type, field_value, field_instance=rel_type_node) field_value_list[i] = field_value task_gs_triple_instance = create_grelation(task_node._id, node_collection.collection.RelationType(rel_type_node), field_value_list) for each in at_list: field_value = [] if request.POST.get(each,""): attributetype_key = node_collection.find_one({"_type": 'AttributeType', 'name': each}) subject = task_node._id object_value = "" if each == 'Assignee': if type(assign) == list: object_value = assign else: field_value.append(assign) object_value = field_value else: field_value = request.POST.get(each, "") date_format_string = "" if each in ["start_time", "end_time"]: date_format_string = "%d/%m/%Y" field_value = parse_template_data(eval(attributetype_key["data_type"]), field_value, date_format_string=date_format_string) # newattribute.object_value = field_value object_value = field_value # newattribute.save() ga_node = create_gattribute(subject, attributetype_key, object_value) if request.FILES.getlist('UploadTask'): attributetype_key = node_collection.find_one({"_type":'AttributeType', 'name':'Upload_Task'}) ga_node = create_gattribute(task_node._id, attributetype_key, file_id) assignee_list = [] assignee_list_id = [] if type(assign) == list: assignee_list_id = assign else: assignee_list_id.append(assign) user_to_be_notified = [] if assignee_list_id: for eachuser in assignee_list_id: if eachuser: bx = User.objects.get(id=int(eachuser)) assignee_list.append(bx.username) user_to_be_notified.append(bx) for eachuser in user_to_be_notified: activ = "Task reported" msg = "Task '" + task_node.name + \ "' has been reported by " + request.user.username + \ "\n - Status: " + request.POST.get('Status', '') + \ "\n - Assignee: " + ", ".join(assignee_list) + \ "\n - Url: http://" + site_domain + "/" + group_name.replace(" ","%20").encode('utf8') + "/task/" + str(task_node._id) set_notif_val(request, group_id, msg, activ, eachuser)
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 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 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 translate_node(request,group_id,node_id=None): """ translate the node content""" # 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) context_variables = { 'title': gst_page.name, 'group_id': group_id, 'groupid': group_id } if request.method == "POST": get_type = get_resource_type(request, node_id) # get_type can be GSystem/File/Author/Group page_node = eval("node_collection.collection"+"."+ get_type)() get_translate_common_fields(request, get_type,page_node, group_id, gst_page,node_id) page_node.save(groupid=group_id) # add triple to the GRelation # then append this ObjectId of GRelation instance in respective subject and object Nodes' relation_set field. relation_type = node_collection.one({'_type': 'RelationType', 'name': 'translation_of'}) gr_node = create_grelation(ObjectId(node_id), relation_type, page_node._id) # grelation = node_collection.collection.GRelation() # grelation.relation_type=relation_type # grelation.subject=ObjectId(node_id) # grelation.right_subject=page_node._id # grelation.name=u"" # grelation.save() return HttpResponseRedirect(reverse('page_details', kwargs={'group_id': group_id, 'app_id': page_node._id})) node = node_collection.one({"_id": ObjectId(node_id)}) fp = history_manager.get_file_path(node) # Retrieve rcs-file for a given version-number rcs.checkout(fp) # Copy content from rcs-version-file data = None with open(fp, 'r') as sf: data = sf.read() # Used json.loads(x) -- to covert string to dictionary object # If want to use key from this converted dictionay, use array notation because dot notation doesn't works! data = json.loads(data) # Remove retrieved rcs-file belonging to the given version-number rcs.checkin(fp) content = data node_details=[] for k,v in content.items(): node_name = content['name'] node_content_org=content['content_org'] node_tags=content['tags'] return render_to_response("ndf/translation_page.html", {'content': content, 'appId':app._id, 'node':node, 'node_name':node_name, 'groupid':group_id, 'group_id':group_id }, context_instance = RequestContext(request) )