Beispiel #1
0
def save_image(request,
               group_name,
               app_id=None,
               app_name=None,
               app_set_id=None,
               slug=None):
    if request.method == "POST":
        #here group_name contains the object id of the group insted of name sent from
        #task template
        ins_objectid = ObjectId()
        if ins_objectid.is_valid(group_name) is False:
            group_object = node_collection.one({
                '_type': {
                    '$in': ['Group', 'Author']
                },
                'name': unicode(group_name)
            })
            group_object = group_object._id
        else:
            group_object = group_name
        for index, each in enumerate(request.FILES.getlist("doc[]", "")):

            title = each.name
            userid = request.POST.get("user", "")
            content_org = request.POST.get('content_org', '')
            tags = request.POST.get('tags', "")
            img_type = request.POST.get("type", "")
            language = request.POST.get("lan", "")
            usrname = request.user.username
            page_url = request.POST.get("page_url", "")
            access_policy = request.POST.get(
                "login-mode",
                '')  # To add access policy(public or private) to file object

            # for storing location in the file

            # location = []
            # location.append(json.loads(request.POST.get("location", "{}")))
            # obs_image = save_file(each,title,userid,group_id, content_org, tags, img_type, language, usrname, access_policy, oid=True, location=location)
            obs_image = save_file(each,
                                  title,
                                  userid,
                                  group_object,
                                  content_org,
                                  tags,
                                  img_type,
                                  language,
                                  usrname,
                                  access_policy,
                                  oid=True)
            # Sample output of (type tuple) obs_image: (ObjectId('5357634675daa23a7a5c2900'), 'True')

            # if image sucessfully get uploaded then it's valid ObjectId
            if obs_image[0] and ObjectId.is_valid(obs_image[0]):
                return StreamingHttpResponse(str(obs_image[0]))

            else:  # file is not uploaded sucessfully or uploaded with error

                return StreamingHttpResponse("UploadError")
Beispiel #2
0
def save_image(request, group_name, app_id=None, app_name=None, app_set_id=None, slug=None):
    if request.method == "POST" :
        #here group_name contains the object id of the group insted of name sent from
        #task template
        ins_objectid  = ObjectId()
        if ins_objectid.is_valid(group_name) is False :
            group_object = node_collection.one({'_type':{'$in':['Group','Author']}, 'name': unicode(group_name)})
            group_object = group_object._id
        else:
            group_object = group_name
        for index, each in enumerate(request.FILES.getlist("doc[]", "")):

            title = each.name
            userid = request.POST.get("user", "")
            content_org = request.POST.get('content_org', '')
            tags = request.POST.get('tags', "")
            img_type = request.POST.get("type", "")
            language = request.POST.get("lan", "")
            usrname = request.user.username
            page_url = request.POST.get("page_url", "")
            access_policy = request.POST.get("login-mode", '') # To add access policy(public or private) to file object

            # for storing location in the file

            # location = []
            # location.append(json.loads(request.POST.get("location", "{}")))
            # obs_image = save_file(each,title,userid,group_id, content_org, tags, img_type, language, usrname, access_policy, oid=True, location=location)
            obs_image = save_file(each,title,userid,group_object, content_org, tags, img_type, language, usrname, access_policy, oid=True)
            # Sample output of (type tuple) obs_image: (ObjectId('5357634675daa23a7a5c2900'), 'True')

            # if image sucessfully get uploaded then it's valid ObjectId
            if obs_image[0] and ObjectId.is_valid(obs_image[0]):
              return StreamingHttpResponse(str(obs_image[0]))

            else: # file is not uploaded sucessfully or uploaded with error

            	return StreamingHttpResponse("UploadError")
Beispiel #3
0
def person_create_edit(request,
                       group_id,
                       app_id,
                       app_set_id=None,
                       app_set_instance_id=None,
                       app_name=None):
    """
  Creates/Modifies document of given person-type.
  """
    auth = None
    if ObjectId.is_valid(group_id) is False:
        group_ins = node_collection.one({'_type': "Group", "name": group_id})
        auth = node_collection.one({
            '_type': 'Author',
            'name': unicode(request.user.username)
        })
        if group_ins:
            group_id = str(group_ins._id)
        else:
            auth = node_collection.one({
                '_type': 'Author',
                'name': unicode(request.user.username)
            })
            if auth:
                group_id = str(auth._id)
    else:
        pass

    app = None
    if app_id is None:
        app = node_collection.one({'_type': "GSystemType", 'name': app_name})
        if app:
            app_id = str(app._id)
    else:
        app = node_collection.one({'_id': ObjectId(app_id)})

    app_name = app.name

    # app_name = "mis"
    app_set = ""
    app_collection_set = []
    title = ""

    person_gst = None
    person_gs = None
    college_node = None
    college_id = None
    student_enrollment_code = u""
    create_student_enrollment_code = False
    existing_colg = []
    registration_date = None

    property_order_list = []

    template = ""
    template_prefix = "mis"

    if request.user:
        if auth is None:
            auth = node_collection.one({
                '_type': 'Author',
                'name': unicode(request.user.username)
            })
        agency_type = auth.agency_type
        agency_type_node = node_collection.one(
            {
                '_type': "GSystemType",
                'name': agency_type
            }, {'collection_set': 1})
        if agency_type_node:
            for eachset in agency_type_node.collection_set:
                app_collection_set.append(
                    node_collection.one({"_id": eachset}, {
                        '_id': 1,
                        'name': 1,
                        'type_of': 1
                    }))

    # for eachset in app.collection_set:
    #   app_collection_set.append(node_collection.one({"_id":eachset}, {'_id': 1, 'name': 1, 'type_of': 1}))
    college_node = node_collection.one(
        {
            "_id": ObjectId(group_id),
            "relation_set.group_of": {
                "$exists": True
            }
        }, {"relation_set.group_of": 1})

    if app_set_id:
        person_gst = node_collection.one(
            {
                '_type': "GSystemType",
                '_id': ObjectId(app_set_id)
            }, {
                'name': 1,
                'type_of': 1
            })
        template = "ndf/" + person_gst.name.strip().lower().replace(
            ' ', '_') + "_create_edit.html"
        title = person_gst.name
        person_gs = node_collection.collection.GSystem()
        person_gs.member_of.append(person_gst._id)

    if app_set_instance_id:
        person_gs = node_collection.one({
            '_type': "GSystem",
            '_id': ObjectId(app_set_instance_id)
        })

    property_order_list = get_property_order_with_value(
        person_gs)  #.property_order

    if request.method == "POST":
        if person_gst.name == "Student" and "_id" not in person_gs:
            create_student_enrollment_code = True

        # [A] Save person-node's base-field(s)
        is_changed = get_node_common_fields(request, person_gs, group_id,
                                            person_gst)

        if is_changed:
            # Remove this when publish button is setup on interface
            person_gs.status = u"PUBLISHED"

        person_gs.save(is_changed=is_changed, groupid=group_id)
        for each_rel in person_gs.relation_set:
            if each_rel and "officer_incharge_of" in each_rel:
                existing_colg = each_rel["officer_incharge_of"]
        if college_node:
            mis_admin = node_collection.one(
                {
                    "_type": "Group",
                    "name": "MIS_admin"
                }, {"_id": 1})

            node_collection.collection.update(
                {"_id": person_gs._id},
                {"$addToSet": {
                    "group_set": mis_admin._id
                }},
                upsert=False,
                multi=False)

        # [B] Store AT and/or RT field(s) of given person-node (i.e., person_gs)
        for tab_details in property_order_list:
            for field_set in tab_details[1]:
                # Fetch only Attribute field(s) / Relation field(s)
                if '_id' in field_set:
                    field_instance = node_collection.one(
                        {'_id': field_set['_id']})
                    fi_name = field_instance["name"]
                    field_instance_type = type(field_instance)

                    if field_instance_type in [AttributeType, RelationType]:
                        field_data_type = field_set['data_type']

                        # Fetch field's value depending upon AT/RT and Parse fetched-value depending upon that field's data-type
                        if field_instance_type == AttributeType:
                            if "File" in field_instance["validators"]:
                                # Special case: AttributeTypes that require file instance as it's value in which case file document's ObjectId is used
                                user_id = request.user.id
                                if fi_name in request.FILES:
                                    field_value = request.FILES[fi_name]

                                else:
                                    field_value = ""

                                # Below 0th index is used because that function returns tuple(ObjectId, bool-value)
                                if field_value != '' and field_value != u'':
                                    file_name = person_gs.name + " -- " + field_instance[
                                        "altnames"]
                                    content_org = ""
                                    tags = ""
                                    field_value = save_file(
                                        field_value,
                                        file_name,
                                        user_id,
                                        group_id,
                                        content_org,
                                        tags,
                                        access_policy="PRIVATE",
                                        count=0,
                                        first_object="",
                                        oid=True)[0]

                            else:
                                # Other AttributeTypes
                                if fi_name in request.POST:
                                    field_value = request.POST[fi_name]

                            # field_instance_type = "GAttribute"
                            if fi_name in [
                                    "12_passing_year", "degree_passing_year"
                            ]:  #, "registration_year"]:
                                field_value = parse_template_data(
                                    field_data_type,
                                    field_value,
                                    date_format_string="%Y")
                            elif fi_name in ["dob", "registration_date"]:
                                field_value = parse_template_data(
                                    field_data_type,
                                    field_value,
                                    date_format_string="%d/%m/%Y")
                                registration_date = field_value
                            else:
                                field_value = parse_template_data(
                                    field_data_type,
                                    field_value,
                                    date_format_string="%d/%m/%Y %H:%M")

                            if field_value:
                                person_gs_triple_instance = create_gattribute(
                                    person_gs._id,
                                    node_collection.collection.AttributeType(
                                        field_instance), field_value)

                        else:
                            if field_instance["object_cardinality"] > 1:
                                field_value_list = request.POST.get(
                                    fi_name, "")
                                if "[" in field_value_list and "]" in field_value_list:
                                    field_value_list = json.loads(
                                        field_value_list)
                                else:
                                    field_value_list = request.POST.getlist(
                                        fi_name)

                            else:
                                field_value_list = request.POST.getlist(
                                    fi_name)

                            if META_TYPE[
                                    3] in field_instance.member_of_names_list:
                                # If Binary relationship found
                                # [id, id, ...]
                                # field_instance_type = "GRelation"
                                for i, field_value in enumerate(
                                        field_value_list):
                                    field_value = parse_template_data(
                                        field_data_type,
                                        field_value,
                                        field_instance=field_instance,
                                        date_format_string="%m/%d/%Y %H:%M")
                                    field_value_list[i] = field_value
                            else:
                                # Relationship Other than Binary one found; e.g, Triadic
                                # [[id, id, ...], [id, id, ...], ...]
                                # field_instance_type = "GRelation"
                                for i, field_value_inner_list in enumerate(
                                        field_value_list):
                                    for j, field_value in enumerate(
                                            field_value_inner_list):
                                        field_value = parse_template_data(
                                            field_data_type,
                                            field_value,
                                            field_instance=field_instance,
                                            date_format_string="%m/%d/%Y %H:%M"
                                        )
                                        field_value_list[i][j] = field_value

                            person_gs_triple_instance = create_grelation(
                                person_gs._id,
                                node_collection.collection.RelationType(
                                    field_instance), field_value_list)

        # Setting enrollment code for student node only while creating it
        if create_student_enrollment_code:
            # Create enrollment code for student node only while registering a new node
            for rel in college_node.relation_set:
                if rel and "group_of" in rel:
                    college_id = rel["group_of"][0]

            student_enrollment_code = get_student_enrollment_code(
                college_id, person_gs._id, registration_date,
                ObjectId(group_id))

            enrollment_code_at = node_collection.one({
                "_type": "AttributeType",
                "name": "enrollment_code"
            })

            try:
                ga_node = create_gattribute(person_gs._id, enrollment_code_at,
                                            student_enrollment_code)
            except Exception as e:
                print "\n StudentEnrollmentCreateError: " + str(e) + "!!!"

        # [C] Code to link GSystem Node and Author node via "has_login" relationship;
        #     and Subscribe the Author node to College group if user "Program Officer"
        person_gs.reload()
        auth_node = None
        for attr in person_gs.attribute_set:
            if "email_id" in attr:
                if attr["email_id"]:
                    auth_node = node_collection.one({
                        '_type':
                        "Author",
                        'email':
                        attr["email_id"].lower()
                    })
                    break

        if auth_node:
            has_login_rt = node_collection.one({
                '_type': "RelationType",
                'name': "has_login"
            })
            if has_login_rt:
                # Linking GSystem Node and Author node via "has_login" relationship;
                gr_node = create_grelation(person_gs._id, has_login_rt,
                                           auth_node._id)

                # Set author_agency field's value of author node as "Program Officer"
                # Required to identify at time of log-in in order to display
                # required modules defined for Program Officers under MIS GApp
                if auth_node.agency_type != u"Program Officer":
                    auth_node.agency_type = u"Program Officer"
                    auth_node.save(groupid=group_id)

            if "Program Officer" in person_gs.member_of_names_list:
                # If Person node (GSystem) is of Program Officer type
                # then only go for subscription
                college_id_list = []
                # Fetch College's ObjectId to which Program Officer is assigned (via "officer_incharge_of")
                for rel in person_gs.relation_set:
                    if "officer_incharge_of" in rel:
                        if rel["officer_incharge_of"]:
                            for college_id in rel["officer_incharge_of"]:
                                if college_id not in college_id_list:
                                    college_id_list.append(college_id)
                            break  # break outer-loop (of relation_set)

                if college_id_list:
                    # If College's ObjectId exists (list as PO might be assigned to more than one college)
                    # Then prepare a list of their corresponding private group(s) (via "has_group")
                    college_cur = node_collection.find(
                        {'_id': {
                            '$in': college_id_list
                        }}, {'relation_set.has_group': 1})

                    college_group_id_list = []
                    for college in college_cur:
                        for rel in college.relation_set:
                            if rel and "has_group" in rel:
                                if rel["has_group"]:
                                    if rel["has_group"][
                                            0] not in college_group_id_list:
                                        college_group_id_list.append(
                                            rel["has_group"][0])

                                    break  # break inner-loop (college.relation_set)

                    if college_group_id_list:
                        # If college-group list exists
                        # Then update their group_admin field (append PO's created_by)
                        res = node_collection.collection.update(
                            {'_id': {
                                '$in': college_group_id_list
                            }}, {
                                '$addToSet': {
                                    'group_admin': auth_node.created_by
                                }
                            },
                            upsert=False,
                            multi=True)
                old_college_id_list = []
                if existing_colg:
                    if len(existing_colg) > len(college_id_list):
                        for each_colg_id in existing_colg:
                            if each_colg_id not in college_id_list:
                                old_college_id_list.append(each_colg_id)

                        old_college_cur = node_collection.find(
                            {'_id': {
                                '$in': old_college_id_list
                            }}, {'relation_set.has_group': 1})

                        old_college_group_id_list = []
                        for college in old_college_cur:
                            for rel in college.relation_set:
                                if rel and "has_group" in rel:
                                    if rel["has_group"]:
                                        if rel["has_group"][
                                                0] not in old_college_group_id_list:
                                            old_college_group_id_list.append(
                                                rel["has_group"][0])

                                        break  # break inner-loop (college.relation_set)

                        if old_college_group_id_list:
                            # If college-group list exists
                            # Then update their group_admin field (remove PO's created_by)
                            res = node_collection.collection.update(
                                {
                                    '_id': {
                                        '$in': old_college_group_id_list
                                    },
                                    '$or': [{
                                        'group_admin': auth_node.created_by
                                    }, {
                                        'author_set': auth_node.created_by
                                    }]
                                }, {
                                    '$pull': {
                                        'group_admin': auth_node.created_by,
                                        'author_set': auth_node.created_by
                                    }
                                },
                                upsert=False,
                                multi=True)
                            # The code below is commented as the college groups are PRIVATE.
                            # for rel in person_gs.relation_set:
                            #   if rel and "officer_incharge_of" in rel:
                            #       pass
                            #   else:
                            #       node_collection.collection.update({'_id': auth_node._id},
                            #       {'$set': {'agency_type': u"Other"}},
                            #       upsert=False, multi=False
                            #       )
                            # Its purpose is to change the agency type back to Other

                            auth_node.reload()
        # if person_gst.name != "Student":
        #     return HttpResponseRedirect(reverse(app_name.lower()+":"+template_prefix+'_app_detail', kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id}))
        # else:
        return HttpResponseRedirect(
            reverse('mis:mis_app_instance_detail',
                    kwargs={
                        'group_id': group_id,
                        "app_id": app_id,
                        "app_set_id": app_set_id,
                        "app_set_instance_id": unicode(person_gs._id)
                    }))

        # return HttpResponseRedirect(reverse(app_name.lower()+":"+template_prefix+'_app_detail', kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id}))

    default_template = "ndf/person_create_edit.html"

    # default_template = "ndf/"+template_prefix+"_create_edit.html"
    context_variables = {
        'groupid': group_id,
        'group_id': group_id,
        'app_id': app_id,
        'app_name': app_name,
        'app_collection_set': app_collection_set,
        'app_set_id': app_set_id,
        'title': title,
        'property_order_list': property_order_list
    }

    if person_gst and person_gst.name in [
            "Voluntary Teacher", "Master Trainer"
    ]:
        nussd_course_type = node_collection.one(
            {
                '_type': "AttributeType",
                'name': "nussd_course_type"
            }, {
                '_type': 1,
                '_id': 1,
                'data_type': 1,
                'complex_data_type': 1,
                'name': 1,
                'altnames': 1
            })

        if nussd_course_type["data_type"] == "IS()":
            # Below code does little formatting, for example:
            # data_type: "IS()" complex_value: [u"ab", u"cd"] dt:
            # "IS(u'ab', u'cd')"
            dt = "IS("
            for v in nussd_course_type.complex_data_type:
                dt = dt + "u'" + v + "'" + ", "
            dt = dt[:(dt.rfind(", "))] + ")"
            nussd_course_type["data_type"] = dt

        nussd_course_type["data_type"] = eval(nussd_course_type["data_type"])
        nussd_course_type["value"] = None
        context_variables['nussd_course_type'] = nussd_course_type

    if app_set_instance_id:
        person_gs.get_neighbourhood(person_gs.member_of)

        if "trainer_teaches_course_in_college" in person_gs:
            l = []
            for each_course_college in person_gs.trainer_teaches_course_in_college:
                # Fetch Course Type (i.e. nussd_course_type)
                ct = ""
                for each_attr in each_course_college[0].attribute_set:
                    if "nussd_course_type" in each_attr and each_attr:
                        ct = each_attr["nussd_course_type"]
                        break

                univ_name = ""
                for each_rel in each_course_college[1].relation_set:
                    if "college_affiliated_to" in each_rel and each_rel:
                        univ = node_collection.find_one({
                            "_id": {
                                "$in": each_rel["college_affiliated_to"]
                            }
                        })
                        univ_name = univ.name if univ else ""

                l.append((ct, each_course_college[0].name,
                          each_course_college[1].name,
                          each_course_college[0]._id.__str__(),
                          each_course_college[1]._id.__str__(), univ_name))
            if l:
                person_gs.trainer_teaches_course_in_college = l

        context_variables['node'] = person_gs

    try:
        return render_to_response([template, default_template],
                                  context_variables,
                                  context_instance=RequestContext(request))

    except TemplateDoesNotExist as tde:
        error_message = "\n PersonCreateEditViewError: This html template (" + str(
            tde) + ") does not exists !!!\n"
        raise Http404(error_message)

    except Exception as e:
        error_message = "\n PersonCreateEditViewError: " + str(e) + " !!!\n"
        raise Exception(error_message)
Beispiel #4
0
def discussion_reply(request, group_id, node_id):
    try:
        group_id = ObjectId(group_id)
    except:
        group_name, group_id = get_group_name_id(group_id)

    try:
        group_object = node_collection.one({'_id': ObjectId(group_id)})
        prior_node = request.POST.get("prior_node_id", "")
        content_org = request.POST.get("reply_text_content", "") # reply content
        node = node_collection.one({"_id": ObjectId(node_id)})
        gs_type_node_id = None

        if u'Twist' not in node.member_of_names_list:
            grel_dict = get_relation_value(node_id,'thread_of', True)
            node = grel_dict['grel_node']
        if node.prior_node:
            gs_type_node_id = node.prior_node[0]

        # if node and node.relation_set:
        #     for each_rel in node.relation_set:
        #         if each_rel and "thread_of" in each_rel:
        #             gs_type_node_id = each_rel['thread_of'][0]
        #             break

        # grel_dict = get_relation_value(node_id,'thread_of')
        # is_cursor = grel_dict.get("cursor",False)
        # if not is_cursor:
        #     gs_type_node_id = grel_dict.get("grel_node")
        #     # grel_id = grel_dict.get("grel_id")

        # print "\n\n node.name === ", node.member_of_names_list, node._id, node.name

        # process and save node if it reply has content
        if content_org:

            user_id = int(request.user.id)
            user_name = unicode(request.user.username)

            # auth = node_collection.one({'_type': 'Author', 'name': user_name })

            # creating empty GST and saving it
            reply_obj = node_collection.collection.GSystem()

            reply_obj.name = unicode("Reply of:" + str(prior_node))
            reply_obj.status = u"PUBLISHED"

            reply_obj.created_by = user_id
            reply_obj.modified_by = user_id
            reply_obj.contributors.append(user_id)

            reply_obj.member_of.append(ObjectId(reply_st._id))
            reply_obj.prior_node.append(ObjectId(prior_node))
            reply_obj.group_set.append(ObjectId(group_id))

            reply_obj.content_org = unicode(content_org)
            filename = slugify(unicode("Reply of:" + str(prior_node))) + "-" + user_name + "-"
            # reply_obj.content = org2html(content_org, file_prefix=filename)
            reply_obj.content = content_org
            if gs_type_node_id:
                reply_obj.origin.append({'prior_node_id_of_thread': ObjectId(gs_type_node_id)})
            if node_id:
                reply_obj.origin.append({'thread_id': ObjectId(node_id)})

            # ==============================
            # try:

            upload_files_count=int(request.POST.get("upload_cnt",0))
            # print "upfiles=",upload_files_count
            lst=[]
            lstobj_collection=[]
            usrid = int(request.user.id)
            if upload_files_count > 0:
                # print "uploaded items",request.FILES.items()
                try:
                    thread_obj = node_collection.one({'_id': ObjectId(prior_node)})
                    # print "thread_obj : ", thread_obj
                    if thread_obj.access_policy:
                        access_policy = thread_obj.access_policy
                    else:
                        access_policy = u'PUBLIC'

                except:
                    access_policy = u'PUBLIC'

                for key,value in request.FILES.items():
                    fname=unicode(value.__dict__['_name'])
                    # print "key=",key,"value=",value,"fname=",fname

                    fileobj,fs=save_file(value,fname,usrid,group_id, "", "", username=unicode(request.user.username), access_policy=access_policy, count=0, first_object="", oid=True)


                    if type(fileobj) == list:
                        obid = str(list(fileobj)[1])
                    else:
                        obid=str(fileobj)

                    try:
                        file_obj=node_collection.find_one({'_id': ObjectId(obid)})
                        lstobj_collection.append(file_obj._id)
                    except:
                        pass
                    if "CourseEventGroup" not in group_object.member_of_names_list:
                        if group_object.edit_policy == 'EDITABLE_MODERATED':
                            t = create_moderator_task(request, file_obj.group_set[0], file_obj._id,on_upload=True)
                # print "::: lstobj_collection: ", lstobj_collection
            # except:
                # lstobj_collection = []
            # ==============================
            reply_obj.collection_set = lstobj_collection
            # print "=== lstobj_collection: ", lstobj_collection

            # saving the reply obj
            reply_obj.save()

            #Update Counter Collection
            # thread_obj = node_collection.one({'_id':ObjectId(node_id)})
            if gs_type_node_id:
                gs_type_node = node_collection.one({'_id':gs_type_node_id})
                active_user_ids_list = [request.user.id]
                if GSTUDIO_BUDDY_LOGIN:
                    active_user_ids_list += Buddy.get_buddy_userids_list_within_datetime(request.user.id, datetime.now())
                    # removing redundancy of user ids:
                    active_user_ids_list = dict.fromkeys(active_user_ids_list).keys()
                Counter.add_comment_pt(resource_obj_or_id=gs_type_node,
                                       current_group_id=group_id,
                                       active_user_id_or_list=active_user_ids_list)


            # if gs_type_node.if_file.mime_type :
            #     file_creator_id = gs_type_node.created_by
            #     if file_creator_id != request.user.id :
            #         counter_obj = Counter.get_counter_obj(request.user.id, ObjectId(group_id))
            #         # counter_obj.no_comments_on_others_files += 1
            #         counter_obj['file']['commented_on_others_res'] += 1
            #         # counter_obj.no_comments_by_user += 1
            #         counter_obj['total_comments_by_user'] += 1
            #         # counter_obj.course_score += GSTUDIO_COMMENT_POINTS
            #         counter_obj['group_points'] += GSTUDIO_COMMENT_POINTS

            #         counter_obj_creator = Counter.get_counter_obj(file_creator_id, ObjectId(group_id))
            #         # counter_obj_creator.no_comments_received_on_files += 1
            #         counter_obj_creator['file']['comments_gained'] += 1
            #         # counter_obj_creator.no_comments_for_user += 1
            #         if str(counter_obj.user_id) in counter_obj_creator.file['comments_by_others_on_res'].keys():
            #             # counter_obj_creator.comments_by_others_on_files[str(counter_obj.user_id)] += 1
            #             counter_obj_creator['file']['comments_by_others_on_res'][str(counter_obj.user_id)] += 1
            #         else:
            #             # counter_obj_creator.comments_by_others_on_files.update({str(counter_obj.user_id):1})
            #             counter_obj_creator.file['comments_by_others_on_res'].update({str(counter_obj.user_id):1})
            #         counter_obj.last_update = datetime.now()
            #         counter_obj_creator.last_update = datetime.now()
            #         counter_obj.save()
            #         counter_obj_creator.save()
            # else :
            #     note_creator_id = gs_type_node.created_by
            #     if note_creator_id != request.user.id :
            #         counter_obj = Counter.get_counter_obj(request.user.id, ObjectId(group_id))
            #         # counter_obj.no_comments_by_user += 1
            #         counter_obj['total_comments_by_user'] += 1
            #         # counter_obj.no_comments_on_others_notes += 1
            #         counter_obj['page']['blog']['commented_on_others_res'] += 1
            #         counter_obj['group_points'] += GSTUDIO_COMMENT_POINTS

            #         counter_obj_creator = Counter.get_counter_obj(note_creator_id, ObjectId(group_id))
            #         # counter_obj_creator.no_comments_for_user += 1
            #         # counter_obj_creator.no_comments_received_on_notes += 1
            #         counter_obj_creator['page']['blog']['comments_gained'] += 1

            #         # if str(counter_obj.user_id) in counter_obj_creator.comments_by_others_on_notes.keys():
            #         if str(counter_obj.user_id) in counter_obj_creator.page.blog['comments_by_others_on_res'].keys():
            #             # counter_obj_creator.comments_by_others_on_notes[str(counter_obj.user_id)] += 1
            #             counter_obj_creator['page']['blog']['comments_by_others_on_res'][str(counter_obj.user_id)] += 1
            #         else:
            #             counter_obj_creator.page.blog['comments_by_others_on_res'].update({str(counter_obj.user_id):1})
            #         counter_obj.last_update = datetime.now()
            #         counter_obj_creator.last_update = datetime.now()
            #         counter_obj.save()
            #         counter_obj_creator.save()

            formated_time = reply_obj.created_at.strftime("%B %d, %Y, %I:%M %p")

            files = []
            for each_coll_item in reply_obj.collection_set:
                temp_list = []
                temp = node_collection.one({'_id': ObjectId(each_coll_item)}, {'mime_type': 1, 'name': 1})
                temp_list.append(str(temp['_id']))
                temp_list.append(str(temp['mime_type']))
                temp_list.append(str(temp['name']))

                files.append(temp_list)

            # print files
            user_names = reply_obj.user_details_dict["contributors"]
            is_grp_admin = False
            if request.user.id in group_object.group_admin:
                is_grp_admin = True
            # ["status_info", "reply_id", "prior_node", "html_content", "org_content", "user_id", "user_name", "created_at" ]
            reply = json.dumps( [ "reply_saved", str(reply_obj._id), str(reply_obj.prior_node[0]), reply_obj.content, reply_obj.content_org, user_id, user_names, formated_time, files,is_grp_admin], cls=DjangoJSONEncoder )

            # print "===========", reply

            # ---------- mail/notification sending -------
            try:
                node_creator_user_obj = User.objects.get(id=node.created_by)
                node_creator_user_name = node_creator_user_obj.username
                if int(request.user.id) not in node.author_set:
                    node.author_set.append(int(request.user.id))
                    node.save()
                site = Site.objects.get(pk=1)
                site = site.name.__str__()

                from_user = user_name

                to_user_list = [node_creator_user_obj]

                msg = "\n\nDear " + node_creator_user_name + ",\n\n" + \
                      "A reply has been added in discussion under the " + \
                      node.member_of_names_list[0] + " named: '" + \
                      node.name + "' by '" + user_name + "'."

                activity = "Discussion Reply"
                render_label = render_to_string(
                    "notification/label.html",
                    {
                        # "sender": from_user,
                        "activity": activity,
                        "conjunction": "-",
                        "link": "url_link"
                    }
                )
                notification.create_notice_type(render_label, msg, "notification")
                notification.send(to_user_list, render_label, {"from_user": from_user})
            except Exception as notification_err:
                print "\n Unable to send notification", notification_err
            # ---------- END of mail/notification sending ---------
            return HttpResponse( reply )

        else: # no reply content

            return HttpResponse(json.dumps(["no_content"]))

    except Exception as e:

        error_message = "\n DiscussionReplyCreateError: " + str(e) + "\n"
        raise Exception(error_message)

        return HttpResponse(json.dumps(["Server Error"]))
Beispiel #5
0
def discussion_reply(request, group_id, node_id):
    try:
        group_id = ObjectId(group_id)
    except:
        group_name, group_id = get_group_name_id(group_id)

    try:
        group_object = node_collection.one({'_id': ObjectId(group_id)})
        prior_node = request.POST.get("prior_node_id", "")
        content_org = request.POST.get("reply_text_content", "") # reply content
        node = node_collection.one({"_id": ObjectId(node_id)})
        gs_type_node_id = None

        if u'Twist' not in node.member_of_names_list:
            # grel_dict = get_relation_value(node_id,'thread_of', True)
            grel_dict = get_relation_value(node._id,'has_thread', True)
            node = grel_dict['grel_node']

        if node.prior_node:
            gs_type_node_id = node.prior_node[0]
        else:
            try:
                has_thread_at = node_collection.one({'_type': 'RelationType', 'name': 'has_thread'})
                has_thread_grel = triple_collection.find_one({'_type': 'GRelation',
                    'relation_type': has_thread_at._id, 'right_subject': node._id,
                    'status': 'PUBLISHED'})
                gs_type_node_id = has_thread_grel.subject
            except Exception as e:
                print "\n Node asssociated with Thread node NOT found.", e
                pass

        # process and save node if it reply has content
        if content_org:

            user_id = int(request.user.id)
            user_name = unicode(request.user.username)
            # auth = node_collection.one({'_type': 'Author', 'name': user_name })

            # creating empty GST and saving it
            reply_obj = node_collection.collection.GSystem()

            reply_obj.name = unicode("Reply of:" + str(prior_node))
            reply_obj.status = u"PUBLISHED"

            reply_obj.created_by = user_id
            reply_obj.modified_by = user_id
            reply_obj.contributors.append(user_id)

            reply_obj.member_of.append(ObjectId(reply_st._id))
            reply_obj.prior_node.append(ObjectId(prior_node))
            reply_obj.group_set.append(ObjectId(group_id))

            reply_obj.content_org = unicode(content_org)
            filename = slugify(unicode("Reply of:" + str(prior_node))) + "-" + user_name + "-"
            # reply_obj.content = org2html(content_org, file_prefix=filename)
            reply_obj.content = content_org
            if gs_type_node_id:
                reply_obj.origin.append({'prior_node_id_of_thread': ObjectId(gs_type_node_id)})
            if node_id:
                reply_obj.origin.append({'thread_id': ObjectId(node_id)})

            # ==============================
            # try:

            upload_files_count=int(request.POST.get("upload_cnt",0))
            # print "upfiles=",upload_files_count
            lst=[]
            lstobj_collection=[]
            usrid = int(request.user.id)
            if upload_files_count > 0:
                # print "uploaded items",request.FILES.items()
                try:
                    thread_obj = node_collection.one({'_id': ObjectId(prior_node)})
                    # print "thread_obj : ", thread_obj
                    if thread_obj.access_policy:
                        access_policy = thread_obj.access_policy
                    else:
                        access_policy = u'PUBLIC'

                except:
                    access_policy = u'PUBLIC'

                for key,value in request.FILES.items():
                    fname=unicode(value.__dict__['_name'])
                    # print "key=",key,"value=",value,"fname=",fname

                    fileobj,fs=save_file(value,fname,usrid,group_id, "", "", username=unicode(request.user.username), access_policy=access_policy, count=0, first_object="", oid=True)


                    if type(fileobj) == list:
                        obid = str(list(fileobj)[1])
                    else:
                        obid=str(fileobj)

                    try:
                        file_obj=node_collection.find_one({'_id': ObjectId(obid)})
                        lstobj_collection.append(file_obj._id)
                    except:
                        pass
                    if "CourseEventGroup" not in group_object.member_of_names_list:
                        if group_object.edit_policy == 'EDITABLE_MODERATED':
                            t = create_moderator_task(request, file_obj.group_set[0], file_obj._id,on_upload=True)
                # print "::: lstobj_collection: ", lstobj_collection
            # except:
                # lstobj_collection = []
            # ==============================
            reply_obj.collection_set = lstobj_collection
            # print "=== lstobj_collection: ", lstobj_collection

            # saving the reply obj
            reply_obj.save()

            #Update Counter Collection
            # thread_obj = node_collection.one({'_id':ObjectId(node_id)})
            if gs_type_node_id:
                gs_type_node = node_collection.one({'_id':gs_type_node_id})
                active_user_ids_list = [request.user.id]
                if GSTUDIO_BUDDY_LOGIN:
                    active_user_ids_list += Buddy.get_buddy_userids_list_within_datetime(request.user.id, datetime.now())
                    # removing redundancy of user ids:
                    active_user_ids_list = dict.fromkeys(active_user_ids_list).keys()
                Counter.add_comment_pt(resource_obj_or_id=gs_type_node,
                                       current_group_id=group_id,
                                       active_user_id_or_list=active_user_ids_list)


            # if gs_type_node.if_file.mime_type :
            #     file_creator_id = gs_type_node.created_by
            #     if file_creator_id != request.user.id :
            #         counter_obj = Counter.get_counter_obj(request.user.id, ObjectId(group_id))
            #         # counter_obj.no_comments_on_others_files += 1
            #         counter_obj['file']['commented_on_others_res'] += 1
            #         # counter_obj.no_comments_by_user += 1
            #         counter_obj['total_comments_by_user'] += 1
            #         # counter_obj.course_score += GSTUDIO_COMMENT_POINTS
            #         counter_obj['group_points'] += GSTUDIO_COMMENT_POINTS

            #         counter_obj_creator = Counter.get_counter_obj(file_creator_id, ObjectId(group_id))
            #         # counter_obj_creator.no_comments_received_on_files += 1
            #         counter_obj_creator['file']['comments_gained'] += 1
            #         # counter_obj_creator.no_comments_for_user += 1
            #         if str(counter_obj.user_id) in counter_obj_creator.file['comments_by_others_on_res'].keys():
            #             # counter_obj_creator.comments_by_others_on_files[str(counter_obj.user_id)] += 1
            #             counter_obj_creator['file']['comments_by_others_on_res'][str(counter_obj.user_id)] += 1
            #         else:
            #             # counter_obj_creator.comments_by_others_on_files.update({str(counter_obj.user_id):1})
            #             counter_obj_creator.file['comments_by_others_on_res'].update({str(counter_obj.user_id):1})
            #         counter_obj.last_update = datetime.now()
            #         counter_obj_creator.last_update = datetime.now()
            #         counter_obj.save()
            #         counter_obj_creator.save()
            # else :
            #     note_creator_id = gs_type_node.created_by
            #     if note_creator_id != request.user.id :
            #         counter_obj = Counter.get_counter_obj(request.user.id, ObjectId(group_id))
            #         # counter_obj.no_comments_by_user += 1
            #         counter_obj['total_comments_by_user'] += 1
            #         # counter_obj.no_comments_on_others_notes += 1
            #         counter_obj['page']['blog']['commented_on_others_res'] += 1
            #         counter_obj['group_points'] += GSTUDIO_COMMENT_POINTS

            #         counter_obj_creator = Counter.get_counter_obj(note_creator_id, ObjectId(group_id))
            #         # counter_obj_creator.no_comments_for_user += 1
            #         # counter_obj_creator.no_comments_received_on_notes += 1
            #         counter_obj_creator['page']['blog']['comments_gained'] += 1

            #         # if str(counter_obj.user_id) in counter_obj_creator.comments_by_others_on_notes.keys():
            #         if str(counter_obj.user_id) in counter_obj_creator.page.blog['comments_by_others_on_res'].keys():
            #             # counter_obj_creator.comments_by_others_on_notes[str(counter_obj.user_id)] += 1
            #             counter_obj_creator['page']['blog']['comments_by_others_on_res'][str(counter_obj.user_id)] += 1
            #         else:
            #             counter_obj_creator.page.blog['comments_by_others_on_res'].update({str(counter_obj.user_id):1})
            #         counter_obj.last_update = datetime.now()
            #         counter_obj_creator.last_update = datetime.now()
            #         counter_obj.save()
            #         counter_obj_creator.save()

            formated_time = reply_obj.created_at.strftime("%B %d, %Y, %I:%M %p")

            files = []
            for each_coll_item in reply_obj.collection_set:
                temp_list = []
                temp = node_collection.one({'_id': ObjectId(each_coll_item)}, {'mime_type': 1, 'name': 1})
                temp_list.append(str(temp['_id']))
                temp_list.append(str(temp['mime_type']))
                temp_list.append(str(temp['name']))

                files.append(temp_list)

            # print files
            user_names = reply_obj.user_details_dict["contributors"]
            is_grp_admin = False
            if request.user.id in group_object.group_admin:
                is_grp_admin = True
            # ["status_info", "reply_id", "prior_node", "html_content", "org_content", "user_id", "user_name", "created_at" ]
            reply = json.dumps( [ "reply_saved", str(reply_obj._id), str(reply_obj.prior_node[0]), reply_obj.content, reply_obj.content_org, user_id, user_names, formated_time, files,is_grp_admin], cls=DjangoJSONEncoder )

            # print "===========", reply

            # ---------- mail/notification sending -------
            try:
                node_creator_user_obj = User.objects.get(id=node.created_by)
                node_creator_user_name = node_creator_user_obj.username
                if int(request.user.id) not in node.author_set:
                    node.author_set.append(int(request.user.id))
                    node.save()
                site = Site.objects.get(pk=1)
                site = site.name.__str__()

                from_user = user_name

                to_user_list = [node_creator_user_obj]

                msg = "\n\nDear " + node_creator_user_name + ",\n\n" + \
                      "A reply has been added in discussion under the " + \
                      node.member_of_names_list[0] + " named: '" + \
                      node.name + "' by '" + user_name + "'."

                activity = "Discussion Reply"
                render_label = render_to_string(
                    "notification/label.html",
                    {
                        # "sender": from_user,
                        "activity": activity,
                        "conjunction": "-",
                        "link": "url_link"
                    }
                )
                notification.create_notice_type(render_label, msg, "notification")
                notification.send(to_user_list, render_label, {"from_user": from_user})
            except Exception as notification_err:
                print "\n Unable to send notification", notification_err
            # ---------- END of mail/notification sending ---------
            return HttpResponse( reply )

        else: # no reply content

            return HttpResponse(json.dumps(["no_content"]))

    except Exception as e:

        error_message = "\n DiscussionReplyCreateError: " + str(e) + "\n"
        raise Exception(error_message)

        return HttpResponse(json.dumps(["Server Error"]))
Beispiel #6
0
def add_node(request, group_id):

    # ins_objectid  = ObjectId()
    # if ins_objectid.is_valid(group_id) is False :
    #     group_ins = node_collection.find_one({'_type': "Group","name": group_id})
    #     auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
    #     if group_ins:
    #         group_id = str(group_ins._id)
    #     else :
    #         auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
    #         if auth :
    #             group_id = str(auth._id)
    # else :
    #     pass
    group_name, group_id = get_group_name_id(group_id)

    try:
        auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
        content_org = request.POST.get("reply","")
        node = request.POST.get("node","")
        thread = request.POST.get("thread","") # getting thread _id
        forumid = request.POST.get("forumid","") # getting forum _id
        sup_id = request.POST.get("supnode","") #getting _id of it's parent node
        tw_name = request.POST.get("twistname","")
        upload_files_count=int(request.POST.get("upload_cnt",0))
        #print "upfiles=",upload_files_count
        lst=[]
        lstobj_collection=[]
        usrid = int(request.user.id)
        if upload_files_count > 0:
            #print "uploaded items",request.FILES.items()
            try:
                thread_obj = node_collection.one({'_id': ObjectId(thread)})
                access_policy = thread_obj.access_policy
            except:
                access_policy = u'PUBLIC'

            for key,value in request.FILES.items():
                fname=unicode(value.__dict__['_name'])
                #print "key=",key,"value=",value,"fname=",fname
                
                fileobj,fs=save_file(value,fname,usrid,group_id, "", "", username=unicode(request.user.username), access_policy=access_policy, count=0, first_object="")

                if type(fileobj) == list:
                    obid = str(list(fileobj)[1])
                else:
                    obid=str(fileobj)
                file_obj=node_collection.find_one({'_id': ObjectId(obid)})
                lstobj_collection.append(file_obj._id) 
        forumobj = ""
        groupobj = ""
        colg = node_collection.one({'_id':ObjectId(group_id)})
        if forumid:
            forumobj = node_collection.one({"_id": ObjectId(forumid)})
    
        sup = node_collection.one({"_id": ObjectId(sup_id)})
    
        if not sup :        
            return HttpResponse("failure")
    
        colrep = node_collection.collection.GSystem()
    
        if node == "Twist":
            name = tw_name
            colrep.member_of.append(twist_gst._id)
        elif node == "Reply":
            name = unicode("Reply of:"+str(sup._id))
            colrep.member_of.append(reply_gst._id)
        #Adding uploaded files id's in collection set of reply
        if upload_files_count > 0:
            colrep.collection_set = lstobj_collection   
    
        colrep.prior_node.append(sup._id)
        colrep.name = name
        
        if content_org:
            colrep.content_org = unicode(content_org)
            # Required to link temporary files with the current user who is modifying this document
            usrname = request.user.username
            filename = slugify(name) + "-" + usrname + "-"
            colrep.content = content_org

       
        colrep.created_by = usrid
        colrep.modified_by = usrid

        if usrid not in colrep.contributors:
            colrep.contributors.append(usrid)
        colrep.prior_node.append(sup._id)
        colrep.name = name

        if content_org:
            colrep.content_org = unicode(content_org)
            # Required to link temporary files with the current user who is modifying this document
            usrname = request.user.username
            filename = slugify(name) + "-" + usrname + "-"
            colrep.content = content_org

        usrid=int(request.user.id)
        colrep.created_by=usrid
        colrep.modified_by = usrid

        if usrid not in colrep.contributors:
            colrep.contributors.append(usrid)
        
        colrep.group_set.append(colg._id)

        colrep.save(groupid=group_id)

        # print "----------", colrep._id
        groupname = colg.name
        
        if node == "Twist" :  
            url="http://"+sitename+"/"+str(group_id)+"/forum/thread/"+str(colrep._id)
            activity=request.user.username+" -added a thread '"
            prefix="' on the forum '"+forumobj.name+"'"
            nodename=name
        
        if node == "Reply":
            threadobj=node_collection.one({"_id": ObjectId(thread)})
            url="http://"+sitename+"/"+str(group_id)+"/forum/thread/"+str(threadobj._id)
            activity=request.user.username+" -added a reply "
            prefix=" on the thread '"+threadobj.name+"' on the forum '"+forumobj.name+"'"
            nodename=""

        link = url

        for each in colg.author_set:
            if each != colg.created_by:
                bx=User.objects.get(id=each)
                msg=activity+"-"+nodename+prefix+" in the group '"+ groupname +"'\n"+"Please visit "+link+" to see the updated page"
                if bx:
                    no_check=forum_notification_status(group_id,auth._id)
                    if no_check:
                        ret = set_notif_val(request,group_id,msg,activity,bx)
        
        bx=User.objects.get(id=colg.created_by)
        msg=activity+"-"+nodename+prefix+" in the group '"+groupname+"' created by you"+"\n"+"Please visit "+link+" to see the updated page"   
        
        if bx:
            no_check=forum_notification_status(group_id,auth._id)
            if no_check:
                ret = set_notif_val(request,group_id,msg,activity,bx)
        if node == "Reply":
            # if exstng_reply:
            #     exstng_reply.prior_node =[]
            #     exstng_reply.prior_node.append(colrep._id)
            #     exstng_reply.save()

            threadobj=node_collection.one({"_id": ObjectId(thread)})
            variables=RequestContext(request,{'thread':threadobj,'user':request.user,'forum':forumobj,'groupid':group_id,'group_id':group_id})
            return render_to_response("ndf/refreshtwist.html",variables)
        else:
            templ=get_template('ndf/refreshthread.html')
            html = templ.render(Context({'forum':forumobj,'user':request.user,'groupid':group_id,'group_id':group_id}))
            return HttpResponse(html)

    except Exception as e:
        return HttpResponse(""+str(e))
    return HttpResponse("success")
Beispiel #7
0
def organization_create_edit(request, group_id, app_id, app_set_id=None, app_set_instance_id=None, app_name=None):
  """
  Creates/Modifies document of given organization-type.
  """
  auth = None
  # if ObjectId.is_valid(group_id) is False :
  #   group_ins = node_collection.one({'_type': "Group","name": group_id})
  #   auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
  #   if group_ins:
  #     group_id = str(group_ins._id)
  #   else :
  #     auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
  #     if auth :
  #       group_id = str(auth._id)
  # else :
  #   pass
  group_name, group_id = get_group_name_id(group_id)
  app = None
  if app_id is None:
    app = node_collection.one({'_type': "GSystemType", 'name': app_name})
    if app:
      app_id = str(app._id)
  else:
    app = node_collection.one({'_id': ObjectId(app_id)},{'_id':1, 'name':1})
  app_name = app.name

  # app_name = "mis"
  app_set = ""
  app_collection_set = []
  title = ""

  organization_gst = None
  organization_gs = None

  property_order_list = []

  template = ""
  template_prefix = "mis"

  if request.user:
    if auth is None:
      auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username)})
    agency_type = auth.agency_type
    agency_type_node = node_collection.one({'_type': "GSystemType", 'name': agency_type}, {'collection_set': 1})
    if agency_type_node:
      for eachset in agency_type_node.collection_set:
        app_collection_set.append(node_collection.one({"_id": eachset}, {'_id': 1, 'name': 1, 'type_of': 1}))      
  # for eachset in app.collection_set:
  #   app_collection_set.append(node_collection.one({"_id":eachset}, {'_id': 1, 'name': 1, 'type_of': 1}))

  if app_set_id:
    organization_gst = node_collection.one({'_type': "GSystemType", '_id': ObjectId(app_set_id)}, {'name': 1, 'type_of': 1})
    template = "ndf/organization_create_edit.html"
    title = organization_gst.name
    organization_gs = node_collection.collection.GSystem()
    organization_gs.member_of.append(organization_gst._id)

  if app_set_instance_id:
    organization_gs = node_collection.one({'_type': "GSystem", '_id': ObjectId(app_set_instance_id)})
  property_order_list = get_property_order_with_value(organization_gs)#.property_order
  if request.method == "POST":
    # [A] Save organization-node's base-field(s)
    is_changed = get_node_common_fields(request, organization_gs, group_id, organization_gst)

    if is_changed:
      # Remove this when publish button is setup on interface
      organization_gs.status = u"PUBLISHED"

    organization_gs.save(is_changed=is_changed,groupid=group_id)

    # [B] Store AT and/or RT field(s) of given organization-node (i.e., organization_gs)
    for tab_details in property_order_list:
      for field_set in tab_details[1]:
        # Fetch only Attribute field(s) / Relation field(s)
        if '_id' in field_set:
          field_instance = node_collection.one({'_id': field_set['_id']})
          field_instance_type = type(field_instance)

          if field_instance_type in [AttributeType, RelationType]:
            if field_instance["name"] == "attendees":
              continue

            field_data_type = field_set['data_type']

            # Fetch field's value depending upon AT/RT and Parse fetched-value depending upon that field's data-type
            if field_instance_type == AttributeType:
              if "File" in field_instance["validators"]:
                # Special case: AttributeTypes that require file instance as it's value in which case file document's ObjectId is used
                
                if field_instance["name"] in request.FILES:
                  field_value = request.FILES[field_instance["name"]]

                else:
                  field_value = ""
                
                # Below 0th index is used because that function returns tuple(ObjectId, bool-value)
                if field_value != '' and field_value != u'':
                  file_name = organization_gs.name + " -- " + field_instance["altnames"]
                  content_org = ""
                  tags = ""
                  field_value = save_file(field_value, file_name, request.user.id, group_id, content_org, tags, access_policy="PRIVATE", count=0, first_object="", oid=True)[0]

              else:
                # Other AttributeTypes 
                field_value = request.POST[field_instance["name"]]

              # field_instance_type = "GAttribute"
              if field_instance["name"] in ["12_passing_year", "degree_passing_year"]: #, "registration_year"]:
                field_value = parse_template_data(field_data_type, field_value, date_format_string="%Y")
              elif field_instance["name"] in ["dob", "registration_date"]:
                field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y")
              else:
                field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y %H:%M")

              if field_value:
                organization_gs_triple_instance = create_gattribute(organization_gs._id, node_collection.collection.AttributeType(field_instance), field_value)

            else:
              if field_instance["object_cardinality"] > 1:
                field_value_list = request.POST.get(field_instance["name"], "")
                if "[" in field_value_list and "]" in field_value_list:
                  field_value_list = json.loads(field_value_list)
                else:
                  field_value_list = request.POST.getlist(field_instance["name"])

              else:
                field_value_list = request.POST.getlist(field_instance["name"])

              # field_instance_type = "GRelation"
              for i, field_value in enumerate(field_value_list):
                field_value = parse_template_data(field_data_type, field_value, field_instance=field_instance, date_format_string="%m/%d/%Y %H:%M")
                field_value_list[i] = field_value

              organization_gs_triple_instance = create_grelation(organization_gs._id, node_collection.collection.RelationType(field_instance), field_value_list)

    # [C] Create private group only for College GSystems
    if "College" in organization_gs.member_of_names_list:
      # Create a group for respective college node
      college_group, college_group_gr = create_college_group_and_setup_data(organization_gs)

    return HttpResponseRedirect(
      reverse(
        app_name.lower()+":"+template_prefix+'_app_detail',
        kwargs={'group_id': group_id, "app_id": app_id, "app_set_id": app_set_id}
      )
    )

  # default_template = "ndf/"+template_prefix+"_create_edit.html"
  context_variables = { 'groupid': group_id, 'group_id': group_id,
                        'app_id': app_id, 'app_name': app_name, 'app_collection_set': app_collection_set, 
                        'app_set_id': app_set_id,
                        'title': title,
                        'property_order_list': property_order_list
                      }
  if app_set_instance_id:
    #   organization_gs.get_neighbourhood(organization_gs.member_of)
    #   context_variables['node'] = organization_gs
    context_variables['node_id'] = organization_gs._id
    context_variables['node_name'] = organization_gs.name

  try:
    return render_to_response(template,
                              context_variables,
                              context_instance = RequestContext(request)
                            )

  except TemplateDoesNotExist as tde:
    error_message = "\n OrganizationCreateEditViewError: This html template (" + str(tde) + ") does not exists !!!\n"
    raise Http404(error_message)

  except Exception as e:
    error_message = "\n OrganizationCreateEditViewError: " + str(e) + " !!!\n"
    raise Exception(error_message)
Beispiel #8
0
def person_create_edit(request, group_id, app_id, app_set_id=None, app_set_instance_id=None, app_name=None):
  """
  Creates/Modifies document of given person-type.
  """
  auth = None
  if ObjectId.is_valid(group_id) is False :
    group_ins = node_collection.one({'_type': "Group", "name": group_id})
    auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
    if group_ins:
      group_id = str(group_ins._id)
    else :
      auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
      if auth :
        group_id = str(auth._id)
  else :
    pass

  app = None
  if app_id is None:
    app = node_collection.one({'_type': "GSystemType", 'name': app_name})
    if app:
      app_id = str(app._id)
  else:
    app = node_collection.one({'_id': ObjectId(app_id)})

  app_name = app.name 

  # app_name = "mis"
  app_set = ""
  app_collection_set = []
  title = ""

  person_gst = None
  person_gs = None
  college_node = None
  college_id = None
  student_enrollment_code = u""
  create_student_enrollment_code = False
  existing_colg = []
  registration_date = None

  property_order_list = []

  template = ""
  template_prefix = "mis"

  if request.user:
    if auth is None:
      auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username)})
    agency_type = auth.agency_type
    agency_type_node = node_collection.one({'_type': "GSystemType", 'name': agency_type}, {'collection_set': 1})
    if agency_type_node:
      for eachset in agency_type_node.collection_set:
        app_collection_set.append(node_collection.one({"_id": eachset}, {'_id': 1, 'name': 1, 'type_of': 1}))

  # for eachset in app.collection_set:
  #   app_collection_set.append(node_collection.one({"_id":eachset}, {'_id': 1, 'name': 1, 'type_of': 1}))
  college_node = node_collection.one({
      "_id": ObjectId(group_id),
      "relation_set.group_of": {"$exists": True}
  }, {
      "relation_set.group_of": 1
  })

  if app_set_id:
    person_gst = node_collection.one({'_type': "GSystemType", '_id': ObjectId(app_set_id)}, {'name': 1, 'type_of': 1})
    template = "ndf/" + person_gst.name.strip().lower().replace(' ', '_') + "_create_edit.html"
    title = person_gst.name
    person_gs = node_collection.collection.GSystem()
    person_gs.member_of.append(person_gst._id)

  if app_set_instance_id:
    person_gs = node_collection.one({'_type': "GSystem", '_id': ObjectId(app_set_instance_id)})

  property_order_list = get_property_order_with_value(person_gs)#.property_order

  if request.method == "POST":
    if person_gst.name == "Student" and "_id" not in person_gs:
      create_student_enrollment_code = True

    # [A] Save person-node's base-field(s)
    is_changed = get_node_common_fields(request, person_gs, group_id, person_gst)

    if is_changed:
      # Remove this when publish button is setup on interface
      person_gs.status = u"PUBLISHED"

    person_gs.save(is_changed=is_changed,groupid=group_id)
    for each_rel in person_gs.relation_set:
      if each_rel and "officer_incharge_of" in each_rel:
        existing_colg = each_rel["officer_incharge_of"]
    if college_node:
        mis_admin = node_collection.one({
            "_type": "Group",
            "name": "MIS_admin"
        }, {
            "_id": 1
        }
        )

        node_collection.collection.update({
            "_id": person_gs._id
        }, {
            "$addToSet": {"group_set": mis_admin._id}
        },
        upsert=False, multi=False
        )

    # [B] Store AT and/or RT field(s) of given person-node (i.e., person_gs)
    for tab_details in property_order_list:
      for field_set in tab_details[1]:
        # Fetch only Attribute field(s) / Relation field(s)
        if '_id' in field_set:
          field_instance = node_collection.one({'_id': field_set['_id']})
          fi_name = field_instance["name"]
          field_instance_type = type(field_instance)

          if field_instance_type in [AttributeType, RelationType]:
            field_data_type = field_set['data_type']

            # Fetch field's value depending upon AT/RT and Parse fetched-value depending upon that field's data-type
            if field_instance_type == AttributeType:
              if "File" in field_instance["validators"]:
                # Special case: AttributeTypes that require file instance as it's value in which case file document's ObjectId is used
                user_id = request.user.id
                if fi_name in request.FILES:
                  field_value = request.FILES[fi_name]

                else:
                  field_value = ""

                # Below 0th index is used because that function returns tuple(ObjectId, bool-value)
                if field_value != '' and field_value != u'':
                  file_name = person_gs.name + " -- " + field_instance["altnames"]
                  content_org = ""
                  tags = ""
                  field_value = save_file(field_value, file_name, user_id, group_id, content_org, tags, access_policy="PRIVATE", count=0, first_object="", oid=True)[0]

              else:
                # Other AttributeTypes
                if fi_name in request.POST:
                    field_value = request.POST[fi_name]

              # field_instance_type = "GAttribute"
              if fi_name in ["12_passing_year", "degree_passing_year"]: #, "registration_year"]:
                field_value = parse_template_data(field_data_type, field_value, date_format_string="%Y")
              elif fi_name in ["dob", "registration_date"]:
                field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y")
                registration_date = field_value
              else:
                field_value = parse_template_data(field_data_type, field_value, date_format_string="%d/%m/%Y %H:%M")

              if field_value:
                person_gs_triple_instance = create_gattribute(person_gs._id, node_collection.collection.AttributeType(field_instance), field_value)

            else:
              if field_instance["object_cardinality"] > 1:
                field_value_list = request.POST.get(fi_name, "")
                if "[" in field_value_list and "]" in field_value_list:
                  field_value_list = json.loads(field_value_list)
                else:
                  field_value_list = request.POST.getlist(fi_name)

              else:
                field_value_list = request.POST.getlist(fi_name)

              if META_TYPE[3] in field_instance.member_of_names_list:
                # If Binary relationship found
                # [id, id, ...]
                # field_instance_type = "GRelation"
                for i, field_value in enumerate(field_value_list):
                  field_value = parse_template_data(field_data_type, field_value, field_instance=field_instance, date_format_string="%m/%d/%Y %H:%M")
                  field_value_list[i] = field_value
              else:
                # Relationship Other than Binary one found; e.g, Triadic
                # [[id, id, ...], [id, id, ...], ...]
                # field_instance_type = "GRelation"
                for i, field_value_inner_list in enumerate(field_value_list):
                  for j, field_value in enumerate(field_value_inner_list):
                    field_value = parse_template_data(field_data_type, field_value, field_instance=field_instance, date_format_string="%m/%d/%Y %H:%M")
                    field_value_list[i][j] = field_value

              person_gs_triple_instance = create_grelation(person_gs._id, node_collection.collection.RelationType(field_instance), field_value_list)

    # Setting enrollment code for student node only while creating it
    if create_student_enrollment_code:
        # Create enrollment code for student node only while registering a new node
        for rel in college_node.relation_set:
          if rel and "group_of" in rel:
            college_id = rel["group_of"][0]

        student_enrollment_code = get_student_enrollment_code(college_id, person_gs._id, registration_date, ObjectId(group_id))

        enrollment_code_at = node_collection.one({
            "_type": "AttributeType", "name": "enrollment_code"
        })

        try:
            ga_node = create_gattribute(person_gs._id, enrollment_code_at, student_enrollment_code)
        except Exception as e:
            print "\n StudentEnrollmentCreateError: " + str(e) + "!!!"

    # [C] Code to link GSystem Node and Author node via "has_login" relationship;
    #     and Subscribe the Author node to College group if user "Program Officer"
    person_gs.reload()
    auth_node = None
    for attr in person_gs.attribute_set:
      if "email_id" in attr:
        if attr["email_id"]:
          auth_node = node_collection.one({'_type': "Author", 'email': attr["email_id"].lower()})
          break

    if auth_node:
      has_login_rt = node_collection.one({'_type': "RelationType", 'name': "has_login"})
      if has_login_rt:
        # Linking GSystem Node and Author node via "has_login" relationship;
        gr_node = create_grelation(person_gs._id, has_login_rt, auth_node._id)

        # Set author_agency field's value of author node as "Program Officer"
        # Required to identify at time of log-in in order to display
        # required modules defined for Program Officers under MIS GApp
        if auth_node.agency_type != u"Program Officer":
          auth_node.agency_type = u"Program Officer"
          auth_node.save(groupid=group_id)

      if "Program Officer" in person_gs.member_of_names_list:
        # If Person node (GSystem) is of Program Officer type
        # then only go for subscription
        college_id_list = []
        # Fetch College's ObjectId to which Program Officer is assigned (via "officer_incharge_of")
        for rel in person_gs.relation_set:
          if "officer_incharge_of" in rel:
            if rel["officer_incharge_of"]:
              for college_id in rel["officer_incharge_of"]:
                if college_id not in college_id_list:
                  college_id_list.append(college_id)
              break  # break outer-loop (of relation_set)

        if college_id_list:
          # If College's ObjectId exists (list as PO might be assigned to more than one college)
          # Then prepare a list of their corresponding private group(s) (via "has_group")
          college_cur = node_collection.find(
            {'_id': {'$in': college_id_list}},
            {'relation_set.has_group': 1}
          )

          college_group_id_list = []
          for college in college_cur:
            for rel in college.relation_set:
              if rel and "has_group" in rel:
                if rel["has_group"]:
                  if rel["has_group"][0] not in college_group_id_list:
                    college_group_id_list.append(rel["has_group"][0])

                  break  # break inner-loop (college.relation_set)

          if college_group_id_list:
            # If college-group list exists
            # Then update their group_admin field (append PO's created_by)
            res = node_collection.collection.update(
              {'_id': {'$in': college_group_id_list}},
              {'$addToSet': {'group_admin': auth_node.created_by}},
              upsert=False, multi=True
            )
        old_college_id_list = []
        if existing_colg:
          if len(existing_colg) > len(college_id_list):
            for each_colg_id in existing_colg:
              if each_colg_id not in college_id_list:
                old_college_id_list.append(each_colg_id)

            old_college_cur = node_collection.find(
              {'_id': {'$in': old_college_id_list}},
              {'relation_set.has_group': 1}
            )

            old_college_group_id_list = []
            for college in old_college_cur:
              for rel in college.relation_set:
                if rel and "has_group" in rel:
                  if rel["has_group"]:
                    if rel["has_group"][0] not in old_college_group_id_list:
                      old_college_group_id_list.append(rel["has_group"][0])

                    break  # break inner-loop (college.relation_set)

            if old_college_group_id_list:
              # If college-group list exists
              # Then update their group_admin field (remove PO's created_by)
              res = node_collection.collection.update(
                {'_id': {'$in': old_college_group_id_list}, '$or': [{'group_admin': auth_node.created_by},
                {'author_set': auth_node.created_by}]},
                {'$pull': {'group_admin': auth_node.created_by, 'author_set': auth_node.created_by}},
                upsert=False, multi=True
              )
              # The code below is commented as the college groups are PRIVATE.
              # for rel in person_gs.relation_set:
              #   if rel and "officer_incharge_of" in rel:
              #       pass
              #   else:
              #       node_collection.collection.update({'_id': auth_node._id},
              #       {'$set': {'agency_type': u"Other"}},
              #       upsert=False, multi=False
              #       )
              # Its purpose is to change the agency type back to Other

              auth_node.reload()
    # if person_gst.name != "Student":
    #     return HttpResponseRedirect(reverse(app_name.lower()+":"+template_prefix+'_app_detail', kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id}))
    # else:
    return HttpResponseRedirect(reverse('mis:mis_app_instance_detail',kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id, "app_set_instance_id":unicode(person_gs._id)}))

    # return HttpResponseRedirect(reverse(app_name.lower()+":"+template_prefix+'_app_detail', kwargs={'group_id': group_id, "app_id":app_id, "app_set_id":app_set_id}))
  
  default_template = "ndf/person_create_edit.html"

  # default_template = "ndf/"+template_prefix+"_create_edit.html"
  context_variables = { 'groupid': group_id, 'group_id': group_id,
                        'app_id': app_id, 'app_name': app_name, 'app_collection_set': app_collection_set, 
                        'app_set_id': app_set_id,
                        'title':title,
                        'property_order_list': property_order_list
                      }

  if person_gst and person_gst.name in ["Voluntary Teacher", "Master Trainer"]:
    nussd_course_type = node_collection.one({'_type': "AttributeType", 'name': "nussd_course_type"}, {'_type': 1, '_id': 1, 'data_type': 1, 'complex_data_type': 1, 'name': 1, 'altnames': 1})

    if nussd_course_type["data_type"] == "IS()":
      # Below code does little formatting, for example:
      # data_type: "IS()" complex_value: [u"ab", u"cd"] dt:
      # "IS(u'ab', u'cd')"
      dt = "IS("
      for v in nussd_course_type.complex_data_type:
          dt = dt + "u'" + v + "'" + ", " 
      dt = dt[:(dt.rfind(", "))] + ")"
      nussd_course_type["data_type"] = dt

    nussd_course_type["data_type"] = eval(nussd_course_type["data_type"])
    nussd_course_type["value"] = None
    context_variables['nussd_course_type'] = nussd_course_type

  if app_set_instance_id:
    person_gs.get_neighbourhood(person_gs.member_of)

    if "trainer_teaches_course_in_college" in person_gs:
      l = []
      for each_course_college in person_gs.trainer_teaches_course_in_college:
        # Fetch Course Type (i.e. nussd_course_type)
        ct = ""
        for each_attr in each_course_college[0].attribute_set:
          if "nussd_course_type" in each_attr and each_attr:
            ct = each_attr["nussd_course_type"]
            break

        univ_name = ""
        for each_rel in each_course_college[1].relation_set:
          if "college_affiliated_to" in each_rel and each_rel:
              univ = node_collection.find_one({"_id": {"$in": each_rel["college_affiliated_to"]}})
              univ_name = univ.name if univ else ""

        l.append((
            ct, each_course_college[0].name, each_course_college[1].name,
            each_course_college[0]._id.__str__(),
            each_course_college[1]._id.__str__(),
            univ_name
        ))
      if l:
        person_gs.trainer_teaches_course_in_college = l

    context_variables['node'] = person_gs

  try:
    return render_to_response([template, default_template], 
                              context_variables,
                              context_instance = RequestContext(request)
                            )

  except TemplateDoesNotExist as tde:
    error_message = "\n PersonCreateEditViewError: This html template (" + str(tde) + ") does not exists !!!\n"
    raise Http404(error_message)

  except Exception as e:
    error_message = "\n PersonCreateEditViewError: " + str(e) + " !!!\n"
    raise Exception(error_message)
Beispiel #9
0
def add_node(request, group_id):

    # ins_objectid  = ObjectId()
    # if ins_objectid.is_valid(group_id) is False :
    #     group_ins = node_collection.find_one({'_type': "Group","name": group_id})
    #     auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
    #     if group_ins:
    #         group_id = str(group_ins._id)
    #     else :
    #         auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
    #         if auth :
    #             group_id = str(auth._id)
    # else :
    #     pass
    group_name, group_id = get_group_name_id(group_id)

    try:
        auth = node_collection.one({
            '_type': 'Author',
            'name': unicode(request.user.username)
        })
        content_org = request.POST.get("reply", "")
        node = request.POST.get("node", "")
        thread = request.POST.get("thread", "")  # getting thread _id
        forumid = request.POST.get("forumid", "")  # getting forum _id
        sup_id = request.POST.get("supnode",
                                  "")  #getting _id of it's parent node
        tw_name = request.POST.get("twistname", "")
        upload_files_count = int(request.POST.get("upload_cnt", 0))
        #print "upfiles=",upload_files_count
        lst = []
        lstobj_collection = []
        usrid = int(request.user.id)
        if upload_files_count > 0:
            #print "uploaded items",request.FILES.items()
            try:
                thread_obj = node_collection.one({'_id': ObjectId(thread)})
                access_policy = thread_obj.access_policy
            except:
                access_policy = u'PUBLIC'

            for key, value in request.FILES.items():
                fname = unicode(value.__dict__['_name'])
                #print "key=",key,"value=",value,"fname=",fname

                fileobj, fs = save_file(value,
                                        fname,
                                        usrid,
                                        group_id,
                                        "",
                                        "",
                                        username=unicode(
                                            request.user.username),
                                        access_policy=access_policy,
                                        count=0,
                                        first_object="")

                if type(fileobj) == list:
                    obid = str(list(fileobj)[1])
                else:
                    obid = str(fileobj)
                file_obj = node_collection.find_one({'_id': ObjectId(obid)})
                lstobj_collection.append(file_obj._id)
        forumobj = ""
        groupobj = ""
        colg = node_collection.one({'_id': ObjectId(group_id)})
        if forumid:
            forumobj = node_collection.one({"_id": ObjectId(forumid)})

        sup = node_collection.one({"_id": ObjectId(sup_id)})

        if not sup:
            return HttpResponse("failure")

        colrep = node_collection.collection.GSystem()

        if node == "Twist":
            name = tw_name
            colrep.member_of.append(twist_gst._id)
        elif node == "Reply":
            name = unicode("Reply of:" + str(sup._id))
            colrep.member_of.append(reply_gst._id)
        #Adding uploaded files id's in collection set of reply
        if upload_files_count > 0:
            colrep.collection_set = lstobj_collection

        colrep.prior_node.append(sup._id)
        colrep.name = name

        if content_org:
            colrep.content_org = unicode(content_org)
            # Required to link temporary files with the current user who is modifying this document
            usrname = request.user.username
            filename = slugify(name) + "-" + usrname + "-"
            colrep.content = content_org

        colrep.created_by = usrid
        colrep.modified_by = usrid

        if usrid not in colrep.contributors:
            colrep.contributors.append(usrid)
        colrep.prior_node.append(sup._id)
        colrep.name = name

        if content_org:
            colrep.content_org = unicode(content_org)
            # Required to link temporary files with the current user who is modifying this document
            usrname = request.user.username
            filename = slugify(name) + "-" + usrname + "-"
            colrep.content = content_org

        usrid = int(request.user.id)
        colrep.created_by = usrid
        colrep.modified_by = usrid

        if usrid not in colrep.contributors:
            colrep.contributors.append(usrid)

        colrep.group_set.append(colg._id)

        colrep.save(groupid=group_id)

        # print "----------", colrep._id
        groupname = colg.name

        if node == "Twist":
            url = "http://" + sitename + "/" + str(
                group_id) + "/forum/thread/" + str(colrep._id)
            activity = request.user.username + " -added a thread '"
            prefix = "' on the forum '" + forumobj.name + "'"
            nodename = name

        if node == "Reply":
            threadobj = node_collection.one({"_id": ObjectId(thread)})
            url = "http://" + sitename + "/" + str(
                group_id) + "/forum/thread/" + str(threadobj._id)
            activity = request.user.username + " -added a reply "
            prefix = " on the thread '" + threadobj.name + "' on the forum '" + forumobj.name + "'"
            nodename = ""

        link = url

        for each in colg.author_set:
            if each != colg.created_by:
                bx = User.objects.get(id=each)
                msg = activity + "-" + nodename + prefix + " in the group '" + groupname + "'\n" + "Please visit " + link + " to see the updated page"
                if bx:
                    no_check = forum_notification_status(group_id, auth._id)
                    if no_check:
                        ret = set_notif_val(request, group_id, msg, activity,
                                            bx)

        bx = User.objects.get(id=colg.created_by)
        msg = activity + "-" + nodename + prefix + " in the group '" + groupname + "' created by you" + "\n" + "Please visit " + link + " to see the updated page"

        if bx:
            no_check = forum_notification_status(group_id, auth._id)
            if no_check:
                ret = set_notif_val(request, group_id, msg, activity, bx)
        if node == "Reply":
            # if exstng_reply:
            #     exstng_reply.prior_node =[]
            #     exstng_reply.prior_node.append(colrep._id)
            #     exstng_reply.save()

            threadobj = node_collection.one({"_id": ObjectId(thread)})
            variables = RequestContext(
                request, {
                    'thread': threadobj,
                    'user': request.user,
                    'forum': forumobj,
                    'groupid': group_id,
                    'group_id': group_id
                })
            return render_to_response("ndf/refreshtwist.html", variables)
        else:
            templ = get_template('ndf/refreshthread.html')
            html = templ.render(
                Context({
                    'forum': forumobj,
                    'user': request.user,
                    'groupid': group_id,
                    'group_id': group_id
                }))
            return HttpResponse(html)

    except Exception as e:
        return HttpResponse("" + str(e))
    return HttpResponse("success")
Beispiel #10
0
def create_resource_gsystem(resource_data):

    # fetching resource from url
    resource_link = resource_data.get("file_name")  # actual download file name
    ebook_unzip_folder = EBOOKS_ROOT + resource_link[:5] + "dd"

    if os.path.isdir(ebook_unzip_folder):
        # Folder already created.
        # print "folder already exists"
        
        resource_link = ebook_unzip_folder + "/" + str(os.listdir(ebook_unzip_folder)[0]) + "/" + resource_link
        # overwritting resource link
        # print "resource_link : ", resource_link

        if os.path.exists(resource_link):
            # checking if file path exists
            resource_link = "file://" + resource_link
            files = urllib2.urlopen(resource_link)
            files = io.BytesIO(files.read())
        else:
            # otherwise return None and break the flow
            errror_message = "\n!! Resource with name of : '"+ str(resource_data["name"]) +"' cannot be created. \n\t - Because resource file : '" + str(resource_link) + "' does not exists."
            print errror_message
            log_list.append(str(errror_message))
            return None
    else:
        # otherwise return None and break the flow
        errror_message = "\n!! Resource with name of : '"+ str(resource_data["name"]) +"' cannot be created. \n\t - Because resource file contained in folder : '" + str(ebook_unzip_folder) + "' does not exists."
        print errror_message
        log_list.append(str(errror_message))
        return None

    filename = resource_link.split("/")[-1]  # actual download file name with extension. e.g: neuron.jpg 
    name = unicode(resource_data["name"])  # name to be given to gsystem
    files.name = filename # as per requirements in save_file()

    userid = nroer_team_id
    content_org = resource_data["content_org"]

    tags = resource_data["tags"]

    img_type = None
    language = resource_data["language"]
    usrname = "nroer_team"
    access_policy = None

    filemd5 = hashlib.md5(files.read()).hexdigest()
    
    fileobj = node_collection.collection.File()

    if fileobj.fs.files.exists({"md5":filemd5}): 

        gridfs_obj_by_md5 = gridfs_collection.find_one({"md5":filemd5})
        
        check_obj_by_name_n_fs_ids = node_collection.find_one({
                                        "_type":"File", 
                                        'member_of': {'$all': [ObjectId(file_gst._id)]},
                                        'group_set': {'$all': [ObjectId(home_group._id)]},
                                        "name": unicode(resource_data["name"]),
                                        "fs_file_ids": {"$in":[ gridfs_obj_by_md5["_id"] ]} 
                                    })
        
        if check_obj_by_name_n_fs_ids:
            # printing appropriate error message
            info_message = "\n- Resource with same name of '"+ str(resource_data["name"]) +"' and _type 'File' exist in the group. Ref _id: "+ str(check_obj_by_name_n_fs_ids._id)
            print info_message
            log_list.append(str(info_message))
            
            return check_obj_by_name_n_fs_ids._id

    else:
        # creating new resource
        files.seek(0)
        
        info_message = "\n- Creating resource: " + str(resource_data["name"])
        log_list.append(str(info_message))
        print info_message

        fileobj_oid, video = save_file(files, name, userid, home_group._id, content_org, tags, img_type, language, usrname, access_policy=u"PUBLIC")
        
        # print "\n------------ fileobj_oid : ", fileobj_oid, "--- ", video
        
        if fileobj_oid:
            # resource is saved in to gridfs along with gsystem creation successfully.

            # featured value
            resource_data["featured"] = True if (resource_data["featured"] == 1) else False

            # adding remaining fields
            node_collection.collection.update(
                                {"_id": fileobj_oid},
                                {'$set': 
                                    {
                                        'status': u"PUBLISHED",
                                        'altnames': resource_data["altnames"].strip(),
                                        'featured': resource_data["featured"]
                                    } 
                                },
                                upsert=False, multi=False
                            )

            update_url_field(fileobj_oid, filename)

            info_message = "\n- Created resource/GSystem object of name: '" + unicode(name) + "' having ObjectId: " + unicode(fileobj_oid)
            log_list.append(info_message)
            print info_message

            log_list.append("\n- Saved resource into gridfs. \n")
            # print "\n----------", fileobj
     
            # fileobj_oid is ObjectId("68jhgc..........") and not whole document
            return fileobj_oid

        else:
            return None
Beispiel #11
0
def check_folder_exists(resource_link, base_folder_name):

    resource_code = resource_link[:5]
    ebook_zip_file = EBOOKS_ROOT + resource_code + "dd.zip"
    # print "ebook_zip_file : ", ebook_zip_file

    if (os.path.exists(ebook_zip_file)):  # check if .zip exists
        ebook_unzip_folder = EBOOKS_ROOT + resource_code + "dd"
        # print "ebook_unzip_folder", ebook_unzip_folder

        if (not (os.path.isdir(ebook_unzip_folder))) and zipfile.is_zipfile(ebook_zip_file):
            # creating the folder for the first time

            info_message = "- Folder does NOT exists. So extracting and creating a new one"
            print info_message
            log_list.append(str(info_message))
            
            # calling method to unzip the zip file
            unzip(ebook_zip_file, ebook_unzip_folder)

            # ----------------------- for cover page -----------------------
            files_subfolder = ebook_unzip_folder + "/" + os.walk(ebook_unzip_folder).next()[1][0]
            files_list = os.listdir(files_subfolder)
            # print "files_list : ", files_list

            # gathering the cover page with .jpg/.png format 
            cover_page_list = [i for i in files_list if i.lower().endswith(('.jpg', '.png'))]
            # print "cover_page_list : ", cover_page_list
            
            if cover_page_list:
                cover_page_name = cover_page_list[0]
                # print "cover_page_name : ", cover_page_name
                cover_page_path = files_subfolder + "/" + cover_page_name
                # print "cover_page_path : ", cover_page_path

                if os.path.exists(cover_page_path):

                    info_message = "\n- Cover page found for : '" + str(base_folder_name) + "' found. Having name : '" + cover_page_name + "'."
                    print info_message
                    log_list.append(str(info_message))

                    cover_pg_link = "file://" + cover_page_path
                    files = urllib2.urlopen(cover_pg_link)
                    files = io.BytesIO(files.read())
                    files.name = cover_page_name # as per requirements in save_file()

                    filemd5 = hashlib.md5(files.read()).hexdigest()
                    fileobj = node_collection.collection.File()

                    if fileobj.fs.files.exists({"md5": filemd5}):
                        info_message = "\n- Cover page resource exists in DB: '" + str(cur_oid._id) + "'"
                        print info_message
                        log_list.append(str(info_message))
                    else:
                        files.seek(0)
                        content_org = ""
                        tags = []
                        img_type = None
                        language = ""

                        cover_page_oid, video = save_file(files, cover_page_name, nroer_team_id, home_group._id, content_org, tags, img_type, language, "nroer_team", u"PUBLIC", count=0, first_object="")

                        cover_page_url = update_url_field(cover_page_oid, cover_page_name)
                        # cover_page_in_content_org = "[[http://" + current_site.domain + "/" + os.getlogin() + "/file/readDoc/" + cover_page_oid.__str__() + "/" + cover_page_name + "]]"
                        # print "cover_page_in_content_org : ", cover_page_in_content_org
            else:
                cover_page_url = None
                cover_page_oid = None

                info_message = "\n- NO cover page found for : '" + str(base_folder_name) + "'"
                print info_message
                log_list.append(str(info_message))

            # ----------------------- END cover page processing -----------------------

            # overwritting resource link
            resource_link = ebook_zip_file
            # print "resource_link : ", resource_link

            name = base_folder_name
            content_org = cover_page_url if cover_page_url else ""

            resource_link = "file://" + resource_link
            files = urllib2.urlopen(resource_link)
            files = io.BytesIO(files.read())
            files.name = resource_code + "dd.zip" # as per requirements in save_file()

            filemd5 = hashlib.md5(files.read()).hexdigest()
            fileobj = node_collection.collection.File()

            if fileobj.fs.files.exists({"md5": filemd5}):
                gridfs_obj_by_md5 = gridfs_collection.find_one({"md5":filemd5})
                
                check_obj_by_name_n_fs_ids = collection.File.find_one({
                                        "_type":"File", 
                                        'member_of': {'$all': [ObjectId(file_gst._id)]},
                                        'group_set': {'$all': [ObjectId(home_group._id)]},
                                        "name": unicode(base_folder_name),
                                        "fs_file_ids": {"$in":[ gridfs_obj_by_md5["_id"] ]} 
                                    })

                if check_obj_by_name_n_fs_ids:
                    # printing appropriate error message
                    info_message = "\n- Resource with same name of '"+ str(base_folder_name) +"' and _type 'File' exist in the group. Ref _id: "+ str(check_obj_by_name_n_fs_ids._id)
                    print info_message
                    log_list.append(str(info_message))
                    return None

            # else process for saving/creating new object
            files.seek(0)
            language = ""

            fileobj_oid, video = save_file(files, name, nroer_team_id, home_group._id, content_org, [], None, language, "nroer_team", u"PUBLIC", count=0, first_object="")

            # creating grelation "has_cover_page"
            if fileobj_oid and cover_page_oid:

                update_url_field(fileobj_oid, resource_code + "dd.zip")
                relation_type_node = node_collection.one({'_type': "RelationType", 'name': "has_cover_page", 'subject_type': {'$in': [file_gst._id]} })
                gr_node = create_grelation(fileobj_oid, relation_type_node, cover_page_oid)

                if gr_node:
                    info_message = "\n- GRelation 'has_cover_page' processing done."
                    print info_message
                    log_list.append(str(info_message))
                else:
                    info_message = "\n!! GRelation 'has_cover_page' could not be created successfully."
                    print info_message
                    log_list.append(str(info_message))

            return fileobj_oid

        elif os.path.isdir(ebook_unzip_folder):
            # Folder already created.
            # print "----------- folder already exists"
            return None
            
    else:
        # otherwise return None and break the flow
        errror_message = "\n!! Resource with name of : '"+ str(base_folder_name) +"' cannot be created. \n\t - Because resource file containing ZIP : '" + ebook_zip_file + "' does not exists."
        print errror_message
        log_list.append(str(errror_message))
        return None
Beispiel #12
0
def discussion_reply(request, group_id, node_id):

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

    try:
        group_object = node_collection.one({'_id': ObjectId(group_id)})
        prior_node = request.POST.get("prior_node_id", "")
        content_org = request.POST.get("reply_text_content",
                                       "")  # reply content
        node = node_collection.one({"_id": ObjectId(node_id)})
        # gs_type_node_id = get_relation_value(node_id,'thread_of')
        gs_type_node_id = None
        if node and node.relation_set:
            for each_rel in node.relation_set:
                if each_rel and "thread_of" in each_rel:
                    gs_type_node_id = each_rel['thread_of'][0]
                    break
        # grel_dict = get_relation_value(node_id,'thread_of')
        # is_cursor = grel_dict.get("cursor",False)
        # if not is_cursor:
        #     gs_type_node_id = grel_dict.get("grel_node")
        #     # grel_id = grel_dict.get("grel_id")

        # print "\n\n node.name === ", node.member_of_names_list, node._id, node.name

        # process and save node if it reply has content
        if content_org:

            user_id = int(request.user.id)
            user_name = unicode(request.user.username)

            # auth = node_collection.one({'_type': 'Author', 'name': user_name })

            # creating empty GST and saving it
            reply_obj = node_collection.collection.GSystem()

            reply_obj.name = unicode("Reply of:" + str(prior_node))
            reply_obj.status = u"PUBLISHED"

            reply_obj.created_by = user_id
            reply_obj.modified_by = user_id
            reply_obj.contributors.append(user_id)

            reply_obj.member_of.append(ObjectId(reply_st._id))
            reply_obj.prior_node.append(ObjectId(prior_node))
            reply_obj.group_set.append(ObjectId(group_id))

            reply_obj.content_org = unicode(content_org)
            filename = slugify(
                unicode("Reply of:" + str(prior_node))) + "-" + user_name + "-"
            # reply_obj.content = org2html(content_org, file_prefix=filename)
            reply_obj.content = content_org
            if gs_type_node_id:
                reply_obj.origin.append(
                    {'prior_node_id_of_thread': ObjectId(gs_type_node_id)})
            if node_id:
                reply_obj.origin.append({'thread_id': ObjectId(node_id)})

            # ==============================
            # try:

            upload_files_count = int(request.POST.get("upload_cnt", 0))
            # print "upfiles=",upload_files_count
            lst = []
            lstobj_collection = []
            usrid = int(request.user.id)
            if upload_files_count > 0:
                # print "uploaded items",request.FILES.items()
                try:
                    thread_obj = node_collection.one(
                        {'_id': ObjectId(prior_node)})
                    # print "thread_obj : ", thread_obj
                    if thread_obj.access_policy:
                        access_policy = thread_obj.access_policy
                    else:
                        access_policy = u'PUBLIC'

                except:
                    access_policy = u'PUBLIC'

                for key, value in request.FILES.items():
                    fname = unicode(value.__dict__['_name'])
                    # print "key=",key,"value=",value,"fname=",fname

                    fileobj, fs = save_file(value,
                                            fname,
                                            usrid,
                                            group_id,
                                            "",
                                            "",
                                            username=unicode(
                                                request.user.username),
                                            access_policy=access_policy,
                                            count=0,
                                            first_object="",
                                            oid=True)

                    if type(fileobj) == list:
                        obid = str(list(fileobj)[1])
                    else:
                        obid = str(fileobj)

                    try:
                        file_obj = node_collection.find_one(
                            {'_id': ObjectId(obid)})
                        lstobj_collection.append(file_obj._id)
                    except:
                        pass
                    if "CourseEventGroup" not in group_object.member_of_names_list:
                        if group_object.edit_policy == 'EDITABLE_MODERATED':
                            t = create_moderator_task(request,
                                                      file_obj.group_set[0],
                                                      file_obj._id,
                                                      on_upload=True)
                # print "::: lstobj_collection: ", lstobj_collection
            # except:
            # lstobj_collection = []
            # ==============================
            reply_obj.collection_set = lstobj_collection
            # print "=== lstobj_collection: ", lstobj_collection

            # saving the reply obj
            reply_obj.save()
            formated_time = reply_obj.created_at.strftime(
                "%B %d, %Y, %I:%M %p")

            files = []
            for each_coll_item in reply_obj.collection_set:
                temp_list = []
                temp = node_collection.one({'_id': ObjectId(each_coll_item)}, {
                    'mime_type': 1,
                    'name': 1
                })
                temp_list.append(str(temp['_id']))
                temp_list.append(str(temp['mime_type']))
                temp_list.append(str(temp['name']))

                files.append(temp_list)

            # print files

            # ["status_info", "reply_id", "prior_node", "html_content", "org_content", "user_id", "user_name", "created_at" ]
            reply = json.dumps([
                "reply_saved",
                str(reply_obj._id),
                str(reply_obj.prior_node[0]), reply_obj.content,
                reply_obj.content_org, user_id, user_name, formated_time, files
            ],
                               cls=DjangoJSONEncoder)

            # print "===========", reply

            # ---------- mail/notification sending -------
            try:
                node_creator_user_obj = User.objects.get(id=node.created_by)
                node_creator_user_name = node_creator_user_obj.username
                if int(request.user.id) not in node.author_set:
                    node.author_set.append(int(request.user.id))
                    node.save()
                site = Site.objects.get(pk=1)
                site = site.name.__str__()

                from_user = user_name

                to_user_list = [node_creator_user_obj]

                msg = "\n\nDear " + node_creator_user_name + ",\n\n" + \
                      "A reply has been added in discussion under the " + \
                      node.member_of_names_list[0] + " named: '" + \
                      node.name + "' by '" + user_name + "'."

                activity = "Discussion Reply"
                render_label = render_to_string(
                    "notification/label.html",
                    {
                        # "sender": from_user,
                        "activity": activity,
                        "conjunction": "-",
                        "link": "url_link"
                    })
                notification.create_notice_type(render_label, msg,
                                                "notification")
                notification.send(to_user_list, render_label,
                                  {"from_user": from_user})
            except Exception as notification_err:
                print "\n Unable to send notification", notification_err
            # ---------- END of mail/notification sending ---------
            return HttpResponse(reply)

        else:  # no reply content

            return HttpResponse(json.dumps(["no_content"]))

    except Exception as e:

        error_message = "\n DiscussionReplyCreateError: " + str(e) + "\n"
        raise Exception(error_message)

        return HttpResponse(json.dumps(["Server Error"]))
Beispiel #13
0
def discussion_reply(request, group_id, node_id):

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

    try:
        group_object = node_collection.one({'_id': ObjectId(group_id)})
        prior_node = request.POST.get("prior_node_id", "")
        content_org = request.POST.get("reply_text_content", "") # reply content
        node = node_collection.one({"_id": ObjectId(node_id)})
        # gs_type_node_id = get_relation_value(node_id,'thread_of')
        gs_type_node_id = None
        if node and node.relation_set:
            for each_rel in node.relation_set:
                if each_rel and "thread_of" in each_rel:
                    gs_type_node_id = each_rel['thread_of'][0]
                    break
        # grel_dict = get_relation_value(node_id,'thread_of')
        # is_cursor = grel_dict.get("cursor",False)
        # if not is_cursor:
        #     gs_type_node_id = grel_dict.get("grel_node")
        #     # grel_id = grel_dict.get("grel_id")

        # print "\n\n node.name === ", node.member_of_names_list, node._id, node.name

        # process and save node if it reply has content  
        if content_org:
      
            user_id = int(request.user.id)
            user_name = unicode(request.user.username)

            # auth = node_collection.one({'_type': 'Author', 'name': user_name })
            
            # creating empty GST and saving it
            reply_obj = node_collection.collection.GSystem()

            reply_obj.name = unicode("Reply of:" + str(prior_node))
            reply_obj.status = u"PUBLISHED"

            reply_obj.created_by = user_id
            reply_obj.modified_by = user_id
            reply_obj.contributors.append(user_id)

            reply_obj.member_of.append(ObjectId(reply_st._id))
            reply_obj.prior_node.append(ObjectId(prior_node))
            reply_obj.group_set.append(ObjectId(group_id))
        
            reply_obj.content_org = unicode(content_org)
            filename = slugify(unicode("Reply of:" + str(prior_node))) + "-" + user_name + "-"
            # reply_obj.content = org2html(content_org, file_prefix=filename)
            reply_obj.content = content_org
            if gs_type_node_id:
                reply_obj.origin.append({'prior_node_id_of_thread': ObjectId(gs_type_node_id)})
            if node_id:
                reply_obj.origin.append({'thread_id': ObjectId(node_id)})

            # ==============================
            # try:

            upload_files_count=int(request.POST.get("upload_cnt",0))
            # print "upfiles=",upload_files_count
            lst=[]
            lstobj_collection=[]
            usrid = int(request.user.id)
            if upload_files_count > 0:
                # print "uploaded items",request.FILES.items()
                try:
                    thread_obj = node_collection.one({'_id': ObjectId(prior_node)})
                    # print "thread_obj : ", thread_obj
                    if thread_obj.access_policy:
                        access_policy = thread_obj.access_policy
                    else:
                        access_policy = u'PUBLIC'
                        
                except:
                    access_policy = u'PUBLIC'

                for key,value in request.FILES.items():
                    fname=unicode(value.__dict__['_name'])
                    # print "key=",key,"value=",value,"fname=",fname
                    
                    fileobj,fs=save_file(value,fname,usrid,group_id, "", "", username=unicode(request.user.username), access_policy=access_policy, count=0, first_object="", oid=True)


                    if type(fileobj) == list:
                        obid = str(list(fileobj)[1])
                    else:
                        obid=str(fileobj)

                    try:
                        file_obj=node_collection.find_one({'_id': ObjectId(obid)})
                        lstobj_collection.append(file_obj._id) 
                    except:
                        pass
                    if "CourseEventGroup" not in group_object.member_of_names_list:
                        if group_object.edit_policy == 'EDITABLE_MODERATED':
                            t = create_moderator_task(request, file_obj.group_set[0], file_obj._id,on_upload=True)
                # print "::: lstobj_collection: ", lstobj_collection
            # except:
                # lstobj_collection = []
            # ==============================
            reply_obj.collection_set = lstobj_collection
            # print "=== lstobj_collection: ", lstobj_collection
        
            # saving the reply obj
            reply_obj.save()
            formated_time = reply_obj.created_at.strftime("%B %d, %Y, %I:%M %p")

            files = []
            for each_coll_item in reply_obj.collection_set:
                temp_list = []
                temp = node_collection.one({'_id': ObjectId(each_coll_item)}, {'mime_type': 1, 'name': 1})
                temp_list.append(str(temp['_id']))
                temp_list.append(str(temp['mime_type']))
                temp_list.append(str(temp['name']))
                
                files.append(temp_list)

            # print files

            # ["status_info", "reply_id", "prior_node", "html_content", "org_content", "user_id", "user_name", "created_at" ]
            reply = json.dumps( [ "reply_saved", str(reply_obj._id), str(reply_obj.prior_node[0]), reply_obj.content, reply_obj.content_org, user_id, user_name, formated_time, files], cls=DjangoJSONEncoder )

            # print "===========", reply

            # ---------- mail/notification sending -------
            try:
                node_creator_user_obj = User.objects.get(id=node.created_by)
                node_creator_user_name = node_creator_user_obj.username
                if int(request.user.id) not in node.author_set:
                    node.author_set.append(int(request.user.id))
                    node.save()
                site = Site.objects.get(pk=1)
                site = site.name.__str__()
                
                from_user = user_name

                to_user_list = [node_creator_user_obj]

                msg = "\n\nDear " + node_creator_user_name + ",\n\n" + \
                      "A reply has been added in discussion under the " + \
                      node.member_of_names_list[0] + " named: '" + \
                      node.name + "' by '" + user_name + "'."

                activity = "Discussion Reply"
                render_label = render_to_string(
                    "notification/label.html",
                    {
                        # "sender": from_user,
                        "activity": activity,
                        "conjunction": "-",
                        "link": "url_link"
                    }
                )
                notification.create_notice_type(render_label, msg, "notification")
                notification.send(to_user_list, render_label, {"from_user": from_user})
            except Exception as notification_err:
                print "\n Unable to send notification", notification_err
            # ---------- END of mail/notification sending ---------
            return HttpResponse( reply )

        else: # no reply content

            return HttpResponse(json.dumps(["no_content"]))      

    except Exception as e:
      
        error_message = "\n DiscussionReplyCreateError: " + str(e) + "\n"
        raise Exception(error_message)

        return HttpResponse(json.dumps(["Server Error"]))