summaryrefslogtreecommitdiff
path: root/gnowsys-ndf/gnowsys_ndf/ndf/views/page.py
blob: f88df0dd6dac03a0c010a5df7a8197aa3bb72220 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
''' -- imports from python libraries -- '''
# import os -- Keep such imports here
import json
from difflib import HtmlDiff

''' -- imports from installed packages -- '''
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response, render
from django.template import RequestContext
from django.template.defaultfilters import slugify
from django.utils.translation import ugettext

try:
  from bson import ObjectId
except ImportError:  # old pymongo
  from pymongo.objectid import ObjectId

''' -- imports from application folders/files -- '''
from gnowsys_ndf.settings import LANGUAGES
from gnowsys_ndf.settings import GAPPS

from gnowsys_ndf.ndf.models import Node, GSystem, Triple
from gnowsys_ndf.ndf.models import node_collection, triple_collection
from gnowsys_ndf.ndf.models import HistoryManager
from gnowsys_ndf.ndf.rcslib import RCS
from gnowsys_ndf.ndf.org2any import org2html
from gnowsys_ndf.ndf.views.methods import get_node_common_fields, get_translate_common_fields,get_page,get_resource_type,diff_string,get_node_metadata,create_grelation_list,get_execution_time,parse_data
from gnowsys_ndf.ndf.management.commands.data_entry import create_gattribute
from gnowsys_ndf.ndf.views.html_diff import htmldiff
from gnowsys_ndf.ndf.views.methods import get_versioned_page, get_page, get_resource_type, diff_string
from gnowsys_ndf.ndf.views.methods import create_gattribute, create_grelation

from gnowsys_ndf.ndf.templatetags.ndf_tags import group_type_info

from gnowsys_ndf.mobwrite.diff_match_patch import diff_match_patch


#######################################################################################################################################

gst_page = node_collection.one({'_type': 'GSystemType', 'name': GAPPS[0]})
history_manager = HistoryManager()
rcs = RCS()
app = gst_page

#######################################################################################################################################
# VIEWS DEFINED FOR GAPP -- 'PAGE'
#######################################################################################################################################
@get_execution_time
def page(request, group_id, app_id=None):
    """Renders a list of all 'Page-type-GSystems' available within the database.
    """
    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)

            print group_id
        else :
            auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })

            if auth :
                group_id = str(auth._id)
    else :
        pass
    if app_id is None:  
        app_ins = node_collection.find_one({'_type': "GSystemType", "name": "Page"})
        if app_ins:
            app_id = str(app_ins._id)
        
    content=[]
    version=[]
    con=[]
    group_object = node_collection.one({'_id': ObjectId(group_id)})

    # Code for user shelf
    shelves = []
    shelf_list = {}
    auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) }) 
    
    # if auth:
    #   has_shelf_RT = node_collection.one({'_type': 'RelationType', 'name': u'has_shelf' })
    #   dbref_has_shelf = has_shelf_RT.get_dbref()
    #   shelf = triple_collection.find({'_type': 'GRelation', 'subject': ObjectId(auth._id), 'relation_type.$id': has_shelf_RT._id})
    #   shelf_list = {}

    #   if shelf:
    #     for each in shelf:
    #         shelf_name = node_collection.one({'_id': ObjectId(each.right_subject)}) 
    #         shelves.append(shelf_name)

    #         shelf_list[shelf_name.name] = []         
    #         for ID in shelf_name.collection_set:
    #           shelf_item = node_collection.one({'_id': ObjectId(ID) })
    #           shelf_list[shelf_name.name].append(shelf_item.name)

    #   else:
    #     shelves = []
    # End of user shelf

    if request.method == "POST":
    
      title = gst_page.name
      search_field = request.POST['search_field']
      page_nodes = node_collection.find({
                                          'member_of': {'$all': [ObjectId(app_id)]},
                                          '$or': [
                                            {'$and': [
                                              {'name': {'$regex': search_field, '$options': 'i'}}, 
                                              {'$or': [
                                                {'access_policy': u"PUBLIC"},
                                                {'$and': [{'access_policy': u"PRIVATE"}, {'created_by': request.user.id}]}
                                                ]
                                              }
                                              ]
                                            },
                                            {'$and': [
                                              {'tags': {'$regex':search_field, '$options': 'i'}},
                                              {'$or': [
                                                {'access_policy': u"PUBLIC"},
                                                {'$and': [{'access_policy': u"PRIVATE"}, {'created_by': request.user.id}]}
                                                ]
                                              }
                                              ]
                                            }
                                          ], 
                                          'group_set': {'$all': [ObjectId(group_id)]},
                                          'status': {'$nin': ['HIDDEN']}
                                      }).sort('last_update', -1)
    
      return render_to_response("ndf/page_list.html",
                                {'title': title, 
                                 'appId':app._id,'shelf_list': shelf_list,'shelves': shelves,
                                 'searching': True, 'query': search_field,
                                 'page_nodes': page_nodes, 'groupid':group_id, 'group_id':group_id
                                }, 
                                context_instance=RequestContext(request)
      )

    elif gst_page._id == ObjectId(app_id):
        # Page list view 
        # code for moderated Groups
        group_type = node_collection.one({'_id': ObjectId(group_id)})
        group_info=group_type_info(group_id)

        title = gst_page.name

        if  group_info == "Moderated":
          
          title = gst_page.name
          node=group_type.prior_node[0]
          page_nodes = node_collection.find({'member_of': {'$all': [ObjectId(app_id)]},
                                             'group_set': {'$all': [ObjectId(node)]},
                                       }).sort('last_update', -1)

          return render_to_response("ndf/page_list.html",
                                    {'title': title, 
                                     'appId':app._id,'shelf_list': shelf_list,'shelves': shelves,
                                     'page_nodes': page_nodes, 'groupid':group_id, 'group_id':group_id
                                    }, 
                                    context_instance=RequestContext(request))
        
        elif group_info == "BaseModerated":
          #code for parent Groups
          node = node_collection.find({'member_of': {'$all': [ObjectId(app_id)]}, 
                                       'group_set': {'$all': [ObjectId(group_id)]},                                           
                                       'status': {'$nin': ['HIDDEN']}
                                      }).sort('last_update', -1)

          if node is None:
            node = node_collection.find({'member_of':ObjectId(app_id)})

          for nodes in node:
            node,ver=get_versioned_page(nodes) 
            content.append(node)  

                    
          # rcs content ends here
          
          return render_to_response("ndf/page_list.html",
                                    {'title': title, 
                                     'appId':app._id,
                                     'shelf_list': shelf_list,'shelves': shelves,
                                     'page_nodes':content,
                                     'groupid':group_id,
                                     'group_id':group_id
                                    }, 
                                    context_instance=RequestContext(request)
            )

        elif group_info == "PUBLIC" or group_info == "PRIVATE" or group_info is None:
          """
          Below query returns only those documents:
          (a) which are pages,
          (b) which belongs to given group,
          (c) which has status either as DRAFT or PUBLISHED, and 
          (d) which has access_policy either as PUBLIC or if PRIVATE then it's created_by must be the logged-in user
          """
          page_nodes = node_collection.find({'member_of': {'$all': [ObjectId(app_id)]},
                                             'group_set': {'$all': [ObjectId(group_id)]},
                                             '$or': [
                                              {'access_policy': u"PUBLIC"},
                                              {'$and': [
                                                {'access_policy': u"PRIVATE"}, 
                                                {'created_by': request.user.id}
                                                ]
                                              }
                                             ],
                                             'status': {'$nin': ['HIDDEN']}
                                         }).sort('last_update', -1)

          # content =[]
          # for nodes in page_nodes:
        		# node,ver=get_page(request,nodes)
          #   if node != 'None':
          #     content.append(node)	

          return render_to_response("ndf/page_list.html",
                                    {'title': title,
                                     'appId':app._id,
                                     'shelf_list': shelf_list,'shelves': shelves,
                                     'page_nodes': page_nodes,
                                     'groupid':group_id,
                                     'group_id':group_id
                                    },
                                    context_instance=RequestContext(request))
        
    else:
        # Page Single instance view
        Group_node = node_collection.one({"_id": ObjectId(group_id)})
       
        if Group_node.prior_node:
            page_node = node_collection.one({"_id": ObjectId(app_id)})
            
        else:
          node = node_collection.one({"_id": ObjectId(app_id)})
          if Group_node.edit_policy == "EDITABLE_NON_MODERATED" or Group_node.edit_policy is None or Group_node.edit_policy == "NON_EDITABLE":
            page_node,ver=get_page(request,node)
          else:
            #else part is kept for time being until all the groups are implemented
            if node.status == u"DRAFT":
              page_node,ver=get_versioned_page(node)
            elif node.status == u"PUBLISHED":
              page_node = node

      
 
        annotations = json.dumps(page_node.annotations)
        page_node.get_neighbourhood(page_node.member_of)
        return render_to_response('ndf/page_details.html', 
                                  { 'node': page_node,
                                    'appId':app._id,
                                    'group_id': group_id,
                                    'shelf_list': shelf_list,
                                    'annotations': annotations,
                                    'shelves': shelves,
                                    'groupid':group_id
                                  },
                                  context_instance = RequestContext(request)
        )        



@login_required
@get_execution_time
def create_edit_page(request, group_id, node_id=None):
    """Creates/Modifies details about the given quiz-item.
    """
    ins_objectid = ObjectId()
    if ins_objectid.is_valid(group_id) is False :
        group_ins = node_collection.find_one({'_type': "Group", "name": group_id})
        auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
        if group_ins:
            group_id = str(group_ins._id)
        else :
            auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
            if auth :
                group_id = str(auth._id)
    else :
        pass

    context_variables = { 'title': gst_page.name,
                          'group_id': group_id,
                          'groupid': group_id
                      }
    
    available_nodes = node_collection.find({'_type': u'GSystem', 'member_of': ObjectId(gst_page._id),'group_set': ObjectId(group_id) })

    nodes_list = []
    for each in available_nodes:
      nodes_list.append(str((each.name).strip().lower()))

    if node_id:
        page_node = node_collection.one({'_type': u'GSystem', '_id': ObjectId(node_id)})
    else:
        page_node = node_collection.collection.GSystem()
        

    if request.method == "POST":
        # get_node_common_fields(request, page_node, group_id, gst_page)
        page_node.save(is_changed=get_node_common_fields(request, page_node, group_id, gst_page))

        # To fill the metadata info while creating and editing page node
        metadata = request.POST.get("metadata_info", '') 
        if metadata:
          # Only while metadata editing
          if metadata == "metadata":
            if page_node:
              get_node_metadata(request,page_node)
        # End of filling metadata

        return HttpResponseRedirect(reverse('page_details', kwargs={'group_id': group_id, 'app_id': page_node._id }))

    else:
        if node_id:

            page_node,ver=get_page(request,page_node)
            page_node.get_neighbourhood(page_node.member_of)
            context_variables['node'] = page_node
            context_variables['groupid']=group_id
            context_variables['group_id']=group_id
        context_variables['nodes_list'] = json.dumps(nodes_list)

        return render_to_response("ndf/page_create_edit.html",
                                  context_variables,
                                  context_instance=RequestContext(request)
                              )


@login_required    
@get_execution_time
def delete_page(request, group_id, node_id):
    """Change the status to Hidden.
    
    Just hide the page from users!
    """
    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
    op = node_collection.collection.update({'_id': ObjectId(node_id)}, {'$set': {'status': u"HIDDEN"}})
    return HttpResponseRedirect(reverse('page', kwargs={'group_id': group_id}))



@get_execution_time
def translate_node(request,group_id,node_id=None):
    """ translate the node content"""
    ins_objectid  = ObjectId()
    if ins_objectid.is_valid(group_id) is False :
        group_ins = node_collection.find_one({'_type': "Group","name": group_id})
        auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
        if group_ins:
            group_id = str(group_ins._id)
        else :
            auth = node_collection.one({'_type': 'Author', 'name': unicode(request.user.username) })
            if auth :
                group_id = str(auth._id)
    else :
        pass

    context_variables = { 'title': gst_page.name,
                          'group_id': group_id,
                          'groupid': group_id
                      }
    if request.method == "POST":
        get_type=get_resource_type(request, node_id)
        page_node = eval("node_collection.collection"+"."+ get_type)()
        get_translate_common_fields(request, get_type,page_node, group_id, gst_page,node_id)
        page_node.save()
        # add triple to the GRelation 
        # then append this ObjectId of GRelation instance in respective subject and object Nodes' relation_set field.
        relation_type = node_collection.one({'_type': 'RelationType', 'name': 'translation_of'})
        gr_node = create_grelation(ObjectId(node_id), relation_type, page_node._id)
        # grelation = node_collection.collection.GRelation()
        # grelation.relation_type=relation_type
        # grelation.subject=ObjectId(node_id)
        # grelation.right_subject=page_node._id
        # grelation.name=u""
        # grelation.save()
        return HttpResponseRedirect(reverse('page_details', kwargs={'group_id': group_id, 'app_id': page_node._id}))

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

    fp = history_manager.get_file_path(node)
    # Retrieve rcs-file for a given version-number
    rcs.checkout(fp)

    # Copy content from rcs-version-file
    data = None
    with open(fp, 'r') as sf:
        data = sf.read()
       
        # Used json.loads(x) -- to covert string to dictionary object
        # If want to use key from this converted dictionay, use array notation because dot notation doesn't works!
        data = json.loads(data)

        # Remove retrieved rcs-file belonging to the given version-number
        rcs.checkin(fp)

        content = data
        node_details=[]
        for k,v in content.items():
            
            node_name = content['name']
            node_content_org=content['content_org']
            node_tags=content['tags']
            
        return render_to_response("ndf/translation_page.html",
                               {'content': content,
                                'appId':app._id,
                                'node':node,
                                'node_name':node_name,
                                'groupid':group_id,
                                'group_id':group_id
                                      },
                             
                              context_instance = RequestContext(request)
    )        


@get_execution_time        
def publish_page(request,group_id,node):
    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

    node = node_collection.one({'_id': ObjectId(node)})
    group = node_collection.one({'_id': ObjectId(group_id)})
    if group.post_node:
        node.status=unicode("PUBLISHED")
        node.save('UnderModeration')
    else:
        page_node,v=get_page(request,node)
        node.content = unicode(page_node.content)
        node.content_org = unicode(page_node.content_org)
        node.status = unicode("PUBLISHED")
        node.modified_by = int(request.user.id)
        node.save()
    #no need to use this section as seprate view is created for group publish
    #if node._type == 'Group':
    # return HttpResponseRedirect(reverse('groupchange', kwargs={'group_id': group_id}))    
    if 'Quiz' in node.member_of_names_list or 'QuizItem' in node.member_of_names_list:
        return HttpResponseRedirect(reverse('quiz_details', kwargs={'group_id': group_id, 'app_id': node._id}))
    return HttpResponseRedirect(reverse('page_details', kwargs={'group_id': group_id, 'app_id': node._id}))