From 070cb90095df4ab5bc7b6e28fd13bb12df29e1f7 Mon Sep 17 00:00:00 2001 From: prashantsinalkar Date: Wed, 2 Oct 2019 20:07:26 +0530 Subject: updated the code and fixed the bugs --- instances.py | 8 +-- website/ajax.py | 22 ++++----- website/models.py | 10 ++++ website/query.py | 13 +++++ website/static/website/js/cloud.js | 63 ++++++++++++++++++------ website/static/website/js/cookiealert.js | 53 ++++++++++++++++++++ website/static/website/templates/index.html | 21 ++++++-- website/urls.py | 1 + website/views.py | 76 +++++++++++++++-------------- 9 files changed, 196 insertions(+), 71 deletions(-) create mode 100644 website/static/website/js/cookiealert.js diff --git a/instances.py b/instances.py index db3167b..f7f0774 100644 --- a/instances.py +++ b/instances.py @@ -50,8 +50,8 @@ def execute_code(code, user_id, R_file_id): os.makedirs(TEMP_DIR) result = requests.post(API_URL, json=jsondata, headers=headers) output = result.json() - output_auth_error = json.loads(json.dumps(output['auth_error'])) - if output_auth_error != '400': + output_status = json.loads(json.dumps(output['status'])) + if output_status != '400': output_data = json.loads(json.dumps(output['data'])) output_error = json.loads(json.dumps(output['error'])) plot_exist = json.loads(json.dumps(output['is_plot'])) @@ -64,7 +64,9 @@ def execute_code(code, user_id, R_file_id): 'plot_path': plot_path_req, } else: - data = {'error': "Invalid request, please try after some time"} + data = {'error': "Invalid request, please try after some time {0}" + .format(output_status) + } return data diff --git a/website/ajax.py b/website/ajax.py index 90658b6..e165aec 100755 --- a/website/ajax.py +++ b/website/ajax.py @@ -192,13 +192,13 @@ def code(request): if not example_id: example_id = int(request.GET.get('example_id')) file_path = request.session['filepath'] - #review = ScilabCloudComment.objects.using('r')\ + #review = R_CloudComment.objects.using('r')\ # .filter(example=example_id).count() review = 0 with connections['r'].cursor() as cursor: cursor.execute(GET_TBC_EXAMPLE_VIEW_SQL, params=[example_id]) exmple = cursor.fetchone() - review_url = "https://scilab.in/cloud_comments/" + str(example_id) + review_url = "https://r.fossee.in/cloud_comments/" + str(example_id) file = utils.get_file(file_path, commit_sha, main_repo=True) code = file @@ -310,15 +310,15 @@ def bug_form_submit(request): 'example_no': example_number, 'comment': comment, } - scilab_comment = ScilabCloudComment() - scilab_comment.type = error_int - scilab_comment.comment = comment - scilab_comment.email = email - scilab_comment.category = comment_data[0].category - scilab_comment.books = book_id - scilab_comment.chapter = chapter_id - scilab_comment.example = ex_id - scilab_comment.save(using='r') + r_comment = R_CloudComment() + r_comment.type = error_int + r_comment.comment = comment + r_comment.email = email + r_comment.category = comment_data[0].category + r_comment.books = book_id + r_comment.chapter = chapter_id + r_comment.example = ex_id + r_comment.save(using='r') subject = "New Cloud Comment" message = render_to_string('email.html', context) from_email = FROM_EMAIL diff --git a/website/models.py b/website/models.py index 38ace40..a10670a 100644 --- a/website/models.py +++ b/website/models.py @@ -2,6 +2,16 @@ from django.db import models # Create your models here. +class Banner(models.Model): + title = models.CharField(max_length=500) + banner = models.TextField(max_length=1000) + position = models.IntegerField() + visible = models.BooleanField() + + def __str__(self): + return self.banner + + class TextbookCompanionCategoryList(models.Model): id = models.IntegerField(unique=True, primary_key=True) category_name = models.CharField(max_length=100) diff --git a/website/query.py b/website/query.py index 23f4cea..8ccd7a2 100644 --- a/website/query.py +++ b/website/query.py @@ -1,9 +1,21 @@ +GET_ALLMAINCATEGORY_SQL = """ + SELECT category_id, maincategory + FROM list_of_category ORDER BY maincategory ASC + """ +GET_ALLSUBCATEGORY_SQL = """ + SELECT id, subcategory_id, subcategory, maincategory_id + FROM list_of_subcategory ORDER BY subcategory ASC + """ + GET_SUBCATEGORY_SQL = """ SELECT id, subcategory_id, subcategory, maincategory_id FROM list_of_subcategory WHERE maincategory_id =%s + ORDER BY subcategory ASC """ + + GET_TBC_PREFERENCE_SQL = """ SELECT DISTINCT (loc.category_id), pe.id, tcbm.sub_category, loc.maincategory, pe.book as book, @@ -18,6 +30,7 @@ GET_TBC_PREFERENCE_SQL = """ WHERE po.proposal_status = 3 AND pe.approval_status = 1 AND pe.id = tcbm.pref_id AND pe.cloud_pref_err_status = 0 AND loc.category_id = %s AND tcbm.sub_category = %s + ORDER BY pe.book ASC """ diff --git a/website/static/website/js/cloud.js b/website/static/website/js/cloud.js index 01153cd..de5d9f3 100644 --- a/website/static/website/js/cloud.js +++ b/website/static/website/js/cloud.js @@ -136,6 +136,7 @@ $(document.body).ready(function() { $("#diff-wrapper").hide(); $("#databox-wrapper").hide(); if ($("#main_categories").val() == 0) { + $('#main_categories').prop('selectedIndex',0); $("#category-wrapper").hide(); $("#books-wrapper").hide(); $("#chapters-wrapper").hide(); @@ -145,6 +146,35 @@ $(document.body).ready(function() { $("#diff-wrapper").hide(); $("#contributor").hide(); $("#databox-wrapper").hide(); + }else{ + $.ajax({ + url: 'get_subcategories/', + dataType: 'JSON', + type: 'GET', + data: { + maincat_id: $("#main_categories").val(), + }, + success: function(data) { + ajax_loader("clear"); + $("#categories").html( + ''); + $("#categories").html( + ' ' + ); + var j = 1; + for (var i = 0; i < + data.length; i++) { + $('#categories').append( + '' + ); + j++; + } + } + }); } if ($("#categories").val() == 0) { $("#books-wrapper").hide(); @@ -335,8 +365,6 @@ $(document.body).ready(function() { var book_id = $('#books').find(":selected").val(); ajax_loader(this); $("#chapters-wrapper").show(); - console.log(book_id); - if (book_id != 0) { $("#download-book").show(); $("#contributor").show(); @@ -404,7 +432,6 @@ $(document.body).ready(function() { var chapter_id = $('#chapters').find( ":selected").val(); $("#examples-wrapper").show(); - console.log(chapter_id); if (chapter_id != 0) { $("#examples-wrapper").show(); $("#download-chapter").show(); @@ -474,7 +501,6 @@ $(document.body).ready(function() { $("#databox-wrapper").hide(); editor.setValue(""); result.setValue(""); - console.log(example_id); ajax_loader('#revisions'); $.ajax({ url: 'get_revisions/', @@ -797,7 +823,6 @@ $(document.body).ready(function() { issue_id = $("#id_issue").val(); id_description_wrapper = $.trim($("#id_description").val()); id_email = $.trim($("#id_email").val()); - console.log(id_description_wrapper.length); if (issue_id == 0 || id_description_wrapper.length == 0 || id_email.length == 0) { if (issue_id == 0) { $('#id_issue').css({ @@ -838,7 +863,6 @@ $(document.body).ready(function() { email: id_email, }, success: function(data) { - console.log(data); alert(data); ajax_loader("clear"); $("#bug_form_wrapper").modal('toggle'); @@ -981,7 +1005,6 @@ $(document.body).ready(function() { search_string: search_string, }, success: function(data) { - console.log(data); $("#popular").html('

Popular


'); for (var i = 0; i < data.length; i++) { $("#popular").append( @@ -999,7 +1022,6 @@ $(document.body).ready(function() { search_string: search_string, }, success: function(data) { - console.log(data); $("#recent").html('

Recent


'); for (var i = 0; i < data.length; i++) { $("#recent").append( @@ -1030,12 +1052,20 @@ $(document.body).ready(function() { }); $(document).on("click", "#reset", function() { - if(confirm("Are you sure you want to reset? Reset will clear of your data/uploaded file.")){ - document.location.reload(true); - } - else{ - return false; - } + $.ajax({ + url : "reset/", + dataType: 'JSON', + type: 'GET', + data:{ reset: '1' }, + + success : function (data) { + document.location.reload(true); + }, + beforeSend:function(){ + return confirm("Are you sure you want to reset? Reset will clear of your data/uploaded file."); + }, + }); + }); }); //document.readOnly() @@ -1048,10 +1078,11 @@ function doSubmit(){ var file = fileSelect.files[0] formData.set("file", file , file.name); var user_id = document.getElementById("user_id"); - formData.set("user_id", user_id.value) - // Http Request + formData.set("user_id", user_id.value); + formData.set("X-Api-Key", key); var request = new XMLHttpRequest(); + request.open('POST', api_url_upload); request.send(formData); return (fileSelect.files[0].name); diff --git a/website/static/website/js/cookiealert.js b/website/static/website/js/cookiealert.js new file mode 100644 index 0000000..cbd5745 --- /dev/null +++ b/website/static/website/js/cookiealert.js @@ -0,0 +1,53 @@ +/* + * Bootstrap Cookie Alert by Wruczek + * https://github.com/Wruczek/Bootstrap-Cookie-Alert + * Released under MIT license + */ +(function () { + "use strict"; + + var cookieAlert = document.querySelector(".cookiealert"); + var acceptCookies = document.querySelector(".acceptcookies"); + + if (!cookieAlert) { + return; + } + + cookieAlert.offsetHeight; // Force browser to trigger reflow (https://stackoverflow.com/a/39451131) + + // Show the alert if we cant find the "acceptCookies" cookie + if (!getCookie("acceptCookies")) { + cookieAlert.classList.add("show"); + } + + // When clicking on the agree button, create a 1 year + // cookie to remember user's choice and close the banner + acceptCookies.addEventListener("click", function () { + setCookie("acceptCookies", true, 365); + cookieAlert.classList.remove("show"); + }); + + // Cookie functions from w3schools + function setCookie(cname, cvalue, exdays) { + var d = new Date(); + d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)); + var expires = "expires=" + d.toUTCString(); + document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; + } + + function getCookie(cname) { + var name = cname + "="; + var decodedCookie = decodeURIComponent(document.cookie); + var ca = decodedCookie.split(';'); + for (var i = 0; i < ca.length; i++) { + var c = ca[i]; + while (c.charAt(0) === ' ') { + c = c.substring(1); + } + if (c.indexOf(name) === 0) { + return c.substring(name.length, c.length); + } + } + return ""; + } +})(); diff --git a/website/static/website/templates/index.html b/website/static/website/templates/index.html index fb0681f..585dafa 100644 --- a/website/static/website/templates/index.html +++ b/website/static/website/templates/index.html @@ -18,6 +18,7 @@ {% csrf_token %} + + + diff --git a/website/urls.py b/website/urls.py index 3f12488..127cf09 100644 --- a/website/urls.py +++ b/website/urls.py @@ -17,4 +17,5 @@ urlpatterns = [ path('update_view_count/', views.update_view_count, name='update_view_count'), path('get_contributor/', ajax.contributor, name='contributor'), + path('reset/', views.reset, name='reset'), ] diff --git a/website/views.py b/website/views.py index 4d1af16..9d17495 100644 --- a/website/views.py +++ b/website/views.py @@ -1,14 +1,15 @@ -from django.shortcuts import render +from django.shortcuts import render, redirect from django.http import HttpResponse from django.template import loader import requests import uuid -from R_on_Cloud.config import (API_URL_UPLOAD) +from R_on_Cloud.config import (API_URL_UPLOAD, API_URL_RESET, AUTH_KEY) from website.models import * from django.db.models import Q import json as simplejson from . import utils from django.db import connections +from collections import defaultdict from .query import * @@ -21,31 +22,18 @@ def dictfetchall(cursor): ] -def catg(cat_id, all_cat): - if all_cat is False: - category = TextbookCompanionCategoryList.objects.using('r')\ - .get(category_id=cat_id) - return category.maincategory - else: - category = TextbookCompanionCategoryList.objects.using('r')\ - .filter(~Q(category_id=0)).order_by('maincategory') - return category - - -def subcatg(subcat_id, all_subcat): - if all_subcat is False: - category = TextbookCompanionSubCategoryList.objects.using('r')\ - .get(id=subcat_id) - return category.subcategory - else: - category = TextbookCompanionSubCategoryList.objects.using('r')\ - .all().order_by('subcategory') - return category +def catg(): + with connections['r'].cursor() as cursor: + cursor.execute(GET_ALLMAINCATEGORY_SQL) + category = dictfetchall(cursor) + return category def get_subcategories(maincat_id): - subcategories = TextbookCompanionSubCategoryList.objects.using('r')\ - .filter(maincategory_id=maincat_id).order_by('subcategory_id') + with connections['r'].cursor() as cursor: + cursor.execute(GET_SUBCATEGORY_SQL, + params=[maincat_id]) + subcategories = dictfetchall(cursor) return subcategories @@ -97,19 +85,12 @@ def index(request): context['reset_req_url'] = API_URL_RESET book_id = request.GET.get('book_id') user = request.user - if 'user_id' in request.session: - context['user_id'] = request.session['user_id'] - else: - context['user_id'] = str(user_id) + if not 'user_id' in request.session: request.session['user_id'] = str(user_id) if not (request.GET.get('eid') or request.GET.get('book_id')): - catg_all = catg(None, all_cat=True) - subcatg_all = subcatg(None, all_subcat=True) - context = { - 'catg': catg_all, - 'subcatg': subcatg_all, - } + catg_all = catg() + if 'maincat_id' in request.session: maincat_id = request.session['maincat_id'] context['maincat_id'] = int(maincat_id) @@ -154,9 +135,12 @@ def index(request): session_code = get_code( request.session['filepath'], commit_sha) context['code'] = session_code - context['user_id'] = request.session['user_id'] - context['reset_req_url'] = API_URL_RESET - + context = { + 'catg': catg_all, + 'api_url_upload': API_URL_UPLOAD, + 'user_id': request.session['user_id'], + 'key': AUTH_KEY, + } template = loader.get_template('index.html') return HttpResponse(template.render(context, request)) elif book_id: @@ -356,3 +340,21 @@ def update_view_count(request): data = Example_views_count[0] return HttpResponse(simplejson.dumps(data), content_type='application/json') + + +def reset(request): + try: + for key, value in list(request.session.items()): + + if key != 'user_id': + del request.session[key] + print('{} => {}'.format(key, value)) + print("done----") + response = {"data" : "ok"} + return HttpResponse(simplejson.dumps(response), + content_type='application/json') + except KeyError: + pass + response = {"data" : "ok"} + return HttpResponse(simplejson.dumps(response), + content_type='application/json') -- cgit