Beispiel #1
0
def write_files(request, group_id, make_collection=False, unique_gs_per_file=True):

	user_id        = request.user.id
	author_obj     = node_collection.one({'_type': u'Author', 'created_by': user_id})
	author_obj_id  = author_obj._id

	group_name, group_id = get_group_name_id(group_id)

	first_obj      = None
	collection_set = []
	uploaded_files = request.FILES.getlist('filehive', [])
	# print "uploaded_files",uploaded_files
	name           = request.POST.get('name')
	# print "name",name

	gs_obj_list    = []
	for each_file in uploaded_files:

		gs_obj = node_collection.collection.GSystem()

		language = request.POST.get('language', GSTUDIO_SITE_DEFAULT_LANGUAGE)
		language = get_language_tuple(language)

		group_set = [ObjectId(group_id), ObjectId(author_obj_id)]

		if name and not first_obj and (name != 'untitled'):
			file_name = name
		else:
			file_name = each_file.name if hasattr(each_file, 'name') else name

		existing_file_gs = gs_obj.fill_gstystem_values(request=request,
									name=file_name,
									group_set=group_set,
									language=language,
									uploaded_file=each_file,
									unique_gs_per_file=unique_gs_per_file)
		# print "existing_file_gs",existing_file_gs
		if (gs_obj.get('_id', None) or existing_file_gs.get('_id', None)) and \
		   (existing_file_gs.get('_id', None) == gs_obj.get('_id', None)):
			if gst_file_id not in gs_obj.member_of:
				gs_obj.member_of.append(gst_file_id)

			gs_obj.save(groupid=group_id,validate=False)

			if 'video' in gs_obj.if_file.mime_type:
				convertVideo.delay(user_id, str(gs_obj._id), file_name)
			if not first_obj:
				first_obj = gs_obj
			else:
				collection_set.append(gs_obj._id)

			gs_obj_list.append(gs_obj)
		elif existing_file_gs:
				gs_obj_list.append(existing_file_gs)

	if make_collection and collection_set:
		first_obj.collection_set = collection_set
		first_obj.save()

	return gs_obj_list
Beispiel #2
0
def user_profile(request, group_id):
    from django.contrib.auth.models import User

    auth_node = get_group_name_id(group_id, get_obj=True)

    user_dict = {}
    user_details = User.objects.get(id=request.user.id)
    user_dict['fname'] = user_details.first_name
    user_dict['lname'] = user_details.last_name

    if request.method == "POST":
        user = User.objects.get(id=request.user.id)
        user_data = request.POST.getlist('forminputs[]', '')
        user_select_data = request.POST.getlist('formselects[]', '')
        apps_to_set = request.POST.getlist('selected_apps_list[]', [])
        apps_to_set = [ObjectId(app_id) for app_id in apps_to_set if app_id]

        apps_list = []
        apps_list_append = apps_list.append
        for each in apps_to_set:
            apps_list_append(node_collection.find_one({"_id": each}))

        at_apps_list = node_collection.one({
            '_type': 'AttributeType',
            'name': 'apps_list'
        })
        ga_node = create_gattribute(auth_node._id, at_apps_list, apps_list)

        for i in user_data:
            a = ast.literal_eval(i)
            if a.get('first_name', None) != None:
                user.first_name = a['first_name']
                user_dict['fname'] = user.first_name
            if a.get('last_name', None) != None:
                user.last_name = a['last_name']
                user_dict['lname'] = user.last_name
        user.save()
        for i in user_select_data:
            a = ast.literal_eval(i)
            if a.get('language_proficiency', None) != None:
                auth_node['language_proficiency'] = []
                for k in a.get('language_proficiency', ''):
                    language = get_language_tuple(k)
                    auth_node['language_proficiency'].append(language)
            if a.get('subject_proficiency', None) != None:
                auth_node['subject_proficiency'] = list(
                    a.get('subject_proficiency', ''))
        auth_node.save()
        user_dict['node'] = auth_node
        user_dict['success'] = True
        return HttpResponse(json.dumps(user_dict, cls=NodeJSONEncoder))
    else:
        user_dict['node'] = auth_node
        return render_to_response(
            "ndf/user_profile_form.html", {
                'group_id': group_id,
                'node': auth_node,
                'user': json.dumps(user_dict, cls=NodeJSONEncoder)
            },
            context_instance=RequestContext(request))
Beispiel #3
0
def get_lang_node(node_id, lang):
    rel_value = get_relation_value(ObjectId(node_id), "translation_of")
    for each in rel_value['grel_node']:
        if each.language[0] == get_language_tuple(lang)[0]:
            trans_node = each
            print "in get_lang_node", trans_node._id, "in language", each.language[
                0]
            return trans_node
Beispiel #4
0
def user_profile(request, group_id):
    from django.contrib.auth.models import User

    auth_node = get_group_name_id(group_id, get_obj=True)

    user_dict={}
    user_details = User.objects.get(id=request.user.id)
    user_dict['fname'] = user_details.first_name
    user_dict['lname']  = user_details.last_name

    if request.method == "POST":
        user = User.objects.get(id=request.user.id)
        user_data = request.POST.getlist('forminputs[]','')
        user_select_data = request.POST.getlist('formselects[]','')
        apps_to_set = request.POST.getlist('selected_apps_list[]', [])
        apps_to_set = [ObjectId(app_id) for app_id in apps_to_set if app_id ]

        apps_list = []
        apps_list_append = apps_list.append
        for each in apps_to_set:
            apps_list_append(
                node_collection.find_one({
                    "_id": each
                })
            )

        at_apps_list = node_collection.one({'_type': 'AttributeType', 'name': 'apps_list'})
        ga_node = create_gattribute(auth_node._id, at_apps_list, apps_list)

        for i in user_data:
			a=ast.literal_eval(i)
			if  a.get('first_name',None) != None:
			  	user.first_name = a['first_name']
			  	user_dict['fname'] = user.first_name
			if a.get('last_name',None) != None:
				user.last_name = a['last_name']
			  	user_dict['lname'] = user.last_name
        user.save()
        for i in user_select_data:
			a=ast.literal_eval(i)
			if  a.get('language_proficiency',None) != None:
				auth_node['language_proficiency'] = []
				for k in a.get('language_proficiency',''):
					language = get_language_tuple(k)
					auth_node['language_proficiency'].append(language)
			if  a.get('subject_proficiency',None) != None:
				auth_node['subject_proficiency'] =  list(a.get('subject_proficiency',''))
        auth_node.save()
        user_dict['node'] = auth_node
        user_dict['success'] = True
        return HttpResponse(json.dumps(user_dict,cls=NodeJSONEncoder))
    else:
		user_dict['node'] = auth_node
		return render_to_response(  "ndf/user_profile_form.html",
				{'group_id':group_id,'node':auth_node,'user':json.dumps(user_dict,cls=NodeJSONEncoder)},
				context_instance=RequestContext(request)
		)
Beispiel #5
0
def show_translation(request, group_id, node_id, lang):
    '''
    for VIEW/READ: show translated provided node to provided LANG CODE
    lang could be either proper/full language-name/language-code
    '''
    node = translated_node_id = None
    grel_node = triple_collection.one({
        '_type': 'GRelation',
        'subject': ObjectId(node_id),
        'relation_type': rt_translation_of._id,
        'language': get_language_tuple(lang),
        # 'status': 'PUBLISHED'
    })

    if grel_node:
        node = Node.get_node_by_id(grel_node.right_subject)
        translated_node_id = node._id

    # code to show other translations
    other_translations_grels = triple_collection.find({
        '_type':
        u'GRelation',
        'subject':
        ObjectId(node_id),
        'relation_type':
        rt_translation_of._id,
        'right_subject': {
            '$nin': [translated_node_id]
        }
    })

    other_translations = node_collection.find(
        {'_id': {
            '$in': [r.right_subject for r in other_translations_grels]
        }})

    # --- END of code to show other translations

    return render_to_response("ndf/translate_detail.html", {
        'group_id': Group.get_group_name_id(group_id)[1],
        'groupid': Group.get_group_name_id(group_id)[1],
        'source_node_id': node_id,
        'source_node_obj': Node.get_node_by_id(node_id),
        'node': node,
        'other_translations': other_translations,
        'card_url_name': 'show_translation',
    },
                              context_instance=RequestContext(request))
Beispiel #6
0
def user_profile(request, group_id):
    from django.contrib.auth.models import User

    auth_node = get_group_name_id(group_id, get_obj=True)

    user_dict = {}
    user_details = User.objects.get(id=request.user.id)
    user_dict['fname'] = user_details.first_name
    user_dict['lname'] = user_details.last_name

    if request.method == "POST":
        user = User.objects.get(id=request.user.id)
        user_data = request.POST.getlist('forminputs[]', '')
        user_select_data = request.POST.getlist('formselects[]', '')
        for i in user_data:
            a = ast.literal_eval(i)
            if a.get('first_name', None) != None:
                user.first_name = a['first_name']
                user_dict['fname'] = user.first_name
            if a.get('last_name', None) != None:
                user.last_name = a['last_name']
                user_dict['lname'] = user.last_name
        user.save()
        for i in user_select_data:
            a = ast.literal_eval(i)
            if a.get('language_proficiency', None) != None:
                auth_node['language_proficiency'] = []
                for k in a.get('language_proficiency', ''):
                    language = get_language_tuple(k)
                    auth_node['language_proficiency'].append(language)
            if a.get('subject_proficiency', None) != None:
                auth_node['subject_proficiency'] = list(
                    a.get('subject_proficiency', ''))
        auth_node.save()
        user_dict['node'] = auth_node
        user_dict['success'] = True
        return HttpResponse(json.dumps(user_dict, cls=NodeJSONEncoder))
    else:
        user_dict['node'] = auth_node
        return render_to_response(
            "ndf/user_profile_form.html", {
                'group_id': group_id,
                'node': auth_node,
                'user': json.dumps(user_dict, cls=NodeJSONEncoder)
            },
            context_instance=RequestContext(request))
