Exemple #1
0
def activity_create_edit(request, group_id, lesson_id=None):
    '''
    creation as well as edit of activities
    returns following list:
    {'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)
    lesson_id = request.POST.get('lesson_id')
    lesson_obj = Node.get_node_by_id(lesson_id)

    # parent unit id
    unit_id_post = request.POST.get('unit_id', '')
    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":
        # activity name
        activity_name = request.POST.get('name', '').strip()
        if not activity_name:
            msg = 'Name can not be empty.'
            result_dict = {'success': 0, 'unit_hierarchy': [], 'msg': msg}
            # return HttpResponse(result_dict)

        # unit_cs: unit collection_set
        lesson_cs_list = lesson_obj.collection_set
        lesson_cs_objs_cur = Node.get_nodes_by_ids_list(lesson_cs_list)
        lesson_cs_names_list = [u.name for u in lesson_cs_objs_cur]

        if activity_name in lesson_cs_names_list:
            msg = u'Activity with same name exists in lesson: ' + lesson_obj.name
            result_dict = {'success': 0, 'unit_hierarchy': [], 'msg': msg}
            # return HttpResponse(0)
        else:
            user_id = request.user.id
            new_activity_obj = node_collection.collection.GSystem()
            new_activity_obj.fill_gstystem_values(name=activity_name,
                                                  member_of=gst_activity_id,
                                                  group_set=unit_group_obj._id,
                                                  created_by=user_id,
                                                  status=u'PUBLISHED')
            new_activity_obj.save(groupid=group_id)

            lesson_obj.collection_set.append(new_activity_obj._id)
            lesson_obj.save(groupid=group_id)
            unit_structure = get_unit_hierarchy(unit_group_obj,
                                                request.LANGUAGE_CODE)

            msg = u'Added activity under lesson: ' + lesson_obj.name
            result_dict = {
                'success': 1,
                'unit_hierarchy': unit_structure,
                'msg': str(new_activity_obj._id)
            }
            # return HttpResponse(json.dumps(unit_structure))

    return HttpResponse(json.dumps(result_dict))
Exemple #2
0
def activity_create_edit(request, group_id, lesson_id=None):
    '''
    creation as well as edit of activities
    returns following list:
    {'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)
    lesson_id = request.POST.get('lesson_id')
    lesson_obj = Node.get_node_by_id(lesson_id)

    # parent unit id
    unit_id_post = request.POST.get('unit_id', '')
    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":
        # activity name
        activity_name = request.POST.get('name', '').strip()
        if not activity_name:
            msg = 'Name can not be empty.'
            result_dict = {'success': 0, 'unit_hierarchy': [], 'msg': msg}
            # return HttpResponse(result_dict)

        # unit_cs: unit collection_set
        lesson_cs_list = lesson_obj.collection_set
        lesson_cs_objs_cur = Node.get_nodes_by_ids_list(lesson_cs_list)
        lesson_cs_names_list = [u.name for u in lesson_cs_objs_cur]

        if activity_name in lesson_cs_names_list:
            msg = u'Activity with same name exists in lesson: ' + lesson_obj.name
            result_dict = {'success': 0, 'unit_hierarchy': [], 'msg': msg}
            # return HttpResponse(0)
        else:
            user_id = request.user.id
            new_activity_obj = node_collection.collection.GSystem()
            new_activity_obj.fill_gstystem_values(name=activity_name,
                                            member_of=gst_activity_id,
                                            group_set=unit_group_obj._id,
                                            created_by=user_id,
                                            status=u'PUBLISHED')
            new_activity_obj.save(groupid=group_id)

            lesson_obj.collection_set.append(new_activity_obj._id)
            lesson_obj.save(groupid=group_id)
            unit_structure = get_unit_hierarchy(unit_group_obj, request.LANGUAGE_CODE)

            msg = u'Added activity under lesson: ' + lesson_obj.name
            result_dict = {'success': 1, 'unit_hierarchy': unit_structure, 'msg': str(new_activity_obj._id)}
            # return HttpResponse(json.dumps(unit_structure))

    return HttpResponse(json.dumps(result_dict))
Exemple #3
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))
Exemple #4
0
def create_assetcontent(asset_id,
                        name,
                        group_name_or_id,
                        created_by,
                        node_id=None,
                        content=None,
                        files=[None],
                        resource_type='Page',
                        request=HttpRequest(),
                        **kwargs):

    # Mandatory arg: 'asset_id'. AssetContent should fall under Asset.
    # And if no Asset exists with supplied arg, can't proceeed.
    asset_obj = Node.get_node_by_id(asset_id)
    if not asset_obj:
        raise ValueError('No Asset exists with supplied asset_id.')

    if not name:
        name = request.POST.get('name') if request else None
    if not created_by:
        created_by = request.user.id if request else None

    group_name, group_id = get_group_name_id(group_name_or_id)
    group_id = ObjectId(group_id)
    if group_id not in asset_obj['group_set']:
        # AssetContent should fall under Asset. If 'group_id' arg is
        # supplied, it should fall under asset's group id.
        raise Exception(
            'Supplied group_id and group_id of Asset does not match.')

    test_content = True if (content or files) else False

    # compulsory values, if not found raise error.
    # if not all([name, created_by, group_id, uploaded_files]):

    if not all([name, created_by, group_id, test_content]):
        raise ValueError(
            '"asset_id", "name", "created_by", "group" and ("content" or "files") are mandatory args.'
        )

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

    group_set = [ObjectId(group_id), ObjectId(author_obj_id)]
    gst_name_id_dict = {
        'Page': gst_page_id,
        'page': gst_page_id,
        'File': gst_file_id,
        'file': gst_file_id
    }

    try:
        member_of_gst_id = gst_name_id_dict[resource_type]
    except Exception, e:
        print "resource_type arg is not supplied."
        # handle condition based on files.
        member_of_gst_id = gst_file_id if files[0] else gst_page_id
