Commit 0c8d0b5a authored by Floreal Cabanettes's avatar Floreal Cabanettes
Browse files

Start working on ajax uploading (not working yet)

parent dc87e236
[global]
upload_folder = /home/fcabanettes/public_html/tmp
data_folder = /home/fcabanettes/public_html/test
# batch system type: local, sge, slurm
batch_system_type = local
......
......@@ -395,4 +395,89 @@ table.drawtooltip td.tt-label {
div.navbar {
background-image: linear-gradient(to bottom,#2B3044 0, #141a30 100%);
}
.input-group {
display: inline-block;
}
.input-group .input-group-btn, .input-group input {
display: inline-block !important;
position: relative !important;
float: none !important;
}
div.in-label {
position: relative;
display: inline-block;
width: 300px;
height: 30px;
}
div.progress {
display: none;
width: 300px;
height: 30px;
position: absolute;
top: 0;
left: 0;
z-index: 10;
opacity: 0.5;
}
div.progress .bar {
height: 100%;
background: green;
}
select.select-type-input, .input-group button, .input-group input {
height: 30px;
line-height: 30px;
}
.input-group button {
padding-top: 0;
}
div.input-group {
padding-left: 15px !important;
}
.upload-btn-wrapper {
position: relative;
height: 30px;
width: 42px;
overflow: hidden;
display: inline-block;
}
.upload-btn-wrapper button {
position: absolute;
top: 0;
left: 0;
height: 30px;
width: 42px;
}
/*.btn {*/
/*border: 2px solid gray;*/
/*color: black;*/
/*background-color: white;*/
/*border-radius: 8px;*/
/*font-size: 20px;*/
/*font-weight: bold;*/
/*}*/
.upload-btn-wrapper input[type=file] {
font-size: 100px;
position: absolute;
left: 0;
top: 0;
opacity: 0;
}
input.show-file {
padding-left: 2px;
padding-right: 2px;
width: auto;
}
\ No newline at end of file
......@@ -18,7 +18,7 @@ d3.boxplot.events.init = function () {
});
$("input#chroms-limits").change(function() {
d3.boxplot.events.set_break_lines_visibility(this.value);
})
});
};
d3.boxplot.events.set_break_lines_visibility = function(value) {
......
if (!dgenies) {
throw "dgenies wasn't included!"
}
dgenies.run = {};
// Init global variables:
dgenies.run.files = [];
dgenies.run.upload_folder = [];
dgenies.run.init = function () {
dgenies.run.set_events();
dgenies.run.init_fileuploads();
};
dgenies.run.init_fileuploads = function () {
$('input.file-query').fileupload({
dataType: 'json',
formData: {folder: dgenies.run.upload_folder},
add: function (e, data) {
dgenies.run.files.push(data);
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress-query').find('.bar').css(
'width',
progress + '%'
);
},
success: function (data, success) {
console.log(data);
dgenies.run.upload_folder[0] = data["folder"];
console.log(dgenies.run.upload_folder);
if (dgenies.run.files.length > 0) {
dgenies.run.files.shift().submit();
}
}
});
$('input.file-target').fileupload({
dataType: 'json',
formData: {folder: dgenies.run.upload_folder},
add: function (e, data) {
dgenies.run.files.push(data);
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress-target').find('.bar').css(
'width',
progress + '%'
);
},
success: function (data, success) {
dgenies.run.upload_folder[0] = data["folder"];
if (dgenies.run.files.length > 0) {
dgenies.run.files.shift().submit();
}
}
});
}
dgenies.run.set_events = function() {
$("input.file-query").change(function () {
if (this.files.length > 0)
dgenies.run.set_filename(this.files[0].name, "query");
else
dgenies.run.set_filename("", "query");
});
$("input.file-target").change(function () {
if (this.files.length > 0)
dgenies.run.set_filename(this.files[0].name, "target");
else
dgenies.run.set_filename("", "target");
});
$("button#submit").click(function () {
dgenies.run.submit();
});
};
dgenies.run.set_filename = function (name, fasta) {
$("input#" + fasta).val(name);
};
dgenies.run.submit = function () {
console.log("submit!");
$("div#progress-query").show();
$("div#progress-target").show();
if (dgenies.run.files.length > 0) {
dgenies.run.files.shift().submit();
}
};
\ No newline at end of file
/*
* jQuery File Upload Processing Plugin 1.3.0
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2012, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/* jshint nomen:false */
/* global define, window */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define([
'jquery',
'./jquery.fileupload'
], factory);
} else {
// Browser globals:
factory(
window.jQuery
);
}
}(function ($) {
'use strict';
var originalAdd = $.blueimp.fileupload.prototype.options.add;
// The File Upload Processing plugin extends the fileupload widget
// with file processing functionality:
$.widget('blueimp.fileupload', $.blueimp.fileupload, {
options: {
// The list of processing actions:
processQueue: [
/*
{
action: 'log',
type: 'debug'
}
*/
],
add: function (e, data) {
var $this = $(this);
data.process(function () {
return $this.fileupload('process', data);
});
originalAdd.call(this, e, data);
}
},
processActions: {
/*
log: function (data, options) {
console[options.type](
'Processing "' + data.files[data.index].name + '"'
);
}
*/
},
_processFile: function (data, originalData) {
var that = this,
dfd = $.Deferred().resolveWith(that, [data]),
chain = dfd.promise();
this._trigger('process', null, data);
$.each(data.processQueue, function (i, settings) {
var func = function (data) {
if (originalData.errorThrown) {
return $.Deferred()
.rejectWith(that, [originalData]).promise();
}
return that.processActions[settings.action].call(
that,
data,
settings
);
};
chain = chain.pipe(func, settings.always && func);
});
chain
.done(function () {
that._trigger('processdone', null, data);
that._trigger('processalways', null, data);
})
.fail(function () {
that._trigger('processfail', null, data);
that._trigger('processalways', null, data);
});
return chain;
},
// Replaces the settings of each processQueue item that
// are strings starting with an "@", using the remaining
// substring as key for the option map,
// e.g. "@autoUpload" is replaced with options.autoUpload:
_transformProcessQueue: function (options) {
var processQueue = [];
$.each(options.processQueue, function () {
var settings = {},
action = this.action,
prefix = this.prefix === true ? action : this.prefix;
$.each(this, function (key, value) {
if ($.type(value) === 'string' &&
value.charAt(0) === '@') {
settings[key] = options[
value.slice(1) || (prefix ? prefix +
key.charAt(0).toUpperCase() + key.slice(1) : key)
];
} else {
settings[key] = value;
}
});
processQueue.push(settings);
});
options.processQueue = processQueue;
},
// Returns the number of files currently in the processsing queue:
processing: function () {
return this._processing;
},
// Processes the files given as files property of the data parameter,
// returns a Promise object that allows to bind callbacks:
process: function (data) {
var that = this,
options = $.extend({}, this.options, data);
if (options.processQueue && options.processQueue.length) {
this._transformProcessQueue(options);
if (this._processing === 0) {
this._trigger('processstart');
}
$.each(data.files, function (index) {
var opts = index ? $.extend({}, options) : options,
func = function () {
if (data.errorThrown) {
return $.Deferred()
.rejectWith(that, [data]).promise();
}
return that._processFile(opts, data);
};
opts.index = index;
that._processing += 1;
that._processingQueue = that._processingQueue.pipe(func, func)
.always(function () {
that._processing -= 1;
if (that._processing === 0) {
that._trigger('processstop');
}
});
});
}
return this._processingQueue;
},
_create: function () {
this._super();
this._processing = 0;
this._processingQueue = $.Deferred().resolveWith(this)
.promise();
}
});
}));
/*
* jQuery File Upload Validation Plugin 1.1.2
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2013, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/* global define, window */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define([
'jquery',
'./jquery.fileupload-process'
], factory);
} else {
// Browser globals:
factory(
window.jQuery
);
}
}(function ($) {
'use strict';
// Append to the default processQueue:
$.blueimp.fileupload.prototype.options.processQueue.push(
{
action: 'validate',
// Always trigger this action,
// even if the previous action was rejected:
always: true,
// Options taken from the global options map:
acceptFileTypes: '@',
maxFileSize: '@',
minFileSize: '@',
maxNumberOfFiles: '@',
disabled: '@disableValidation'
}
);
// The File Upload Validation plugin extends the fileupload widget
// with file validation functionality:
$.widget('blueimp.fileupload', $.blueimp.fileupload, {
options: {
/*
// The regular expression for allowed file types, matches
// against either file type or file name:
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
// The maximum allowed file size in bytes:
maxFileSize: 10000000, // 10 MB
// The minimum allowed file size in bytes:
minFileSize: undefined, // No minimal file size
// The limit of files to be uploaded:
maxNumberOfFiles: 10,
*/
// Function returning the current number of files,
// has to be overriden for maxNumberOfFiles validation:
getNumberOfFiles: $.noop,
// Error and info messages:
messages: {
maxNumberOfFiles: 'Maximum number of files exceeded',
acceptFileTypes: 'File type not allowed',
maxFileSize: 'File is too large',
minFileSize: 'File is too small'
}
},
processActions: {
validate: function (data, options) {
if (options.disabled) {
return data;
}
var dfd = $.Deferred(),
settings = this.options,
file = data.files[data.index],
fileSize;
if (options.minFileSize || options.maxFileSize) {
fileSize = file.size;
}
if ($.type(options.maxNumberOfFiles) === 'number' &&
(settings.getNumberOfFiles() || 0) + data.files.length >
options.maxNumberOfFiles) {
file.error = settings.i18n('maxNumberOfFiles');
} else if (options.acceptFileTypes &&
!(options.acceptFileTypes.test(file.type) ||
options.acceptFileTypes.test(file.name))) {
file.error = settings.i18n('acceptFileTypes');
} else if (fileSize > options.maxFileSize) {
file.error = settings.i18n('maxFileSize');
} else if ($.type(fileSize) === 'number' &&
fileSize < options.minFileSize) {
file.error = settings.i18n('minFileSize');
} else {
delete file.error;
}
if (file.error || data.files.error) {
data.files.error = true;
dfd.rejectWith(this, [data]);
} else {
dfd.resolveWith(this, [data]);
}
return dfd.promise();
}
}
});
}));
This diff is collapsed.
import os
class uploadfile():
def __init__(self, name, type=None, size=None, not_allowed_msg=''):
self.name = name
self.type = type
self.size = size
self.not_allowed_msg = not_allowed_msg
self.url = "data/%s" % name
def get_file(self):
if self.type != None:
# POST an image
if self.type.startswith('image'):
return {"name": self.name,
"type": self.type,
"size": self.size,
"url": self.url}
# POST an normal file
elif self.not_allowed_msg == '':
return {"name": self.name,
"type": self.type,
"size": self.size,
"url": self.url}
# File type is not allowed
else:
return {"error": self.not_allowed_msg,
"name": self.name,
"type": self.type,
"size": self.size}
# GET normal file from disk
else:
return {"name": self.name,
"size": self.size,
"url": self.url}
......@@ -15,6 +15,12 @@ class AppConfigReader(object):
self.reader = RawConfigParser()
self.reader.read(os.path.join(os.path.dirname(inspect.getfile(self.__class__)), self.CONFIG_FILE_PATH))
def get_upload_folder(self):
try:
return self.reader.get("global", "upload_folder")
except NoOptionError:
raise Exception("No upload folder found in application.properties (global section)")
def get_app_data(self):
try:
return self.reader.get("global", "data_folder")
......
......@@ -8,6 +8,7 @@ from lib.paf import Paf
from config_reader import AppConfigReader
from lib.job_manager import JobManager
from lib.functions import *
from lib.upload_file import uploadfile
import sys
app_folder = os.path.dirname(os.path.realpath(__file__))
......@@ -20,10 +21,13 @@ sqlite_file = os.path.join(app_folder, "database.sqlite")
# Init config reader:
config_reader = AppConfigReader()
UPLOAD_FOLDER = config_reader.get_upload_folder()
app_title = "D-GENIES - Dotplot for Genomes Interactive, E-connected and Speedy"
# Init Flask:
app = Flask(__name__, static_url_path='/static')
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['SECRET_KEY'] = 'dsqdsq-255sdA-fHfg52-25Asd5'
# Folder containing data:
......@@ -168,5 +172,43 @@ def sort_graph(id_res):
return jsonify({"success": False, "message": paf.error})
@app.route("/upload", methods=['POST'])
def upload():
folder = request.form["folder"]
print(folder)
files = request.files[list(request.files.keys())[0]]
if files:
filename = files.filename
folder_files = os.path.join(app.config["UPLOAD_FOLDER"], folder)
if folder == "null" or not os.path.exists(folder_files):
folder_files = os.path.join(app.config["UPLOAD_FOLDER"], random_string(5) + "_" +
datetime.datetime.fromtimestamp(time.time()).strftime('%Y%m%d%H%M%S'))
while os.path.exists(folder_files):
folder_files = os.path.join(app.config["UPLOAD_FOLDER"], random_string(5) + "_" +
datetime.datetime.fromtimestamp(time.time()).strftime('%Y%m%d%H%M%S'))
os.makedirs(folder_files)
filename = get_valid_uploaded_filename(filename, folder_files)
mime_type = files.content_type
if not allowed_file(files.filename):
result = uploadfile(name=filename, type=mime_type, size=0, not_allowed_msg="File type not allowed")
else:
# save file to disk
uploaded_file_path = os.path.join(folder_files, filename)
files.save(uploaded_file_path)
# get file size after saving
size = os.path.getsize(uploaded_file_path)
# return json for js call back
result = uploadfile(name=filename, type=mime_type, size=size)
return jsonify({"files": [result.get_file()], "folder": os.