-
Notifications
You must be signed in to change notification settings - Fork 0
/
views.py
executable file
·2018 lines (1609 loc) · 78.6 KB
/
views.py
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
from collections import defaultdict
from django.contrib.auth.decorators import login_required
from django.contrib.contenttypes.models import ContentType
from django.contrib.messages.views import SuccessMessageMixin
from django.core.mail import EmailMultiAlternatives
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
from django.db.models import Q
from django.http import HttpResponse, JsonResponse
from django.shortcuts import get_object_or_404, render, redirect
from django.utils.html import escape
from django.views import generic
from haystack.forms import SearchForm
from django.conf import settings
from django.contrib import messages
from django.http import Http404
from tinymce.widgets import TinyMCE
from contacts.forms import ContactCreateForm
from stratigraphies.neo4jdao import Neo4jDAO
from users.models import User
from .forms import ArtefactsForm, ArtefactsCreateForm, DocumentUpdateForm, DocumentCreateForm, ArtefactFilter, \
OriginCreateForm, ChronologyCreateForm, AlloyCreateForm, TechnologyCreateForm, EnvironmentCreateForm, \
MicrostructureCreateForm, MetalCreateForm, CorrosionFormCreateForm, CorrosionTypeCreateForm, \
RecoveringDateCreateForm, ImageCreateForm, TypeCreateForm, ContactAuthorForm, ShareArtefactForm, \
ShareWithFriendForm, ObjectCreateForm, ObjectUpdateForm, CollaborationCommentForm, TokenHideForm, \
PublicationDecisionForm, PublicationDelegateForm, PublicationRejectDecisionForm, StratigraphyCreateForm
from .models import Artefact, Document, Collaboration_comment, Field, Object, Section, Image, \
Stratigraphy, Token, Publication, SectionTemplate
from . import models
import logging
logger = logging.getLogger(__name__)
"""
def displayOntology(request):
sparql = SPARQLWrapper("http://micorr-dev.ig.he-arc.ch:3030/ds/query")
#-------------------
#USING SPARQLWrapper
#-----------------
# Querying the ontology
sparql.setQuery(""
SELECT ?x ?fname
WHERE {?x <http://micorr.ig.he-arc.ch/vocab#artefacts_alloy_name> ?fname}
"")
sparql.setReturnFormat(JSON)
results = sparql.query()
# Convert the results to a dictionary
dict = results.convert()
listResultsWrapper = []
# Loop through the results
for result in dict["results"]["bindings"]:
listResultsWrapper.append(result["fname"]["value"])
#-----------------
#USING SPARQLStore
#-----------------
g = rdflib.ConjunctiveGraph('SPARQLStore')
g.open("http://micorr-dev.ig.he-arc.ch:3030/ds/query")
#Querying the ontology
qres = g.query(""
SELECT ?x ?fname
WHERE {?x <http://micorr.ig.he-arc.ch/vocab#artefacts_alloy_name> ?fname}
"")
listResultsStore = []
# Loop through the results
for row in qres:
listResultsStore.append(row.fname)
return render(request, "artefacts/artefact_ontology_answer.html", locals())
"""
def searchStratigraphy(self):
neo = Neo4jDAO()
stratigraphy = Neo4jDAO.addStratigraphy(neo, "Search", "search")
if stratigraphy:
return redirect("/micorr/#/stratigraphy/" + stratigraphy)
class ArtefactsListView(generic.ListView):
"""
A list of all the artefacts in the filter
"""
queryset = Artefact.objects.select_related('alloy', 'type', 'chronology_period', 'technology',
'microstructure')
def get(self, request, *args, **kwargs):
"""
Applies a filter to the artefacts list
The user can make a full text search and/or a filter-based search
"""
artefactssearch = SearchForm(request.GET)
artefactsfilter = ArtefactFilter(request.GET)
searchresults = artefactssearch.search()
filtered_artefacts_list = []
if request.GET.get('q'):
for artefact in searchresults:
if artefact.object in artefactsfilter.qs:
filtered_artefacts_list.append(artefact.object)
else:
for artefact in artefactsfilter.qs:
if artefact.published :
filtered_artefacts_list.append(artefact)
return render(request, "artefacts/artefact_list.html",
{'search': artefactssearch, 'results': filtered_artefacts_list, 'filter': artefactsfilter,
'self': self, 'node_base_url': settings.NODE_BASE_URL})
def get_section_groups(artefact, form, formObject):
"""
Utility function shared by ArtefactDetailView and ArtefactUpdateView
build a list of list of Section instances grouped by categories for the given artefact object
associate actual form and fieldset with each group based on their name as saved in SectionTemplate records
:param artefact: instance of Artefact
:param form: instance of ArtefactsForm (FieldsetForm based)
:param formObject: instance of ObjectUpdateForm
:return: section_groups
"""
# we group the sections by category
# and associate corresponding form and fieldset with each group
section_groups, group = [], []
current_category = None
for s in artefact.section_set.all():
if current_category != s.template.section_category:
if len(group):
section_groups.append(group)
current_category = s.template.section_category
group = []
group.append({'section': s, 'fieldset': form.get_fieldset(s.template.fieldset),
'form': formObject if s.template.fieldset == 'artefact' else form})
if len(group): # last group case
section_groups.append(group)
return section_groups
class ArtefactsDetailView(generic.DetailView):
"""
A detail view of a selected artefact
"""
queryset = Artefact.objects.select_related('alloy', 'type', 'origin', 'recovering_date', 'chronology_period',
'environment', 'location', 'owner', 'technology', 'sample_location',
'responsible_institution', 'microstructure', 'corrosion_form', 'corrosion_type')
template_name = 'artefacts/artefact_update_page.html'
def get_context_data(self, **kwargs):
"""
Allows the template to use the selected artefact as well as its foreign keys pointers
"""
context = super(ArtefactsDetailView, self).get_context_data(**kwargs)
context['documents'] = self.object.document_set.all()
context['node_base_url'] = settings.NODE_BASE_URL
form = ArtefactsForm(instance=self.object, label_suffix='')
formObject = ObjectUpdateForm(instance=self.object.object, label_suffix='')
context['section_groups'] = get_section_groups(self.object, form, formObject)
context['authors_fieldset'] = form.get_fieldset('authors')
return context
class ArtefactsUpdateView(SuccessMessageMixin, generic.UpdateView):
"""
A view which allows the user to edit an artefact
When the editing is finished, it redirects the user to the artefact detail page
"""
model = Artefact
form_class = ArtefactsForm
template_name_suffix = '_update_page'
success_message = 'Your artefact has been saved successfully!'
def get_context_data(self, **kwargs):
context = super(ArtefactsUpdateView,self).get_context_data(**kwargs)
#if user want to update an artefact with parent (= artefact for publication), raise 404
errorUpdatePublicationArtefact(self.kwargs['pk'])
formObject = ObjectUpdateForm(instance=self.object.object)
form=context['form']
# integrate with django_tinymce for content and complementary_information textareas
# that are not rendered by TinyMCE widget and were missing tinymce class data-mce-conf attribute to be handled by
# common tinmce_init . so we generate each data-mce-conf and add them to sections dict
# they will be added to textarea elements in the template
section_groups = get_section_groups(self.object, form, formObject)
mce_widget = TinyMCE(mce_attrs={'mode':'exact'})
for sections in section_groups:
for s in sections:
s_order = s['section'].template.order
if s['section'].template.has_content:
name = 's{}_content'.format(s_order)
s['content_mce_conf']=json.dumps(mce_widget.get_mce_config({'class':'tinymce','id':name,'name':name}))
if s['section'].template.has_complementary_information:
name = 's{}_complementary_information'.format(s_order)
s['complementary_information_mce_conf']=json.dumps(mce_widget.get_mce_config({'class':'tinymce','id':name,'name':name}))
context.update(authors_fieldset=form.get_fieldset('authors'),
section_groups=section_groups,
node_base_url=settings.NODE_BASE_URL,
view='ArtefactsUpdateView')
return context
def post(self, request, *args, **kwargs):
self.object = self.get_object()
artefact = self.object
# Save updates for the object name (4 following lines)
objForm = ObjectUpdateForm(request.POST, instance=artefact.object)
if objForm.is_valid():
objForm.save()
# retrieve section related vars from POST
for st in SectionTemplate.objects.filter(page_template=1).all():
s_prefix = "s{}_".format(st.order)
section_update = {k: request.POST.get(s_prefix+k, '') for k in ['content','complementary_information'] if getattr(st,"has_"+k)}
section, created = Section.objects.update_or_create(artefact=artefact,template=st, defaults=section_update)
if created:
artefact.section_set.add(section)
if request.is_ajax():
form = self.get_form()
if form.is_valid():
self.object = form.save()
return JsonResponse(dict(message='Artefact saved successfully'))
else:
return JsonResponse(dict(error='Error saving artefacts'))
else:
return super(ArtefactsUpdateView, self).post(request, **kwargs)
def get_success_url(self):
return reverse('artefacts:artefact-update',args=[self.kwargs['pk']] )
class ArtefactsDeleteView(generic.DeleteView):
"""
A view which allows the user to delete an artefact
When the artefact is deleted, it redirects the user to the artefact list
"""
model = Artefact
template_name_suffix = '_confirm_delete'
def get_success_url(self):
object = Object.objects.get(pk=self.kwargs['object_id'])
object.delete()
return reverse('users:detail', kwargs={'username': self.request.user})
class ObjectCreateView(generic.CreateView):
model = Object
template_name_suffix = '_create_form'
form_class = ObjectCreateForm
def form_valid(self, form):
form.instance.user = self.request.user
self.object = form.save()
artefact = Artefact.objects.create(object=self.object)
# add empty sections to new artefact based on default page template
for st in SectionTemplate.objects.filter(page_template=1).all():
artefact.section_set.create(artefact=artefact, template=st)
return super(ObjectCreateView, self).form_valid(form)
def get_success_url(self):
return reverse('artefacts:artefact-update', kwargs={'pk': self.object.artefact_set.first().pk})
@login_required
def newAuthor(request):
return handlePopAdd(request, ContactCreateForm, 'author')
@login_required
def newType(request):
return handlePopAdd(request, TypeCreateForm, 'type')
@login_required
def newOrigin(request):
return handlePopAdd(request, OriginCreateForm, 'origin')
@login_required
def newRecoveringDate(request):
return handlePopAdd(request, RecoveringDateCreateForm, 'recovering_date')
@login_required
def newChronologyPeriod(request):
return handlePopAdd(request, ChronologyCreateForm, 'chronology_period')
@login_required
def newEnvironment(request):
return handlePopAdd(request, EnvironmentCreateForm, 'environment')
@login_required
def newLocation(request):
return handlePopAdd(request, ContactCreateForm, 'location')
@login_required
def newOwner(request):
return handlePopAdd(request, ContactCreateForm, 'owner')
@login_required
def newAlloy(request):
return handlePopAdd(request, AlloyCreateForm, 'alloy')
@login_required
def newTechnology(request):
return handlePopAdd(request, TechnologyCreateForm, 'technology')
@login_required
def newSampleLocation(request):
return handlePopAdd(request, ContactCreateForm, 'sample_location')
@login_required
def newResponsibleInstitution(request):
return handlePopAdd(request, ContactCreateForm, 'responsible_institution')
@login_required
def newMicrostructure(request):
return handlePopAdd(request, MicrostructureCreateForm, 'microstructure')
@login_required
def newMetal1(request):
return handlePopAdd(request, MetalCreateForm, 'metal1', 'metal')
@login_required
def newMetalX(request):
return handlePopAdd(request, MetalCreateForm, 'metalx', 'metal')
@login_required
def newCorrosionForm(request):
return handlePopAdd(request, CorrosionFormCreateForm, 'corrosion_form')
@login_required
def newCorrosionType(request):
return handlePopAdd(request, CorrosionTypeCreateForm, 'corrosion_type')
def handlePopAdd(request, addForm, field, field_name=None):
if request.method == "POST":
form = addForm(request.POST)
if form.is_valid():
try:
newObject = form.save()
except form.ValidationError, error:
newObject = None
if newObject:
return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>' % (escape(newObject._get_pk_val()), escape(newObject)))
else:
form = addForm()
if not field_name:
field_name = field
pageContext = {'form': form, 'field': field, 'field_name':field_name}
return render(request, "artefacts/popadd.html", pageContext)
def contactAuthor(request, artefact_id):
if request.method == 'POST':
artefact = get_object_or_404(Artefact, pk=artefact_id)
form = ContactAuthorForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']+" (about MiCorr artefact : "+artefact.object.name+")"
message = form.cleaned_data['message']
sender = form.cleaned_data['sender']
cc_myself = form.cleaned_data['cc_myself']
recipients = artefact.get_authors_email()
if cc_myself:
recipients.append(sender)
send_mail(subject, message, sender, recipients)
pageContext = {}
messages.add_message(request, messages.SUCCESS, 'Your message has been sent!')
return render(request, 'artefacts/contact_author_confirmation.html', pageContext)
else:
form = ContactAuthorForm()
pageContext = {'form': form, 'artefact_id': artefact_id}
return render(request, 'artefacts/contact_author_form.html', pageContext)
def shareArtefact(request, artefact_id):
if request.method == 'POST':
artefact = get_object_or_404(Artefact, pk=artefact_id)
form = ShareArtefactForm(request.POST)
if form.is_valid():
subject = "Shared MiCorr artefact : "+artefact.object.name
recipient = [form.cleaned_data['recipient']]
right = form.cleaned_data['right']
comment = form.cleaned_data['comment']
cc_myself = form.cleaned_data['cc_myself']
sender = request.user.email
# create a link with a new generated token. example :
# 'localhost:8000/artefacts/110?token=8a21008e-383b-4c13-bd9e-9c8387bf29b0'
token = Token.tokenManager.create_token(right, artefact, request.user, comment, '-'.join(recipient))
if right == 'R':
link = request.get_host() + '/artefacts/' + artefact_id + '/?token='+token.uuid
elif right == 'W':
#link = request.get_host() + '/artefacts/' + artefact_id + '/update/?token='+token.uuid
link = request.get_host() + '/artefacts/collaboration/'
token.link = link
token.save()
# create text and html content to have a clickable link
text_message = "A MiCorr user shared an artefact with you. Please follow this " \
"link : "+link
html_message = '<p>A MiCorr user shared an artefact with you. ' \
'Please follow this link : <a href="'+link+'">'+link+'.</p>'
if cc_myself:
recipient.append(sender)
msg = EmailMultiAlternatives(subject, text_message, sender, recipient)
msg.attach_alternative(html_message, "text/html")
msg.send()
messages.add_message(request, messages.SUCCESS, 'New share added successfully')
pageContext = {'artefact': artefact}
return render(request, 'artefacts/token_list.html', pageContext)
else:
form = ShareArtefactForm()
pageContext = {'form': form, 'artefact_id': artefact_id}
return render(request, 'artefacts/share_artefact_form.html', pageContext)
def shareArtefactWithFriend(request, artefact_id):
if request.method == 'POST':
artefact = get_object_or_404(Artefact, pk=artefact_id)
form = ShareWithFriendForm(request.POST)
if form.is_valid():
subject = "Shared MiCorr artefact : "+artefact.object.name
recipient = [form.cleaned_data['recipient']]
message = form.cleaned_data['message']
if request.user.is_anonymous():
sender = 'noreply@micorr.org'
else:
sender = request.user.email
link = request.get_host() + '/artefacts/' + artefact_id
# create text and html content to have a clickable link
text_message = "A MiCorr user shared an artefact with you. \n " + message \
+ " \n \n To see the artefact, please follow this link : "+link
html_message = '<p>A MiCorr user shared an artefact with you.\n ' + message \
+ ' \n \n Please follow this link : <a href="'+link+'">'+link+'.</p>'
msg = EmailMultiAlternatives(subject, text_message, sender, recipient)
msg.attach_alternative(html_message, "text/html")
msg.send()
messages.add_message(request, messages.SUCCESS, 'The artefact was shared successfully')
pageContext = {'artefact': artefact}
return render(request, 'artefacts/token_list.html', pageContext)
else:
form = ShareWithFriendForm()
pageContext = {'form': form, 'artefact_id': artefact_id}
return render(request, 'artefacts/share_artefact_with_friend_form.html', pageContext)
def listToken(request, artefact_id):
artefact = get_object_or_404(Artefact, pk=artefact_id)
pageContext = {'artefact': artefact}
return render(request, 'artefacts/token_list.html', pageContext)
class TokenDeleteView(generic.DeleteView):
model = Token
template_name_suffix = '_confirm_delete'
def get_success_url(self):
artefact_id = get_object_or_404(Token, pk=self.kwargs['pk']).artefact.id
return reverse('artefacts:list_tokens', kwargs={'artefact_id': artefact_id})
def getTokenRightByUuid(token_uuid):
token_right = None
if token_uuid is not None:
token = get_object_or_404(Token, uuid=token_uuid)
token_right = token.right
return token_right
def isArtefactOfConnectedUser(request, artefact_id):
artefact = get_object_or_404(Artefact, pk=artefact_id)
is_artefact_of_connected_user = False
if request.user.id == artefact.object.user.id:
is_artefact_of_connected_user = True
return is_artefact_of_connected_user
# Write right when :
# - artefact.user = logged user
# - token.right = 'W'
def hasWriteRight(request, artefact_id, token_uuid):
has_write_right = False
if request.user.is_superuser or request.user.has_perm('artefacts.change_artefact') or (isArtefactOfConnectedUser(request, artefact_id)) or (getTokenRightByUuid(token_uuid) == 'W'):
has_write_right = True
return has_write_right
# Read right when :
# artefact.user = logged user
# token.right = 'R'
# artefact was validated by a micorr admin
def hasReadRight(request, artefact_id, token_uuid):
has_write_right = False
if request.user.is_superuser or request.user.has_perm('artefacts.change_artefact') or ('foo.view_bar')or isArtefactOfConnectedUser(request, artefact_id) or getTokenRightByUuid(token_uuid) == 'R' or isValidatedById(artefact_id):
has_write_right = True
return has_write_right
def isValidatedById(artefact_id):
artefact = get_object_or_404(Artefact, pk=artefact_id)
return artefact.validated
def isFirstUseOfToken(token_uuid):
firstUse = False
token = get_object_or_404(Token, uuid=token_uuid)
if token.already_used == False:
firstUse = True
return firstUse
def sendFirstUseOfTokenEmail(token_uuid):
if isFirstUseOfToken(token_uuid):
token = get_object_or_404(Token, uuid=token_uuid)
token.already_used = True
token.save()
subject = 'First use of MiCorr token'
message = 'Your token has been used : \n Artefact : ' + token.artefact.object.name + '\n Comment : ' + str(token.comment) + '\n Link : ' + str(token.link)
sender = 'micorr@he-arc.ch'
recipient = [token.user.email]
# return 0 if not sent
return send_mail(subject, message, sender, recipient)
class ImageCreateView(generic.CreateView):
model = Image
template_name_suffix="_create_form"
form_class = ImageCreateForm
def get(self, request, **kwargs):
self.object = None
form_class = self.get_form_class()
form = self.get_form(form_class)
section_id = kwargs['section_id']
return self.render_to_response(self.get_context_data(form=form, section_id=section_id))
def form_valid(self, form):
form.instance.section = get_object_or_404(Section, pk=self.kwargs['section_id'])
return super(ImageCreateView, self).form_valid(form)
def get_success_url(self):
return reverse('artefacts:image-refresh', kwargs={'section_id': self.kwargs['section_id']})
class ImageUpdateView(generic.UpdateView):
model = Image
template_name_suffix="_update_form"
form_class = ImageCreateForm
def get(self, request, **kwargs):
self.object = get_object_or_404(Image, id=self.kwargs['pk'])
form_class = self.get_form_class()
form = self.get_form(form_class)
section_id = kwargs['section_id']
image_id = kwargs['pk']
return self.render_to_response(self.get_context_data(form=form, section_id=section_id, image_id=image_id))
def get_success_url(self):
return reverse('artefacts:image-refresh', kwargs={'section_id': self.kwargs['section_id']})
class ImageDeleteView(generic.DeleteView):
model = Image
template_name_suffix = '_confirm_delete'
def get_success_url(self):
section_id = get_object_or_404(Image, pk=self.kwargs['pk']).section.id
return reverse('artefacts:image-refresh', kwargs={'section_id': section_id})
def RefreshDivView(request, section_id):
object_section = get_object_or_404(Section, pk=section_id)
return render(request, 'artefacts/image_section.html', {'object_section': object_section})
def StratigraphyListView(request, section_id):
stratigraphies = Neo4jDAO().getStratigraphiesByUser(request.user.id)
return render(request, 'artefacts/stratigraphies_list.html', {'node_base_url': settings.NODE_BASE_URL, 'stratigraphies': stratigraphies, 'section_id': section_id})
def StratigraphyAddView(request, section_id, stratigraphy_uid):
stratigraphy = Stratigraphy.objects.get_or_create(uid=stratigraphy_uid, section=get_object_or_404(Section, id=section_id))[0]
stratigraphy.image = settings.NODE_BASE_URL + 'exportStratigraphy?name='+ stratigraphy_uid +'&width=300&format=png'
stratigraphy.save()
return render(request, 'artefacts/strat-refresh.html', {'section_id': section_id})
class StratigraphyUpdateView(generic.UpdateView):
model = Stratigraphy
template_name_suffix="_update_form"
form_class = StratigraphyCreateForm
def get(self, request, **kwargs):
self.object = get_object_or_404(self.model, pk=self.kwargs['pk'])
return self.render_to_response(self.get_context_data(form=self.get_form(),section_id=kwargs['section_id'], pk=self.object.pk))
def get_success_url(self):
return reverse('artefacts:strat-refresh', kwargs={'section_id': self.object.section_id})
class StratigraphyDeleteView(generic.DeleteView):
model = Stratigraphy
template_name_suffix = '_confirm_delete'
def get_success_url(self):
section_id = get_object_or_404(Stratigraphy, pk=self.kwargs['pk']).section.id
return reverse('artefacts:strat-refresh', kwargs={'section_id': section_id})
def RefreshStratDivView(request, section_id):
section = get_object_or_404(Section, pk=section_id)
return render(request, 'artefacts/stratigraphy.html', { 'view':'ArtefactsUpdateView', 'section': section, 'node_base_url': settings.NODE_BASE_URL})
class DocumentUpdateView(generic.UpdateView):
"""
A view which allows the user to edit a document
When the editing is finished, it redirects the user to the related artefact detail page
"""
model = Document
template_name_suffix = '_update_form'
form_class = DocumentUpdateForm
def get_success_url(self):
return reverse('artefacts:artefact-detail', kwargs={'pk': self.kwargs.get('artefact_id', None)}, )
class DocumentDeleteView(generic.DeleteView):
"""
A view which allows the user to delete a document
When the document is deleted, it redirects the user to the related artefact detail page
"""
model = Document
template_name_suffix = '_confirm_delete'
def get_success_url(self):
return reverse('artefacts:artefact-detail', kwargs={'pk': self.kwargs.get('artefact_id', None)}, )
class DocumentCreateView(generic.CreateView):
"""
A view which allows the user to create a document
When the document is created, it redirects the user to the related artefact detail page
"""
model = Document
template_name_suffix = '_create_form'
form_class = DocumentCreateForm
def get_context_data(self, **kwargs):
"""
Allows the template to use the selected artefact
"""
context = super(DocumentCreateView, self).get_context_data(**kwargs)
artefact = get_object_or_404(Artefact, pk=self.kwargs['artefact_id'])
context['artefact'] = artefact
return context
def form_valid(self, form):
"""
Add the selected artefact as the document foreign key
"""
artefact = get_object_or_404(Artefact, pk=self.kwargs['artefact_id'])
form.instance.artefact = artefact
return super(DocumentCreateView, self).form_valid(form)
def get_success_url(self):
return reverse('artefacts:artefact-detail', kwargs={'pk': self.kwargs.get('artefact_id', None)}, )
def errorUpdatePublicationArtefact(artefact_id) :
artefact = get_object_or_404(Artefact, pk=artefact_id)
if artefact.parent :
raise Http404
def errorAccessToken(token_id, user) :
token = get_object_or_404(Token, pk=token_id)
if token.user != user and token.recipient != user.email :
raise Http404
class CollaborationListView(generic.ListView):
model = Token
template_name_suffix = '_collaboration_menu'
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(CollaborationListView, self).get_context_data(**kwargs)
user = self.request.user
# Add all the objects of the user in a variable
tokensShared = []
tokensReceived = []
modelToken = ContentType.objects.get(model='token')
modelSection = ContentType.objects.get(model='section')
# Research tokens shared by the user
nbTotSha = 0
newCommentsForTokenSha = {}
try :
tokensShared = self.request.user.token_set.filter(right='W', hidden_by_author=False).order_by('-modified')
for token in tokensShared :
nbCommSha = 0
commentsToken = Collaboration_comment.objects.filter(content_type_id=modelToken.id, object_model_id=token.id, sent=True, read=False).exclude(user=self.request.user)
nbCommSha = nbCommSha + len(commentsToken)
commentsSection = Collaboration_comment.objects.filter(content_type_id=modelSection.id, token_for_section=token, sent=True, read=False).exclude(user=self.request.user)
nbCommSha = nbCommSha + len(commentsSection)
newCommentsForTokenSha[token.id] = nbCommSha
nbTotSha = nbTotSha+nbCommSha
except:
pass
# Research tokens shared with the user
nbTotRec=0
newTokens=0
newCommentsForTokenRec = {}
try :
tokensReceived = Token.tokenManager.filter(recipient=user.email, right='W', hidden_by_recipient=False)
for token in tokensReceived :
nbCommRec=0
commentsToken = Collaboration_comment.objects.filter(content_type_id=modelToken.id, object_model_id=token.id, sent=True, read=False).exclude(user=self.request.user)
nbCommRec = nbCommRec + len(commentsToken)
commentsSection = Collaboration_comment.objects.filter(content_type_id=modelSection.id, token_for_section=token, sent=True, read=False).exclude(user=self.request.user)
nbCommRec = nbCommRec + len(commentsSection)
newCommentsForTokenRec[token.id] = nbCommRec
nbTotRec = nbTotRec+nbCommRec
if token.read == False :
newTokens = newTokens + 1
except :
pass
context['newCommentsSha'] = nbTotSha
context['newCommentsRec'] = nbTotRec
context['newTokens'] = newTokens
context['commentsForEachTokenSha'] = newCommentsForTokenSha
context['commentsForEachTokenRec'] = newCommentsForTokenRec
context['tokens_shared_by_me'] = tokensShared
context['tokens_shared_with_me'] = tokensReceived
context['user'] = user
return context
class CollaborationUpdateView(generic.UpdateView):
model = Artefact
template_name_suffix = '_collaboration_update'
form_class = ArtefactsForm
def get_object(self, queryset=None):
token = Token.tokenManager.get(id=self.kwargs['token_id'])
obj = Artefact.objects.get(id=token.artefact.id)
return obj
def get(self, request, **kwargs):
errorAccessToken(self.kwargs['token_id'], self.request.user)
token = Token.tokenManager.get(id=self.kwargs['token_id'])
artefact = Artefact.objects.get(id=token.artefact.id)
sections = artefact.section_set.all()
obj = Object.objects.get(id=artefact.object.id)
user=self.request.user
if token.read == False :
token.read = True
token.save()
self.object = artefact
form_class = self.get_form_class()
form = self.get_form(form_class)
sectionComments = []
sectionDict = defaultdict(list)
tokenComments = []
tokenDict = defaultdict(list)
token_type = ContentType.objects.get(model='token')
unreadCommentsField = {}
unreadCommentsSection = {}
fields = Field.objects.all()
try:
# Get all comments for the current token
allTokenComments = Collaboration_comment.objects.filter(content_type_id=token_type.id, object_model_id=token.id)
# Get first comments of all fields
firstTokenComments = []
for tokenComm in allTokenComments:
if not tokenComm.parent:
firstTokenComments.append(tokenComm)
# Sort comments using parent_id
allTokenCommentsSorted = []
for firstToken in firstTokenComments:
idToken = firstToken.id
allTokenCommentsSorted.append(firstToken)
while idToken != 0:
try:
currentToken = allTokenComments.get(parent_id=idToken)
allTokenCommentsSorted.append(currentToken)
idToken = currentToken.id
except:
idToken = 0
# Filter only sent comments or comments from user connected
for tokenComm in allTokenCommentsSorted:
if tokenComm.sent or self.request.user == tokenComm.user:
tokenComments.append(tokenComm)
# Create a dictonary 'key-list' with field title as a key
for tokenComment in tokenComments:
tokenDict[tokenComment.field.title].append(tokenComment)
# Research fields with unread comments
for field in fields :
unreadCommentsField[field.title] = False
for tokenComment in tokenComments :
if tokenComment.read == False and tokenComment.user != self.request.user :
unreadCommentsField[tokenComment.field.title] = True
except:
pass
section_type = ContentType.objects.get(model='section')
allSectionsComments = []
for section in sections:
# Get all comments from each section
comments = Collaboration_comment.objects.filter(content_type_id=section_type.id, object_model_id=section.id, token_for_section_id=token.id)
for comment in comments:
allSectionsComments.append(comment)
sectionShortTitle = getSectionShortName(section.template.title)
unreadCommentsSection[sectionShortTitle] = False
# Get first comments of all sections
firstSectionComments = []
for sectionComm in allSectionsComments:
if not sectionComm.parent:
firstSectionComments.append(sectionComm)
# Sort comments using parent_id
allSectionCommentsSorted = []
for firstSection in firstSectionComments:
idSection = firstSection.id
allSectionCommentsSorted.append(firstSection)
isFound = None
while idSection != 0:
for comm in allSectionsComments:
isFound = 0
if comm.parent_id == idSection:
allSectionCommentsSorted.append(comm)
idSection = comm.id
isFound = 1
if isFound == 0:
idSection = 0
for commentSectionSorted in allSectionCommentsSorted:
# Filter only sent comments or comments from user connected
if commentSectionSorted.token_for_section == token:
if commentSectionSorted.sent or self.request.user == commentSectionSorted.user:
sectionComments.append(commentSectionSorted)
section = get_object_or_404(Section, pk=commentSectionSorted.object_model_id)
sectionShortTitle = getSectionShortName(section.template.title)
sectionDict[sectionShortTitle].append(commentSectionSorted)
if commentSectionSorted.read == False and commentSectionSorted.user != user:
unreadCommentsSection[sectionShortTitle] = True
# get section templates (for default page (#1) )
templates=list(SectionTemplate.objects.filter(page_template=1).all())
object_section = Section.objects.get_or_create(template=templates[0], artefact=artefact)[0]
description_section = Section.objects.get_or_create(template=templates[1], artefact=artefact)[0]
zone_section = Section.objects.get_or_create(template=templates[2], artefact=artefact)[0]
macroscopic_section = Section.objects.get_or_create(template=templates[3], artefact=artefact)[0]
sample_section = Section.objects.get_or_create(template=templates[4], artefact=artefact)[0]
analyses_performed = Section.objects.get_or_create(template=templates[5], artefact=artefact)[0].content
metal_section = Section.objects.get_or_create(template=templates[6], artefact=artefact)[0]
corrosion_section = Section.objects.get_or_create(template=templates[7], artefact=artefact)[0]
synthesis_section = Section.objects.get_or_create(template=templates[8], artefact=artefact)[0]
conclusion_text = Section.objects.get_or_create(template=templates[9], artefact=artefact)[0].content
references_text = Section.objects.get_or_create(template=templates[10], artefact=artefact)[0].content
stratigraphies = artefact.stratigraphy_set.all
return render(request, 'artefacts/collaboration_artefact_update.html', self.get_context_data(artefact=artefact, form=form, object_section=object_section, description_section=description_section,
zone_section=zone_section, macroscopic_section=macroscopic_section,
sample_section=sample_section, analyses_performed=analyses_performed,
metal_section=metal_section, corrosion_section=corrosion_section,
synthesis_section=synthesis_section, conclusion_text=conclusion_text,
references_text=references_text, stratigraphies=stratigraphies,
tokenComments=dict(tokenDict), sectionComments=dict(sectionDict),
unreadCommentsField=unreadCommentsField, unreadCommentsSection=unreadCommentsSection,
user=user, node_base_url=settings.NODE_BASE_URL))
def post(self, request, *args, **kwargs):
token = get_object_or_404(Token, pk=self.kwargs['token_id'])
artefact = get_object_or_404(Artefact, pk=token.artefact.id)
# get section templates (for default page (#1) )
templates = list(SectionTemplate.objects.filter(page_template=1).all())
section_1 = Section.objects.get_or_create(template=templates[0], artefact=artefact)[0]
artefact.section_set.add(section_1)
section_2 = Section.objects.get_or_create(template=templates[1], artefact=artefact)[0]
section_2.complementary_information = request.POST['complementary_information']
artefact.section_set.add(section_2)
section_3 = Section.objects.get_or_create(template=templates[1], artefact=artefact)[0]
artefact.section_set.add(section_3)
section_4 = Section.objects.get_or_create(template=templates[3], artefact=artefact)[0]
section_4.content = request.POST['macroscopic_text']
artefact.section_set.add(section_4)
section_5 = Section.objects.get_or_create(template=templates[4], artefact=artefact)[0]
section_5.complementary_information = request.POST['sample_complementary_information']
# images sample
artefact.section_set.add(section_5)
section_6 = Section.objects.get_or_create(template=templates[5], artefact=artefact)[0]
section_6.content = request.POST['analyses_performed']
artefact.section_set.add(section_6)
section_7 = Section.objects.get_or_create(template=templates[6], artefact=artefact)[0]
section_7.content = request.POST['metal_text']
section_7.complementary_information = request.POST['metal_complementary_information']
# images metal
artefact.section_set.add(section_7)
section_8 = Section.objects.get_or_create(template=templates[7], artefact=artefact)[0]
section_8.content = request.POST['corrosion_text']
section_8.complementary_information = request.POST['corrosion_complementary_information']
artefact.section_set.add(section_8)
section_9 = Section.objects.get_or_create(template=templates[8], artefact=artefact)[0]
section_9.content=request.POST['synthesis_text']
artefact.section_set.add(section_9)
section_10 = Section.objects.get_or_create(template=templates[9], artefact=artefact)[0]
section_10.content = request.POST['conclusion_text']
artefact.section_set.add(section_10)
section_11 = Section.objects.get_or_create(template=templates[10], artefact=artefact)[0]
section_11.content = request.POST['references_text']
artefact.section_set.add(section_11)
return super(CollaborationUpdateView, self).post(request, **kwargs)
def get_success_url(self):
return reverse('artefacts:collaboration_menu')
class CollaborationCommentView(generic.CreateView):
model = Collaboration_comment
template_name_suffix = '_form'
form_class = CollaborationCommentForm
"""
A detail view of a selected artefact
"""
queryset = Artefact.objects.select_related('alloy', 'type', 'origin', 'recovering_date', 'chronology_period',
'environment', 'location', 'owner', 'technology', 'sample_location',
'responsible_institution', 'microstructure', 'corrosion_form', 'corrosion_type')
def get_context_data(self, **kwargs):
user = self.request.user
errorAccessToken(self.kwargs['pk'], self.request.user)
context = super(CollaborationCommentView, self).get_context_data(**kwargs)
token = get_object_or_404(Token, pk=self.kwargs['pk'])