Exemple #5
0
def unit_order_list(request, group_id, node_id):
    response_dict = {"success": False}
    unit_id_list = request.POST.get('unit_list', [])
    print "untlst:", unit_id_list
    try:
        items_sort_list_gattr_node = triple_collection.one({
            '_type':
            'GAttribute',
            'subject':
            ObjectId(node_id),
            'attribute_type':
            at_items_sort_list._id,
            'status':
            u'PUBLISHED'
        })
        if items_sort_list_gattr_node:
            ga_node = delete_gattribute(node_id=items_sort_list_gattr_node._id,
                                        deletion_type=0)

        if unit_id_list:
            unit_id_list = json.loads(unit_id_list)
            unit_obj_list = map(
                lambda each_id: Node.get_node_by_id(ObjectId(each_id)),
                unit_id_list)
            ga_node = create_gattribute(ObjectId(node_id), 'items_sort_list',
                                        unit_obj_list)
            response_dict["success"] = True

    except Exception as module_order_list_err:
        print "\nError Occurred in module_order_list(). ", module_order_list_err
        pass
    return HttpResponse(json.dumps(response_dict))
Exemple #6
0
def module_create_edit(request, group_id, module_id=None, cancel_url='list_modules'):
    if request.method == "GET":

        template = 'ndf/module_form.html'
        additional_form_fields = {}
        module_attrs = ['educationalsubject', 'educationallevel']
        # ma: module attr
        module_attr_values = {ma: '' for ma in module_attrs}

        if module_id:
            # existing module.
            url_name = 'node_edit'
            url_kwargs={'group_id': group_id, 'node_id': module_id, 'detail_url_name': 'module_detail'}
            # updating module attr dict:
            module_obj = Node.get_node_by_id(module_id)
            module_attr_values = module_obj.get_attributes_from_names_list(module_attrs)

        else:
            # new module
            url_name = 'node_create'
            url_kwargs={'group_id': group_id, 'member_of': 'Module', 'detail_url_name': 'module_detail'}

        additional_form_fields = {
            'attribute': {
                'Subject': {
                    'name' :'educationalsubject',
                    'widget': 'dropdown',
                    'value': module_attr_values['educationalsubject'],
                    'all_options': GSTUDIO_RESOURCES_EDUCATIONAL_SUBJECT
                },
                'Grade': {
                    'name' :'educationallevel',
                    'widget': 'dropdown',
                    'widget_attr': 'multiple',
                    'value': module_attr_values['educationallevel'],
                    'all_options': GSTUDIO_RESOURCES_EDUCATIONAL_LEVEL
                }
            }
        }

        req_context = RequestContext(request, {
                                    'title': 'Module', 'node_obj': Node.get_node_by_id(module_id),
                                    'group_id': group_id, 'groupid': group_id,
                                    'additional_form_fields': additional_form_fields,
                                    'post_url': reverse(url_name, kwargs=url_kwargs)
                                })
        return render_to_response(template, req_context)
Exemple #7
0
def module_create_edit(request, group_id, module_id=None, cancel_url='list_modules'):
    if request.method == "GET":

        template = 'ndf/module_form.html'
        additional_form_fields = {}
        module_attrs = ['educationalsubject', 'educationallevel']
        # ma: module attr
        module_attr_values = {ma: '' for ma in module_attrs}

        if module_id:
            # existing module.
            url_name = 'node_edit'
            url_kwargs={'group_id': group_id, 'node_id': module_id, 'detail_url_name': 'module_detail'}
            # updating module attr dict:
            module_obj = Node.get_node_by_id(module_id)
            module_attr_values = module_obj.get_attributes_from_names_list(module_attrs)

        else:
            # new module
            url_name = 'node_create'
            url_kwargs={'group_id': group_id, 'member_of': 'Module', 'detail_url_name': 'module_detail'}

        additional_form_fields = {
            'attribute': {
                'Subject': {
                    'name' :'educationalsubject',
                    'widget': 'dropdown',
                    'value': module_attr_values['educationalsubject'],
                    'all_options': GSTUDIO_RESOURCES_EDUCATIONAL_SUBJECT
                },
                'Grade': {
                    'name' :'educationallevel',
                    'widget': 'dropdown',
                    'widget_attr': 'multiple',
                    'value': module_attr_values['educationallevel'],
                    'all_options': GSTUDIO_RESOURCES_EDUCATIONAL_LEVEL
                }
            }
        }

        req_context = RequestContext(request, {
                                    'title': 'Module', 'node_obj': Node.get_node_by_id(module_id),
                                    'group_id': group_id, 'groupid': group_id,
                                    'additional_form_fields': additional_form_fields,
                                    'post_url': reverse(url_name, kwargs=url_kwargs)
                                })
        return render_to_response(template, req_context)
Exemple #8
0
def module_detail(request, group_id, node_id):
    '''
    detail of of selected module
    '''
    group_name, group_id = Group.get_group_name_id(group_id)

    module_obj = Node.get_node_by_id(node_id)
    module_detail_query = {
        '_id': {
            '$in': module_obj.collection_set
        },
        'status':
        'PUBLISHED',
        '$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
        }]
    }

    # 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)
    template = 'ndf/module_detail.html'

    req_context = RequestContext(
        request, {
            'title': 'Module',
            'node': module_obj,
            'units_under_module': units_under_module,
            'group_id': group_id,
            'groupid': group_id,
            'card': 'ndf/event_card.html',
            'card_url_name': 'groupchange'
        })
    return render_to_response(template, req_context)