Beispiel #7
0
def user_profile(request, group_id):
	from django.contrib.auth.models import User

	auth_node = get_group_name_id(group_id, get_obj=True)

	user_dict={}
	user_details = User.objects.get(id=request.user.id)
	user_dict['fname'] = user_details.first_name
	user_dict['lname']  = user_details.last_name

	if request.method == "POST":
		user = User.objects.get(id=request.user.id)
		user_data = request.POST.getlist('forminputs[]','')
		user_select_data = request.POST.getlist('formselects[]','')
		for i in user_data:
			a=ast.literal_eval(i)
			if  a.get('first_name',None) != None:
			  	user.first_name = a['first_name']
			  	user_dict['fname'] = user.first_name
			if a.get('last_name',None) != None:
				user.last_name = a['last_name']
			  	user_dict['lname'] = user.last_name
		user.save()
		for i in user_select_data:
			a=ast.literal_eval(i)
			if  a.get('language_proficiency',None) != None:
				auth_node['language_proficiency'] = []
				for k in a.get('language_proficiency',''):
					language = get_language_tuple(k)
					auth_node['language_proficiency'].append(language)
			if  a.get('subject_proficiency',None) != None:			
				auth_node['subject_proficiency'] =  list(a.get('subject_proficiency',''))
		auth_node.save()
		user_dict['node'] = auth_node
		user_dict['success'] = True
		return HttpResponse(json.dumps(user_dict,cls=NodeJSONEncoder))
	else:
		user_dict['node'] = auth_node
		return render_to_response(  "ndf/user_profile_form.html",
				{'group_id':group_id,'node':auth_node,'user':json.dumps(user_dict,cls=NodeJSONEncoder)},
				context_instance=RequestContext(request)
		)
Beispiel #8
0
def show_translation(request, group_id, node_id, lang):
    '''
    for VIEW/READ: show translated provided node to provided LANG CODE
    lang could be either proper/full language-name/language-code
    '''
    node = translated_node_id = None
    grel_node = triple_collection.one({
                            '_type': 'GRelation',
                            'subject': ObjectId(node_id),
                            'relation_type': rt_translation_of._id,
                            'language': get_language_tuple(lang),
                            # 'status': 'PUBLISHED'
                        })

    if grel_node:
        node = Node.get_node_by_id(grel_node.right_subject)
        translated_node_id = node._id

    # code to show other translations
    other_translations_grels = triple_collection.find({
                            '_type': u'GRelation',
                            'subject': ObjectId(node_id),
                            'relation_type': rt_translation_of._id,
                            'right_subject': {'$nin': [translated_node_id]}
                        })

    other_translations = node_collection.find({'_id': {'$in': [r.right_subject for r in other_translations_grels]} })

    # --- END of code to show other translations

    return render_to_response("ndf/translate_detail.html",
                          {
                            'group_id': Group.get_group_name_id(group_id)[1],
                            'groupid': Group.get_group_name_id(group_id)[1],
                            'source_node_id': node_id,
                            'source_node_obj': Node.get_node_by_id(node_id),
                            'node': node,
                            'other_translations': other_translations,
                            'card_url_name': 'show_translation',
                           },
                          context_instance=RequestContext(request))
Beispiel #9
0
def unit_create_edit(request, group_id, unit_group_id=None):
    '''
    creation as well as eit of units
    '''

    parent_group_name, parent_group_id = Group.get_group_name_id(group_id)
    print "inside unit_create_edit", parent_group_name, parent_group_id
    print "request path", request.method
    unit_node = None
    if request.method == "GET":
        unit_node = node_collection.one({'_id': ObjectId(unit_group_id)})
        template = "ndf/create_unit.html"
        all_groups = node_collection.find({'_type': "Group"}, {"name": 1})
        all_groups_names = [str(each_group.name) for each_group in all_groups]
        print "group names :", all_groups_names
        modules = GSystem.query_list('home', 'Module', request.user.id)

        context_variables = {
            'group_id': parent_group_id,
            'groupid': parent_group_id,
            'all_groups_names': all_groups_names,
            'modules': modules
        }

        if unit_node:
            # get all modules which are parent's of this unit/group
            parent_modules = node_collection.find({
                '_type': 'GSystem',
                'member_of': gst_module_id,
                'collection_set': {
                    '$in': [unit_node._id]
                }
            })
            context_variables.update({
                'unit_node':
                unit_node,
                'title':
                'Create Unit',
                'module_val_list': [str(pm._id) for pm in parent_modules]
            })
        req_context = RequestContext(request, context_variables)
        return render_to_response(template, req_context)

    elif request.method == "POST":
        group_name = request.POST.get('name', '')
        group_altnames = request.POST.get('altnames', '')
        unit_id_post = request.POST.get('node_id', '')
        unit_altnames = request.POST.get('altnames', '')
        content = request.POST.get('content', '')
        tags = request.POST.get('tags', [])
        language = request.POST.get('lan', '')
        group_type = request.POST.get('group_type', u'PUBLIC')

        educationallevel_val = request.POST.get('educationallevel', '')
        educationalsubject_val = request.POST.get('educationalsubject', '')
        # unit_group_id = unit_id_post if unit_id_post else unit_group_id
        # unit_group_name, unit_group_id = Group.get_group_name_id(unit_group_id)
        if unit_id_post:
            unit_node = node_collection.one({'_id': ObjectId(unit_id_post)})
        success_flag = False
        if unit_node:
            if unit_node.altnames is not unit_altnames:
                unit_node.altnames = unit_altnames
                success_flag = True
        else:
            unit_group = CreateGroup(request)
            result = unit_group.create_group(group_name,
                                             group_id=parent_group_id,
                                             member_of=gst_base_unit_id,
                                             node_id=unit_group_id)
            success_flag = result[0]
            unit_node = result[1]

        unit_id = unit_node._id
        if language:
            language_val = get_language_tuple(unicode(language))
            unit_node.language = language_val
        if educationallevel_val and "choose" not in educationallevel_val.lower(
        ):
            educationallevel_at = node_collection.one({
                '_type':
                'AttributeType',
                'name':
                "educationallevel"
            })
            create_gattribute(unit_node._id, educationallevel_at,
                              educationallevel_val)
        if educationalsubject_val and "choose" not in educationalsubject_val.lower(
        ):
            educationalsubject_at = node_collection.one({
                '_type':
                'AttributeType',
                'name':
                "educationalsubject"
            })
            create_gattribute(unit_node._id, educationalsubject_at,
                              educationalsubject_val)

        # modules
        module_val = request.POST.getlist('module', [])
        if module_val:
            update_unit_in_modules(module_val, unit_id)

        if not success_flag:
            return HttpResponseRedirect(
                reverse('list_units',
                        kwargs={
                            'group_id': parent_group_id,
                            'groupid': parent_group_id,
                        }))

        # if tags:
        #     if not type(tags) is list:
        #         tags = [unicode(t.strip()) for t in tags.split(",") if t != ""]
        #     unit_node.tags = tags
        if tags:
            tags = json.loads(tags)
        else:
            tags = []
        # unit_node.tags = tags
        unit_node.fill_group_values(group_type=group_type,
                                    tags=tags,
                                    author_set=unit_node.author_set)
        unit_node.content = content
        tab_name = request.POST.get('tab_name', '')
        resource_name = request.POST.get('resource_name', '')
        blog_name = request.POST.get('blog_name', '')
        section_name = request.POST.get('section_name', '')
        subsection_name = request.POST.get('subsection_name', '')

        if tab_name:
            unit_node['project_config'].update({"tab_name": tab_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list:
            unit_node['project_config'].update({"tab_name": "Lessons"})
        else:
            unit_node['project_config'].update({"tab_name": "Tab Name"})

        if resource_name:
            unit_node['project_config'].update(
                {"resource_name": resource_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list:
            unit_node['project_config'].update({"resource_name": "Resources"})
        else:
            unit_node['project_config'].update(
                {"resource_name": "Resource Name"})

        if blog_name:
            unit_node['project_config'].update({"blog_name": blog_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list:
            unit_node['project_config'].update({"blog_name": "e-Notes"})
        else:
            unit_node['project_config'].update({"blog_name": "blog Name"})

        if section_name:
            unit_node['project_config'].update({"section_name": section_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list:
            unit_node['project_config'].update({"section_name": "Lesson"})
        else:
            unit_node['project_config'].update({"section_name": "Section"})

        if subsection_name:
            unit_node['project_config'].update(
                {"subsection_name": subsection_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list:
            unit_node['project_config'].update(
                {"subsection_name": "Add from Activities"})
        else:
            unit_node['project_config'].update(
                {"subsection_name": "Add SubSection"})

        unit_node.save()
        return HttpResponseRedirect(
            reverse('course_content', kwargs={'group_id': unit_node._id}))
Beispiel #10
0
def get_filtered_topic_resources(request, group_id, node_id):

    selfilters = request.POST.get('filters', None)
    query_dict = get_filter_querydict(json.loads(selfilters)) if selfilters else {}
    # print query_dict

    node_rel_cur = node_collection.one(
                                    {
                                        '_id': ObjectId( node_id ),
                                        'relation_set.taught_by': {'$exists': 'true'}
                                    },
                                    {
                                        'relation_set.taught_by': 1, '_id': 0
                                    }
                                )
    
    node_rel_list = node_rel_cur.relation_set[0].get('taught_by', [])

    filtered_taught_by_res = node_collection.find({
                        '_id': {'$in': node_rel_list},
                        '$and': query_dict
                    })

    primary_lang_resources = {}
    other_lang_resources = {}
    all_educationaluse = []
    language_selected = list(get_language_tuple(request.LANGUAGE_CODE))
    # print language_selected,"request.LANGUAGE_CODE: ", request.LANGUAGE_CODE

    # print filtered_taught_by_res.count()
    for each_res in filtered_taught_by_res:
        # if each_res.language :
        #     pass
        att_set_dict = get_dict_from_list_of_dicts(each_res.attribute_set)
        educationaluse = att_set_dict['educationaluse']

        all_educationaluse.append(educationaluse)

        if language_selected == each_res.language:
            temp = primary_lang_resources.get(educationaluse, [])
            temp.append(each_res)
            primary_lang_resources[educationaluse] = temp
            temp = ""
        else:
            temp = other_lang_resources.get(educationaluse, [])
            temp.append(each_res)
            other_lang_resources[educationaluse] = temp
            temp = ""

    # print "primary_lang_resources : ", primary_lang_resources
    # print "other_lang_resources: ", other_lang_resources

    all_educationaluse = list(set(all_educationaluse))

    # data = json.dumps({'primary_lang_resources': primary_lang_resources, 'other_lang_resources': other_lang_resources, 'all_educationaluse': all_educationaluse })

    # return HttpResponse(data)

    # return HttpResponse({'primary_lang_resources': primary_lang_resources, 'other_lang_resources': other_lang_resources, 'all_educationaluse': all_educationaluse })


    return render_to_response('ndf/topic_resources_listing.html', 
                                    { 
                                    'primary_lang_resources': primary_lang_resources, 'other_lang_resources': other_lang_resources, 'all_educationaluse': all_educationaluse,
                                    # 'node': obj,'app_id': app_id,"theme_id": theme_id, "prior_obj": prior_obj,
                                      'group_id': group_id,'groupid':group_id,
                                      'filtered_topics': 'filtered_topics'
                                      # 'shelves': shelves,'topic': topic, 'nav_list':nav_li,
                                      # 'shelf_list': shelf_list,'breadcrumbs_list': breadcrumbs_list
                                    },
                                    context_instance = RequestContext(request)
                            )
Beispiel #11
0
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))
Beispiel #12
0
def node_create_edit(request,
                    group_id=None,
                    member_of=None,
                    detail_url_name=None,
                    node_type='GSystem',
                    node_id=None):
    '''
    creation as well as edit of node
    '''
    # check for POST method to node update operation
    if request.method == "POST":

        # put validations
        if node_type not in node_collection.db.connection._registered_documents.keys():
            raise ValueError('Improper node_type passed')

        kwargs={}
        group_name, group_id = Group.get_group_name_id(group_id)
        member_of_name, member_of_id = GSystemType.get_gst_name_id(member_of)

        if node_id: # existing node object
            node_obj = Node.get_node_by_id(node_id)

        else: # create new
            kwargs={
                    'group_set': group_id,
                    'member_of': member_of_id
                    }
            node_obj = node_collection.collection[node_type]()

        language = get_language_tuple(request.POST.get('language', None))
        node_obj.fill_gstystem_values(request=request,
                                    language=language,
                                            **kwargs)
        node_obj.save(group_id=group_id)
        node_id = node_obj['_id']

        # Consider for Blog page creation
        if member_of_name == "Page":
            blog_page_gst_name, blog_page_gst_id = GSystemType.get_gst_name_id("Blog page")
            if blog_page_gst_id in node_obj.type_of:
                discussion_enable_at = node_collection.one({"_type": "AttributeType", "name": "discussion_enable"})
                create_gattribute(node_obj._id, discussion_enable_at, True)
                return_status = create_thread_for_node(request,group_id, node_obj)

                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()

        post_req = request.POST
        attrs_to_create_update = [f for f in post_req.keys() if ('attribute' in f)]
        attrs_to_create_update = [a.split('_')[1] for a in attrs_to_create_update]

        for each_attr_name in attrs_to_create_update:
            each_attr_name_obj = Node.get_name_id_from_type(each_attr_name, 'AttributeType', get_obj=True)
            post_req_attr_key = 'attribute_'+each_attr_name
            post_method = 'getlist' if (each_attr_name_obj.data_type in [list, 'list']) else 'get'
            create_gattribute(node_id,
                            each_attr_name_obj,
                            object_value=getattr(post_req, post_method)(post_req_attr_key))


        return HttpResponseRedirect(reverse(detail_url_name, kwargs={'group_id': group_id, 'node_id': node_id}))
Beispiel #13
0
def node_create_edit(request,
                    group_id=None,
                    member_of=None,
                    detail_url_name=None,
                    node_type='GSystem',
                    node_id=None):
    '''
    creation as well as edit of node
    '''
    # check for POST method to node update operation
    if request.method == "POST":

        # put validations
        if node_type not in node_collection.db.connection._registered_documents.keys():
            raise ValueError('Improper node_type passed')

        kwargs={}
        group_name, group_id = Group.get_group_name_id(group_id)
        member_of_name, member_of_id = GSystemType.get_gst_name_id(member_of)

        if node_id: # existing node object
            node_obj = Node.get_node_by_id(node_id)

        else: # create new
            kwargs={
                    'group_set': group_id,
                    'member_of': member_of_id
                    }
            node_obj = node_collection.collection[node_type]()

        language = get_language_tuple(request.POST.get('language', None))
        node_obj.fill_gstystem_values(request=request,
                                    language=language,
                                            **kwargs)
        node_obj.save(group_id=group_id)
        node_id = node_obj['_id']

        # Consider for Blog page creation
        if member_of_name == "Page":
            blog_page_gst_name, blog_page_gst_id = GSystemType.get_gst_name_id("Blog page")
            if blog_page_gst_id in node_obj.type_of:
                discussion_enable_at = node_collection.one({"_type": "AttributeType", "name": "discussion_enable"})
                create_gattribute(node_obj._id, discussion_enable_at, True)
                return_status = create_thread_for_node(request,group_id, node_obj)

                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()

        post_req = request.POST
        attrs_to_create_update = [f for f in post_req.keys() if ('attribute' in f)]
        attrs_to_create_update = [a.split('_')[1] for a in attrs_to_create_update]

        for each_attr_name in attrs_to_create_update:
            each_attr_name_obj = Node.get_name_id_from_type(each_attr_name, 'AttributeType', get_obj=True)
            post_req_attr_key = 'attribute_'+each_attr_name
            post_method = 'getlist' if (each_attr_name_obj.data_type in [list, 'list']) else 'get'
            create_gattribute(node_id,
                            each_attr_name_obj,
                            object_value=getattr(post_req, post_method)(post_req_attr_key))


        return HttpResponseRedirect(reverse(detail_url_name, kwargs={'group_id': group_id, 'node_id': node_id}))
Beispiel #14
0
def module_detail(request, group_id, node_id,title=""):
    '''
    detail of of selected module
    '''
    group_name, group_id = Group.get_group_name_id(group_id)

    module_obj = Node.get_node_by_id(ObjectId(node_id))
    context_variable = {
                        'group_id': group_id, 'groupid': group_id,
                        'node': module_obj, 'title': title,
                        'card': 'ndf/event_card.html', 'card_url_name': 'groupchange'
                    }

    # module_detail_query = {'member_of': gst_base_unit_id,
    #           '_id': {'$nin': module_unit_ids},
    #           'status':'PUBLISHED',
    #             }
    # if not gstaff_access:
    #     module_detail_query.update({'$or': [
    #           {'created_by': request.user.id},
    #           {'group_admin': request.user.id},
    #           {'author_set': request.user.id},
    #           # No check on group-type PUBLIC for DraftUnits.
    #           # {'group_type': 'PUBLIC'}
    #           ]})



    gstaff_access = check_is_gstaff(group_id,request.user)

    module_detail_query = {'_id': {'$in': module_obj.collection_set},
    'status':'PUBLISHED'
    }
    
    '''
    if not gstaff_access:
        module_detail_query.update({'$or': [
        {'$and': [
            {'member_of': gst_base_unit_id},
            {'$or': [
              {'created_by': request.user.id},
              {'group_admin': request.user.id},
              {'author_set': request.user.id},
            ]}
        ]},
        {'member_of': gst_announced_unit_id}
      ]})
    '''
    primary_lang_tuple = get_language_tuple(GSTUDIO_PRIMARY_COURSE_LANGUAGE)
    if title == "courses":
        module_detail_query.update({'$or': [
        {'$and': [
            {'member_of': {'$in': [gst_announced_unit_id, gst_ce_id]}},
            {'$or': [
              {'created_by': request.user.id},
              {'group_admin': request.user.id},
              {'author_set': request.user.id},
              {
               '$and': [
                   {'group_type': u'PUBLIC'},
                   {'language': primary_lang_tuple},
               ]
              },
            ]}
        ]},
        #{'member_of': gst_announced_unit_id }
      ]})

    
    if title == "drafts":
        module_detail_query.update({'$or': [
        {'$and': [
            {'member_of': gst_base_unit_id},
            {'$or': [
              {'created_by': request.user.id},
              {'group_admin': request.user.id},
              {'author_set': request.user.id},
            ]}
        ]},
      ]}) 

    # units_under_module = Node.get_nodes_by_ids_list(module_obj.collection_set)
    '''
    gstaff_access = check_is_gstaff(group_id, request.user)

    if gstaff_access:
        module_detail_query.update({'member_of': {'$in': [gst_announced_unit_id, gst_base_unit_id]}})
    else:
        module_detail_query.update({'member_of': gst_announced_unit_id})
    '''
    units_under_module = node_collection.find(module_detail_query).sort('last_update', -1)
    context_variable.update({'units_under_module': units_under_module})

    units_sort_list = get_attribute_value(node_id, 'items_sort_list')

    if units_sort_list:
        context_variable.update({'units_sort_list': units_sort_list})
    else:
        context_variable.update({'units_sort_list': list(units_under_module)})

    template = 'ndf/module_detail.html'

    return render_to_response(
        template,
        context_variable,
        context_instance=RequestContext(request))
Beispiel #15
0
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 }))
Beispiel #16
0
def module_detail(request, group_id, node_id, title=""):
    '''
    detail of of selected module
    '''
    group_name, group_id = Group.get_group_name_id(group_id)
    print "in module_detail and group id, title", group_id, title
    print "node_id", node_id
    module_obj = Node.get_node_by_id(ObjectId(node_id))
    context_variable = {
        'group_id': group_id,
        'groupid': group_id,
        'node': module_obj,
        'title': title,
        'card': 'ndf/event_card.html',
        'card_url_name': 'groupchange'
    }

    # module_detail_query = {'member_of': gst_base_unit_id,
    #           '_id': {'$nin': module_unit_ids},
    #           'status':'PUBLISHED',
    #             }
    # if not gstaff_access:
    #     module_detail_query.update({'$or': [
    #           {'created_by': request.user.id},
    #           {'group_admin': request.user.id},
    #           {'author_set': request.user.id},
    #           # No check on group-type PUBLIC for DraftUnits.
    #           # {'group_type': 'PUBLIC'}
    #           ]})

    gstaff_access = check_is_gstaff(group_id, request.user)

    module_detail_query = {
        '_id': {
            '$in': module_obj.collection_set
        },
        'status': 'PUBLISHED'
    }
    '''
    if not gstaff_access:
        module_detail_query.update({'$or': [
        {'$and': [
            {'member_of': gst_base_unit_id},
            {'$or': [
              {'created_by': request.user.id},
              {'group_admin': request.user.id},
              {'author_set': request.user.id},
            ]}
        ]},
        {'member_of': gst_announced_unit_id}
      ]})
    '''
    primary_lang_tuple = get_language_tuple(GSTUDIO_PRIMARY_COURSE_LANGUAGE)
    if title == "courses":

        #   module_detail_query.update({'$or': [
        #   {'$and': [
        #       {'member_of': {'$in': [gst_announced_unit_id, gst_ce_id]}},
        #       {'$or': [
        #         {'created_by': request.user.id},
        #         {'group_admin': request.user.id},
        #         {'author_set': request.user.id},
        #         {
        #          '$and': [
        #              {'group_type': u'PUBLIC'},
        #              {'language': primary_lang_tuple},
        #          ]
        #         },
        #       ]}
        #   ]},
        #   #{'member_of': gst_announced_unit_id }
        # ]})
        #
        # # above can be delete after robust testing of following new query:

        module_detail_query.update({
            'status':
            'PUBLISHED',
            '$or': [{
                'group_admin': request.user.id
            }, {
                'created_by': request.user.id
            }, {
                'author_set': request.user.id
            }, {
                'member_of': gst_announced_unit_id
            }, {
                'language': primary_lang_tuple,
                'group_type': u'PUBLIC',
                'member_of': gst_ce_id
            }]
        })

    if title == "drafts":
        module_detail_query.update({
            '$or': [
                {
                    '$and': [{
                        'member_of': gst_base_unit_id
                    }, {
                        '$or': [
                            {
                                'created_by': request.user.id
                            },
                            {
                                'group_admin': request.user.id
                            },
                            {
                                'author_set': request.user.id
                            },
                        ]
                    }]
                },
            ]
        })

    # units_under_module = Node.get_nodes_by_ids_list(module_obj.collection_set)
    '''
    gstaff_access = check_is_gstaff(group_id, request.user)

    if gstaff_access:
        module_detail_query.update({'member_of': {'$in': [gst_announced_unit_id, gst_base_unit_id]}})
    else:
        module_detail_query.update({'member_of': gst_announced_unit_id})
    '''
    units_under_module = node_collection.find(module_detail_query).sort(
        'last_update', -1)
    context_variable.update({'units_under_module': units_under_module})

    units_sort_list = get_attribute_value(node_id, 'items_sort_list')
    from django.core.cache import cache
    test = cache.get('5945db6e2c4796014abd1784attribute_valueitems_sort_list')
    print "test:", test
    if units_sort_list:
        #print "from attribute:",units_sort_list
        context_variable.update({'units_sort_list': units_sort_list})
    else:
        print "no items_sort_list"
        context_variable.update({'units_sort_list': list(units_under_module)})

    template = 'ndf/module_detail.html'
    print "units of selected module", units_sort_list
    return render_to_response(template,
                              context_variable,
                              context_instance=RequestContext(request))
Beispiel #17
0
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
                }))
Beispiel #18
0
def themes(request, group_id, app_id=None, app_set_id=None):

    try:
        group_id = ObjectId(group_id)
    except:
        group_name, group_id = get_group_name_id(group_id)

    theme_GST = node_collection.one({'_type': 'GSystemType', 'name': 'Theme'})

    if app_id is None:
        # app_ins = node_collection.find_one({'_type': 'GSystemType', 'name': 'Topics'})
        app_ins = app
        # if app_ins:
        app_id = str(app_ins._id)

    # Code for user shelf
    shelves = []
    shelf_list = {}
    auth = node_collection.one({
        '_type': 'Author',
        'name': unicode(request.user.username)
    })

    # --- shelf commented for time being ---
    #
    # 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 = []
    # End of user shelf

    appName = "topics"
    title = appName
    nodes_dict = []
    themes_list_items = ""
    themes_hierarchy = ""
    themes_cards = ""
    node = ""
    nodes = ""
    unfold_tree = request.GET.get('unfold', '')
    selected = request.GET.get('selected', '')
    # print "selected: ", selected
    tree = request.GET.get('tree', 'hierarchical')
    unfold = "false"

    # topics_GST = node_collection.find_one({'_type': 'GSystemType', 'name': 'Topics'})
    topics_GST = app

    if unfold_tree:
        unfold = unfold_tree

    if app_set_id:
        themes_list_items = True
        app_GST = node_collection.find_one({"_id": ObjectId(app_set_id)})

        if app_GST:
            title = theme_GST.name
            nodes = list(
                node_collection.find({
                    'member_of': {
                        '$all': [theme_GST._id]
                    },
                    'group_set': {
                        '$all': [ObjectId(group_id)]
                    }
                }))

            nodes_dict = []
            for each in nodes:
                nodes_dict.append({
                    "id":
                    str(each._id),
                    "name":
                    each.name,
                    "created_by":
                    User.objects.get(id=each.created_by).username,
                    "created_at":
                    each.created_at
                })

    # to display the tree hierarchy of themes items inside particular theme(Here app_id defines the Theme id)
    elif ObjectId(app_id) != topics_GST._id:
        themes_hierarchy = True
        themes_cards = ""
        Theme_obj = node_collection.one({'_id': ObjectId(app_id)})
        if Theme_obj:
            node = Theme_obj

    else:
        # This will show Themes as a card view on landing page of Topics
        themes_cards = True
        # if request.user.username:
        #     nodes_dict = node_collection.find({'member_of': {'$all': [theme_GST._id]},'group_set':{'$all': [ObjectId(group_id)]}})
        # else:
        #     nodes_dict = node_collection.find({'member_of': {'$all': [theme_GST._id]},'group_set':{'$all': [ObjectId(group_id)]}})

    lang = list(get_language_tuple(request.LANGUAGE_CODE))
    nodes_dict = node_collection.find({
        'member_of': {
            '$all': [theme_GST._id]
        },
        'group_set': {
            '$all': [ObjectId(group_id)]
        },
        'language': lang
    })

    return render_to_response("ndf/theme.html", {
        'theme_GST_id': theme_GST._id,
        'theme_GST': theme_GST,
        'themes_cards': themes_cards,
        'theme_GST': theme_GST,
        'group_id': group_id,
        'groupid': group_id,
        'node': node,
        'shelf_list': shelf_list,
        'shelves': shelves,
        'tree': tree,
        'nodes': nodes_dict,
        'app_id': app_id,
        'app_name': appName,
        "selected": selected,
        'title': title,
        'themes_list_items': themes_list_items,
        'themes_hierarchy': themes_hierarchy,
        'unfold': unfold,
        'appId': app._id,
        'group_name': group_name
    },
                              context_instance=RequestContext(request))
Beispiel #19
0
def explore_courses(request):

    # this will be announced tab
    title = 'courses'
    context_variable = {
                        'title': title, 
                        'group_id': group_id, 'groupid': group_id,
                    }
    module_sort_list = get_attribute_value(group_id, 'items_sort_list')

    if module_sort_list:
        modules_cur = map(Node,module_sort_list)
        context_variable.update({'modules_is_cur': False})
    else:
        modules_cur = node_collection.find({'member_of': gst_module_id ,'status':'PUBLISHED'}).sort('last_update', -1)
        context_variable.update({'modules_is_cur': True})

    module_unit_ids = [val for each_module in modules_cur for val in each_module.collection_set ]


    primary_lang_tuple = get_language_tuple(GSTUDIO_PRIMARY_COURSE_LANGUAGE)

    '''
    katkamrachana - 14June2017
    About following query:

        [A]. Finding CourseEventGroup instances(First $and in $or):
                    Find CourseEventGroup instances, that are published.
                    Get courses that are linked to the request.user
                    Also find courses, that are "PUBLIC AND LANGUAGE falls under
                    GSTUDIO_PRIMARY_COURSE_LANGUAGE"
                    Hence, Apply language constraint. Introduced to display concerned
                    course for i2c(in 3 languages)
        [B]. Finding announced_unit instances(Second $and in $or):
                    Find announced_unit instances, that are published.
                    Get courses that are linked to the request.user
                    Also find courses, that are "PUBLIC"
                    No check on language
        [C]. Check using _type field in case conditions A and B fail, only Groups are
                 to be listed and not GSystems
        [D]. Check using name field in case conditions A and B fail,
                executing condition C then do not display factory Groups.

    '''
    base_unit_cur = node_collection.find({
                                            '$or': [
                                                {
                                                    '$and': [
                                                                {'member_of': ce_gst._id},
                                                                {'status':'PUBLISHED'},
                                                                {'$or':
                                                                    [
                                                                        {'created_by': request.user.id},
                                                                        {'group_admin': request.user.id},
                                                                        {'author_set': request.user.id},
                                                                        {
                                                                            '$and': [
                                                                                {'group_type': 'PUBLIC'},
                                                                                {'language': primary_lang_tuple},
                                                                            ]
                                                                        }
                                                                    ]
                                                                }
                                                            ]
                                                },
                                                {
                                                    '$and': [
                                                                {'member_of': announced_unit_gst._id},
                                                                {'status':'PUBLISHED'},
                                                                {'$or':
                                                                    [
                                                                        {'created_by': request.user.id},
                                                                        {'group_admin': request.user.id},
                                                                        {'author_set': request.user.id},
                                                                        {'group_type': 'PUBLIC'}
                                                                    ]
                                                                }
                                                            ]
                                                }
                                            ],
                                            '_type': 'Group',
                                            'name': {'$nin': GSTUDIO_DEFAULT_GROUPS_LIST},
                                            '_id': {'$nin': module_unit_ids},
                                              }).sort('last_update', -1)
    # base_unit_page_cur = paginator.Paginator(base_unit_cur, page_no, GSTUDIO_NO_OF_OBJS_PP)

    context_variable.update({'modules_cur': modules_cur,'units_cur': base_unit_cur})

    return render_to_response(
        # "ndf/explore.html", changed as per new Clix UI
        "ndf/explore_2017.html",
        # "ndf/lms_explore.html",
        context_variable,
        context_instance=RequestContext(request))
Beispiel #20
0
def get_filtered_topic_resources(request, group_id, node_id):

    selfilters = request.POST.get('filters', None)
    query_dict = get_filter_querydict(
        json.loads(selfilters)) if selfilters else {}
    # print query_dict

    node_rel_cur = node_collection.one(
        {
            '_id': ObjectId(node_id),
            'relation_set.taught_by': {
                '$exists': 'true'
            }
        }, {
            'relation_set.taught_by': 1,
            '_id': 0
        })

    node_rel_list = node_rel_cur.relation_set[0].get('taught_by', [])

    filtered_taught_by_res = node_collection.find({
        '_id': {
            '$in': node_rel_list
        },
        '$and': query_dict
    })

    primary_lang_resources = {}
    other_lang_resources = {}
    all_educationaluse = []
    language_selected = list(get_language_tuple(request.LANGUAGE_CODE))
    # print language_selected,"request.LANGUAGE_CODE: ", request.LANGUAGE_CODE

    # print filtered_taught_by_res.count()
    for each_res in filtered_taught_by_res:
        # if each_res.language :
        #     pass
        att_set_dict = get_dict_from_list_of_dicts(each_res.attribute_set)
        educationaluse = att_set_dict['educationaluse']

        all_educationaluse.append(educationaluse)

        if language_selected == each_res.language:
            temp = primary_lang_resources.get(educationaluse, [])
            temp.append(each_res)
            primary_lang_resources[educationaluse] = temp
            temp = ""
        else:
            temp = other_lang_resources.get(educationaluse, [])
            temp.append(each_res)
            other_lang_resources[educationaluse] = temp
            temp = ""

    # print "primary_lang_resources : ", primary_lang_resources
    # print "other_lang_resources: ", other_lang_resources

    all_educationaluse = list(set(all_educationaluse))

    # data = json.dumps({'primary_lang_resources': primary_lang_resources, 'other_lang_resources': other_lang_resources, 'all_educationaluse': all_educationaluse })

    # return HttpResponse(data)

    # return HttpResponse({'primary_lang_resources': primary_lang_resources, 'other_lang_resources': other_lang_resources, 'all_educationaluse': all_educationaluse })

    return render_to_response(
        'ndf/topic_resources_listing.html',
        {
            'primary_lang_resources': primary_lang_resources,
            'other_lang_resources': other_lang_resources,
            'all_educationaluse': all_educationaluse,
            # 'node': obj,'app_id': app_id,"theme_id": theme_id, "prior_obj": prior_obj,
            'group_id': group_id,
            'groupid': group_id,
            'filtered_topics': 'filtered_topics'
            # 'shelves': shelves,'topic': topic, 'nav_list':nav_li,
            # 'shelf_list': shelf_list,'breadcrumbs_list': breadcrumbs_list
        },
        context_instance=RequestContext(request))
Beispiel #21
0
def unit_create_edit(request, group_id, unit_group_id=None):
    '''
    creation as well as eit of units
    '''

    parent_group_name, parent_group_id = Group.get_group_name_id(group_id)
    unit_node = None
    if request.method == "GET":
        unit_node = node_collection.one({'_id': ObjectId(unit_group_id)})
        template = "ndf/create_unit.html"
        all_groups = node_collection.find({'_type': "Group"},{"name":1})
        all_groups_names = [str(each_group.name) for each_group in all_groups]
        modules = GSystem.query_list('home', 'Module', request.user.id)

        context_variables = {'group_id': parent_group_id,'groupid': parent_group_id, 'all_groups_names': all_groups_names, 
        'modules': modules}
        if unit_node:
            # get all modules which are parent's of this unit/group
            parent_modules = node_collection.find({
                    '_type': 'GSystem',
                    'member_of': gst_module_id,
                    'collection_set': {'$in': [unit_node._id]}
                })
            context_variables.update({'unit_node': unit_node, 'title': 'Create Unit',  'module_val_list': [str(pm._id) for pm in parent_modules]})
        req_context = RequestContext(request, context_variables)
        return render_to_response(template, req_context)

    elif request.method == "POST":
        group_name = request.POST.get('name', '')
        group_altnames = request.POST.get('altnames', '')
        unit_id_post = request.POST.get('node_id', '')
        unit_altnames = request.POST.get('altnames', '')
        content = request.POST.get('content', '')
        tags = request.POST.get('tags', [])
        language = request.POST.get('lan', '')
        group_type = request.POST.get('group_type', u'PUBLIC')

        educationallevel_val = request.POST.get('educationallevel', '')
        educationalsubject_val = request.POST.get('educationalsubject', '')
        # unit_group_id = unit_id_post if unit_id_post else unit_group_id
        # unit_group_name, unit_group_id = Group.get_group_name_id(unit_group_id)
        if unit_id_post:
            unit_node = node_collection.one({'_id': ObjectId(unit_id_post)})
        success_flag = False
        if unit_node:
            if unit_node.altnames is not unit_altnames:
                unit_node.altnames = unit_altnames
                success_flag = True
        else:
            unit_group = CreateGroup(request)
            result = unit_group.create_group(group_name,
                                            group_id=parent_group_id,
                                            member_of=gst_base_unit_id,
                                            node_id=unit_group_id)
            success_flag = result[0]
            unit_node = result[1]

        unit_id = unit_node._id
        if language:
            language_val = get_language_tuple(unicode(language))
            unit_node.language = language_val
        if educationallevel_val and "choose" not in educationallevel_val.lower():
            educationallevel_at = node_collection.one({'_type': 'AttributeType', 'name': "educationallevel"})
            create_gattribute(unit_node._id, educationallevel_at, educationallevel_val)
        if educationalsubject_val and "choose" not in educationalsubject_val.lower():
            educationalsubject_at = node_collection.one({'_type': 'AttributeType', 'name': "educationalsubject"})
            create_gattribute(unit_node._id, educationalsubject_at, educationalsubject_val)
        # modules
        module_val = request.POST.getlist('module', [])
        # get all modules which are parent's of this unit/group
        parent_modules = node_collection.find({
                '_type': 'GSystem',
                'member_of': gst_module_id,
                'collection_set': {'$in': [unit_id]}
            })
        # check for any mismatch in parent_modules and module_val
        if parent_modules or module_val:
            # import ipdb; ipdb.set_trace()
            module_oid_list = [ObjectId(m) for m in module_val if m]
            parent_modules_oid_list = [o._id for o in parent_modules]

            # summing all ids to iterate over
            oids_set = set(module_oid_list + parent_modules_oid_list)

            for each_oid in oids_set:
                if each_oid not in module_oid_list:
                    # it is an old module existed with curent unit.
                    # remove current node's id from it's collection_set
                    # existing deletion
                    each_node_obj = Node.get_node_by_id(each_oid)
                    each_node_obj_cs = each_node_obj.collection_set
                    each_node_obj_cs.pop(each_node_obj_cs.index(unit_id))
                    each_node_obj.collection_set = each_node_obj_cs
                    each_node_obj.save(group_id=group_id)
                elif each_oid not in parent_modules_oid_list:
                    # if this id does not exists with existing parent's id list
                    # then add current node_id in collection_set of each_oid.
                    # new addition
                    each_node_obj = Node.get_node_by_id(each_oid)
                    if unit_id not in each_node_obj.collection_set:
                        each_node_obj.collection_set.append(unit_id)
                        each_node_obj.save(group_id=group_id)

        if not success_flag:
            return HttpResponseRedirect(reverse('list_units', kwargs={'group_id': parent_group_id, 'groupid': parent_group_id,}))

        # if tags:
        #     if not type(tags) is list:
        #         tags = [unicode(t.strip()) for t in tags.split(",") if t != ""]
        #     unit_node.tags = tags
        if tags:
            tags = json.loads(tags)
        else:
            tags = []
        # unit_node.tags = tags
        unit_node.fill_group_values(group_type=group_type,tags=tags,author_set=unit_node.author_set)
        unit_node.content = content
        tab_name = request.POST.get('tab_name', '')
        section_name = request.POST.get('section_name', '')
        subsection_name = request.POST.get('subsection_name', '')
        if tab_name:
            unit_node['project_config'].update( {"tab_name":tab_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list :
            unit_node['project_config'].update( {"tab_name":"Lessons"})
        else:
            unit_node['project_config'].update( {"tab_name":"Tab Name"})
        
        if section_name:
            unit_node['project_config'].update( {"section_name":section_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list :
            unit_node['project_config'].update({"section_name":"Lesson"})
        else:
            unit_node['project_config'].update({"section_name":"Section"})

        if subsection_name:
            unit_node['project_config'].update( {"subsection_name":subsection_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list :
            unit_node['project_config'].update({"subsection_name":"Add from Activities"})
        else:
            unit_node['project_config'].update({"subsection_name":"Add SubSection"})

        unit_node.save()
        return HttpResponseRedirect(reverse('course_about',
            kwargs={'group_id': unit_node._id}))
Beispiel #22
0
def write_files(request, group_id, make_collection=False, unique_gs_per_file=True, **kwargs):

	user_id = request.user.id
	try:
		user_id = Author.extract_userid(request, **kwargs)
	except Exception as e:
		pass
	# print "user_id: ", user_id

	# author_obj = node_collection.one({'_type': u'Author', 'created_by': int(user_id)})
	author_obj = Author.get_author_obj_from_name_or_id(user_id)
	author_obj_id = author_obj._id
	kwargs['created_by'] = user_id

	group_name, group_id = get_group_name_id(group_id)

	first_obj      = None
	collection_set = []
	uploaded_files = request.FILES.getlist('filehive', [])
	name           = request.POST.get('name')

	gs_obj_list    = []
	for each_file in uploaded_files:

		gs_obj = node_collection.collection.GSystem()

		language = request.POST.get('language', GSTUDIO_SITE_DEFAULT_LANGUAGE)
		language = get_language_tuple(language)

		group_set = [ObjectId(group_id), ObjectId(author_obj_id)]

		if name and not first_obj and (name != 'untitled'):
			file_name = name
		else:
			file_name = each_file.name if hasattr(each_file, 'name') else name

		existing_file_gs = gs_obj.fill_gstystem_values(request=request,
									name=file_name,
									group_set=group_set,
									language=language,
									uploaded_file=each_file,
									unique_gs_per_file=unique_gs_per_file,
									**kwargs)
		# print "existing_file_gs",existing_file_gs
		if (gs_obj.get('_id', None) or existing_file_gs.get('_id', None)) and \
		   (existing_file_gs.get('_id', None) == gs_obj.get('_id', None)):
			if gst_file_id not in gs_obj.member_of:
				gs_obj.member_of.append(gst_file_id)

			gs_obj.save(groupid=group_id,validate=False)

			if 'video' in gs_obj.if_file.mime_type:
				convertVideo.delay(user_id, str(gs_obj._id), file_name)
			if not first_obj:
				first_obj = gs_obj
			else:
				collection_set.append(gs_obj._id)

			gs_obj_list.append(gs_obj)
		elif existing_file_gs:
				gs_obj_list.append(existing_file_gs)

	if make_collection and collection_set:
		first_obj.collection_set = collection_set
		first_obj.save()

	return gs_obj_list
Beispiel #23
0
        file_not_found_msg += "- Name     : " + resource_data["name"] + "\n"
        file_not_found_msg += "- File Name: " + resource_data["file_name"] + "\n"
        file_not_found_msg += "- URL      : " + resource_link + "\n\n"
        file_not_found_msg += "- ERROR    : " + str(e) + "\n\n"
        log_file_not_found.append(file_not_found_msg)
        return None

    # print "======", type(files)
    files = io.BytesIO(files.read())
    files.name = filename

    name = unicode(resource_data["name"])  # name to be given to gsystem
    userid = resource_data["created_by"]
    content_org = resource_data["content_org"]
    tags = resource_data["tags"]
    language = get_language_tuple(eval(resource_data['language']))
    group_set_id = ObjectId(group_set_id) if group_set_id else home_group._id

    img_type = None
    access_policy = None
    usrname = "nroer_team"

    files.seek(0)

    fh_obj = filehive_collection.collection.Filehive()

    # file_md5 = fh_obj.get_file_md5(files)
    # # print "file_md5 : ", file_md5

    # filehive_obj = filehive_collection.find_one({'md5': unicode(file_md5)})
    # # print 'filehive\n', filehive_obj, "\n\n"
Beispiel #24
0
def unit_create_edit(request, group_id, unit_group_id=None):
    '''
    creation as well as eit of units
    '''

    parent_group_name, parent_group_id = Group.get_group_name_id(group_id)
    unit_node = None
    if request.method == "GET":
        unit_node = node_collection.one({'_id': ObjectId(unit_group_id)})
        template = "ndf/create_unit.html"
        all_groups = node_collection.find({'_type': "Group"}, {"name": 1})
        all_groups_names = [str(each_group.name) for each_group in all_groups]
        modules = GSystem.query_list('home', 'Module', request.user.id)

        context_variables = {
            'group_id': parent_group_id,
            'groupid': parent_group_id,
            'all_groups_names': all_groups_names,
            'modules': modules
        }
        if unit_node:
            # get all modules which are parent's of this unit/group
            parent_modules = node_collection.find({
                '_type': 'GSystem',
                'member_of': gst_module_id,
                'collection_set': {
                    '$in': [unit_node._id]
                }
            })
            context_variables.update({
                'unit_node':
                unit_node,
                'title':
                'Create Unit',
                'module_val_list': [str(pm._id) for pm in parent_modules]
            })
        req_context = RequestContext(request, context_variables)
        return render_to_response(template, req_context)

    elif request.method == "POST":
        group_name = request.POST.get('name', '')
        group_altnames = request.POST.get('altnames', '')
        unit_id_post = request.POST.get('node_id', '')
        unit_altnames = request.POST.get('altnames', '')
        content = request.POST.get('content', '')
        tags = request.POST.get('tags', [])
        language = request.POST.get('lan', '')

        educationallevel_val = request.POST.get('educationallevel', '')
        educationalsubject_val = request.POST.get('educationalsubject', '')
        # unit_group_id = unit_id_post if unit_id_post else unit_group_id
        # unit_group_name, unit_group_id = Group.get_group_name_id(unit_group_id)
        if unit_id_post:
            unit_node = node_collection.one({'_id': ObjectId(unit_id_post)})
        success_flag = False
        if unit_node:
            if unit_node.altnames is not unit_altnames:
                unit_node.altnames = unit_altnames
                success_flag = True
        else:
            unit_group = CreateGroup(request)
            result = unit_group.create_group(group_name,
                                             group_id=parent_group_id,
                                             member_of=gst_base_unit_id,
                                             node_id=unit_group_id)
            success_flag = result[0]
            unit_node = result[1]

        unit_id = unit_node._id
        if language:
            language_val = get_language_tuple(unicode(language))
            unit_node.language = language_val
        if educationallevel_val and "choose" not in educationallevel_val.lower(
        ):
            educationallevel_at = node_collection.one({
                '_type':
                'AttributeType',
                'name':
                "educationallevel"
            })
            create_gattribute(unit_node._id, educationallevel_at,
                              educationallevel_val)
        if educationalsubject_val and "choose" not in educationalsubject_val.lower(
        ):
            educationalsubject_at = node_collection.one({
                '_type':
                'AttributeType',
                'name':
                "educationalsubject"
            })
            create_gattribute(unit_node._id, educationalsubject_at,
                              educationalsubject_val)
        # modules
        module_val = request.POST.getlist('module', [])
        # get all modules which are parent's of this unit/group
        parent_modules = node_collection.find({
            '_type': 'GSystem',
            'member_of': gst_module_id,
            'collection_set': {
                '$in': [unit_id]
            }
        })
        # check for any mismatch in parent_modules and module_val
        if parent_modules or module_val:
            # import ipdb; ipdb.set_trace()
            module_oid_list = [ObjectId(m) for m in module_val if m]
            parent_modules_oid_list = [o._id for o in parent_modules]

            # summing all ids to iterate over
            oids_set = set(module_oid_list + parent_modules_oid_list)

            for each_oid in oids_set:
                if each_oid not in module_oid_list:
                    # it is an old module existed with curent unit.
                    # remove current node's id from it's collection_set
                    # existing deletion
                    each_node_obj = Node.get_node_by_id(each_oid)
                    each_node_obj_cs = each_node_obj.collection_set
                    each_node_obj_cs.pop(each_node_obj_cs.index(unit_id))
                    each_node_obj.collection_set = each_node_obj_cs
                    each_node_obj.save(group_id=group_id)
                elif each_oid not in parent_modules_oid_list:
                    # if this id does not exists with existing parent's id list
                    # then add current node_id in collection_set of each_oid.
                    # new addition
                    each_node_obj = Node.get_node_by_id(each_oid)
                    if unit_id not in each_node_obj.collection_set:
                        each_node_obj.collection_set.append(unit_id)
                        each_node_obj.save(group_id=group_id)

        if not success_flag:
            return HttpResponseRedirect(
                reverse('list_units',
                        kwargs={
                            'group_id': parent_group_id,
                            'groupid': parent_group_id,
                        }))

        # if tags:
        #     if not type(tags) is list:
        #         tags = [unicode(t.strip()) for t in tags.split(",") if t != ""]
        #     unit_node.tags = tags
        if tags:
            tags = json.loads(tags)
        else:
            tags = []
        # unit_node.tags = tags
        unit_node.fill_gstystem_values(tags=tags,
                                       author_set=unit_node.author_set)
        unit_node.content = content
        tab_name = request.POST.get('tab_name', '')
        section_name = request.POST.get('section_name', '')
        subsection_name = request.POST.get('subsection_name', '')
        if tab_name:
            unit_node['project_config'].update({"tab_name": tab_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list:
            unit_node['project_config'].update({"tab_name": "Lessons"})
        else:
            unit_node['project_config'].update({"tab_name": "Tab Name"})

        if section_name:
            unit_node['project_config'].update({"section_name": section_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list:
            unit_node['project_config'].update({"section_name": "Lesson"})
        else:
            unit_node['project_config'].update({"section_name": "Section"})

        if subsection_name:
            unit_node['project_config'].update(
                {"subsection_name": subsection_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list:
            unit_node['project_config'].update(
                {"subsection_name": "Add from Activities"})
        else:
            unit_node['project_config'].update(
                {"subsection_name": "Add SubSection"})

        unit_node.save()
        return HttpResponseRedirect(
            reverse('course_about', kwargs={'group_id': unit_node._id}))
Beispiel #25
0
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)
Beispiel #26
0
def get_lang_node(node_id,lang):
    rel_value = get_relation_value(ObjectId(node_id),"translation_of")
    for each in rel_value['grel_node']:
        if each.language[0] ==  get_language_tuple(lang)[0]:
            trans_node = each
            return trans_node
Beispiel #27
0
def create_edit_quiz_item(request, group_id, node_id=None, trans_node_id=None, lang='en'):
    """Creates/Modifies details about the given quiz-item.
    """
    try:
        group_id = ObjectId(group_id)
    except:
        group_name, group_id = get_group_name_id(group_id)
    group_object = node_collection.one({'_id': ObjectId(group_id)})
    rt_translation_of = Node.get_name_id_from_type('translation_of', 'RelationType', get_obj=True)

    node = quiz_node = quiz_node_id = quiz_item_node = None
    existing_grel = translate_grel = None

    translated_node = Node.get_node_by_id(ObjectId(trans_node_id))
    question_content = None
    options_list = []
    group_object_member_of_names_list = group_object.member_of_names_list
    gst_quiz_item_node = node_collection.one({'_type': u'GSystemType', 'name': u'QuizItem'})
    if "CourseEventGroup" in group_object_member_of_names_list or "announced_unit" in group_object_member_of_names_list:
        gst_quiz_item_node = gst_quiz_item_event

    current_url = resolve(request.path_info).url_name
    context_variables = { 'title': gst_quiz_item_node.name,
                          'quiz_type_choices': QUIZ_TYPE_CHOICES,
                          'group_id': group_id,
                          'groupid': group_id,
                        }

    if "translate" in current_url:
        context_variables.update({'translate': True})
    language = get_language_tuple(lang)
    quiz_node_id = request.GET.get('quiznode','')
    return_url = request.GET.get('return_url','')
    if return_url:
        context_variables['return_url'] = return_url
    if quiz_node_id:
        quiz_node = node_collection.one({'_id': ObjectId(quiz_node_id)})
        context_variables['quiz_node_id'] = quiz_node._id
    if node_id:
        node = node_collection.one({'_id': ObjectId(node_id)})
        if gst_quiz._id in node.member_of:
            # Add question from a given Quiz category's context
            quiz_node = node
        else:
            # Edit a question
            quiz_item_node = node
    if translated_node:
        question_content = translated_node.content
        options_list = get_quiz_item_options(translated_node)
    else:
        if quiz_item_node:
            question_content = quiz_item_node.content
            options_list = get_quiz_item_options(quiz_item_node)
            existing_grel = triple_collection.one({
                                                '_type': 'GRelation',
                                                'subject': ObjectId(quiz_item_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)
                if translated_node:
                    trans_node_id = translated_node._id
    if request.method == "POST":
        usrid = int(request.user.id)
        usrname = unicode(request.user.username)
        translate = request.POST.get('translate', False)
        quiz_node_id = request.POST.get('quiz_node_id','')
        maximum_attempts_val = request.POST.get('maximum_attempts','1')
        problem_weight_val = request.POST.get('problem_weight','1')
        show_correct_ans_val = request.POST.get('show_correct_ans','False')
        check_ans_val = request.POST.get('check_ans','False')
        quiz_type = request.POST.get('quiz_type_val','')
        # print "\n\n maximum_attempts",maximum_attempts_val
        # print "\n problem_weight",problem_weight_val
        # print "\n show_correct_ans",show_correct_ans_val
        if translate:
            translated_node = created_trans_node(request, group_id, node_id, trans_node_id, language)
            if quiz_type == QUIZ_TYPE_CHOICES[1] or quiz_type == QUIZ_TYPE_CHOICES[2]:
                    options = options_attachment(request, translated_node, language)
        # if node_id:
        #     quiz_item_node = node_collection.one({'_id': ObjectId(node_id)})
        # else:
        #     # Add miscellaneous question
        #     quiz_item_node = node_collection.collection.GSystem()

        elif node_id:
            node = node_collection.one({'_id': ObjectId(node_id)})

            if gst_quiz._id in node.member_of:
                # Add question from a given Quiz category's context
                quiz_node = node
                quiz_item_node = node_collection.collection.GSystem()

            else:
                # Edit a question
                quiz_item_node = node
        else:
            # Add miscellaneous question
            quiz_item_node = node_collection.collection.GSystem()
            # quiz_item_node = node_collection.one({'_id': ObjectId(node_id)})
        # question_content = request.POST.get('content_org','')

        if not translate:

            name,content = get_quiz_item_name_content(request)
            quiz_item_node.name = unicode(name)

            quiz_type_AT = node_collection.one({'_type': "AttributeType", 'name': "quiz_type"})
            correct_answer_AT = node_collection.one({'_type': "AttributeType", 'name': "correct_answer"})
            quizitem_show_correct_ans_AT = node_collection.one({'_type': "AttributeType", 'name': "quizitem_show_correct_ans"})
            quizitem_problem_weight_AT = node_collection.one({'_type': "AttributeType", 'name': "quizitem_problem_weight"})
            quizitem_max_attempts_AT = node_collection.one({'_type': "AttributeType", 'name': "quizitem_max_attempts"})
            quizitem_check_ans_AT = node_collection.one({'_type': "AttributeType", 'name': "quizitem_check_answer"})

            quiz_item_node.altnames = quiz_item_node.content
            quiz_item_node.save(is_changed=get_node_common_fields(request, quiz_item_node, group_id, gst_quiz_item_node),groupid=group_id)
            # quiz_item_node.language = language
            if quiz_node_id:
                quiz_node = node_collection.one({'_id': ObjectId(quiz_node_id)})

            # create gattribute quiz_type,options, correct_answer
            # quiz_item_node['quiz_type'] = unicode(quiz_type)
            create_gattribute(quiz_item_node._id, quizitem_max_attempts_AT, int(maximum_attempts_val))
            create_gattribute(quiz_item_node._id, quizitem_problem_weight_AT, float(problem_weight_val))
            create_gattribute(quiz_item_node._id, quizitem_show_correct_ans_AT, eval(show_correct_ans_val))
            create_gattribute(quiz_item_node._id, quiz_type_AT, unicode(quiz_type))
            create_gattribute(quiz_item_node._id, quizitem_check_ans_AT, eval(check_ans_val))

            # If "quiz_type" is either 'Single-Choice' or 'Multiple-Choice', then only extract options
            if quiz_type == QUIZ_TYPE_CHOICES[1] or quiz_type == QUIZ_TYPE_CHOICES[2]:
                options = options_attachment(request, quiz_item_node, language)

            # Extracting correct-answer, depending upon 'Multiple-Choice' / 'Single-Choice'
            qt_initial = quiz_type[:quiz_type.find("-")].lower()
            # quiz_item_node['correct_answer'] = []

            correct_ans_val = None
            if quiz_type == QUIZ_TYPE_CHOICES[1]: # Single Choice
                correct_ans_val = request.POST.getlist('correct_answer_' + qt_initial)
                # quiz_item_node['correct_answer'].append(correct_answer)
            elif quiz_type == QUIZ_TYPE_CHOICES[2]: # Multiple Choice
                correct_ans_val = request.POST.getlist('correct_answer_' + qt_initial)
                # quiz_item_node['correct_answer'] = correct_answer

            if correct_ans_val: # To handle if Quiz-type is Short-Response
                correct_answer = map(int,correct_ans_val) # Convert list of unicode ele to list of int ele
                correct_ans_val_list = [options[each_val-1] for each_val in correct_answer]
                create_gattribute(quiz_item_node._id, correct_answer_AT, correct_ans_val_list)

            # thread_obj = create_thread_for_node(request,group_id, quiz_item_node)

            quiz_item_node.reload()
            quiz_item_node.status = u"PUBLISHED"

            quiz_item_node.save(groupid=group_id)

            # Create a thread for QuizItem also. Can be used in preview
            # Create thread node
            thread_node = create_thread_for_node(request,group_id, quiz_item_node)
            if "QuizItemEvent" in quiz_item_node.member_of_names_list:
                return_url = request.POST.get("return_url")
                # print "\n\n return_url", return_url, type(return_url)
                if return_url:
                    return HttpResponseRedirect(reverse(return_url, kwargs={'group_id': group_id}))
            if quiz_node:
                quiz_node.collection_set.append(quiz_item_node._id)
                quiz_node.save(groupid=group_id)
        return HttpResponseRedirect(reverse('quiz', kwargs={'group_id': group_id}))
    else:
        if node_id:
            if quiz_item_node:
                quiz_item_node.get_neighbourhood(quiz_item_node.member_of)
                context_variables.update({'node': quiz_item_node,
                    'groupid':group_id, 'group_id': group_id,
                    'translated_node': translated_node,
                    'question_content': question_content, 
                    'options_list': options_list })
        return render_to_response("ndf/quiz_item_create_edit.html",
                                  context_variables,
                                  context_instance=RequestContext(request)
                              )
Beispiel #28
0
def themes(request, group_id, app_id=None, app_set_id=None):

    try:
        group_id = ObjectId(group_id)
    except:
        group_name, group_id = get_group_name_id(group_id)

    theme_GST = node_collection.one({'_type': 'GSystemType', 'name': 'Theme'})

    if app_id is None:
        # app_ins = node_collection.find_one({'_type': 'GSystemType', 'name': 'Topics'})
        app_ins = app
        # if app_ins:
        app_id = str(app_ins._id)

    # Code for user shelf
    shelves = []
    shelf_list = {}
    auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) 
    
    # --- shelf commented for time being ---
    # 
    # 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 = []
    # End of user shelf

    appName = "topics"
    title = appName
    nodes_dict = []
    themes_list_items = ""
    themes_hierarchy = ""
    themes_cards = ""
    node = ""
    nodes = ""
    unfold_tree = request.GET.get('unfold','')
    selected = request.GET.get('selected','')
    # print "selected: ", selected
    tree = request.GET.get('tree', 'hierarchical')
    unfold = "false"

    # topics_GST = node_collection.find_one({'_type': 'GSystemType', 'name': 'Topics'})
    topics_GST = app
    
    if unfold_tree:
        unfold = unfold_tree
    
    if app_set_id:
        themes_list_items = True
        app_GST = node_collection.find_one({"_id": ObjectId(app_set_id)})
        
        if app_GST:
            title = theme_GST.name
            nodes = list(node_collection.find({'member_of': {'$all': [theme_GST._id]},'group_set':{'$all': [ObjectId(group_id)]}}))
            
            nodes_dict = []
            for each in nodes:
                nodes_dict.append({"id":str(each._id), "name":each.name, "created_by":User.objects.get(id=each.created_by).username, "created_at":each.created_at})

    # to display the tree hierarchy of themes items inside particular theme(Here app_id defines the Theme id)
    elif ObjectId(app_id) != topics_GST._id:
        themes_hierarchy = True
        themes_cards = ""
        Theme_obj = node_collection.one({'_id': ObjectId(app_id)})
        if Theme_obj:
            node = Theme_obj

    else:
        # This will show Themes as a card view on landing page of Topics
        themes_cards = True
        # if request.user.username:
        #     nodes_dict = node_collection.find({'member_of': {'$all': [theme_GST._id]},'group_set':{'$all': [ObjectId(group_id)]}})
        # else:
        #     nodes_dict = node_collection.find({'member_of': {'$all': [theme_GST._id]},'group_set':{'$all': [ObjectId(group_id)]}})
        
    lang = list(get_language_tuple(request.LANGUAGE_CODE))
    nodes_dict = node_collection.find({'member_of': {'$all': [theme_GST._id]},'group_set':{'$all': [ObjectId(group_id)]}, 'language': lang})

    return render_to_response("ndf/theme.html",
                               {'theme_GST_id':theme_GST._id, 'theme_GST':theme_GST, 'themes_cards': themes_cards, 'theme_GST':theme_GST,
                               'group_id': group_id,'groupid': group_id,'node': node,'shelf_list': shelf_list,'shelves': shelves, 'tree': tree,
                               'nodes':nodes_dict,'app_id': app_id,'app_name': appName,"selected": selected,
                               'title': title,'themes_list_items': themes_list_items,
                               'themes_hierarchy': themes_hierarchy, 'unfold': unfold,
                                'appId':app._id,
                               },
                             
                              context_instance = RequestContext(request)
    )       
Beispiel #29
0
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))
Beispiel #30
0
def explore_courses(request):

    # this will be announced tab
    title = 'courses'
    context_variable = {
        'title': title,
        'group_id': group_id,
        'groupid': group_id,
    }
    module_sort_list = get_attribute_value(group_id, 'items_sort_list')

    if module_sort_list:
        modules_cur = map(Node, module_sort_list)
        context_variable.update({'modules_is_cur': False})
    else:
        modules_cur = node_collection.find({
            'member_of': gst_module_id,
            'status': 'PUBLISHED'
        }).sort('last_update', -1)
        context_variable.update({'modules_is_cur': True})

    module_unit_ids = [
        val for each_module in modules_cur
        for val in each_module.collection_set
    ]

    primary_lang_tuple = get_language_tuple(GSTUDIO_PRIMARY_COURSE_LANGUAGE)
    '''
    katkamrachana - 14June2017
    About following query:

        [A]. Finding CourseEventGroup instances(First $and in $or):
                    Find CourseEventGroup instances, that are published.
                    Get courses that are linked to the request.user
                    Also find courses, that are "PUBLIC AND LANGUAGE falls under
                    GSTUDIO_PRIMARY_COURSE_LANGUAGE"
                    Hence, Apply language constraint. Introduced to display concerned
                    course for i2c(in 3 languages)
        [B]. Finding announced_unit instances(Second $and in $or):
                    Find announced_unit instances, that are published.
                    Get courses that are linked to the request.user
                    Also find courses, that are "PUBLIC"
                    No check on language
        [C]. Check using _type field in case conditions A and B fail, only Groups are
                 to be listed and not GSystems
        [D]. Check using name field in case conditions A and B fail,
                executing condition C then do not display factory Groups.

    '''
    base_unit_cur = node_collection.find({
        '$or': [{
            '$and': [{
                'member_of': ce_gst._id
            }, {
                'status': 'PUBLISHED'
            }, {
                '$or': [{
                    'created_by': request.user.id
                }, {
                    'group_admin': request.user.id
                }, {
                    'author_set': request.user.id
                }, {
                    '$and': [
                        {
                            'group_type': 'PUBLIC'
                        },
                        {
                            'language': primary_lang_tuple
                        },
                    ]
                }]
            }]
        }, {
            '$and': [{
                'member_of': announced_unit_gst._id
            }, {
                'status': 'PUBLISHED'
            }, {
                '$or': [{
                    'created_by': request.user.id
                }, {
                    'group_admin': request.user.id
                }, {
                    'author_set': request.user.id
                }, {
                    'group_type': 'PUBLIC'
                }]
            }]
        }],
        '_type':
        'Group',
        'name': {
            '$nin': GSTUDIO_DEFAULT_GROUPS_LIST
        },
        '_id': {
            '$nin': module_unit_ids
        },
    }).sort('last_update', -1)
    # base_unit_page_cur = paginator.Paginator(base_unit_cur, page_no, GSTUDIO_NO_OF_OBJS_PP)

    context_variable.update({
        'modules_cur': modules_cur,
        'units_cur': base_unit_cur
    })

    return render_to_response(
        # "ndf/explore.html", changed as per new Clix UI
        "ndf/explore_2017.html",
        # "ndf/lms_explore.html",
        context_variable,
        context_instance=RequestContext(request))
Beispiel #31
0
def unit_create_edit(request, group_id, unit_group_id=None):
    '''
    creation as well as eit of units
    '''

    parent_group_name, parent_group_id = Group.get_group_name_id(group_id)
    unit_node = None
    if request.method == "GET":
        unit_node = node_collection.one({'_id': ObjectId(unit_group_id)})
        template = "ndf/create_unit.html"
        all_groups = node_collection.find({'_type': "Group"},{"name":1})
        all_groups_names = [str(each_group.name) for each_group in all_groups]
        modules = GSystem.query_list('home', 'Module', request.user.id)

        context_variables = {'group_id': parent_group_id,'groupid': parent_group_id, 'all_groups_names': all_groups_names, 
        'modules': modules}
        if unit_node:
            # get all modules which are parent's of this unit/group
            parent_modules = node_collection.find({
                    '_type': 'GSystem',
                    'member_of': gst_module_id,
                    'collection_set': {'$in': [unit_node._id]}
                })
            context_variables.update({'unit_node': unit_node, 'title': 'Create Unit',  'module_val_list': [str(pm._id) for pm in parent_modules]})
        req_context = RequestContext(request, context_variables)
        return render_to_response(template, req_context)

    elif request.method == "POST":
        group_name = request.POST.get('name', '')
        group_altnames = request.POST.get('altnames', '')
        unit_id_post = request.POST.get('node_id', '')
        unit_altnames = request.POST.get('altnames', '')
        content = request.POST.get('content', '')
        tags = request.POST.get('tags', [])
        language = request.POST.get('lan', '')
        group_type = request.POST.get('group_type', u'PUBLIC')

        educationallevel_val = request.POST.get('educationallevel', '')
        educationalsubject_val = request.POST.get('educationalsubject', '')
        # unit_group_id = unit_id_post if unit_id_post else unit_group_id
        # unit_group_name, unit_group_id = Group.get_group_name_id(unit_group_id)
        if unit_id_post:
            unit_node = node_collection.one({'_id': ObjectId(unit_id_post)})
        success_flag = False
        if unit_node:
            if unit_node.altnames is not unit_altnames:
                unit_node.altnames = unit_altnames
                success_flag = True
        else:
            unit_group = CreateGroup(request)
            result = unit_group.create_group(group_name,
                                            group_id=parent_group_id,
                                            member_of=gst_base_unit_id,
                                            node_id=unit_group_id)
            success_flag = result[0]
            unit_node = result[1]

        unit_id = unit_node._id
        if language:
            language_val = get_language_tuple(unicode(language))
            unit_node.language = language_val
        if educationallevel_val and "choose" not in educationallevel_val.lower():
            educationallevel_at = node_collection.one({'_type': 'AttributeType', 'name': "educationallevel"})
            create_gattribute(unit_node._id, educationallevel_at, educationallevel_val)
        if educationalsubject_val and "choose" not in educationalsubject_val.lower():
            educationalsubject_at = node_collection.one({'_type': 'AttributeType', 'name': "educationalsubject"})
            create_gattribute(unit_node._id, educationalsubject_at, educationalsubject_val)

        # modules
        module_val = request.POST.getlist('module', [])
        if module_val:
            update_unit_in_modules(module_val, unit_id)

        if not success_flag:
            return HttpResponseRedirect(reverse('list_units', kwargs={'group_id': parent_group_id, 'groupid': parent_group_id,}))

        # if tags:
        #     if not type(tags) is list:
        #         tags = [unicode(t.strip()) for t in tags.split(",") if t != ""]
        #     unit_node.tags = tags
        if tags:
            tags = json.loads(tags)
        else:
            tags = []
        # unit_node.tags = tags
        unit_node.fill_group_values(group_type=group_type,tags=tags,author_set=unit_node.author_set)
        unit_node.content = content
        tab_name = request.POST.get('tab_name', '')
        resource_name = request.POST.get('resource_name', '')
        blog_name = request.POST.get('blog_name', '')
        section_name = request.POST.get('section_name', '')
        subsection_name = request.POST.get('subsection_name', '')

        if tab_name:
            unit_node['project_config'].update( {"tab_name":tab_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list :
            unit_node['project_config'].update( {"tab_name":"Lessons"})
        else:
            unit_node['project_config'].update( {"tab_name":"Tab Name"})

        if resource_name:
            unit_node['project_config'].update( {"resource_name":resource_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list :
            unit_node['project_config'].update( {"resource_name":"Resources"})
        else:
            unit_node['project_config'].update( {"resource_name":"Resource Name"})

        if blog_name:
            unit_node['project_config'].update( {"blog_name":blog_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list :
            unit_node['project_config'].update( {"blog_name":"e-Notes"})
        else:
            unit_node['project_config'].update( {"blog_name":"blog Name"})
        
        if section_name:
            unit_node['project_config'].update( {"section_name":section_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list :
            unit_node['project_config'].update({"section_name":"Lesson"})
        else:
            unit_node['project_config'].update({"section_name":"Section"})

        if subsection_name:
            unit_node['project_config'].update( {"subsection_name":subsection_name})
        elif "base_unit" in unit_node.member_of_names_list or "announced_unit" in unit_node.member_of_names_list :
            unit_node['project_config'].update({"subsection_name":"Add from Activities"})
        else:
            unit_node['project_config'].update({"subsection_name":"Add SubSection"})

        unit_node.save()
        return HttpResponseRedirect(reverse('course_content',
            kwargs={'group_id': unit_node._id}))
        file_not_found_msg += "- Name     : " + resource_data["name"] + "\n"
        file_not_found_msg += "- File Name: " + resource_data["file_name"] + "\n"
        file_not_found_msg += "- URL      : " + resource_link + "\n\n"
        file_not_found_msg += "- ERROR    : " + str(e) + "\n\n"
        log_file_not_found.append(file_not_found_msg)
        return None

    files = io.BytesIO(files.read())
    files.name = filename

    name = unicode(resource_data["name"])  # name to be given to gsystem
    userid = resource_data["created_by"]
    # content_org = resource_data["content_org"]
    tags = resource_data["tags"]
    if resource_data['language']:
        language = get_language_tuple(eval(resource_data['language']))
    else:
        language = ('en', 'English')
    group_set_id = ObjectId(group_set_id) if group_set_id else home_group._id

    img_type = None
    access_policy = None
    usrname = "nroer_team"

    files.seek(0)

    fh_obj = filehive_collection.collection.Filehive()

    filehive_obj_exists = fh_obj.check_if_file_exists(files)

    if filehive_obj_exists: