Example #1
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))
Example #2
0
def unit_detail(request, group_id):
    '''
    detail of of selected units
    '''
    # parent_group_name, parent_group_id = Group.get_group_name_id(group_id)
    unit_group_obj = Group.get_group_name_id(group_id, get_obj=True)

    unit_structure = get_unit_hierarchy(unit_group_obj, request.LANGUAGE_CODE)
    # template = "ndf/unit_structure.html"
    # template = 'ndf/gevent_base.html'
    template = 'ndf/lms.html'

    # print unit_structure
    req_context = RequestContext(
        request, {
            'title': 'unit_authoring',
            'hide_bannerpic': True,
            'group_id': unit_group_obj._id,
            'groupid': unit_group_obj._id,
            'group_name': unit_group_obj.name,
            'unit_obj': unit_group_obj,
            'group_obj': unit_group_obj,
            'unit_structure': json.dumps(unit_structure)
        })
    return render_to_response(template, req_context)
Example #3
0
def list_units(request, group_id):
    '''
    listing of units
    '''
    parent_group_name, parent_group_id = Group.get_group_name_id(group_id)
    all_base_units = node_collection.find({
        '_type':
        'Group',
        'group_set': {
            '$in': [parent_group_id]
        },
        'member_of': {
            '$in': [gst_base_unit_id]
        },
        '$or': [{
            'status': u'PUBLIC'
        }, {
            '$and': [{
                'access_policy': u"PRIVATE"
            }, {
                'created_by': request.user.id
            }]
        }]
    }).sort('last_update', -1)

    template = "ndf/explore_2017.html"
    req_context = RequestContext(request, {
        'group_id': parent_group_id,
        'all_unit_objs': all_base_units
    })
    return render_to_response(template, req_context)
Example #4
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))
Example #5
0
def list_units(request, group_id):
    '''
    listing of units
    '''
    parent_group_name, parent_group_id = Group.get_group_name_id(group_id)
    all_base_units = node_collection.find({
                                    '_type': 'Group',
                                    'group_set': {'$in': [parent_group_id]},
                                    'member_of': {'$in': [gst_base_unit_id]},
                                    '$or':[
                                        {'status': u'PUBLIC'},
                                        {
                                            '$and': [
                                                {'access_policy': u"PRIVATE"},
                                                {'created_by': request.user.id}
                                            ]
                                        }
                                    ]
                                }).sort('last_update', -1)

    template = "ndf/explore_2017.html"
    req_context = RequestContext(request, {
                                'group_id': parent_group_id,
                                'all_unit_objs': all_base_units
                            })
    return render_to_response(template, req_context)
Example #6
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)
Example #7
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)
Example #8
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)
Example #9
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))
Example #10
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))
Example #11
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))
Example #12
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))
Example #13
0
    def handle(self, *args, **options):
        print "Enter 'group name(case sensitive)' OR 'id': "
        group_name_or_id = raw_input()
        group_obj = Group.get_group_name_id(group_name_or_id, get_obj=True)

        if not group_obj:
            raise ValueError('\nSorry. Request could not be completed. \
                \nGroup/Course, matching argument entered "' + group_name_or_id + '" does not exists!')

        group_users = group_obj.author_set
        # print group_users

        # CSV file name-convention: schoolcode-course-name-datetimestamp.csv
        try:
            group_name = slugify(group_obj['name'])
        except Exception, e:
            print e
            group_name = 'i2c'
Example #14
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)
Example #15
0
def unit_detail(request, group_id):
    '''
    detail of of selected units
    '''
    # parent_group_name, parent_group_id = Group.get_group_name_id(group_id)
    unit_group_obj = Group.get_group_name_id(group_id, get_obj=True)

    unit_structure = get_unit_hierarchy(unit_group_obj, request.LANGUAGE_CODE)
    # template = "ndf/unit_structure.html"
    template = 'ndf/gevent_base.html'

    # print unit_structure
    req_context = RequestContext(request, {
                                'title': 'unit_authoring',
                                'hide_bannerpic': True,
                                'group_id': group_id,
                                'groupid': group_id,
                                'unit_obj': unit_group_obj,
                                'unit_structure': json.dumps(unit_structure)
                            })
    return render_to_response(template, req_context)
Example #16
0
def unit_create_edit(request, group_id, unit_group_id=None):
    '''
    creation as well as eit of units
    '''

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        unit_node.save()
        return HttpResponseRedirect(
            reverse('course_content', kwargs={'group_id': unit_node._id}))