Exemple #9
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))
Exemple #10
0
 def validate_deletion(node_id,force_deletion=False):
     try:
         node_obj = Node.get_node_by_id(node_id)
         if node_obj:
             if force_deletion:
                 print "\n Force Deletion on: ", node_obj._id
                 node_obj.delete()
             else:
                 del_status, del_status_msg = delete_node(node_id=node_obj._id, deletion_type=1)
                 validate_deletion(node_id,force_deletion=True)
     except Exception as validate_deletion_err:
         print "\n Error occurred.", str(validate_deletion_err)
Exemple #11
0
def create_assetcontent(asset_id,
						name,
						group_name_or_id,
						created_by,
						node_id=None,
						content=None,
						files=[None],
						resource_type='Page',
						request=HttpRequest(),
						**kwargs):

	# Mandatory arg: 'asset_id'. AssetContent should fall under Asset.
	# And if no Asset exists with supplied arg, can't proceeed.
	asset_obj = Node.get_node_by_id(asset_id)
	if not asset_obj:
		raise ValueError('No Asset exists with supplied asset_id.')

	if not name:
		name = request.POST.get('name') if request else None
	if not created_by:
		created_by = request.user.id if request else None

	group_name, group_id = get_group_name_id(group_name_or_id)
	group_id = ObjectId(group_id)
	if group_id not in asset_obj['group_set']:
		# AssetContent should fall under Asset. If 'group_id' arg is
		# supplied, it should fall under asset's group id.
		raise Exception('Supplied group_id and group_id of Asset does not match.')

	test_content = True if (content or files) else False

	# compulsory values, if not found raise error.
	# if not all([name, created_by, group_id, uploaded_files]):

	if not all([name, created_by, group_id, test_content]):
		raise ValueError('"asset_id", "name", "created_by", "group" and ("content" or "files") are mandatory args.')

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

	group_set = [ObjectId(group_id), ObjectId(author_obj_id)]
	gst_name_id_dict = {
		'Page': gst_page_id, 'page': gst_page_id,
		'File': gst_file_id, 'file': gst_file_id
	}

	try:
		member_of_gst_id = gst_name_id_dict[resource_type]
	except Exception, e:
		print "resource_type arg is not supplied."
		# handle condition based on files.
		member_of_gst_id = gst_file_id if files[0] else gst_page_id
Exemple #12
0
def module_order_list(request):
    response_dict = {"success": False}
    module_id_list = request.POST.get('module_list', [])
    try:
        if module_id_list:
            module_id_list = json.loads(module_id_list)
            module_obj_list = map(lambda each_id: Node.get_node_by_id(ObjectId(each_id)), module_id_list)
            ga_node = create_gattribute(ObjectId(group_id), 'items_sort_list', module_obj_list)
            response_dict["success"] = True
    except Exception as module_order_list_err:
        print "\nError Occurred in module_order_list(). ", module_order_list_err
        pass
    return HttpResponse(json.dumps(response_dict))
Exemple #13
0
 def validate_deletion(node_id, force_deletion=False):
     try:
         node_obj = Node.get_node_by_id(node_id)
         if node_obj:
             if force_deletion:
                 print "\n Force Deletion on: ", node_obj._id
                 node_obj.delete()
             else:
                 del_status, del_status_msg = delete_node(
                     node_id=node_obj._id, deletion_type=1)
                 validate_deletion(node_id, force_deletion=True)
     except Exception as validate_deletion_err:
         print "\n Error occurred.", str(validate_deletion_err)
Exemple #14
0
def module_order_list(request):
    response_dict = {"success": False}
    module_id_list = request.POST.get('module_list', [])
    try:
        if module_id_list:
            module_id_list = json.loads(module_id_list)
            module_obj_list = map(lambda each_id: Node.get_node_by_id(ObjectId(each_id)), module_id_list)
            ga_node = create_gattribute(ObjectId(group_id), 'items_sort_list', module_obj_list)
            response_dict["success"] = True
    except Exception as module_order_list_err:
        print "\nError Occurred in module_order_list(). ", module_order_list_err
        pass
    return HttpResponse(json.dumps(response_dict))
Exemple #15
0
 def _group_deletion(group_id):
     try:
         group_obj = Group.get_group_name_id(group_id, get_obj=True)
         if group_obj:
             Group.purge_group(group_id, proceed=proceed_flag)
             validate_deletion(group_id)
         else:
             node_obj = Node.get_node_by_id(group_id)
             # If the ObjectId entered is not of a Group
             if node_obj:
                 if node_obj.collection_set:
                     for each_obj_id in node_obj.collection_set:
                         _group_deletion(each_obj_id)
                 del_status, del_status_msg = delete_node(node_id=node_obj._id, deletion_type=1)
                 validate_deletion(node_obj._id)
     except Exception as group_del_err:
         print "\n Error occurred.", str(group_del_err)
Exemple #16
0
def get_group_content(node_id, lang="en"):

    print "inside group content", node_id
    grp_dict = {}
    node_obj = Node.get_node_by_id(node_id)
    if node_obj:
        trans_grp = get_lang_node(node_id, lang)
        if trans_grp:
            grp_dict['label'] = trans_grp.name
            grp_dict['altlabel'] = trans_grp.altnames
            grp_dict['content'] = trans_grp.content
        else:
            grp_dict['label'] = node_obj.name
            grp_dict['altlabel'] = node_obj.altnames
            grp_dict['content'] = node_obj.content

    return grp_dict
Exemple #17
0
 def _group_deletion(group_id):
     try:
         group_obj = Group.get_group_name_id(group_id, get_obj=True)
         if group_obj:
             Group.purge_group(group_id, proceed=proceed_flag)
             validate_deletion(group_id)
         else:
             node_obj = Node.get_node_by_id(group_id)
             # If the ObjectId entered is not of a Group
             if node_obj:
                 if node_obj.collection_set:
                     for each_obj_id in node_obj.collection_set:
                         _group_deletion(each_obj_id)
                 del_status, del_status_msg = delete_node(
                     node_id=node_obj._id, deletion_type=1)
                 validate_deletion(node_obj._id)
     except Exception as group_del_err:
         print "\n Error occurred.", str(group_del_err)
Exemple #18
0
def module_detail(request, group_id, node_id):
    '''
    detail of of selected module
    '''
    group_name, group_id = Group.get_group_name_id(group_id)

    module_obj = Node.get_node_by_id(node_id)
    module_detail_query = {'_id': {'$in': module_obj.collection_set},
    'status':'PUBLISHED',
    '$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}
      ]}



    # 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)
    template = 'ndf/module_detail.html'

    req_context = RequestContext(request, {
                                'title': 'Module',
                                'node': module_obj, 'units_under_module': units_under_module,
                                'group_id': group_id, 'groupid': group_id,
                                'card': 'ndf/event_card.html', 'card_url_name': 'groupchange'
                            })
    return render_to_response(template, req_context)
Exemple #19
0
def module_order_list(request):
    response_dict = {"success": False}
    module_id_list = request.POST.get('module_list', [])
    try:
        items_sort_list_gattr_node = triple_collection.one({'_type': 'GAttribute', 'subject': group_id, 
            'attribute_type': at_items_sort_list._id, 'status': u'PUBLISHED'})
        if items_sort_list_gattr_node:
            ga_node = delete_gattribute(node_id=items_sort_list_gattr_node._id, deletion_type=0)

        if module_id_list:
            module_id_list = json.loads(module_id_list)
            module_obj_list = map(lambda each_id: Node.get_node_by_id(ObjectId(each_id)), module_id_list)
            ga_node = create_gattribute(ObjectId(group_id), 'items_sort_list', module_obj_list)
            response_dict["success"] = True

    except Exception as module_order_list_err:
        print "\nError Occurred in module_order_list(). ", module_order_list_err
        pass
    return HttpResponse(json.dumps(response_dict))
Exemple #20
0
def all_translations(request, group_id, node_id):
    '''
    returns all translated nodes of provided node.
    '''
    node_obj = Node.get_node_by_id(node_id)
    # node_translation_grels = node_obj.get_relation('translation_of', status='PUBLISHED')
    # return node_translation_grels

    # node_translation_grels = node_obj.get_relation('translation_of')
    all_translation_nodes = node_obj.get_relation_right_subject_nodes(
        'translation_of')

    return render_to_response("ndf/translation_list.html", {
        'group_id': Group.get_group_name_id(group_id)[1],
        'groupid': Group.get_group_name_id(group_id)[1],
        'nodes': all_translation_nodes,
        'node': node_obj,
        'source_node_id': node_id,
        'card_url_name': 'show_translation',
        'supported_languages': supported_languages
    },
                              context_instance=RequestContext(request))
Exemple #21
0
def all_translations(request, group_id, node_id):
    '''
    returns all translated nodes of provided node.
    '''
    node_obj = Node.get_node_by_id(node_id)
    # node_translation_grels = node_obj.get_relation('translation_of', status='PUBLISHED')
    # return node_translation_grels

    # node_translation_grels = node_obj.get_relation('translation_of')
    all_translation_nodes = node_obj.get_relation_right_subject_nodes('translation_of')

    return render_to_response("ndf/translation_list.html",
                              {
                                'group_id': Group.get_group_name_id(group_id)[1],
                                'groupid': Group.get_group_name_id(group_id)[1],
                                'nodes': all_translation_nodes,
                                'node': node_obj,
                                'source_node_id': node_id,
                                'card_url_name': 'show_translation',
                                'supported_languages': supported_languages
                               },
                              context_instance=RequestContext(request))
Exemple #22
0
                  re.IGNORECASE)

# To collect all the activities under the English module
english_module_names = ['English Elementary', 'English Beginner']
english_modules = node_collection.find(
    {
        '_type': 'GSystem',
        'name': {
            '$in': english_module_names
        }
    }, {
        '_id': 1,
        'collection_set': 1
    })

page_gst_id = Node.get_name_id_from_type('Page', 'GSystemType')[1]
trnsnd_gst_id = Node.get_name_id_from_type('trans_node', 'GSystemType')[1]
gsystemnds = node_collection.find({
    '_type': 'GSystem',
    'member_of': {
        '$in': [trnsnd_gst_id, page_gst_id]
    },
    'group_set': {
        '$in':
        [eachid for each in english_modules for eachid in each.collection_set]
    },
    'collection_set': [],
    'content': regx
})

#For each node if the pattern matched more than twice then we change the first 2 occurances of the string "toggler" with "toggler09"
Exemple #23
0
    ObjectId('59425f864975ac013d976ac6'),
    ObjectId('59425ead4975ac013bf0f54b'),
    ObjectId('594260a54975ac013d976dc3')
]

module_sort_order_ids = [u'59abb47c69602a0156036296', u'5945db6e2c4796014abd1784',\
 u'5945db2e2c4796014ddff67a', u'5945de532c4796014abd181a', u'5945de362c4796014ce12d7f',\
 u'5938ed2369602a014cb67195', u'5945ddca2c4796014ddff735', u'599c139269602a013fe31aa2',\
 u'59816df569602a015784baea', u'594b833869602a013f0cb6ce', u'594cfbea69602a014089845b', \
 u'597ebd7b69602a0154bb417e', u'5945daf42c4796014ce12d2d', u'59aff39869602a0155bfac16']

try:
    module_obj_list = []
    for each_id in module_sort_order_ids:
        try:
            each_node = Node.get_node_by_id(ObjectId(each_id))
            if each_node:
                module_obj_list.append(each_node)
        except Exception as modulde_not_found_err:
            print "\nError in module_not_found for each_id: ", each_id, "\nError: ", modulde_not_found_err
            pass
    print "\nTotal modules: ", len(module_obj_list)
    home_grp_id = node_collection.one({'_type': 'Group', 'name': 'home'})._id
    create_gattribute(home_grp_id, 'items_sort_list', module_obj_list)
except Exception as module_sort_order_ids_err:
    pass
    print "\nError in module_sort_order_ids. ", module_sort_order_ids_err
units_cur = node_collection.find({
    '_type': 'Group',
    '_id': {
        '$in': units_for_renaming_leaf_nodes
Exemple #24
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))
Exemple #25
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}))
Exemple #26
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))
Exemple #27
0
'''
Script which updates the collection_set of the Groups defined for OER with the respective modules

'''
from gnowsys_ndf.ndf.models import node_collection, triple_collection, Node, GAttribute
from bson import ObjectId

OER_GROUPS = ['Mathematics', 'Science', 'English']
oer_grp_details = {}
for eachgrp in OER_GROUPS:
    nd_data = Node.get_name_id_from_type(eachgrp, 'Group', True)
    oer_grp_details.update({str(nd_data.name): nd_data})

module_gst_id = Node.get_name_id_from_type('Module', 'GSystemType')[1]
allmodules_cur = node_collection.find({
    '_type': 'GSystem',
    'member_of': module_gst_id
})

for each in all_modules_cur:
    attrbval = GAttribute.get_triples_from_sub_type_list(
        each._id, 'educationalsubject')
    #print attrbval
    if attrbval and attrbval['educationalsubject'] != None:
        sbjt = attrbval['educationalsubject']['object_value']
        print sbjt, each._id
        if sbjt in oer_grp_details.keys():
            oer_grp_details[sbjt].collection_set.append(each._id)
    else:
        pass
Exemple #28
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}))
Exemple #29
0
def get_unit_hierarchy(unit_group_obj, lang="en"):
    '''
    ARGS: unit_group_obj
    Result will be of following form:
    {
        name: 'Lesson1',
        type: 'lesson',
        id: 'l1',
        activities: [
            {
                name: 'Activity 1',
                type: 'activity',
                id: 'a1'
            },
            {
                name: 'Activity 1',
                type: 'activity',
                id: 'a2'
            }
        ]
    }, {
        name: 'Lesson2',
        type: 'lesson',
        id: 'l2',
        activities: [
            {
                name: 'Activity 1',
                type: 'activity',
                id: 'a1'
            }
        ]
    }
    '''
    unit_structure = []
    for each in unit_group_obj.collection_set:
        lesson_dict = {}
        lesson = Node.get_node_by_id(each)
        if lesson:
            trans_lesson = get_lang_node(lesson._id, lang)
            if trans_lesson:
                lesson_dict['name'] = trans_lesson.name
            else:
                lesson_dict['name'] = lesson.name
            lesson_dict['type'] = 'lesson'
            lesson_dict['id'] = str(lesson._id)
            lesson_dict['language'] = lesson.language[0]
            lesson_dict['activities'] = []
            if lesson.collection_set:
                for each_act in lesson.collection_set:
                    activity_dict = {}
                    activity = Node.get_node_by_id(each_act)
                    if activity:
                        trans_act = get_lang_node(activity._id, lang)
                        if trans_act:
                            # activity_dict['name'] = trans_act.name
                            activity_dict[
                                'name'] = trans_act.altnames or trans_act.name
                        else:
                            # activity_dict['name'] = activity.name
                            activity_dict[
                                'name'] = activity.altnames or activity.name
                        activity_dict['type'] = 'activity'
                        activity_dict['id'] = str(activity._id)
                        lesson_dict['activities'].append(activity_dict)
            unit_structure.append(lesson_dict)

    return unit_structure
'''


import re
from gnowsys_ndf.ndf.models import node_collection, Node
from bs4 import BeautifulSoup  

#To identify the href starting with digit but not with "/"
regx = re.compile('<a href="[\d\w]*\/course\/notebook\/\?create=True"',re.IGNORECASE)
regx1 = '^\d' 

le_module_name = "Linear Equations"
le_modules = node_collection.find({'_type':'GSystem','name':le_module_name},{'collection_set':1})

page_gst_id = Node.get_name_id_from_type('Page','GSystemType')[1]
trnsnd_gst_id =Node.get_name_id_from_type('trans_node','GSystemType')[1]
#Extracting all activities under the Linear Equations module
legsystmnds = node_collection.find({
        '_type':'GSystem', 
        'member_of':{'$in':[page_gst_id,trnsnd_gst_id]},
        'group_set':{'$in':[eachid for each in le_modules for eachid in each.collection_set]},
        'collection_set':[],
        'content':regx})
   

#To fetch the faulty hrefs and update them accordingly. This covers the e-Notes as well as Upload
for index, each_nd in enumerate(legsystmnds,start =1):
     soup = BeautifulSoup(each_nd.content)         
     findflg = soup.find_all('a')
     flag = False
Exemple #31
0
from django.http import HttpRequest
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse

from gnowsys_ndf.ndf.models import Node, GSystem, GSystemType, RelationType, Group
from gnowsys_ndf.ndf.models import node_collection, triple_collection
from gnowsys_ndf.ndf.views.methods import get_group_name_id, get_language_tuple, create_grelation
from gnowsys_ndf.settings import GSTUDIO_DEFAULT_LANGUAGE
from gnowsys_ndf.ndf.templatetags.ndf_tags import get_relation_value

# gst_page_name, gst_page_id = GSystemType.get_gst_name_id(u'Page')
rt_translation_of = Node.get_name_id_from_type('translation_of',
                                               'RelationType',
                                               get_obj=True)
supported_languages = ['Hindi', 'Telugu']
trans_node_gst_name, trans_node_gst_id = GSystemType.get_gst_name_id(
    "trans_node")


def all_translations(request, group_id, node_id):
    '''
    returns all translated nodes of provided node.
    '''
    node_obj = Node.get_node_by_id(node_id)
    # node_translation_grels = node_obj.get_relation('translation_of', status='PUBLISHED')
    # return node_translation_grels

    # node_translation_grels = node_obj.get_relation('translation_of')
Exemple #32
0
def get_course_content_hierarchy(unit_group_obj,lang="en"):
    '''
    ARGS: unit_group_obj
    Result will be of following form:
    {
        name: 'Lesson1',
        type: 'lesson',
        id: 'l1',
        activities: [
            {
                name: 'Activity 1',
                type: 'activity',
                id: 'a1'
            },
            {
                name: 'Activity 1',
                type: 'activity',
                id: 'a2'
            }
        ]
    }, {
        name: 'Lesson2',
        type: 'lesson',
        id: 'l2',
        activities: [
            {
                name: 'Activity 1',
                type: 'activity',
                id: 'a1'
            }
        ]
    }
    '''

    unit_structure = []
    for each in unit_group_obj.collection_set:
        lesson_dict ={}
        lesson = Node.get_node_by_id(each)
        if lesson:
            trans_lesson = get_lang_node(lesson._id,lang)
            if trans_lesson:
                lesson_dict['label'] = trans_lesson.name
            else:
                lesson_dict['label'] = lesson.name
            lesson_dict['id'] = lesson._id
            lesson_dict['type'] = 'unit-name'
            lesson_dict['children'] = []
            if lesson.collection_set:
                for each_act in lesson.collection_set:
                    activity_dict ={}
                    activity = Node.get_node_by_id(each_act)
                    if activity:
                        trans_act_name = get_lang_node(each_act,lang)
                        # activity_dict['label'] = trans_act_name.name or activity.name  
                        if trans_act_name:
                            activity_dict['label'] = trans_act_name.altnames or trans_act_name.name
                            # activity_dict['label'] = trans_act_name.name
                        else:
                            # activity_dict['label'] = activity.name
                            activity_dict['label'] = activity.altnames or activity.name
                        activity_dict['type'] = 'activity-group'
                        activity_dict['id'] = str(activity._id)
                        lesson_dict['children'].append(activity_dict)
            unit_structure.append(lesson_dict)
    return unit_structure
Exemple #33
0
def _get_unit_hierarchy(unit_group_obj,lang="en"):
    '''
    ARGS: unit_group_obj
    Result will be of following form:
    {
        name: 'Lesson1',
        type: 'lesson',
        id: 'l1',
        activities: [
            {
                name: 'Activity 1',
                type: 'activity',
                id: 'a1'
            },
            {
                name: 'Activity 1',
                type: 'activity',
                id: 'a2'
            }
        ]
    }, {
        name: 'Lesson2',
        type: 'lesson',
        id: 'l2',
        activities: [
            {
                name: 'Activity 1',
                type: 'activity',
                id: 'a1'
            }
        ]
    }
    '''
    unit_structure = []
    for each in unit_group_obj.collection_set:
        lesson_dict ={}
        lesson = Node.get_node_by_id(each)
        if lesson:
            trans_lesson = get_lang_node(lesson._id,lang)
            if trans_lesson:
                lesson_dict['name'] = trans_lesson.name
            else:
                lesson_dict['name'] = lesson.name
            lesson_dict['type'] = 'lesson'
            lesson_dict['id'] = str(lesson._id)
            lesson_dict['language'] = lesson.language[0]
            lesson_dict['activities'] = []
            if lesson.collection_set:
                for each_act in lesson.collection_set:
                    activity_dict ={}
                    activity = Node.get_node_by_id(each_act)
                    if activity:
                        trans_act = get_lang_node(activity._id,lang)
                        if trans_act:
                            # activity_dict['name'] = trans_act.name
                            activity_dict['name'] = trans_act.altnames or trans_act.name
                        else:
                            # activity_dict['name'] = activity.name
                            activity_dict['name'] = activity.altnames or activity.name
                        activity_dict['type'] = 'activity'
                        activity_dict['id'] = str(activity._id)
                        lesson_dict['activities'].append(activity_dict)
            unit_structure.append(lesson_dict)

    return unit_structure
Exemple #34
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))
Exemple #35
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(node_id)

    # 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}
      ]})
    '''

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

    if title == "drafts":
        print "(((((((((((((((((((((((((("
        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)
    template = 'ndf/module_detail.html'

    req_context = RequestContext(
        request, {
            'title': title,
            'node': module_obj,
            'units_under_module': units_under_module,
            'group_id': group_id,
            'groupid': group_id,
            'card': 'ndf/event_card.html',
            'card_url_name': 'groupchange'
        })
    return render_to_response(template, req_context)
Exemple #36
0
This script modifies two particular activities under Geometrical Reasoning

GR:I  --> Analysing and Describing shapes -->Analysing Shapes -->Sorting Shapes
GR:II --> Property Based Reasoning --> Representing Relationships 2

Hence this may not work for every server
'''


import re
from gnowsys_ndf.ndf.models import node_collection,triple_collection,Node
from bs4 import BeautifulSoup  
from bson import ObjectId
'''To identify the href without "/"'''
regx1 = '^/sugar/activities/Paint.activity/'
trnslnof_gst_id = Node.get_name_id_from_type('translation_of','RelationType')[1]
activities_list = list(map(ObjectId,['59425d1c4975ac013cccbba3','59425e4d4975ac013cccbcb4']))
trnsnds_list = []
for each in activities_list:
       trnsnds_list.append(triple_collection.find({'_type':'GRelation','relation_type':trnslnof_gst_id,'subject':each}).distinct('right_subject'))

activities_list.extend(eachid for eachlst in trnsnds_list for eachid in eachlst)

grgsystmnds = node_collection.find({'_type':'GSystem',
				    '_id':{'$in':activities_list}})

#for each in grgsystemnds:
#       each.get_relation_right_subject_nodes('translation_of')

   
'''To fetch the faulty hrefs and update them accordingly.'''
Exemple #37
0
if not os.path.exists(GSTUDIO_LOGS_DIR_PATH):
    os.makedirs(GSTUDIO_LOGS_DIR_PATH)

log_file_name = 'export_users_analytics.log'
log_file_path = os.path.join(GSTUDIO_LOGS_DIR_PATH, log_file_name)
log_file = open(log_file_path, 'a+')
script_start_str = "\n\n######### Script ran on : " + time.strftime("%c") + " #########\n----------------\n"
log_file.write(str(script_start_str))

column_keys_list = ["server_id", "school_name", "school_code", "module_name", "unit_name", "username", "user_id", "first_name", "last_name", "roll_no", "grade", "enrollment_status", "buddy_userids", "buddy_usernames", "total_lessons", "lessons_visited", "percentage_lessons_visited", "total_activities", "activities_visited", "percentage_activities_visited", "total_quizitems", "visited_quizitems", "attempted_quizitems", "unattempted_quizitems", "correct_attempted_quizitems", "notapplicable_quizitems", "incorrect_attempted_quizitems", "user_files", "total_files_viewed_by_user", "other_viewing_my_files", "unique_users_commented_on_user_files", "total_rating_rcvd_on_files", "commented_on_others_files", "cmts_on_user_files", "total_cmnts_by_user", "user_notes", "others_reading_my_notes", "cmts_on_user_notes", "cmnts_rcvd_by_user", "total_notes_read_by_user", "commented_on_others_notes", "total_rating_rcvd_on_notes", "correct_attempted_assessments", "unattempted_assessments", "visited_assessments", "notapplicable_assessments", "incorrect_attempted_assessments", "attempted_assessments", "total_assessment_items"]

column_keys_dict = OrderedDict()
map(lambda x: column_keys_dict.update({x: "NA"}), column_keys_list)

module_gst_name, module_gst_id = Node.get_name_id_from_type('Module', 'GSystemType')

class Command(BaseCommand):

    def handle(self, *args, **options):
        gst_base_unit_name, gst_base_unit_id = GSystemType.get_gst_name_id('announced_unit')
        gst_course_ev_gr = node_collection.one({'_type': 'GSystemType', 'name': 'CourseEventGroup'})
        all_course_groups = node_collection.find({'_type': 'Group', 'member_of': {'$in': [gst_course_ev_gr._id, gst_base_unit_id]} })
        all_course_groups_count = all_course_groups.count()
        csv_created_count = 0

        for gr_index, each_group_obj in enumerate(all_course_groups, 1):
            assessment_and_quiz_data = True
            print "\n\n[ %d / %d ]" % (gr_index, all_course_groups_count)
            try:
                print "Exporting CSV for :", each_group_obj.name, "(Altnames:", each_group_obj.altnames, ")\n"
Exemple #38
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
                }))
Exemple #39
0
    from pymongo.objectid import ObjectId

from django.http import HttpRequest
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse

from gnowsys_ndf.ndf.models import Node, GSystem, GSystemType, RelationType, Group
from gnowsys_ndf.ndf.models import node_collection, triple_collection
from gnowsys_ndf.ndf.views.methods import get_group_name_id, get_language_tuple, create_grelation
from gnowsys_ndf.settings import GSTUDIO_DEFAULT_LANGUAGE

# gst_page_name, gst_page_id = GSystemType.get_gst_name_id(u'Page')
rt_translation_of = Node.get_name_id_from_type('translation_of', 'RelationType', get_obj=True)
supported_languages = ['Hindi', 'Telugu']
trans_node_gst_name, trans_node_gst_id = GSystemType.get_gst_name_id("trans_node")



def all_translations(request, group_id, node_id):
    '''
    returns all translated nodes of provided node.
    '''
    node_obj = Node.get_node_by_id(node_id)
    # node_translation_grels = node_obj.get_relation('translation_of', status='PUBLISHED')
    # return node_translation_grels

    # node_translation_grels = node_obj.get_relation('translation_of')
    all_translation_nodes = node_obj.get_relation_right_subject_nodes('translation_of')
Exemple #40
0
def get_course_content_hierarchy(unit_group_obj, lang="en"):
    '''
    ARGS: unit_group_obj
    Result will be of following form:
    {
        name: 'Lesson1',
        type: 'lesson',
        id: 'l1',
        activities: [
            {
                name: 'Activity 1',
                type: 'activity',
                id: 'a1'
            },
            {
                name: 'Activity 1',
                type: 'activity',
                id: 'a2'
            }
        ]
    }, {
        name: 'Lesson2',
        type: 'lesson',
        id: 'l2',
        activities: [
            {
                name: 'Activity 1',
                type: 'activity',
                id: 'a1'
            }
        ]
    }
    '''

    unit_structure = []
    for each in unit_group_obj.collection_set:
        lesson_dict = {}
        lesson = Node.get_node_by_id(each)
        if lesson:
            trans_lesson = get_lang_node(lesson._id, lang)
            if trans_lesson:
                lesson_dict['label'] = trans_lesson.name
            else:
                lesson_dict['label'] = lesson.name
            lesson_dict['id'] = lesson._id
            lesson_dict['type'] = 'unit-name'
            lesson_dict['children'] = []
            if lesson.collection_set:
                for each_act in lesson.collection_set:
                    activity_dict = {}
                    activity = Node.get_node_by_id(each_act)
                    if activity:
                        trans_act_name = get_lang_node(each_act, lang)
                        # activity_dict['label'] = trans_act_name.name or activity.name
                        if trans_act_name:
                            activity_dict[
                                'label'] = trans_act_name.altnames or trans_act_name.name
                            print "in side activity loop", trans_act_name._id, "in language", lang
                            # activity_dict['label'] = trans_act_name.name
                        else:
                            # activity_dict['label'] = activity.name
                            activity_dict[
                                'label'] = activity.altnames or activity.name
                        activity_dict['type'] = 'activity-group'
                        activity_dict['id'] = str(activity._id)
                        lesson_dict['children'].append(activity_dict)
            unit_structure.append(lesson_dict)
    return unit_structure
if not os.path.exists(GSTUDIO_LOGS_DIR_PATH):
    os.makedirs(GSTUDIO_LOGS_DIR_PATH)

log_file_name = 'export_users_analytics.log'
log_file_path = os.path.join(GSTUDIO_LOGS_DIR_PATH, log_file_name)
log_file = open(log_file_path, 'a+')
script_start_str = "\n\n######### Script ran on : " + time.strftime("%c") + " #########\n----------------\n"
log_file.write(str(script_start_str))

column_keys_list = ["server_id", "school_name", "school_code", "module_name", "unit_name", "username", "user_id", "first_name", "last_name", "roll_no", "grade", "enrollment_status", "buddy_userids", "buddy_usernames", "total_lessons", "lessons_visited", "percentage_lessons_visited", "total_activities", "activities_visited", "percentage_activities_visited", "total_quizitems", "visited_quizitems", "attempted_quizitems", "unattempted_quizitems", "correct_attempted_quizitems", "notapplicable_quizitems", "incorrect_attempted_quizitems", "user_files", "total_files_viewed_by_user", "other_viewing_my_files", "unique_users_commented_on_user_files", "total_rating_rcvd_on_files", "commented_on_others_files", "cmts_on_user_files", "total_cmnts_by_user", "user_notes", "others_reading_my_notes", "cmts_on_user_notes", "cmnts_rcvd_by_user", "total_notes_read_by_user", "commented_on_others_notes", "total_rating_rcvd_on_notes", "correct_attempted_assessments", "unattempted_assessments", "visited_assessments", "notapplicable_assessments", "incorrect_attempted_assessments", "attempted_assessments", "total_assessment_items"]

column_keys_dict = OrderedDict()
map(lambda x: column_keys_dict.update({x: "NA"}), column_keys_list)

module_gst_name, module_gst_id = Node.get_name_id_from_type('Module', 'GSystemType')

class Command(BaseCommand):

    def handle(self, *args, **options):
        gst_base_unit_name, gst_base_unit_id = GSystemType.get_gst_name_id('announced_unit')
        gst_course_ev_gr = node_collection.one({'_type': 'GSystemType', 'name': 'CourseEventGroup'})
        all_course_groups = node_collection.find({'_type': 'Group', 'member_of': {'$in': [gst_course_ev_gr._id, gst_base_unit_id]} })
        all_course_groups_count = all_course_groups.count()
        csv_created_count = 0

        for gr_index, each_group_obj in enumerate(all_course_groups, 1):
            assessment_and_quiz_data = True
            print "\n\n[ %d / %d ]" % (gr_index, all_course_groups_count)
            try:
                print "Exporting CSV for :", each_group_obj.name, "(Altnames:", each_group_obj.altnames, ")\n"
Exemple #42
0
 ObjectId('59425f864975ac013d976ac6'),
 ObjectId('59425ead4975ac013bf0f54b'),
 ObjectId('594260a54975ac013d976dc3')]

module_sort_order_ids = [u'59abb47c69602a0156036296', u'5945db6e2c4796014abd1784',\
 u'5945db2e2c4796014ddff67a', u'5945de532c4796014abd181a', u'5945de362c4796014ce12d7f',\
 u'5938ed2369602a014cb67195', u'5945ddca2c4796014ddff735', u'599c139269602a013fe31aa2',\
 u'59816df569602a015784baea', u'594b833869602a013f0cb6ce', u'594cfbea69602a014089845b', \
 u'597ebd7b69602a0154bb417e', u'5945daf42c4796014ce12d2d', u'59aff39869602a0155bfac16']


try:
    module_obj_list = []
    for each_id in module_sort_order_ids:
        try:
            each_node = Node.get_node_by_id(ObjectId(each_id))
            if each_node:
                module_obj_list.append(each_node)
        except Exception as modulde_not_found_err:
            print "\nError in module_not_found for each_id: ", each_id, "\nError: ", modulde_not_found_err
            pass
    print "\nTotal modules: ", len(module_obj_list)
    home_grp_id = node_collection.one({'_type': 'Group', 'name': 'home'})._id
    create_gattribute(home_grp_id, 'items_sort_list', module_obj_list)
except Exception as module_sort_order_ids_err:
    pass
    print "\nError in module_sort_order_ids. ", module_sort_order_ids_err
units_cur = node_collection.find({'_type': 'Group', '_id': {'$in': units_for_renaming_leaf_nodes}})
for each_unit in units_cur:
    try:
        if each_unit:
Exemple #43
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 }))
Exemple #44
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}))
Exemple #45
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}))
Exemple #46
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))
'''
Script which updates the reources with corresponding group_id

'''


from gnowsys_ndf.ndf.models import node_collection,triple_collection,Node
from bson import ObjectId

OER_GROUPS = ['Mathematics','Science','English']
grp_gst_id = Node.get_name_id_from_type('Group','GSystemType')[1]

oergrp_nds = node_collection.find({'_type':'Group','member_of':grp_gst_id,'name':{'$in':OER_GROUPS}})

for eachnd in  oergrp_nds:
	units_under_modules = Node.get_tree_nodes(eachnd._id,'collection_set',2,True)
	for each_unit in units_under_modules: