-
Notifications
You must be signed in to change notification settings - Fork 57
/
views.py
1467 lines (1364 loc) · 69.2 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
# -*- coding: utf-8 -*-
# SPDX-FileCopyrightText: 2017 Rohit Lodha
# Copyright (c) 2017 Rohit Lodha
# SPDX-License-Identifier: Apache-2.0
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from django.contrib.auth import authenticate,login ,logout,update_session_auth_hash
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.urls import reverse
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from src.version import spdx_online_tools_version
from src.version import java_tools_version
from src.version import ntia_conformance_checker_version
import codecs
import jpype
import requests
from lxml import etree
import os
import logging
import json
from traceback import format_exc
from json import dumps
from time import time
from urllib.parse import urljoin
import datetime
import uuid
from wsgiref.util import FileWrapper
import os
import subprocess
from social_django.models import UserSocialAuth
from app.models import UserID, LicenseNames
from app.forms import UserRegisterForm,UserProfileForm,InfoForm,OrgInfoForm
import app.utils as utils
import app.core as core
from django.forms import model_to_dict
from app.generateXml import generateLicenseXml
logging.basicConfig(filename="error.log", format="%(levelname)s : %(asctime)s : %(message)s")
logger = logging.getLogger()
from .forms import LicenseRequestForm, LicenseNamespaceRequestForm
from .models import LicenseRequest, LicenseNamespace
from spdx_license_matcher.utils import get_spdx_license_text
def index(request):
""" View for index
returns index.html template
"""
context_dict={}
return render(request,
'app/index.html',context_dict
)
def about(request):
""" View for about
returns about.html template
"""
context_dict={
'spdx_online_tools_version':spdx_online_tools_version,
'java_tools_version':java_tools_version,
'ntia_conformance_checker_version':ntia_conformance_checker_version,
}
return render(request,
'app/about.html',context_dict
)
def submitNewLicense(request):
""" View for submit new licenses
returns submit_new_license.html template
"""
context_dict = {}
ajaxdict = {}
githubIssueId = ""
if request.method=="POST":
if not request.user.is_authenticated:
if (request.is_ajax()):
ajaxdict["type"] = "auth_error"
ajaxdict["data"] = "Please login using GitHub to use this feature."
response = dumps(ajaxdict)
return HttpResponse(response,status=401)
return HttpResponse("Please login using GitHub to use this feature.",status=401)
try:
user = request.user
try:
""" Getting user info for submitting github issue """
github_login = user.social_auth.get(provider='github')
token = github_login.extra_data["access_token"]
username = github_login.extra_data["login"]
form = LicenseRequestForm(request.POST, auto_id='%s')
if form.is_valid() and request.is_ajax():
licenseAuthorName = form.cleaned_data['licenseAuthorName']
licenseName = form.cleaned_data['fullname']
licenseIdentifier = form.cleaned_data['shortIdentifier']
licenseOsi = form.cleaned_data['osiApproved']
licenseSourceUrls = request.POST.getlist('sourceUrl')
licenseExamples = request.POST.getlist('exampleUrl')
licenseHeader = form.cleaned_data['licenseHeader']
licenseComments = form.cleaned_data['comments']
licenseText = form.cleaned_data['text']
licenseNotes = ''
listVersionAdded = ''
data = {}
urlType = utils.NORMAL
if 'urlType' in request.POST:
# This is present only when executing submit license via tests
urlType = request.POST["urlType"]
matchingIds, matchingType, _ = utils.check_spdx_license(licenseText)
matches = ['Perfect match', 'Standard License match', 'Close match']
if matchingType in matches:
data['matchType'] = matchingType
if isinstance(matchingIds, list):
matchingIds = ", ".join(matchingIds)
if matchingType == "Close match":
data['inputLicenseText'] = licenseText
data['xml'] = generateLicenseXml(licenseOsi, licenseIdentifier, licenseName,
listVersionAdded, licenseSourceUrls, licenseHeader, licenseNotes, licenseText)
originalLicenseText = get_spdx_license_text(matchingIds)
data['originalLicenseText'] = originalLicenseText
data['licenseOsi'] = licenseOsi
data['licenseIdentifier'] = licenseIdentifier
data['licenseName'] = licenseName
data['listVersionAdded'] = listVersionAdded
data['licenseSourceUrls'] = licenseSourceUrls
data['licenseHeader'] = licenseHeader
data['licenseNotes'] = licenseNotes
data['licenseAuthorName'] = licenseAuthorName
data['comments'] = licenseComments
data['matchIds'] = matchingIds
statusCode = 409
data['statusCode'] = str(statusCode)
return JsonResponse(data)
matches, issueUrl = utils.check_new_licenses_and_rejected_licenses(licenseText, urlType)
# Check if the license text doesn't matches with the rejected as well as not yet approved licenses
if not matches:
xml = generateLicenseXml(licenseOsi, licenseIdentifier, licenseName,
listVersionAdded, licenseSourceUrls, licenseHeader, licenseNotes, licenseText)
now = datetime.datetime.now()
licenseRequest = LicenseRequest(licenseAuthorName=licenseAuthorName, fullname=licenseName, shortIdentifier=licenseIdentifier,
submissionDatetime=now, notes=licenseNotes, xml=xml)
licenseRequest.save()
licenseId = licenseRequest.id
serverUrl = request.build_absolute_uri('/')
licenseRequestUrl = os.path.join(serverUrl, reverse('license-requests')[1:], str(licenseId))
statusCode, githubIssueId = utils.createIssue(licenseAuthorName, licenseName, licenseIdentifier,
licenseComments, licenseSourceUrls, licenseHeader,
licenseOsi, licenseExamples, licenseRequestUrl, token, urlType)
# If the license text matches with either rejected or yet not approved license then return 409 Conflict
else:
statusCode = 409
matchingString = 'The following license ID(s) match: ' + ", ".join(matches)
data['matchingStr'] = matchingString
data['issueUrl'] = issueUrl
data['statusCode'] = str(statusCode)
data['issueId'] = str(githubIssueId)
return JsonResponse(data)
except UserSocialAuth.DoesNotExist:
""" User not authenticated with GitHub """
if (request.is_ajax()):
ajaxdict["type"] = "auth_error"
ajaxdict["data"] = "Please login using GitHub to use this feature."
response = dumps(ajaxdict)
return HttpResponse(response,status=401)
return HttpResponse("Please login using GitHub to use this feature.",status=401)
except:
""" Other errors raised """
logger.error(str(format_exc()))
if (request.is_ajax()):
ajaxdict["type"] = "error"
ajaxdict["data"] = "Unexpected error, please email the SPDX technical workgroup that the following error has occurred: " + format_exc()
response = dumps(ajaxdict)
return HttpResponse(response,status=500)
return HttpResponse("Unexpected error, please email the SPDX technical workgroup that the following error has occurred: " + format_exc(), status=500)
else:
email=""
if not request.user.is_authenticated:
github_login=None
else:
try:
github_login = request.user.social_auth.get(provider='github')
username = github_login.extra_data["login"]
email = User.objects.get(username=username).email
except UserSocialAuth.DoesNotExist as AttributeError:
github_login = None
context_dict["github_login"] = github_login
form = LicenseRequestForm(auto_id='%s', email=email)
context_dict['form'] = form
return render(request,
'app/submit_new_license.html', context_dict
)
def submitNewLicenseNamespace(request):
""" View for submit new licenses namespace
returns submit_new_license_namespace.html template
"""
context_dict = {}
ajaxdict = {}
if request.method=="POST":
if not request.user.is_authenticated:
if (request.is_ajax()):
ajaxdict["type"] = "auth_error"
ajaxdict["data"] = "Please login using GitHub to use this feature."
response = dumps(ajaxdict)
return HttpResponse(response,status=401)
return HttpResponse("Please login using GitHub to use this feature.",status=401)
try:
user = request.user
try:
""" Getting user info for submitting github issue """
github_login = user.social_auth.get(provider='github')
token = github_login.extra_data["access_token"]
username = github_login.extra_data["login"]
form = LicenseNamespaceRequestForm(request.POST, auto_id='%s')
if form.is_valid() and request.is_ajax():
statusCode = None
licenseAuthorName = form.cleaned_data['licenseAuthorName']
fullname = form.cleaned_data['fullname']
url = [form.cleaned_data['url']]
description = form.cleaned_data['description']
userEmail = form.cleaned_data['userEmail']
namespace = form.cleaned_data['namespace']
shortIdentifier = form.cleaned_data['shortIdentifier']
publiclyShared = form.cleaned_data['publiclyShared']
organisation = form.cleaned_data['organisation']
licenseListUrl = form.cleaned_data['license_list_url']
githubRepoUrl = form.cleaned_data['github_repo_url']
licenseText = ''
now = datetime.datetime.now()
urlLst = ''.join(e for e in url)
licenseOsi = ''
listVersionAdded = ''
licenseHeader = ''
licenseNotes = ''
xml = generateLicenseXml(licenseOsi, shortIdentifier, fullname,
listVersionAdded, url, licenseHeader, licenseNotes, licenseText)
licenseExists = utils.licenseExists(namespace, shortIdentifier, token)
if licenseExists["exists"]:
if (request.is_ajax()):
ajaxdict["type"] = "license_exists"
ajaxdict["title"] = "License exists"
ajaxdict["data"] = """License already exists on the SPDX license list.\n
It has the reference: """ + licenseExists["referenceNumber"] + """,\n
name: """ + licenseExists["name"] + """\n
and ID: """ + licenseExists["licenseId"]
response = dumps(ajaxdict)
return HttpResponse(response,status=401)
return HttpResponse("Please submit another license namespace",status=401)
else:
licenseNamespaceRequest = LicenseNamespace(licenseAuthorName=licenseAuthorName,
fullname=fullname,
url=urlLst,
submissionDatetime=now,
userEmail=userEmail,
description=description,
namespace=namespace,
organisation=organisation,
publiclyShared=publiclyShared,
shortIdentifier=shortIdentifier,
license_list_url=licenseListUrl,
github_repo_url=githubRepoUrl,
xml=xml)
licenseNamespaceRequest.save()
urlType = utils.NORMAL
if 'urlType' in request.POST:
# This is present only when executing submit license namespace via tests
urlType = request.POST["urlType"]
statusCode = utils.createLicenseNamespaceIssue(licenseNamespaceRequest, token, urlType)
data = {'statusCode' : str(statusCode)}
return JsonResponse(data)
except UserSocialAuth.DoesNotExist:
""" User not authenticated with GitHub """
if (request.is_ajax()):
ajaxdict["type"] = "auth_error"
ajaxdict["data"] = "Please login using GitHub to use this feature."
response = dumps(ajaxdict)
return HttpResponse(response,status=401)
return HttpResponse("Please login using GitHub to use this feature.",status=401)
except:
""" Other errors raised """
logger.error(str(format_exc()))
if (request.is_ajax()):
ajaxdict["type"] = "error"
ajaxdict["data"] = "Unexpected error, please email the SPDX technical workgroup that the following error has occurred: " + format_exc()
response = dumps(ajaxdict)
return HttpResponse(response,status=500)
return HttpResponse("Unexpected error, please email the SPDX technical workgroup that the following error has occurred: " + format_exc(), status=500)
else:
email=""
if not request.user.is_authenticated:
github_login=None
else:
try:
github_login = request.user.social_auth.get(provider='github')
username = github_login.extra_data["login"]
email = User.objects.get(username=username).email
except UserSocialAuth.DoesNotExist as AttributeError:
github_login = None
context_dict["github_login"] = github_login
form = LicenseNamespaceRequestForm(auto_id='%s', email=email)
context_dict['form'] = form
return render(request,
'app/submit_new_license_namespace.html', context_dict
)
def licenseInformation(request, licenseId):
""" View for license request and archive request information
returns license_information.html template
"""
if "archive_requests" in str(request.META.get('PATH_INFO')):
if not LicenseRequest.objects.filter(archive='True').filter(id=licenseId).exists():
return render(request,
'404.html',{},status=404
)
else:
if not LicenseRequest.objects.filter(archive='False').filter(id=licenseId).exists():
return render(request,
'404.html',{},status=404
)
licenseRequest = LicenseRequest.objects.get(id=licenseId)
context_dict = {}
licenseInformation = {}
licenseInformation['fullname'] = licenseRequest.fullname
licenseInformation['shortIdentifier'] = licenseRequest.shortIdentifier
licenseInformation['submissionDatetime'] = licenseRequest.submissionDatetime
licenseInformation['licenseAuthorName'] = licenseRequest.licenseAuthorName
licenseInformation['archive'] = licenseRequest.archive
xmlString = licenseRequest.xml
data = utils.parseXmlString(xmlString)
licenseInformation['osiApproved'] = data['osiApproved']
licenseInformation['crossRefs'] = data['crossRefs']
licenseInformation['notes'] = data['notes']
licenseInformation['standardLicenseHeader'] = data['standardLicenseHeader']
licenseInformation['text'] = data['text']
context_dict ={'licenseInformation': licenseInformation}
if request.method == 'POST':
tempFilename = 'output.xml'
xmlFile = open(tempFilename, 'wt', encoding='utf-8')
xmlFile.write(xmlString)
xmlFile.close()
xmlFile = open(tempFilename, 'rt', encoding='utf-8')
myfile = FileWrapper(xmlFile)
response = HttpResponse(myfile, content_type='application/xml')
response['Content-Disposition'] = 'attachment; filename=' + licenseRequest.shortIdentifier + '.xml'
xmlFile.close()
os.remove(tempFilename)
return response
return render(request,
'app/license_information.html',context_dict
)
def licenseNamespaceInformation(request, licenseId):
""" View for license namespace request and archive request information
returns license_namespace_information.html template
"""
if "archive_namespace_requests" in str(request.META.get('PATH_INFO')):
if not LicenseNamespace.objects.filter(archive='True').filter(id=licenseId).exists():
return render(request,
'404.html',{},status=404
)
else:
if not LicenseNamespace.objects.filter(archive='False').filter(id=licenseId).exists():
return render(request,
'404.html',{},status=404
)
licenseNamespaceRequest = LicenseNamespace.objects.get(id=licenseId)
context_dict = {}
licenseInformation = {}
licenseInformation['fullname'] = licenseNamespaceRequest.fullname
licenseInformation['shortIdentifier'] = licenseNamespaceRequest.shortIdentifier
licenseInformation['submissionDatetime'] = licenseNamespaceRequest.submissionDatetime
licenseInformation['userEmail'] = licenseNamespaceRequest.userEmail
licenseInformation['licenseAuthorName'] = licenseNamespaceRequest.licenseAuthorName
licenseInformation['archive'] = licenseNamespaceRequest.archive
licenseInformation['notes'] = licenseNamespaceRequest.notes
licenseInformation['namespace'] = licenseNamespaceRequest.namespace
licenseInformation['url'] = licenseNamespaceRequest.url
licenseInformation['description'] = licenseNamespaceRequest.description
licenseInformation['publiclyShared'] = licenseNamespaceRequest.publiclyShared
xmlString = licenseNamespaceRequest.xml
data = utils.parseXmlString(xmlString)
licenseInformation['osiApproved'] = data['osiApproved']
licenseInformation['crossRefs'] = data['crossRefs']
licenseInformation['notes'] = data['notes']
licenseInformation['standardLicenseHeader'] = data['standardLicenseHeader']
licenseInformation['text'] = data['text']
context_dict ={'licenseInformation': licenseInformation}
if request.method == 'POST':
tempFilename = 'output.xml'
xmlFile = open(tempFilename, 'wt', encoding='utf-8')
xmlFile.write(xmlString)
xmlFile.close()
xmlFile = open(tempFilename, 'rt', encoding='utf-8')
myfile = FileWrapper(xmlFile)
response = HttpResponse(myfile, content_type='application/xml')
response['Content-Disposition'] = 'attachment; filename=' + licenseNamespaceRequest.shortIdentifier + '.xml'
xmlFile.close()
os.remove(tempFilename)
return response
return render(request,
'app/license_namespace_information.html',context_dict
)
def ntia_check(request):
""" View for ntia checker tool
returns ntia_conformance_checker.html template
"""
if request.user.is_authenticated or settings.ANONYMOUS_LOGIN_ENABLED:
context_dict={}
if request.method == 'POST':
core.initialise_jpype()
result = core.ntia_check_helper(request)
jpype.detachThreadFromJVM()
context_dict = result.get('context', None)
status = result.get('status', None)
response = result.get('response', None)
message = result.get('message', None)
if response and status:
return HttpResponse(response, status=status)
elif context_dict and status:
return render(request, 'app/ntia_conformance_checker.html', context_dict, status=status)
else:
return HttpResponse(message, status=status)
else :
""" GET,HEAD """
return render(request,
'app/ntia_conformance_checker.html',context_dict
)
else :
return HttpResponseRedirect(settings.LOGIN_URL)
def validate(request):
""" View for validate tool
returns validate.html template
"""
if request.user.is_authenticated or settings.ANONYMOUS_LOGIN_ENABLED:
context_dict={}
if request.method == 'POST':
core.initialise_jpype()
result = core.license_validate_helper(request)
jpype.detachThreadFromJVM()
context_dict = result.get('context', None)
status = result.get('status', None)
response = result.get('response', None)
message = result.get('message', None)
if response and status:
return HttpResponse(response, status=status)
elif context_dict and status:
return render(request, 'app/validate.html', context_dict, status=status)
else:
return HttpResponse(message, status=status)
else :
""" GET,HEAD """
return render(request,
'app/validate.html',context_dict
)
else :
return HttpResponseRedirect(settings.LOGIN_URL)
def validate_xml(request):
""" View to validate xml text against SPDX License XML Schema,
used in the license xml editor """
if request.user.is_authenticated or settings.ANONYMOUS_LOGIN_ENABLED:
context_dict={}
if request.method == 'POST':
ajaxdict=dict()
try :
if "xmlText" in request.POST:
""" Saving file to the media directory """
xmlText = request.POST['xmlText']
xmlText = xmlText.encode('utf-8') if isinstance(xmlText, str) else xmlText
folder = str(request.user) + "/" + str(int(time()))
if not os.path.isdir(str(settings.MEDIA_ROOT +"/"+ folder)):
os.makedirs(str(settings.MEDIA_ROOT +"/"+ folder))
uploaded_file_url = settings.MEDIA_ROOT + '/' + folder + '/' + 'xmlFile.xml'
with open(uploaded_file_url, 'wb') as f:
f.write(xmlText)
""" Get schema text from GitHub,
if it fails use the file in examples folder """
try:
schema_url = 'https://raw.githubusercontent.com/spdx/license-list-XML/master/schema/ListedLicense.xsd'
schema_text = requests.get(schema_url, timeout=5).text
xmlschema_doc = etree.fromstring(schema_text.encode('utf-8'))
except:
schema_url = settings.BASE_DIR + "/examples/xml-schema.xsd"
with open(schema_url) as f:
xmlschema_doc = etree.parse(f)
""" Using the lxml etree functions """
xmlschema = etree.XMLSchema(xmlschema_doc)
with open(uploaded_file_url) as f:
xml_input = etree.parse(f)
try:
xmlschema.assertValid(xml_input)
""" If the xml is valid """
if (request.is_ajax()):
ajaxdict["type"] = "valid"
ajaxdict["data"] = "This XML is valid against SPDX License Schema."
response = dumps(ajaxdict)
return HttpResponse(response,status=200)
return HttpResponse("This XML is valid against SPDX License Schema.",status=200)
except Exception as e:
if (request.is_ajax()):
ajaxdict["type"] = "invalid"
ajaxdict["data"] = "This XML is not valid against SPDX License Schema.\n"+str(e)
response = dumps(ajaxdict)
return HttpResponse(response,status=200)
return HttpResponse("This XML is not valid against SPDX License Schema.\n"+str(e),status=200)
else :
""" If no xml text is given."""
if (request.is_ajax()):
ajaxdict["type"] = "error"
ajaxdict["data"] = "No XML text given."
response = dumps(ajaxdict)
return HttpResponse(response,status=400)
return HttpResponse("No XML text given.", status=400)
except etree.XMLSyntaxError as e:
""" XML not valid """
if (request.is_ajax()):
ajaxdict["type"] = "error"
ajaxdict["data"] = "XML Parsing Error.\n The XML is not valid. Please correct the XML text and try again."
response = dumps(ajaxdict)
return HttpResponse(response,status=400)
return HttpResponse("XML Parsing Error.\n The XML is not valid. Please correct the XML text and try again.", status=400)
except :
""" Other error raised """
logger.error(str(format_exc()))
if (request.is_ajax()):
ajaxdict["type"] = "error"
ajaxdict["data"] = "Unexpected error, please email the SPDX technical workgroup that the following error has occurred: " + format_exc()
response = dumps(ajaxdict)
return HttpResponse(response,status=500)
return HttpResponse("Unexpected error, please email the SPDX technical workgroup that the following error has occurred: " + format_exc(), status=500)
else :
""" GET,HEAD """
return HttpResponseRedirect(settings.HOME_URL)
else :
return HttpResponseRedirect(settings.LOGIN_URL)
def compare(request):
""" View for compare tool
returns compare.html template
"""
if request.user.is_authenticated or settings.ANONYMOUS_LOGIN_ENABLED:
context_dict={}
if request.method == 'POST':
core.initialise_jpype()
result = core.license_compare_helper(request)
jpype.detachThreadFromJVM()
context_dict = result.get('context', None)
status = result.get('status', None)
response = result.get('response', None)
if response and status:
return HttpResponse(response, status=status)
elif context_dict and status:
return render(request, 'app/compare.html', context_dict, status=status)
elif response:
return HttpResponse(response)
else :
"""GET,HEAD"""
return render(request,
'app/compare.html',context_dict
)
else :
return HttpResponseRedirect(settings.LOGIN_URL)
def convert(request):
""" View for convert tool
returns convert.html template
"""
if request.user.is_authenticated or settings.ANONYMOUS_LOGIN_ENABLED:
context_dict={}
if request.method == 'POST':
core.initialise_jpype()
result = core.license_convert_helper(request)
jpype.detachThreadFromJVM()
context_dict = result.get('context', None)
status = result.get('status', None)
response = result.get('response', None)
if response and status:
return HttpResponse(response, status=status)
elif context_dict and status:
return render(request, 'app/convert.html', context_dict, status=status)
elif response:
return HttpResponse(response)
else :
return render(request,
'app/convert.html',context_dict
)
else :
return HttpResponseRedirect(settings.LOGIN_URL)
def check_license(request):
""" View for check license tool
returns check_license.html template
"""
if request.user.is_authenticated or settings.ANONYMOUS_LOGIN_ENABLED:
context_dict={}
if request.method == 'POST':
result = core.license_check_helper(request)
context_dict = result.get('context', None)
status = result.get('status', None)
response = result.get('response', None)
if response and status:
return HttpResponse(response, status=status)
elif context_dict and status:
return render(request, 'app/check_license.html', context_dict, status=status)
elif response:
return HttpResponse(response)
else:
"""GET,HEAD"""
return render(request,
'app/check_license.html',context_dict
)
else:
return HttpResponseRedirect(settings.LOGIN_URL)
def license_diff(request):
""" View for diff section tool
returns license_diff.html template
"""
if request.user.is_authenticated or settings.ANONYMOUS_LOGIN_ENABLED:
context_dict = {}
if request.method == 'POST':
result = core.license_diff_helper(request)
return JsonResponse(result)
else:
"""GET,HEAD"""
return render(request,
'app/license_diff.html', context_dict
)
else:
return HttpResponseRedirect(settings.LOGIN_URL)
def xml_upload(request):
""" View for uploading XML file
returns xml_upload.html
"""
if request.user.is_authenticated or settings.ANONYMOUS_LOGIN_ENABLED:
context_dict={}
ajaxdict = {}
if request.method == 'POST':
try:
if "xmlTextButton" in request.POST:
""" If user provides XML text using textarea """
if len(request.POST["xmltext"])>0 :
page_id = request.POST['page_id']
request.session[page_id] = [request.POST["xmltext"], ""]
if(request.is_ajax()):
ajaxdict["redirect_url"] = '/app/edit/'+page_id+'/'
response = dumps(ajaxdict)
return HttpResponse(response, status=200)
return render(request,
'app/editor.html',context_dict,status=200
)
else:
if (request.is_ajax()):
ajaxdict["type"] = "error"
ajaxdict["data"] = "No license XML text provided. Please input some license XML text to edit."
response = dumps(ajaxdict)
return HttpResponse(response,status=404)
context_dict["error"] = "No license XML text provided. Please input some license XML text to edit."
return render(request,
'app/xml_upload.html',context_dict,status=404
)
elif "licenseNameButton" in request.POST:
""" If license name is provided by the user """
name = request.POST["licenseName"]
if len(name) <= 0:
if (request.is_ajax()):
ajaxdict["type"] = "error"
ajaxdict["data"] = "No license name given. Please provide a SPDX license or exception name to edit."
response = dumps(ajaxdict)
return HttpResponse(response,status=400)
context_dict["error"] = "No license name given. Please provide a SPDX license or exception name to edit."
return render(request,
'app/xml_upload.html',context_dict,status=400
)
url = utils.check_license_name(name)
if url[0] is False:
if (request.is_ajax()):
ajaxdict["type"] = "error"
ajaxdict["data"] = "License or Exception name does not exist. Please provide a valid SPDX license or exception name to edit."
response = dumps(ajaxdict)
return HttpResponse(response,status=404)
context_dict["error"] = "License or Exception name does not exist. Please provide a valid SPDX license or exception name to edit."
return render(request,
'app/xml_upload.html',context_dict,status=404
)
url[0] += ".xml"
response = requests.get(url[0])
if(response.status_code == 200):
page_id = request.POST['page_id']
request.session[page_id] = [response.text, url[1]]
if (request.is_ajax()):
ajaxdict["redirect_url"] = '/app/edit/'+page_id+'/'
response = dumps(ajaxdict)
return HttpResponse(response, status=200)
return render(request,
'app/editor.html',context_dict,status=200
)
else:
if (request.is_ajax()):
ajaxdict["type"] = "error"
ajaxdict["data"] = "The application could not be connected. Please try again."
response = dumps(ajaxdict)
return HttpResponse(response,status=500)
context_dict["error"] = "The application could not be connected. Please try again."
return render(request,
'app/xml_upload.html',context_dict,status=500
)
elif "uploadButton" in request.POST:
""" If user uploads the XML file """
if "file" in request.FILES and len(request.FILES["file"])>0:
""" Saving XML file to the media directory """
xml_file = request.FILES['file']
if not xml_file.name.endswith(".xml"):
if (request.is_ajax()):
ajaxdict["type"] = "error"
ajaxdict["data"] = "Please select a SPDX license XML file."
response = dumps(ajaxdict)
return HttpResponse(response,status=400)
context_dict["error"] = "Please select a SPDX license XML file."
return render(request,
'app/xml_upload.html',context_dict,status=400
)
folder = str(request.user) + "/" + str(int(time()))
fs = FileSystemStorage(location=settings.MEDIA_ROOT +"/"+ folder,
base_url=urljoin(settings.MEDIA_URL, folder+'/')
)
filename = fs.save(xml_file.name, xml_file)
page_id = request.POST['page_id']
with open(str(fs.location+'/'+filename), 'rt', encoding='utf-8' ) as f:
request.session[page_id] = [f.read(), ""]
if (request.is_ajax()):
ajaxdict["redirect_url"] = '/app/edit/'+page_id+'/'
response = dumps(ajaxdict)
return HttpResponse(response, status=200)
return render(request,
'app/xml_upload.html',context_dict,status=200
)
else :
""" If no file is uploaded """
if (request.is_ajax()):
ajaxdict["type"] = "error"
ajaxdict["data"] = "No file uploaded. Please upload a SPDX license XML file to edit."
response = dumps(ajaxdict)
return HttpResponse(response,status=400)
context_dict["error"] = "No file uploaded. Please upload a SPDX license XML file to edit."
return render(request,
'app/xml_upload.html',context_dict,status=400
)
elif "newButton" in request.POST:
""" If the user starts with new XML """
xml_text = """<?xml version="1.0" encoding="UTF-8"?>\n<SPDXLicenseCollection xmlns="http://www.spdx.org/license">\n<license></license>\n</SPDXLicenseCollection>"""
page_id = request.POST['page_id']
request.session[page_id] = [xml_text, ""]
ajaxdict["redirect_url"] = '/app/edit/'+page_id+'/'
response = dumps(ajaxdict)
return HttpResponse(response, status=200)
else:
ajaxdict["type"] = "error"
ajaxdict["data"] = "Bad Request."
response = dumps(ajaxdict)
return HttpResponse(response, status=400)
except:
logger.error(str(format_exc()))
if (request.is_ajax()):
ajaxdict["type"] = "error"
ajaxdict["data"] = "Unexpected error, please email the SPDX technical workgroup that the following error has occurred: " + format_exc()
response = dumps(ajaxdict)
return HttpResponse(response, status=500)
context_dict["error"] = "Unexpected error, please email the SPDX technical workgroup that the following error has occurred: " + format_exc()
return render(request,
'app/xml_upload.html',context_dict,status=500
)
else :
""" GET,HEAD Request """
return render(request, 'app/xml_upload.html', {})
else:
return HttpResponseRedirect(settings.LOGIN_URL)
def autocompleteModel(request):
if 'term' in request.GET:
result = LicenseNames.objects.filter(name__icontains=request.GET['term']).values_list('name',flat=True)
return HttpResponse( json.dumps( [ name for name in result ] ) )
return HttpResponse()
def license_xml_edit(request, page_id):
"""View for editing the License XML file
returns editor.html """
context_dict = {}
if (page_id in request.session):
if request.user.is_authenticated:
user = request.user
try:
github_login = user.social_auth.get(provider='github')
except UserSocialAuth.DoesNotExist:
github_login = None
context_dict["github_login"] = github_login
context_dict["xml_text"] = request.session[page_id][0]
context_dict["license_name"] = request.session[page_id][1]
return render(request,
'app/editor.html',context_dict,status=200
)
else:
return HttpResponseRedirect('/app/xml_upload')
def get_context_dict_for_license_xml(request, license_obj):
context_dict = {}
if request.user.is_authenticated:
user = request.user
try:
github_login = user.social_auth.get(provider="github")
except UserSocialAuth.DoesNotExist:
github_login = None
context_dict["github_login"] = github_login
context_dict["xml_text"] = license_obj.xml
context_dict["license_name"] = license_obj.fullname
return context_dict
def edit_license_xml(request, license_id=None):
"""View for editing the XML file corresponsing to a license entry
returns editor.html"""
if license_id:
if not LicenseRequest.objects.filter(id=license_id).exists():
return render(request, "404.html", {}, status=404)
license_obj = LicenseRequest.objects.get(id=license_id)
context_dict = get_context_dict_for_license_xml(request, license_obj)
return render(request, "app/editor.html", context_dict, status=200)
else:
return HttpResponseRedirect('/app/license_requests')
def edit_license_namespace_xml(request, license_id=None):
"""View for editing the XML file corresponsing to a license namespace entry
returns editor.html"""
if license_id:
if not LicenseNamespace.objects.filter(id=license_id).exists():
return render(request, "404.html", {}, status=404)
license_obj = LicenseNamespace.objects.get(id=license_id)
context_dict = get_context_dict_for_license_xml(request, license_obj)
return render(request, "app/ns_editor.html", context_dict, status=200)
else:
return HttpResponseRedirect('/app/license_namespace_requests')
def archiveRequests(request, license_id=None):
""" View for archive license requests
returns archive_requests.html template
"""
context_dict = {}
if request.user.is_authenticated:
user = request.user
github_login = user.social_auth.get(provider='github')
if utils.checkPermission(user):
context_dict['authorized'] = "True"
else:
github_login = None
if request.method == "POST" and request.is_ajax():
if not request.user.is_authenticated:
ajaxdict = {}
ajaxdict["type"] = "auth_error"
ajaxdict["data"] = "Please login using GitHub to use this feature."
response = dumps(ajaxdict)
return HttpResponse(response,status=401)
if 'authorized' not in context_dict:
ajaxdict = {}
ajaxdict["type"] = "auth_error"
ajaxdict["data"] = "You are not authorised to perform this action"
response = dumps(ajaxdict)
return HttpResponse(response, status=401)
archive = request.POST.get('archive', True)
license_id = request.POST.get('license_id', False)
if license_id:
LicenseRequest.objects.filter(pk=license_id).update(archive=archive)
archiveRequests = LicenseRequest.objects.filter(archive='True').order_by('-submissionDatetime')
context_dict['archiveRequests'] = archiveRequests
context_dict['github_login'] = github_login
return render(request,
'app/archive_requests.html',context_dict
)
def archiveNamespaceRequests(request, license_id=None):
""" View for archive namespace license requests
returns archive_namespace_requests.html template
"""
if request.method == "POST" and request.is_ajax():
archive = request.POST.get('archive', False)
license_id = request.POST.get('license_id', False)
if license_id:
LicenseNamespace.objects.filter(pk=license_id).update(archive=archive)
archiveRequests = LicenseNamespace.objects.filter(archive='True').order_by('-submissionDatetime')
context_dict={'archiveRequests': archiveRequests}
return render(request,
'app/archive_namespace_requests.html',context_dict
)
def promoteNamespaceRequests(request, license_id=None):
""" View for promote namespace license requests
returns promote_namespace_requests.html template
"""
if request.method == "POST" and request.is_ajax():
promoted = request.POST.get('promoted', False)
license_id = request.POST.get('license_id', False)
if license_id:
"""Create corresponding license request and issue"""
model_dict = model_to_dict(LicenseNamespace.objects.get(pk=license_id), exclude=['id'])
licenseOsi = ""
licenseHeader = ""
licenseComments = ""
licenseExamples = []
user = request.user
github_login = user.social_auth.get(provider='github')
token = github_login.extra_data["access_token"]
licenseNotes = ''
listVersionAdded = ''
licenseAuthorName = model_dict["licenseAuthorName"]
licenseName = model_dict["namespace"]
licenseIdentifier = model_dict["shortIdentifier"]
licenseSourceUrls = [model_dict["url"]]
licenseText = model_dict["description"]
userEmail = model_dict["userEmail"]
xml = generateLicenseXml(licenseOsi, licenseIdentifier, licenseName,
listVersionAdded, licenseSourceUrls, licenseHeader, licenseNotes, licenseText)
now = datetime.datetime.now()
licenseRequest = LicenseRequest(licenseAuthorName=licenseAuthorName, fullname=licenseName, shortIdentifier=licenseIdentifier,
submissionDatetime=now, userEmail=userEmail, notes=licenseNotes, xml=xml)
licenseRequest.save()
licenseId = licenseRequest.id
serverUrl = request.build_absolute_uri('/')
licenseRequestUrl = os.path.join(serverUrl, reverse('license-requests')[1:], str(licenseId))
urlType = utils.NORMAL
if 'urlType' in request.POST:
# This is present only when executing submit license via tests
urlType = request.POST["urlType"]
statusCode, githubIssueId = utils.createIssue(licenseAuthorName, licenseName, licenseIdentifier,
licenseComments, licenseSourceUrls, licenseHeader, licenseOsi,
licenseExamples, licenseRequestUrl, token, urlType)
return_tuple = (statusCode, licenseRequest)
statusCode = return_tuple[0]
if statusCode == 201:
LicenseNamespace.objects.filter(pk=license_id).update(promoted=promoted, license_request_id=return_tuple[1].id)
promotedRequests = LicenseNamespace.objects.filter(promoted='True').order_by('-submissionDatetime')