Example #17
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))
Example #18
0
def event_detail(request,
                 group_id,
                 app_id=None,
                 app_set_id=None,
                 app_set_instance_id=None):
    """
  View for handling Event and it's sub-types detail-view
  """

    try:
        group_id = ObjectId(group_id)
    except:
        group_name, group_id = get_group_name_id(group_id)
    group_obj = node_collection.one({'_id': group_id})
    session_node = ""
    app = None
    session_node = ""
    '''if app_id is None:
    app = node_collection.one({'_type': "GSystemType", 'name': app_name})
    if app:
      app_id = str(app._id)
  else:'''
    app = node_collection.one({'_id': ObjectId(app_id)})

    #app_name = app.name

    app_set = ""
    app_collection_set = []
    title = ""
    marks_enter = ""
    session_node = ""
    event_gst = None
    event_gs = None
    reschedule = True
    reschedule_time = ""
    event_task_date_reschedule = ""
    event_task_Attendance_reschedule = ""
    marks = ""
    property_order_list = []

    #template_prefix = "mis"

    if request.user:
        auth = node_collection.one({
            '_type': 'Author',
            'name': unicode(request.user.username)
        })
    '''  agency_type = auth.agency_type
    Event_Types = node_collection.one({'_type': "GSystemType", 'name': agency_type}, {'collection_set': 1})
    if Event_Types:
      for eachset in Event_Types.collection_set:
        app_collection_set.append(node_collection.one({"_id": eachset}, {'_id': 1, 'name': 1, 'type_of': 1}))      
  '''
    # for eachset in app.collection_set:
    #   app_collection_set.append(node_collection.one({"_id":eachset}, {'_id': 1, 'name': 1, 'type_of': 1}))
    group_inverse_rel_id = []
    Group_type = node_collection.one({'_id': ObjectId(group_id)})
    for i in Group_type.relation_set:
        if unicode("group_of") in i.keys():
            group_inverse_rel_id = i['group_of']

    Group_name = node_collection.one({
        '_type': 'GSystem',
        '_id': {
            '$in': group_inverse_rel_id
        }
    })
    Eventtype = 'Eventtype'
    if Group_name:

        if (any(unicode('has_group') in d
                for d in Group_name.relation_set)) == True:
            Eventtype = 'CollegeEvents'
        else:
            Eventtype = 'Eventtype'

    Glisttype = node_collection.find({"name": "GList"})
    Event_Types = node_collection.one(
        {
            "member_of": ObjectId(Glisttype[0]["_id"]),
            "name": Eventtype
        }, {'collection_set': 1})
    app_collection_set = []
    if Event_Types:
        for eachset in Event_Types.collection_set:
            app_collection_set.append(
                node_collection.one({"_id": eachset}, {
                    '_id': 1,
                    'name': 1,
                    'type_of': 1
                }))

    nodes = None
    if app_set_id:
        event_gst = node_collection.one(
            {
                '_type': "GSystemType",
                '_id': ObjectId(app_set_id)
            }, {
                'name': 1,
                'type_of': 1
            })
        title = event_gst.name

        template = "ndf/event_list.html"

        if request.method == "POST":
            search = request.POST.get("search", "")
            classtype = request.POST.get("class", "")
            # nodes = list(node_collection.find({'name':{'$regex':search, '$options': 'i'},'member_of': {'$all': [event_gst._id]}}))
            nodes = node_collection.find({
                'member_of': event_gst._id,
                'name': {
                    '$regex': search,
                    '$options': 'i'
                }
            })
        else:
            nodes = node_collection.find({
                'member_of': event_gst._id,
                'group_set': ObjectId(group_id)
            }).sort('last_update', -1)

    node = None
    marks_entry_completed = True
    marks_list = []
    Assesslist = []
    batch = []
    session_node = ""
    if app_set_instance_id:
        template = "ndf/event_details.html"

        node = node_collection.one({
            '_type': "GSystem",
            '_id': ObjectId(app_set_instance_id)
        })
        # property_order_list = get_property_order_with_value(node)
        # print "\n property_order_list: ", property_order_list, "\n"

        node.get_neighbourhood(node.member_of)
        course = []
        val = False

        for i in node.attribute_set:
            if unicode('event_edit_reschedule') in i.keys():
                try:
                    if (unicode('reschedule_till')
                            in i['event_edit_reschedule']) == True:
                        reschedule_time = i['event_edit_reschedule'][
                            'reschedule_till']
                    if (unicode('reschedule_allow')
                            in i['event_edit_reschedule']):
                        reschedule = i['event_edit_reschedule'][
                            'reschedule_allow']
                except:
                    pass
            if (unicode('event_attendance_task')) in i.keys():
                event_task_Attendance_reschedule = i['event_attendance_task'][
                    'Reschedule_Task']

            if (unicode('event_date_task')) in i.keys():
                event_task_date_reschedule = i['event_date_task'][
                    'Reschedule_Task']
            if (unicode('marks_entry_completed')) in i.keys():
                marks_entry_completed = i['marks_entry_completed']

        for i in node.relation_set:
            if unicode('event_has_batch') in i.keys():
                batch = node_collection.one({
                    '_type':
                    "GSystem",
                    '_id':
                    ObjectId(i['event_has_batch'][0])
                })
                batch_relation = node_collection.one(
                    {
                        '_type': "GSystem",
                        '_id': ObjectId(batch._id)
                    }, {'relation_set': 1})
                for i in batch_relation['relation_set']:
                    if unicode('has_course') in i.keys():
                        announced_course = node_collection.one({
                            "_type":
                            "GSystem",
                            '_id':
                            ObjectId(i['has_course'][0])
                        })
                        for i in announced_course.relation_set:
                            if unicode('announced_for') in i.keys():
                                course = node_collection.one({
                                    "_type":
                                    "GSystem",
                                    '_id':
                                    ObjectId(i['announced_for'][0])
                                })
                batch = batch.name
            if unicode('session_of') in i.keys():
                event_has_session = node_collection.one({
                    '_type':
                    "GSystem",
                    '_id':
                    ObjectId(i['session_of'][0])
                })
                session_node = node_collection.one(
                    {'_id': ObjectId(event_has_session._id)},
                    {'attribute_set': 1})

    #   print "\n node.keys(): ", node.keys(), "\n"
    # default_template = "ndf/"+template_prefix+"_create_edit.html"
    Mis_admin = node_collection.one({"_type": "Group", "name": "MIS_admin"})
    if Mis_admin:
        Mis_admin_list = Mis_admin.group_admin
        Mis_admin_list.append(Mis_admin.created_by)
        if request.user.id in Mis_admin_list:
            Add = "Allow"
        else:
            Add = "Stop"
    else:
        Add = "Stop"
    #fecth the data
    can_access_val = Group.can_access(request.user.id, group_obj)
    context_variables = {
        'groupid': group_id,
        'group_id': group_id,
        'app_id': app_id,
        'app_collection_set': app_collection_set,
        'app_set_id': app_set_id,
        'title': title,
        'nodes': nodes,
        'node': node,
        'event_gst': event_gst.name,
        'Add': Add,
        'reschedule_time': reschedule_time,
        'reschedule': reschedule,
        'task_date': event_task_date_reschedule,
        'task_attendance': event_task_Attendance_reschedule,
        'marks_entry_completed': marks_entry_completed,
        'Eventtype': Eventtype,
        # 'property_order_list': property_order_list
    }

    if app_set_instance_id:  #only if we view details of the particular event
        if request.user.id:
            usr = node_collection.one({
                '_type': u'Author',
                'name': unicode(request.user.username)
            })
            usrid = usr._id

        bbb = False
        open_event = False

        for i in node.attribute_set:
            if unicode('start_time') in i.keys():
                start_time = i['start_time']
            elif unicode('end_time') in i.keys():
                end_time = i['end_time']
            elif unicode('is_bigbluebutton') in i.keys():
                bbb = i['is_bigbluebutton']
            elif unicode('open_event') in i.keys():
                open_event = i['open_event']
        # st_time = node.attribute_set[0]['start_time']
        # end_time = node.attribute_set[1]['end_time']

        now = datetime.datetime.now()

        beg = start_time
        end = end_time
        days_left = 0
        hours_left = 0
        shortly = False

        if now <= end and beg <= now:
            active = 0
        elif now > end:
            active = 1
        else:
            active = -1
            days_left = (start_time - now).days
            hours_left = (start_time - now).seconds // 3600

            if hours_left == 0:
                shortly = True

        is_attendee = False
        is_moderator = False
        attendee_list = []
        moderator_list = []

        if open_event and can_access_val:
            is_attendee = True

        for i in node.relation_set:
            if unicode('has_attendees') in i.keys():
                attendee_list = i['has_attendees']
            elif unicode('event_coordinator') in i.keys():
                moderator_list = i['event_coordinator']

        for i in moderator_list:
            if usrid == i:
                is_attendee = True
                is_moderator = True

        if not is_moderator:
            for i in attendee_list:
                if usrid == i:
                    is_attendee = True
                    break

        url = ""

        if active == 0:
            createMeeting(node.name, node._id, 'welcome', 'mPW', 'aPW', SALT,
                          URL, 'logout.html')

            if is_moderator:
                url = joinURL(node._id, request.user, 'mPW', SALT, URL)
            else:
                url = joinURL(node._id, request.user, 'aPW', SALT, URL)

        extra_context_variables = {
            'show': is_attendee,
            'url': url,
            'active': active,
            'days_left': days_left,
            'is_bbb': bbb,
            'shortly': shortly,
            'hours_left': hours_left,
            'open_event': open_event,
        }
        context_variables.update(extra_context_variables)

    if batch:
        context_variables.update({'batch': batch})
        if course:
            context_variables.update({'course': course})
    else:
        context_variables.update({'Assesslist': Assesslist})
    # print "\n template-list: ", [template, default_template]
    # template = "ndf/fgh.html"
    # default_template = "ndf/dsfjhk.html"
    # return render_to_response([template, default_template],

    if session_node:
        session_min_marks = ""
        session_max_marks = ""
        for attr in session_node.attribute_set:
            if attr and u"min_marks" in attr:
                session_min_marks = attr[u"min_marks"]
            elif attr and u"max_marks" in attr:
                session_max_marks = attr[u"max_marks"]
        context_variables.update({'session_min_marks': session_min_marks})
        context_variables.update({'session_max_marks': session_max_marks})

    return render_to_response(template,
                              context_variables,
                              context_instance=RequestContext(request))
Example #19
0
    def handle(self, *args, **options):

        print "Enter group name or _id: "
        group_id = raw_input()

        Group.purge_group(group_id, proceed=False)
Example #20
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))
Example #21
0
    def handle(self, *args, **options):

        print "Enter group name or _id: "
        group_id = raw_input()

        Group.purge_group(group_id, proceed=False)
Example #22
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))
Example #23
0
    # FLAGS:
    header_written = False
    csv_created = 0
    all_rows = []

    for index, each_user in enumerate(group_users, 1):
        try:
            analytics_data = course_analytics(None, group_obj._id, each_user, get_result_dict=True, assessment_and_quiz_data=assessment_and_quiz_data, get_counter_obj_in_result=True)
            if not analytics_data:
                print "\n!! Haven't got course analytics for group: %s \n" % group_name
                continue

            user_attr_list = ['first_name', 'last_name', 'enrollment_code', 'educationallevel']
            user_attr_dict = {attr: '' for attr in user_attr_list}
            try:
                user_attr_dict = GAttribute.get_triples_from_sub_type_list(Group.get_group_name_id(analytics_data['username'])[1], user_attr_list, get_obj=False)
            except Exception as e:
                print "\n!! Exception in getting triples values for user (%d): %s"%(each_user, e)
                pass

            print "[",index, "] Group User ID: ", each_user

            each_row_dict = column_keys_dict.copy()    
            each_row_dict['server_id'] = GSTUDIO_INSTITUTE_ID
            each_row_dict['school_code'] = GSTUDIO_INSTITUTE_ID_SECONDARY
            each_row_dict['school_name'] = GSTUDIO_INSTITUTE_NAME
            each_row_dict['module_name'] = [(i.altnames if (i.altnames and i.altnames.strip()) else i.name) for i in node_collection.find({'_type': 'GSystem', 'member_of': module_gst_id, 'collection_set': group_obj._id}) if i]
            each_row_dict['unit_name'] = group_name

            temp_lessons_stat_str = analytics_data['level1_progress_stmt']
            temp_lessons_stat_str = analytics_data['level1_progress_stmt']
Example #24
0
def api_get_gs_nodes(request):

    get_parameters_dict = request.GET.dict()

    if not get_parameters_dict:
        aggregated_dict = gst_api_fields_dict.copy()
        aggregated_dict.update(api_name_model_name_dict)
        aggregated_dict.pop('_id')

        query_parameters_dict = {
                                    'Fields': aggregated_dict.keys(),
                                    'Attributes': node_collection.find({'_type': 'AttributeType'}).distinct('name'),
                                    'Relations': node_collection.find({'_type': 'RelationType'}).distinct('name')
                                }
        return HttpResponse(json.dumps(query_parameters_dict, indent=4), content_type='application/json')


    # GET: api/v1/<group_id>/<files>/<nroer_team>/
    exception_occured = ''
    oid_name_dict = {}
    gst_id = None
    # try:
    #     group_id = ObjectId(group_name_or_id)
    # except Exception as e:
    #     group_name, group_id = get_group_name_id(group_name_or_id)
    #     oid_name_dict[group_id] = group_name

    gsystem_structure_dict = GSystem.structure
    gsystem_keys = gsystem_structure_dict.keys()

    gst_all_fields_dict = {i: 1 for i in gsystem_keys}

    query_dict = {
                    '_type': 'GSystem',
                    'status': u'PUBLISHED',
                    'access_policy': 'PUBLIC',
                    # 'group_set': ObjectId(group_id),
                    # 'member_of': ObjectId(gst_id),
                    # 'created_by': user_id,
                }

    sample_gs = GSystem()
    attributes = {}

    # GET parameters:
    get_created_by = request.GET.get('created_by', None)
    if get_created_by:
        username_or_id_int = 0
        try:
            username_or_id_int = int(get_created_by)
        except Exception as e:
            pass

        auth_obj = node_collection.one({'_type': u'Author', '$or': [{'name': unicode(get_created_by)}, {'created_by': username_or_id_int} ] })
        if auth_obj:
            oid_name_dict[auth_obj._id] = auth_obj.name
            # user_id = auth_obj.created_by
            get_parameters_dict['created_by'] = auth_obj.created_by
        else:
            return HttpResponse('Requested user does not exists.', content_type='text/plain')

    get_resource_type = request.GET.get('resource_type', None)
    if get_resource_type:
        gst_name, gst_id = GSystemType.get_gst_name_id(get_resource_type)
        oid_name_dict[gst_id] = gst_name
        get_parameters_dict['member_of'] = [gst_id]
        attributes = sample_gs.get_possible_attributes([gst_id]) 

    get_workspace = request.GET.get('workspace', None)
    if get_workspace:
        group_name, group_id = Group.get_group_name_id(get_workspace)
        oid_name_dict[group_id] = group_name
        get_parameters_dict['group_set'] = [group_id]

    for key, val in get_parameters_dict.iteritems():
        stripped_key = key.split('.')[0]
        if stripped_key in gsystem_keys:
            query_dict.update({ key: ({'$regex': val, '$options': 'i'} if isinstance(gsystem_structure_dict[stripped_key], basestring or unicode) else val) })

        elif stripped_key in gst_attributes(gst_id):
            query_dict.update({('attribute_set.' + stripped_key): {'$regex': val, '$options': 'i'}})

    # print "query_dict: ", query_dict

    human = eval(request.GET.get('human', '1'))

    gst_fields = gst_api_fields_dict if human else gst_all_fields_dict

    all_resources = node_collection.find(query_dict, gst_fields)

    if human:
        gst_fields = gst_api_fields_dict

        # converting ids to human readable names:
        # Django User:
        user_fields = ['created_by', 'modified_by', 'contributors']
        all_users = []
        for each_field in user_fields:
            all_users += all_resources.distinct(each_field)
        all_users = list(set(all_users))

        userid_name_dict_cur = node_collection.find({'_type': u'Author', 'created_by': {'$in': all_users}}, {'name': 1, 'created_by': 1, '_id': 0})
        userid_name_dict = {i['created_by']: i['name'] for i in userid_name_dict_cur}

        # Mongo ids
        oid_fields = [ k for k, v in gsystem_structure_dict.iteritems() if v in [bson.objectid.ObjectId, [bson.objectid.ObjectId]] ]
        all_oid_list = []
        for each_field in oid_fields:
            all_oid_list += all_resources.distinct(each_field)
        all_oid_list = list(set(all_oid_list))

        oid_name_dict_cur = node_collection.find({'_id': {'$in': all_oid_list}}, {'name': 1})
        oid_name_dict = {i['_id']: i['name'] for i in oid_name_dict_cur}

        python_cur_list = []
        python_cur_list_append = python_cur_list.append
        for each_gs in all_resources:

            # attaching attributes:
            # NEEDS to optimize.
            for key, value in each_gs.get_possible_attributes(each_gs.member_of).iteritems():
                each_gs[key] = value['data_type']
                each_gs[key] = value['object_value']

            # mapping user id to username.
            for each_field in user_fields:
                each_gs[each_field] = [userid_name_dict.get(i, i) for i in each_gs[each_field]] if isinstance(each_gs[each_field], list) else userid_name_dict.get(each_gs[each_field], each_gs[each_field])

            # mapping mongo _id to name.
            for each_field in oid_fields:
                each_gs[each_field] = [oid_name_dict.get(i, i) for i in each_gs[each_field]] if isinstance(each_gs[each_field], list) else oid_name_dict[each_gs[each_field]]

            python_cur_list_append(each_gs)

        json_result = json.dumps(python_cur_list, cls=NodeJSONEncoder, sort_keys=True, indent=4)

    else:
        json_result = dumps(all_resources, sort_keys=True, indent=4)

    return HttpResponse(json_result, content_type='application/json')
Example #25
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}))
Example #26
0
def unit_create_edit(request, group_id, unit_group_id=None):
    '''
    creation as well as eit of units
    '''

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

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

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

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

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

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

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

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

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

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

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

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

        unit_node.save()
        return HttpResponseRedirect(reverse('course_content',
            kwargs={'group_id': unit_node._id}))
Example #27
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))
    # FLAGS:
    header_written = False
    csv_created = 0
    all_rows = []

    for index, each_user in enumerate(group_users, 1):
        try:
            analytics_data = course_analytics(None, group_obj._id, each_user, get_result_dict=True, assessment_and_quiz_data=assessment_and_quiz_data, get_counter_obj_in_result=True)
            if not analytics_data:
                print "\n!! Haven't got course analytics for group: %s \n" % group_name
                continue

            user_attr_list = ['first_name', 'last_name', 'enrollment_code', 'educationallevel']
            user_attr_dict = {attr: '' for attr in user_attr_list}
            try:
                user_attr_dict = GAttribute.get_triples_from_sub_type_list(Group.get_group_name_id(analytics_data['username'])[1], user_attr_list, get_obj=False)
            except Exception as e:
                print "\n!! Exception in getting triples values for user (%d): %s"%(each_user, e)
                pass

            print index, "] Group User ID: ", each_user

            each_row_dict = column_keys_dict.copy()    
            each_row_dict['server_id'] = GSTUDIO_INSTITUTE_ID
            each_row_dict['school_code'] = GSTUDIO_INSTITUTE_ID_SECONDARY
            each_row_dict['school_name'] = GSTUDIO_INSTITUTE_NAME
            each_row_dict['module_name'] = [(i.altnames if (i.altnames and i.altnames.strip()) else i.name) for i in node_collection.find({'_type': 'GSystem', 'member_of': module_gst_id, 'collection_set': group_obj._id}) if i]
            each_row_dict['unit_name'] = group_name

            temp_lessons_stat_str = analytics_data['level1_progress_stmt']
            temp_lessons_stat_str = analytics_data['level1_progress_stmt']
Example #29
0
def api_get_gs_nodes(request):

    get_parameters_dict = request.GET.dict()

    if not get_parameters_dict:
        aggregated_dict = gst_api_fields_dict.copy()
        aggregated_dict.update(api_name_model_name_dict)
        aggregated_dict.pop('_id')

        query_parameters_dict = {
            'Fields':
            aggregated_dict.keys(),
            'Attributes':
            node_collection.find({
                '_type': 'AttributeType'
            }).distinct('name'),
            'Relations':
            node_collection.find({
                '_type': 'RelationType'
            }).distinct('name')
        }
        return HttpResponse(json.dumps(query_parameters_dict, indent=4),
                            content_type='application/json')

    # GET: api/v1/<group_id>/<files>/<nroer_team>/
    exception_occured = ''
    oid_name_dict = {}
    gst_id = None
    # try:
    #     group_id = ObjectId(group_name_or_id)
    # except Exception as e:
    #     group_name, group_id = get_group_name_id(group_name_or_id)
    #     oid_name_dict[group_id] = group_name

    gsystem_structure_dict = GSystem.structure
    gsystem_keys = gsystem_structure_dict.keys()

    gst_all_fields_dict = {i: 1 for i in gsystem_keys}

    query_dict = {
        '_type': 'GSystem',
        'status': u'PUBLISHED',
        'access_policy': 'PUBLIC',
        # 'group_set': ObjectId(group_id),
        # 'member_of': ObjectId(gst_id),
        # 'created_by': user_id,
    }

    sample_gs = GSystem()
    attributes = {}

    # GET parameters:
    get_created_by = request.GET.get('created_by', None)
    if get_created_by:
        username_or_id_int = 0
        try:
            username_or_id_int = int(get_created_by)
        except Exception as e:
            pass

        auth_obj = node_collection.one({
            '_type':
            u'Author',
            '$or': [{
                'name': unicode(get_created_by)
            }, {
                'created_by': username_or_id_int
            }]
        })
        if auth_obj:
            oid_name_dict[auth_obj._id] = auth_obj.name
            # user_id = auth_obj.created_by
            get_parameters_dict['created_by'] = auth_obj.created_by
        else:
            return HttpResponse('Requested user does not exists.',
                                content_type='text/plain')

    get_resource_type = request.GET.get('resource_type', None)
    if get_resource_type:
        gst_name, gst_id = GSystemType.get_gst_name_id(get_resource_type)
        oid_name_dict[gst_id] = gst_name
        get_parameters_dict['member_of'] = [gst_id]
        attributes = sample_gs.get_possible_attributes([gst_id])

    get_workspace = request.GET.get('workspace', None)
    if get_workspace:
        group_name, group_id = Group.get_group_name_id(get_workspace)
        oid_name_dict[group_id] = group_name
        get_parameters_dict['group_set'] = [group_id]

    for key, val in get_parameters_dict.iteritems():
        stripped_key = key.split('.')[0]
        if stripped_key in gsystem_keys:
            query_dict.update({
                key: ({
                    '$regex': val,
                    '$options': 'i'
                } if isinstance(gsystem_structure_dict[stripped_key],
                                basestring or unicode) else val)
            })

        elif stripped_key in gst_attributes(gst_id):
            query_dict.update({
                ('attribute_set.' + stripped_key): {
                    '$regex': val,
                    '$options': 'i'
                }
            })

    # print "query_dict: ", query_dict

    human = eval(request.GET.get('human', '1'))

    gst_fields = gst_api_fields_dict if human else gst_all_fields_dict

    all_resources = node_collection.find(query_dict, gst_fields)

    if human:
        gst_fields = gst_api_fields_dict

        # converting ids to human readable names:
        # Django User:
        user_fields = ['created_by', 'modified_by', 'contributors']
        all_users = []
        for each_field in user_fields:
            all_users += all_resources.distinct(each_field)
        all_users = list(set(all_users))

        userid_name_dict_cur = node_collection.find(
            {
                '_type': u'Author',
                'created_by': {
                    '$in': all_users
                }
            }, {
                'name': 1,
                'created_by': 1,
                '_id': 0
            })
        userid_name_dict = {
            i['created_by']: i['name']
            for i in userid_name_dict_cur
        }

        # Mongo ids
        oid_fields = [
            k for k, v in gsystem_structure_dict.iteritems()
            if v in [bson.objectid.ObjectId, [bson.objectid.ObjectId]]
        ]
        all_oid_list = []
        for each_field in oid_fields:
            all_oid_list += all_resources.distinct(each_field)
        all_oid_list = list(set(all_oid_list))

        oid_name_dict_cur = node_collection.find(
            {'_id': {
                '$in': all_oid_list
            }}, {'name': 1})
        oid_name_dict = {i['_id']: i['name'] for i in oid_name_dict_cur}

        python_cur_list = []
        python_cur_list_append = python_cur_list.append
        for each_gs in all_resources:

            # attaching attributes:
            # NEEDS to optimize.
            for key, value in each_gs.get_possible_attributes(
                    each_gs.member_of).iteritems():
                each_gs[key] = value['data_type']
                each_gs[key] = value['object_value']

            # mapping user id to username.
            for each_field in user_fields:
                each_gs[each_field] = [
                    userid_name_dict.get(i, i) for i in each_gs[each_field]
                ] if isinstance(each_gs[each_field],
                                list) else userid_name_dict.get(
                                    each_gs[each_field], each_gs[each_field])

            # mapping mongo _id to name.
            for each_field in oid_fields:
                each_gs[each_field] = [
                    oid_name_dict.get(i, i) for i in each_gs[each_field]
                ] if isinstance(each_gs[each_field],
                                list) else oid_name_dict[each_gs[each_field]]

            python_cur_list_append(each_gs)

        json_result = json.dumps(python_cur_list,
                                 cls=NodeJSONEncoder,
                                 sort_keys=True,
                                 indent=4)

    else:
        json_result = dumps(all_resources, sort_keys=True, indent=4)

    return HttpResponse(json_result, content_type='application/json')
Example #30
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)
Example #31
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
                }))
Example #32
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}))
Example #33
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 }))
Example #34
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}))
Example #35
0
def event_detail(request, group_id, app_id=None, app_set_id=None, app_set_instance_id=None):
  """
  View for handling Event and it's sub-types detail-view
  """

  try:
        group_id = ObjectId(group_id)
  except:
        group_name, group_id = get_group_name_id(group_id)
  group_obj = node_collection.one({'_id': group_id})
  session_node = ""
  app = None
  session_node = ""
  '''if app_id is None:
    app = node_collection.one({'_type': "GSystemType", 'name': app_name})
    if app:
      app_id = str(app._id)
  else:'''
  app = node_collection.one({'_id': ObjectId(app_id)})
  
  #app_name = app.name 

  app_set = ""
  app_collection_set = []
  title = ""
  marks_enter= ""
  session_node = "" 
  event_gst = None
  event_gs = None
  reschedule = True
  reschedule_time = ""
  event_task_date_reschedule = ""
  event_task_Attendance_reschedule = ""
  marks=""
  property_order_list = []
  
  #template_prefix = "mis"

  if request.user:
      auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username)})
  '''  agency_type = auth.agency_type
    Event_Types = node_collection.one({'_type': "GSystemType", 'name': agency_type}, {'collection_set': 1})
    if Event_Types:
      for eachset in Event_Types.collection_set:
        app_collection_set.append(node_collection.one({"_id": eachset}, {'_id': 1, 'name': 1, 'type_of': 1}))      
  '''
  # for eachset in app.collection_set:
  #   app_collection_set.append(node_collection.one({"_id":eachset}, {'_id': 1, 'name': 1, 'type_of': 1}))
  group_inverse_rel_id = []
  Group_type=node_collection.one({'_id':ObjectId(group_id)})
  for i in Group_type.relation_set:
       if unicode("group_of") in i.keys():
          group_inverse_rel_id = i['group_of']
  
  Group_name = node_collection.one({'_type':'GSystem','_id':{'$in':group_inverse_rel_id}})
  Eventtype='Eventtype'
  if Group_name:

      if (any( unicode('has_group') in d for d in Group_name.relation_set)) == True:
           Eventtype='CollegeEvents'     
      else:
           Eventtype='Eventtype'

  Glisttype=node_collection.find({"name":"GList"})
  Event_Types = node_collection.one({"member_of":ObjectId(Glisttype[0]["_id"]),"name":Eventtype},{'collection_set': 1})
  app_collection_set=[]
  if Event_Types:
    for eachset in Event_Types.collection_set:
          app_collection_set.append(node_collection.one({"_id": eachset}, {'_id': 1, 'name': 1, 'type_of': 1}))      

  
  nodes = None
  if app_set_id:
    event_gst = node_collection.one({'_type': "GSystemType", '_id': ObjectId(app_set_id)}, {'name': 1, 'type_of': 1})
    title = event_gst.name
  
    template = "ndf/event_list.html"

    if request.method=="POST":
      search = request.POST.get("search","")
      classtype = request.POST.get("class","")
      # nodes = list(node_collection.find({'name':{'$regex':search, '$options': 'i'},'member_of': {'$all': [event_gst._id]}}))
      nodes = node_collection.find({'member_of': event_gst._id, 'name': {'$regex': search, '$options': 'i'}})
    else:
      nodes = node_collection.find({'member_of': event_gst._id, 'group_set': ObjectId(group_id)}).sort('last_update', -1)
      
  node = None
  marks_entry_completed = True
  marks_list=[]
  Assesslist=[]
  batch=[]
  session_node = ""
  if app_set_instance_id :
    template = "ndf/event_details.html"

    node = node_collection.one({'_type': "GSystem", '_id': ObjectId(app_set_instance_id)})
    # property_order_list = get_property_order_with_value(node)
    # print "\n property_order_list: ", property_order_list, "\n"
    
    node.get_neighbourhood(node.member_of)
    course=[]
    val=False
    
    for i in node.attribute_set:
       if unicode('event_edit_reschedule') in i.keys():
          try: 
           if (unicode('reschedule_till') in i['event_edit_reschedule']) == True:
              reschedule_time = i['event_edit_reschedule']['reschedule_till']  
           if (unicode('reschedule_allow') in i['event_edit_reschedule']):    
              reschedule = i['event_edit_reschedule']['reschedule_allow']
          except:
               pass
       if (unicode('event_attendance_task')) in i.keys():
           event_task_Attendance_reschedule = i['event_attendance_task']['Reschedule_Task']
            
       if(unicode('event_date_task')) in i.keys():
           event_task_date_reschedule = i['event_date_task']['Reschedule_Task']     
       if(unicode('marks_entry_completed')) in i.keys():    
           marks_entry_completed = i['marks_entry_completed'] 
                
    for i in node.relation_set:
       if unicode('event_has_batch') in i.keys():
            batch=node_collection.one({'_type':"GSystem",'_id':ObjectId(i['event_has_batch'][0])})
            batch_relation=node_collection.one({'_type':"GSystem",'_id':ObjectId(batch._id)},{'relation_set':1})
            for i in batch_relation['relation_set']:
               if  unicode('has_course') in i.keys(): 
                   announced_course =node_collection.one({"_type":"GSystem",'_id':ObjectId(i['has_course'][0])})
                   for i in  announced_course.relation_set:
                      if unicode('announced_for') in i.keys():
                            course=node_collection.one({"_type":"GSystem",'_id':ObjectId(i['announced_for'][0])})
            batch=batch.name
       if unicode('session_of') in i.keys():
            event_has_session = node_collection.one({'_type':"GSystem",'_id':ObjectId(i['session_of'][0])})
            session_node = node_collection.one({'_id':ObjectId(event_has_session._id)},{'attribute_set':1})

           
  #   print "\n node.keys(): ", node.keys(), "\n"
  # default_template = "ndf/"+template_prefix+"_create_edit.html"
  Mis_admin=node_collection.one({"_type":"Group","name":"MIS_admin"})
  if  Mis_admin:
    Mis_admin_list=Mis_admin.group_admin
    Mis_admin_list.append(Mis_admin.created_by)
    if request.user.id in Mis_admin_list:
        Add = "Allow"  
    else: 
        Add = "Stop"
  else:
    Add="Stop"       
  #fecth the data
  can_access_val = Group.can_access(request.user.id, group_obj)
  context_variables = { 'groupid': group_id, 'group_id': group_id, 
                          'app_id': app_id,'app_collection_set': app_collection_set, 
                          'app_set_id': app_set_id,
                          'title':title,
                          'nodes': nodes, 'node': node,
                          'event_gst':event_gst.name,
                          'Add':Add,
                          'reschedule_time' : reschedule_time,
                          'reschedule'    : reschedule, 
                          'task_date' : event_task_date_reschedule,
                          'task_attendance' : event_task_Attendance_reschedule,
                          'marks_entry_completed' :marks_entry_completed,
                          'Eventtype':Eventtype, 
                           # 'property_order_list': property_order_list
                        }

  if app_set_instance_id: #only if we view details of the particular event
    if request.user.id:
      usr = node_collection.one({'_type':u'Author','name':unicode(request.user.username)})
      usrid = usr._id
 

    bbb = False
    open_event = False

    for i in node.attribute_set:
      if unicode('start_time') in i.keys():
        start_time = i['start_time']
      elif unicode('end_time') in i.keys():
        end_time = i['end_time']
      elif unicode('is_bigbluebutton') in i.keys():
        bbb = i['is_bigbluebutton']
      elif unicode('open_event') in i.keys():
        open_event = i['open_event']    
    # st_time = node.attribute_set[0]['start_time']
    # end_time = node.attribute_set[1]['end_time']
    
    now = datetime.datetime.now()

    beg = start_time
    end = end_time
    days_left = 0
    hours_left = 0
    shortly = False

    if now <= end and beg <= now :
      active =  0
    elif now > end : 
      active = 1
    else:
      active = -1  
      days_left = (start_time-now).days
      hours_left = (start_time-now).seconds//3600

      if hours_left == 0:
        shortly = True  


    is_attendee = False
    is_moderator = False 
    attendee_list = []
    moderator_list = []   

    if open_event and can_access_val:
      is_attendee = True

    for i in node.relation_set:
      if unicode('has_attendees') in i.keys():
        attendee_list =  i['has_attendees']
      elif unicode('event_coordinator') in i.keys():
        moderator_list = i['event_coordinator']

    for i in moderator_list:
      if usrid == i:
        is_attendee = True
        is_moderator = True

    if not is_moderator:    
      for i in attendee_list:
        if usrid == i:
          is_attendee = True
          break 

    url = ""      

    if active == 0:      
      createMeeting(node.name, node._id, 'welcome', 'mPW', 'aPW', SALT , URL, 'logout.html')
      
      if is_moderator:
        url = joinURL(node._id, request.user, 'mPW', SALT, URL)
      else:
        url = joinURL(node._id, request.user, 'aPW', SALT, URL)        

    extra_context_variables = {'show':is_attendee,
                          'url':url,
                          'active':active,
                          'days_left':days_left,
                          'is_bbb': bbb,
                          'shortly':shortly,
                          'hours_left':hours_left, 
                          'open_event':open_event,
                        }
    context_variables.update(extra_context_variables)

  
  if batch :
      context_variables.update({'batch':batch}) 
      if course:
          context_variables.update({'course':course})
  else  :    
      context_variables.update({'Assesslist':Assesslist}) 
    # print "\n template-list: ", [template, default_template]
    # template = "ndf/fgh.html"
    # default_template = "ndf/dsfjhk.html"
    # return render_to_response([template, default_template], 

  if session_node:
    session_min_marks = ""
    session_max_marks = ""
    for attr in session_node.attribute_set:
      if attr and u"min_marks" in attr:
        session_min_marks = attr[u"min_marks"]
      elif attr and u"max_marks" in attr:
        session_max_marks = attr[u"max_marks"]
    context_variables.update({'session_min_marks':session_min_marks})
    context_variables.update({'session_max_marks':session_max_marks})   

  return render_to_response(template, 
                              context_variables,
                              context_instance = RequestContext(request)
                            )
Example #36
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}))