def load_file(directory, rel_path): """ Load the file using the right function according to the type map to its extension. Catch every exception raised by the corresponding loading function or the parser. Return: - (PLTP/PL, []) if the PLTP/PL was loaded successfully - (PLTP/PL, warning_list) if the PLTP/PL was loaded with warnings - (None, error_msg) if PLTP/PL couldn't be loaded / an exception was catch """ try: typ = get_type(directory, rel_path) if typ == 'pltp': return load_pltp(directory, rel_path) elif typ == 'pl': return load_pl(directory, rel_path) elif typ == 'pla': return load_pla(directory, rel_path) except Exception as e: if not settings.DEBUG: return None, htmlprint.code(str(e)) return (None, (htmlprint.code(str(e)) + '<br>DEBUG set to True - Showing Traceback :<br>' + htmlprint.html_exc()))
def commit(request): """ Execute an add and commit of the targeted entry with the informations of POST. """ post = json.loads(request.body.decode()) path = post.get('path') if not path: return HttpResponseBadRequest(missing_parameter('path')) commit = post.get('commit') if not commit: return HttpResponseBadRequest(missing_parameter('commit')) user = request.user if not user.email: return HttpResponseBadRequest("User must have an email") if user.first_name and user.last_name: name = user.get_full_name() else: name = user.get_username() ret, out, err = gitcmd.commit(join_fb_root(path), commit, name=name, mail=request.user.email) if not ret: return HttpResponse(htmlprint.code(out + err)) else: # pragma: no cover return HttpResponseNotFound(htmlprint.code(err + out))
def reload_pla(directory, rel_path, original): """Reload the given file as a PLTP. Also reload its PL, but without modyfing their ID. original is a pltp returned by load_pltp or reload_pltp Return: - (PLTP, []) if the PLTP was loaded successfully - (PLTP, warning_list) if the PLTP was loaded with warnings """ try: dic, warnings = parse_file(directory, rel_path) original_type = get_activity_type_class(original.activity_type)() if "type" in dic and original.activity_type != dic["type"]: return None, f"Activity type must remain '{original.activity_type}'" original.activity_data = { **dic, **original_type.install(original), "__reload_path": os.path.join(directory.name, rel_path) } pl_list = list() for item in dic['__pl']: pl_directory = Directory.objects.get(name=item['directory_name']) pl, pl_warnings = load_pl(pl_directory, item['path']) if pl is None: return None, pl_warnings warnings += pl_warnings pl_list.append(pl) originals = list(original.indexed_pl()) original.pl.clear() for pl in pl_list: correspond = list( filter( lambda i: i.directory == pl.directory and i.rel_path == pl. rel_path, originals)) if correspond: correspond = correspond[0] correspond.json = pl.json correspond.save() logger.info("PL '" + str(correspond.id) + " (" + correspond.name + ")' has been updated.") PLPosition.objects.create(parent=original, pl=correspond) else: pl.save() logger.info("PL '" + str(pl.id) + " (" + pl.name + ")' has been created.") PLPosition.objects.create(parent=original, pl=pl) original.save() logger.info("Activity '" + original.name + "' has been reloaded.") return original, [htmlprint.code(warning) for warning in warnings] except Exception as e: # pragma: no cover if not settings.DEBUG: return None, htmlprint.code(str(e)) return (None, (htmlprint.code(str(e)) + '<br>DEBUG set to True - Showing Traceback :<br>' + htmlprint.html_exc()))
def status(request): """ Execute a git status on the targeted entry.""" path = request.GET.get('path') if not path: return HttpResponseBadRequest(missing_parameter('path')) ret, out, err = gitcmd.status(join_fb_root(path)) if not ret: return HttpResponse(htmlprint.code(out + err)) else: # pragma: no cover return HttpResponseNotFound(htmlprint.code(out + err))
def show(request): """ Execute a git show on the targeted entry.""" path = request.GET.get('path') if not path: return HttpResponseBadRequest(missing_parameter('path')) try: ret, out, err = gitcmd.show_last_revision(join_fb_root(path)) if not ret: return HttpResponse(out) else: # pragma: no cover return HttpResponseNotFound(htmlprint.code(out + err)) except Exception as e: # pragma: no cover error = htmlprint.code(str(type(e)) + ' - ' + str(e)) return HttpResponseNotFound(error)
def reload_pltp(directory, rel_path, original): """Reload the given file as a PLTP. Also reload its PL, but without modyfing their ID. original is a pltp returned by load_pltp or reload_pltp Return: - (PLTP, []) if the PLTP was loaded successfully - (PLTP, warning_list) if the PLTP was loaded with warnings """ try: dic, warnings = parse_file(directory, rel_path) pl_list = list() for item in dic['__pl']: pl_directory = Directory.objects.get(name=item['directory_name']) pl, pl_warnings = load_pl(pl_directory, item['path']) warnings += pl_warnings pl_list.append(pl) originals = list(original.pl.all()) original.pl.clear() for pl in pl_list: correspond = list( filter( lambda i: i.directory == pl.directory and i.rel_path == pl. rel_path, originals)) if correspond: correspond = correspond[0] correspond.json = pl.json correspond.save() logger.info("PL '" + str(correspond.id) + " (" + correspond.name + ")' has been updated.") Index.objects.create(pltp=original, pl=correspond) else: pl.save() logger.info("PL '" + str(pl.id) + " (" + pl.name + ")' has been created.") Index.objects.create(pltp=original, pl=pl) original.json = dic original.save() logger.info("PLTP '" + original.sha1 + " (" + original.name + ")' has been updated.") return original, [htmlprint.code(warning) for warning in warnings] except Exception as e: # pragma: no cover if not settings.DEBUG: return None, htmlprint.code(str(e)) return (None, (htmlprint.code(str(e)) + '<br>DEBUG set to True - Showing Traceback :<br>' + htmlprint.html_exc()))
def raw_evaluate(self, request, answers, test=False): """Evaluate the exercise with the given answers according to the current context. Parameters: request - (django.http.request) Current Django request object. answers - (dict) Answers of the student. test - (bool) Whether this exercise is in a testing session or not. """ evaluator = SandboxEval(self.envid, answers) if not evaluator.check(): self.build(request, test=test) evaluator = SandboxEval(self.envid, answers) response = evaluator.call() answer = { "answers": answers, "user": request.user, "pl": self.pl, "grade": response['grade'], } if response['status'] < 0: # Sandbox Error feedback = response['feedback'] if request.user.profile.can_load() and response['sandboxerr']: feedback += "<br><hr>Sandbox error:<br>" + htmlprint.code( response['sandboxerr']) feedback += "<br><hr>Received on stderr:<br>" + htmlprint.code( response['stderr']) elif response['status'] > 0: # Grader Error feedback = ( "Une erreur s'est produite lors de l'exécution du grader " + ("(exit code: %d, env: %s). Merci de prévenir votre professeur" % (response['status'], response['id']))) if request.user.profile.can_load(): feedback += "<br><hr>Received on stderr:<br>" + htmlprint.code( response['stderr']) else: # Success feedback = response['feedback'] if request.user.profile.can_load() and response['stderr']: feedback += "<br><br>Received on stderr:<br>" + htmlprint.code( response['stderr']) self.context.update(response['context']) self.context['answers__'] = answers self.save() return answer, feedback, response['status']
def build(self, request, test=False, seed=None): """Build the exercise with the given according to the current context. Parameters: request - (django.http.request) Current Django request object. test - (bool) Whether this exercise is in a testing session or not. """ self.context = self.pl.json if 'components.py' not in self.context: self.context['__files']['components.py'] = components_source() self.context['seed'] = seed if seed else create_seed() self.save() response = SandboxBuild(dict(self.context), test=test).call() if response['status'] < 0: msg = ( "Une erreur s'est produit sur la sandbox (exit code: %d, env: %s)." + " Merci de prévenir votre professeur.") % ( response['status'], response['id']) if request.user.profile.can_load(): msg += "<br><br>" + htmlprint.code(response['sandboxerr']) raise SandboxError(msg) if response['status'] > 0: msg = ( "Une erreur s'est produite lors de l'exécution du script before/build " + ("(exit code: %d, env: %s). Merci de prévenir votre professeur" % (response['status'], response['id']))) if request.user.profile.can_load() and response['stderr']: msg += "<br><br>Reçu sur stderr:<br>" + htmlprint.code( response['stderr']) raise BuildScriptError(msg) context = dict(response['context']) keys = list(response.keys()) for key in keys: response[key + "__"] = response[key] for key in keys: del response[key] del response['context__'] context.update(response) self.envid = response['id__'] self.context.update(context) self.built = True self.save()
def test_pl_option(request, filebrowser, target): """ Allwo to test a PL.""" if request.method != 'GET': return HttpResponseNotAllowed(['GET']) try: path = join(filebrowser.full_path(), target) rel_path = join(filebrowser.relative, target).replace(filebrowser.directory.name, "") pl, warnings = load_file(filebrowser.directory, rel_path) if not pl: messages.error(request, warnings) return redirect_fb(request.GET.get('relative_h', '.')) exercise = PLInstance(pl.json) request.session['exercise'] = dict(exercise.dic) preview = exercise.render(request) return render(request, 'filebrowser/test_pl.html', { 'preview': preview, }) except Exception as e: msg = "Impossible to display '" + target + "' : " + htmlprint.code( str(type(e)) + ' - ' + str(e)) if settings.FILEBROWSER_ROOT in msg: msg = msg.replace(settings.FILEBROWSER_ROOT + "/", "") messages.error(request, msg) return redirect_fb(request.GET.get('relative_h', '.'))
def apply_option_post(request): """ Apply an option using the POST method """ if not request.method == 'POST': return HttpResponseNotAllowed(['POST']) path = request.POST.get('relative_h', None) name = request.POST.get('name_h', None) option = request.POST.get('option_h', None) typ = request.POST.get('type_h', None) if not (name and path and option and typ): return HttpResponseBadRequest( "Missing one of 'relative_h', 'name_h', 'option_h' or 'type_h' argument" ) if typ == 'directory': path = '.' fb = Filebrowser(path=path) try: if typ == "entry": return ENTRY_OPTIONS[option].process_option( request, fb, name, ) else: return DIRECTORY_OPTIONS[option].process_option(request, fb, name) except Exception as e: messages.error( request, "Impossible to apply the option " + option + " : " + htmlprint.code(str(type(e)) + " - " + str(e))) return redirect_fb(path)
def status_option(request, filebrowser, target): """ Execute a git status on the targeted entry.""" if request.method != 'GET': return HttpResponseNotAllowed(['GET']) if not filebrowser.directory: d = Directory.objects.get(name=target) done, msg = d.status() else: done, msg = filebrowser.directory.status() if done: messages.success(request, "Status done.<br>" + htmlprint.code(msg)) else: messages.error(request, "Couldn't status:<br>" + htmlprint.code(msg)) return redirect_fb(request.GET.get('relative_h', '.'))
def download_option(request, filebrowser, target): """ Allow the user to download target""" if request.method != 'GET': return HttpResponseNotAllowed(['GET']) try: path = join(filebrowser.full_path(), target) filename = target if isdir(path): shutil.make_archive(path, 'zip', root_dir=path) filename = filename + ".zip" path += ".zip" with open(path, 'rb') as f: response = HttpResponse(f.read()) response['Content-Type'] = magic.from_file(path, mime=True) response[ 'Content-Disposition'] = "attachment; filename=" + filename return response except Exception as e: msg = "Impossible to download '" + target + "' : " + htmlprint.code( str(type(e)) + ' - ' + str(e)) if settings.FILEBROWSER_ROOT in msg: msg = msg.replace(settings.FILEBROWSER_ROOT + "/", "") messages.error(request, msg) return redirect_fb(request.GET.get('relative_h', '.'))
def right_edit(request): """ View used to add the new right of a Directory. """ if request.method != 'POST': return HttpResponseNotAllowed(['POST']) name = request.POST.get('directory', None) write = request.POST.getlist('write') read = request.POST.getlist('read') try: d = Directory.objects.get(name=name) d.write_auth.clear() d.read_auth.clear() for item in write: d.write_auth.add(User.objects.get(id=item)) for item in read: d.read_auth.add(User.objects.get(id=item)) messages.success(request, "Rights of '" + name + "' successfully edited.") except Exception as e: raise e msg = "Impossible to edit rights of '" + name + "' : " + htmlprint.code( str(type(e)) + " - " + str(e)) if settings.FILEBROWSER_ROOT in msg: msg = msg.replace(settings.FILEBROWSER_ROOT, "") messages.error(request, msg) return redirect(reverse(index))
def extract_option(request, filebrowser, target): """ Extract the given archive """ if request.method != 'GET': return HttpResponseNotAllowed(['GET']) try: path = join(filebrowser.full_path(), target) mime = magic.from_file(path, mime=True).split('/')[1] if mime == 'zip': with zipfile.ZipFile(path) as arc: arc.extractall( join(filebrowser.full_path(), splitext(target)[0])) elif mime in ['x-xz', 'gzip']: with tarfile.open(path) as arc: arc.extractall( join(filebrowser.full_path(), splitext(target)[0])) else: raise ValueError("Can't extract '" + mime + "' files.") messages.success(request, "Archive '" + target + "' successfully extracted.") except Exception as e: msg = "Impossible to extract '" + target + "' : " + htmlprint.code( str(type(e)) + ' - ' + str(e)) if settings.FILEBROWSER_ROOT in msg: msg = msg.replace(settings.FILEBROWSER_ROOT + "/", "") messages.error(request, msg) return redirect_fb(request.GET.get('relative_h', '.'))
def rights_option(request, filebrowser, target): """ Open a page allowing the user to edit the rights of his targeted Directory.""" if request.method != 'GET': return HttpResponseNotAllowed(['GET']) try: if not filebrowser.directory: d = Directory.objects.get(name=target) else: d = filebrowser.directory form = RightForm() form.initial['write'] = [user.id for user in d.write_auth.all()] form.initial['read'] = [user.id for user in d.read_auth.all()] return render(request, 'filebrowser/edit_rights.html', { 'form': form, 'directory': d.name, }) except Exception as e: msg = "Impossible to display '" + target + "' : " + htmlprint.code( str(type(e)) + ' - ' + str(e)) if settings.FILEBROWSER_ROOT in msg: msg = msg.replace(settings.FILEBROWSER_ROOT + "/", "") messages.error(request, msg) return redirect_fb(request.GET.get('relative_h', '.'))
def reload_activity(path, activity): try: path_components = path.split('/') directory = Directory.objects.get(name=path_components[0]) relative = os.path.join(*(path_components[1:])) pltp, warnings = rp(directory, relative, activity) if not pltp and not warnings: # pragma: no cover return HttpResponse("This PLTP is already loaded") elif not pltp: # pragma: no cover return HttpResponseNotFound( f"Failed to load '{os.path.basename(path)}': \n{warnings}") else: activity.reload() msg = '' if warnings: # pragma: no cover for warning in warnings: msg += str(warning) return HttpResponse(msg + "L'activité <b>'" + pltp.name + "'</b> a bien été rechargé.") except Exception as e: # pragma: no cover msg = "Impossible to load '" + os.path.basename( path) + "' : " + htmlprint.code(str(type(e)) + ' - ' + str(e)) if settings.DEBUG: msg += ("DEBUG set to True: " + htmlprint.html_exc()) return HttpResponseNotFound(msg)
def mkdir_option(request, filebrowser, target): """Create a new folder named target at filebrowser.full_path()""" if request.method != 'POST': return HttpResponseNotAllowed(['POST']) name = request.POST.get('name', None) relative = request.POST.get('relative', None) if not name or not relative: return HttpResponseBadRequest try: path = abspath(join(join(filebrowser.full_path(), relative), name)) if isdir(path): messages.error( request, "A folder with that name ('" + name + "') already exists") elif isfile(path): messages.error( request, "A file with that name ('" + name + "') already exists") else: os.mkdir(path) messages.success(request, "Folder '" + name + "' successfully created !") except Exception as e: msg = "Impossible to create '" + name + "' : " + htmlprint.code( str(type(e)) + ' - ' + str(e)) if settings.FILEBROWSER_ROOT in msg: msg = msg.replace(settings.FILEBROWSER_ROOT + "/", "") messages.error(request, msg) return redirect_fb(request.POST.get('relative_h', '.'))
def edit_option(request, filebrowser, target): """ Start an editor to edit target.""" if request.method != 'GET': return HttpResponseNotAllowed(['GET']) try: path = join(filebrowser.full_path(), target) with open(path, 'r') as f: content = f.read() return render( request, 'filebrowser/editor.html', { 'file_content': content, 'filename': basename(path), 'filepath': path.replace(settings.FILEBROWSER_ROOT + '/', ''), 'dir_name': filebrowser.directory.name, }) except Exception as e: msg = "Impossible to edit '" + target + "' : " + htmlprint.code( str(type(e)) + ' - ' + str(e)) if settings.FILEBROWSER_ROOT in msg: msg = msg.replace(settings.FILEBROWSER_ROOT + "/", "") messages.error(request, msg) return redirect_fb(request.GET.get('relative_h', '.'))
def search_in_files(request): # TODO ADD TEST path = request.GET.get('path') if not path: return HttpResponseBadRequest(missing_parameter('path')) query = request.GET.get('query') if not query: return HttpResponseBadRequest(missing_parameter('query')) cwd = os.getcwd() try: if (not path.startswith(HOME_DIR) and not path.startswith(LIB_DIR)): return HttpResponseBadRequest('cannot search outside of root directories') path = join_fb_root(path) if not os.path.isdir(path): return HttpResponseBadRequest('path should point to a directory') os.chdir(path) p = subprocess.Popen("grep -nr '{0}' .".format(query), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out, err = p.communicate() finally: os.chdir(cwd) ret, out, err = p.returncode, out.decode().strip("\n"), err.decode() if not ret: return HttpResponse(out) else: # pragma: no cover return HttpResponseNotFound(htmlprint.code(out + err))
def test_pl(request): path = request.GET.get('path') if not path: return HttpResponseBadRequest(missing_parameter('path')) try: path_components = path.split('/') directory = Directory.objects.get(name=path_components[0]) relative = os.path.join(*(path_components[1:])) pl, warnings = load_file(directory, relative) if not pl: return HttpResponseBadRequest(warnings.replace(settings.FILEBROWSER_ROOT, "")) pl.save() exercise = SessionTest.objects.create(pl=pl, user=request.user) preview = exercise.get_exercise(request) return render(request, 'filebrowser/test.html', { 'preview': preview, 'id': pl.id, }) except Exception as e: # pragma: no cover msg = ("Impossible to test '" + os.path.basename(path) + "' : " + htmlprint.code( str(type(e)) + ' - ' + str(e))) return HttpResponseBadRequest(msg.replace(settings.FILEBROWSER_ROOT, ""))
def git_commit(request): """ Execute an add and commit of the targeted entry with the informations of POST. """ post = json.loads(request.body.decode()) path = post.get('path') if not path: return HttpResponseBadRequest("parameter 'path' is missing") commit = post.get('commit') if not commit: return HttpResponseBadRequest("Missing 'commit' parameter") ret, out, err = gitcmd.commit(join_fb_root(path), commit) if not ret: return HttpResponse(htmlprint.code(out + err)) else: # pragma: no cover return HttpResponseNotFound(htmlprint.code(err + out))
def rename_resource(request): """Rename a file or folder """ post = json.loads(request.body.decode()) path = post.get('path') target = post.get('target') if not path: return HttpResponseBadRequest(missing_parameter('path')) if not target: return HttpResponseBadRequest(missing_parameter('target')) path = join_fb_root(path) name = os.path.basename(path) new_path = os.path.join(os.path.dirname(path), target) try: if any(c in target for c in settings.FILEBROWSER_DISALLOWED_CHAR): msg = "Can't rename '{0}' to '{1}': name should not contain any of {2}." \ .format(name, target, settings.FILEBROWSER_DISALLOWED_CHAR) return HttpResponseBadRequest(msg) if os.path.exists(new_path): msg = "Can't rename '{0}' to '{1}': this name is already used.".format(name, target) return HttpResponseBadRequest(msg) os.rename(path, new_path) return JsonResponse( {'path': rm_fb_root(new_path), 'status': 200}) except Exception as e: # pragma: no cover msg = "Impossible to rename '{0}' to '{1}': {2}".format(name, target, htmlprint.code( str(type(e)) + ' - ' + str(e))) if settings.DEBUG: msg += ("DEBUG set to True: " + htmlprint.html_exc()) return HttpResponseNotFound(msg)
def upload_resource(request): # TODO ADD TEST """ Allow the user to upload a file in the filebrowser """ if request.method != 'POST': return HttpResponseNotAllowed(['POST']) f = request.FILES.get('file') if not f: return HttpResponseBadRequest(missing_parameter('file')) path = request.POST.get('path') if not path: return HttpResponseBadRequest(missing_parameter('path')) name = f.name try: path = os.path.join(join_fb_root(path), name) if os.path.exists(path): return HttpResponseBadRequest("This file's name is already used : " + name) else: with open(path, 'wb+') as dest: for chunk in f.chunks(): dest.write(chunk) return HttpResponse() except Exception as e: # pragma: no cover msg = "Impossible to upload '" + path + "' : " + htmlprint.code( str(type(e)) + ' - ' + str(e)) if settings.DEBUG: messages.error(request, "DEBUG set to True: " + htmlprint.html_exc()) return HttpResponseNotFound(msg)
def delete_resource(request): """Delete a file or folder """ post = json.loads(request.body.decode()) path = post.get('path') if not path: return HttpResponseBadRequest(missing_parameter('path')) if is_root(path): return HttpResponseBadRequest('cannot delete a root folder') try: path = join_fb_root(path) shutil.rmtree( path, ignore_errors=True) if os.path.isdir(path) else os.remove(path) if not path.startswith("lib/"): add_commit_path(request, path, action="deleted") return JsonResponse({'success': True}) except Exception as e: # pragma: no cover path = path.replace(settings.FILEBROWSER_ROOT, '') error = htmlprint.code(str(e).replace(settings.FILEBROWSER_ROOT, '')) msg = "Impossible to delete '%s' : %s" % (path, error) if settings.DEBUG: msg += ("DEBUG: " + htmlprint.html_exc()) return HttpResponseNotFound(msg)
def create_resource(request): """Create a new file or folder """ post = json.loads(request.body.decode()) path = post.get('path') if not path: return HttpResponseBadRequest(missing_parameter('path')) path = join_fb_root(path) name = os.path.basename(path) try: if any(c in name for c in settings.FILEBROWSER_DISALLOWED_CHAR): msg = "Can't create '%s': name should not contain any of %s." return HttpResponseBadRequest(msg % (name, str(settings.FILEBROWSER_DISALLOWED_CHAR))) if os.path.exists(path): return HttpResponseBadRequest("Can't create '%s': this name is already used." % name) if post.get('type', '') == 'file': with open(path, "w") as f: print(post.get('content', ''), file=f) return JsonResponse({'path': rm_fb_root(path)}) else: os.mkdir(path) return JsonResponse({'path': rm_fb_root(path)}) except Exception as e: # pragma: no cover msg = "Impossible to create '{0}' : {1}".format(name, htmlprint.code( str(type(e)) + ' - ' + str(e))) messages.error(request, msg) if settings.DEBUG: msg += ("DEBUG set to True: " + htmlprint.html_exc()) return HttpResponseNotFound(msg)
def checkout_option(request, filebrowser, target): """ Execute a checkout of the targeted entry with the informations of POST. """ if request.method != 'POST': return HttpResponseNotAllowed(['POST']) if not filebrowser.directory: d = Directory.objects.get(name=target) done, msg = d.checkout() else: done, msg = filebrowser.directory.checkout( path=filebrowser.full_path() + '/' + target) if done: messages.success(request, "Checkout done.<br>" + htmlprint.code(msg)) else: messages.error(request, "Couldn't checkout:<br>" + htmlprint.code(msg)) return redirect_fb(request.POST.get('relative_h', '.'))
def push(request): """ Execute a git push on the targeted entry with the informations of POST.""" post = json.loads(request.body.decode()) username = post.get('username', None) password = post.get('password', None) path = post.get('path', None) if not path: return HttpResponseBadRequest(missing_parameter('path')) ret, out, err = gitcmd.push(join_fb_root(path), username=username, password=password) if not ret: return HttpResponse(htmlprint.code(out + err)) else: # pragma: no cover return HttpResponseNotFound(htmlprint.code(err + out))
def test_code(self): s = h.code("def sqrt(x): return x*x") print(s) self.assertIn("def sqrt(x): return x*x", s) self.assertTrue('<code' in s) self.assertTrue('<pre' in s) self.assertTrue('</code>' in s) self.assertTrue('</pre>' in s)
def preview_pl(request): """ Used by the PL editor to preview a PL and test the preview's answers""" if request.method != 'POST': return HttpResponse('405 Method Not Allowed', status=405) post = json.loads(request.body.decode()) if post['requested_action'] == 'preview': # Asking for preview try: path = settings.FILEBROWSER_ROOT + '/' + post['path'] shutil.copyfile(path, path + ".bk") with open(path, 'w+') as f: # Writting editor content into the file print(post['content'], file=f) directory = Directory.objects.get(name=post['directory']) rel_path = post['path'].replace(directory.name, "") pl, warnings = load_file(directory, rel_path) if not pl: preview = '<div class="alert alert-danger" role="alert"> Failed to load \'' + basename( rel_path) + "': \n" + warnings + "</div>" else: if warnings: [ messages.warning(request, warning) for warning in warnings ] exercise = PLInstance(pl.json) request.session['exercise'] = dict(exercise.dic) preview = exercise.render(request) except Exception as e: preview = '<div class="alert alert-danger" role="alert"> Failed to load \'' \ + basename(rel_path) + "': \n\n" \ + htmlprint.code(str(e)) + "</div>" finally: shutil.move(path + ".bk", path) return HttpResponse(json.dumps({'preview': preview}), content_type='application/json') elif post['requested_action'] == 'submit': # Answer from the preview exercise = request.session.get('exercise', None) if exercise: exercise = PLInstance(exercise) success, feedback = exercise.evaluate(post['inputs']) if (success == None): feedback_type = "info" elif success: feedback_type = "success" else: feedback_type = "failed" return HttpResponse(json.dumps({ 'feedback_type': feedback_type, 'feedback': feedback }), content_type='application/json') return HttpResponseBadRequest(content="Couldn't resolve ajax request")
def push_option(request, filebrowser, target): """ Execute a git push on the targeted entry with the informations of POST.""" if request.method != 'POST': return HttpResponseNotAllowed(['POST']) username = request.POST.get('username', None) password = request.POST.get('password', None) if not filebrowser.directory: d = Directory.objects.get(name=target) done, msg = d.push(username=username, password=password) else: done, msg = filebrowser.directory.push(username=username, password=password) if done: messages.success(request, "Push done.<br>" + htmlprint.code(msg)) else: messages.error(request, "Couldn't push:<br>" + htmlprint.code(msg)) return redirect_fb(request.POST.get('relative_h', '.'))