cryptpad/www/form/export.js

80 lines
2.5 KiB
JavaScript
Raw Normal View History

2021-06-24 13:59:38 +00:00
define([
'/common/common-util.js',
'/customize/messages.js'
], function (Util, Messages) {
var Export = {};
var escapeCSV = function (v) {
2021-06-30 10:47:02 +00:00
if (!/("|,|\n|;)/.test(v)) {
2021-06-24 13:59:38 +00:00
return v || '';
}
var value = '';
var vv = (v || '').replaceAll('"', '""');
value += '"' + vv + '"';
return value;
};
Export.results = function (content, answers, TYPES, order, isArray) {
2021-06-24 13:59:38 +00:00
if (!content || !content.form) { return; }
var csv = "";
2021-09-24 13:53:44 +00:00
var array = [];
2021-06-24 13:59:38 +00:00
var form = content.form;
2021-07-06 14:09:30 +00:00
var questions = [Messages.form_poll_time, Messages.share_formView];
order.forEach(function (key) {
2021-06-24 13:59:38 +00:00
var obj = form[key];
if (!obj) { return; }
2021-07-06 14:09:30 +00:00
var type = obj.type;
if (!TYPES[type]) { return; } // Ignore static types
var c;
if (TYPES[type] && TYPES[type].exportCSV) { c = TYPES[type].exportCSV(false, obj); }
if (!c) { c = [obj.q || Messages.form_default]; }
Array.prototype.push.apply(questions, c);
});
2021-06-24 13:59:38 +00:00
questions.forEach(function (v, i) {
if (i) { csv += ','; }
csv += escapeCSV(v);
});
2021-09-24 13:53:44 +00:00
array.push(questions);
2021-06-24 13:59:38 +00:00
Object.keys(answers || {}).forEach(function (key) {
var obj = answers[key];
csv += '\n';
var time = new Date(obj.time).toISOString();
var msg = obj.msg || {};
2021-06-30 10:36:24 +00:00
var user = msg._userdata || {};
2021-09-24 13:53:44 +00:00
var line = [];
line.push(time);
line.push(user.name || Messages.anonymous);
order.forEach(function (key) {
2021-06-30 10:47:02 +00:00
var type = form[key].type;
2021-07-06 14:09:30 +00:00
if (!TYPES[type]) { return; } // Ignore static types
if (TYPES[type].exportCSV) {
2021-09-24 13:53:44 +00:00
var res = TYPES[type].exportCSV(msg[key], form[key]);
Array.prototype.push.apply(line, res);
2021-06-30 10:47:02 +00:00
return;
}
2021-09-24 13:53:44 +00:00
line.push(String(msg[key] || ''));
2021-06-24 13:59:38 +00:00
});
2021-09-24 13:53:44 +00:00
line.forEach(function (v, i) {
if (i) { csv += ','; }
csv += escapeCSV(v);
});
array.push(line);
2021-06-24 13:59:38 +00:00
});
2021-09-24 13:53:44 +00:00
if (isArray) { return array; }
2021-06-24 13:59:38 +00:00
return csv;
};
Export.main = function (content, cb) {
var json = Util.clone(content || {});
delete json.answers;
cb(new Blob([JSON.stringify(json, 0, 2)], {
type: 'application/json;charset=utf-8'
}));
};
return Export;
});