♻️ Make timelapse bulk download server side
This commit is contained in:
1 parent
211669db1c
commit
c4ec17c1ff
9 files changed
+126
-94
No files matched your search
@@ -11,11 +11,9 @@
|
||||
* [Bootstrap Tabdrop](http://www.eyecon.ro/bootstrap-tabdrop): Apache License 2.0
|
||||
* [css-element-queries](https://github.com/marcj/css-element-queries): MIT
|
||||
* [Detect Mobile Browser](http://detectmobilebrowsers.com/): Public Domain
|
||||
* [FileSaver.js](https://github.com/eligrey/FileSaver.js): MIT
|
||||
* [Flot](http://www.flotcharts.org/): MIT
|
||||
* [HLS.js](https://github.com/video-dev/hls.js): Apache License 2.0
|
||||
* [JavaScript MD5](https://github.com/blueimp/JavaScript-MD5): MIT
|
||||
* [JSZip](https://github.com/Stuk/jszip): MIT, GPLv3 (dual licensed)
|
||||
* [JQuery](http://jquery.com/): MIT
|
||||
* [JQuery Bootstrap Wizard](http://github.com/VinceG/twitter-bootstrap-wizard): MIT, GPL (dual licensed)
|
||||
* [JQuery File Upload](https://github.com/blueimp/jQuery-File-Upload): MIT
|
||||
|
||||
@@ -754,6 +754,13 @@ class Server(object):
|
||||
status_code=404,
|
||||
)
|
||||
}
|
||||
timelapses_path_validator = {
|
||||
"path_validation": util.tornado.path_validation_factory(
|
||||
lambda path: not octoprint.util.is_hidden_path(path)
|
||||
and octoprint.timelapse.valid_timelapse(path),
|
||||
status_code=400,
|
||||
)
|
||||
}
|
||||
|
||||
def joined_dict(*dicts):
|
||||
if not len(dicts):
|
||||
@@ -780,6 +787,23 @@ class Server(object):
|
||||
timelapse_path_validator,
|
||||
),
|
||||
),
|
||||
# zipped timelapse bundles
|
||||
(
|
||||
r"/downloads/timelapses",
|
||||
util.tornado.DynamicZipBundleHandler,
|
||||
joined_dict(
|
||||
{
|
||||
"as_attachment": True,
|
||||
"attachment_name": "octoprint-timelapses.zip",
|
||||
"path_processor": lambda x: (
|
||||
x,
|
||||
os.path.join(self._settings.getBaseFolder("timelapse"), x),
|
||||
),
|
||||
},
|
||||
timelapse_permission_validator,
|
||||
timelapses_path_validator,
|
||||
),
|
||||
),
|
||||
# uploaded printables
|
||||
(
|
||||
r"/downloads/files/local/(.*)",
|
||||
@@ -1973,7 +1997,6 @@ class Server(object):
|
||||
"js/lib/ResizeSensor.js",
|
||||
"js/lib/less.min.js",
|
||||
"js/lib/hls.js",
|
||||
"js/lib/jszip.min.js",
|
||||
"js/lib/FileSaver.min.js",
|
||||
]
|
||||
js_client = [
|
||||
|
||||
@@ -1468,6 +1468,71 @@ class StaticZipBundleHandler(CorsSupportMixin, tornado.web.RequestHandler):
|
||||
return
|
||||
|
||||
|
||||
class DynamicZipBundleHandler(StaticZipBundleHandler):
|
||||
# noinspection PyMethodOverriding
|
||||
def initialize(
|
||||
self,
|
||||
path_validation=None,
|
||||
path_processor=None,
|
||||
as_attachment=True,
|
||||
attachment_name=None,
|
||||
access_validation=None,
|
||||
):
|
||||
if as_attachment and not attachment_name:
|
||||
raise ValueError("attachment name must be set if as_attachment is True")
|
||||
|
||||
self._path_validator = path_validation
|
||||
self._path_processor = path_processor
|
||||
self._as_attachment = as_attachment
|
||||
self._attachment_name = attachment_name
|
||||
self._access_validator = access_validation
|
||||
|
||||
def get(self, *args, **kwargs):
|
||||
if self._access_validator is not None:
|
||||
self._access_validator(self.request)
|
||||
|
||||
files = list(
|
||||
map(octoprint.util.to_unicode, self.request.query_arguments.get("files", []))
|
||||
)
|
||||
return self._get_files_zip(files)
|
||||
|
||||
def post(self, *args, **kwargs):
|
||||
if self._access_validator is not None:
|
||||
self._access_validator(self.request)
|
||||
|
||||
import json
|
||||
|
||||
content_type = self.request.headers.get("Content-Type", "")
|
||||
try:
|
||||
if "application/json" in content_type:
|
||||
data = json.loads(self.request.body)
|
||||
else:
|
||||
data = self.request.body_arguments
|
||||
except Exception:
|
||||
raise tornado.web.HTTPError(400)
|
||||
|
||||
return self._get_files_zip(
|
||||
list(map(octoprint.util.to_unicode, data.get("files", [])))
|
||||
)
|
||||
|
||||
def _get_files_zip(self, files):
|
||||
files = self.normalize_files(files)
|
||||
if not files:
|
||||
raise tornado.web.HTTPError(400)
|
||||
|
||||
for f in files:
|
||||
if "path" in f:
|
||||
if callable(self._path_processor):
|
||||
path = self._path_processor(f["path"])
|
||||
if isinstance(path, tuple):
|
||||
f["name"], f["path"] = path
|
||||
else:
|
||||
f["path"] = path
|
||||
self._path_validator(f["path"])
|
||||
|
||||
return self.stream_zip(files)
|
||||
|
||||
|
||||
class SystemInfoBundleHandler(StaticZipBundleHandler):
|
||||
# noinspection PyMethodOverriding
|
||||
def initialize(self, access_validation=None):
|
||||
|
||||
@@ -216,6 +216,16 @@
|
||||
return this.get(url, params);
|
||||
};
|
||||
|
||||
OctoPrintClient.prototype.bulkDownloadUrl = function (url, files) {
|
||||
return (
|
||||
url +
|
||||
"?" +
|
||||
_.map(files, function (f) {
|
||||
return "files=" + encodeURIComponent(f);
|
||||
}).join("&")
|
||||
);
|
||||
};
|
||||
|
||||
OctoPrintClient.prototype.upload = function (url, file, filename, additional) {
|
||||
additional = additional || {};
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
var url = "api/timelapse";
|
||||
|
||||
var downloadUrl = "downloads/timelapse";
|
||||
var bulkDownloadUrl = "downloads/timelapses";
|
||||
|
||||
var timelapseUrl = function (filename) {
|
||||
return url + "/" + filename;
|
||||
@@ -86,6 +87,10 @@
|
||||
return this.base.download(timelapseDownloadUrl(filename), opts);
|
||||
};
|
||||
|
||||
OctoPrintTimelapseClient.prototype.bulkDownloadUrl = function (filenames) {
|
||||
return this.base.bulkDownloadUrl(bulkDownloadUrl, filenames);
|
||||
};
|
||||
|
||||
OctoPrintTimelapseClient.prototype.delete = function (filename, opts) {
|
||||
return this.base.delete(timelapseUrl(filename), opts);
|
||||
};
|
||||
|
||||
@@ -377,83 +377,29 @@ $(function () {
|
||||
);
|
||||
};
|
||||
|
||||
self.downloadMarkedFiles = function () {
|
||||
if (
|
||||
!self.loginState.hasPermission(self.access.permissions.TIMELAPSE_DOWNLOAD)
|
||||
)
|
||||
return;
|
||||
self.enableBulkDownload = ko.pureComputed(function () {
|
||||
return (
|
||||
self.markedForFileDeletion().length &&
|
||||
!self.isBusy() &&
|
||||
!self.bulkDownloadUrlTooLong()
|
||||
);
|
||||
});
|
||||
|
||||
self.bulkDownloadUrlTooLong = ko.pureComputed(function () {
|
||||
return BASEURL.length + self.bulkDownloadUrl().length >= 2000;
|
||||
});
|
||||
|
||||
self.bulkDownloadButtonUrl = ko.pureComputed(function () {
|
||||
var files = self.markedForFileDeletion();
|
||||
var zip = new JSZip();
|
||||
if (!files.length || self.bulkDownloadUrlTooLong()) {
|
||||
return "javascript:void(0)";
|
||||
}
|
||||
return self.bulkDownloadUrl();
|
||||
});
|
||||
|
||||
var handler = function (filename) {
|
||||
let curTimelapse = self.listHelper.allItems.find(
|
||||
(item) => item.name === _.escape(filename)
|
||||
);
|
||||
return fetch(curTimelapse.url)
|
||||
.then(
|
||||
function (content) {
|
||||
zip.file(_.escape(filename), content.blob());
|
||||
deferred.notify(
|
||||
_.sprintf(gettext("Packed %(filename)s"), {
|
||||
filename: _.escape(filename)
|
||||
}),
|
||||
true
|
||||
);
|
||||
},
|
||||
function (reason) {
|
||||
var short = _.sprintf(
|
||||
gettext("Packing of %(filename)s failed, continuing..."),
|
||||
{filename: _.escape(filename)}
|
||||
);
|
||||
var long = _.sprintf(
|
||||
gettext("Packing of %(filename)s failed: %(error)s"),
|
||||
{
|
||||
filename: _.escape(filename),
|
||||
error: _.escape(reason.responseText)
|
||||
}
|
||||
);
|
||||
deferred.notify(short, long, false);
|
||||
}
|
||||
)
|
||||
.finally(function () {
|
||||
var d = $.Deferred();
|
||||
d.resolve.apply(d, arguments);
|
||||
});
|
||||
};
|
||||
|
||||
var deferred = $.Deferred();
|
||||
var promise = deferred.promise();
|
||||
|
||||
var options = {
|
||||
title: gettext("Packing files"),
|
||||
max: files.length,
|
||||
output: true
|
||||
};
|
||||
var dialog = showProgressModal(options, promise);
|
||||
|
||||
var requests = [];
|
||||
_.each(files, function (filename) {
|
||||
let request = handler(filename);
|
||||
requests.push(request);
|
||||
});
|
||||
|
||||
$.when.apply($, requests).done(function () {
|
||||
deferred.resolve();
|
||||
self.requestData();
|
||||
});
|
||||
|
||||
promise.then(function () {
|
||||
zip.generateAsync({
|
||||
type: "blob",
|
||||
compression: "STORE"
|
||||
}).then(function (blob) {
|
||||
saveAs(blob, "OctoPrint-Timelapses.zip");
|
||||
dialog.modal("hide");
|
||||
});
|
||||
});
|
||||
|
||||
return promise;
|
||||
self.bulkDownloadUrl = function () {
|
||||
var files = self.markedForFileDeletion();
|
||||
return OctoPrint.timelapse.bulkDownloadUrl(files);
|
||||
};
|
||||
|
||||
self.markUnrenderedOnPage = function () {
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
(function(a,b){if("function"==typeof define&&define.amd)define([],b);else if("undefined"!=typeof exports)b();else{b(),a.FileSaver={exports:{}}.exports}})(this,function(){"use strict";function b(a,b){return"undefined"==typeof b?b={autoBom:!1}:"object"!=typeof b&&(console.warn("Deprecated: Expected third argument to be a object"),b={autoBom:!b}),b.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(a.type)?new Blob(["\uFEFF",a],{type:a.type}):a}function c(a,b,c){var d=new XMLHttpRequest;d.open("GET",a),d.responseType="blob",d.onload=function(){g(d.response,b,c)},d.onerror=function(){console.error("could not download file")},d.send()}function d(a){var b=new XMLHttpRequest;b.open("HEAD",a,!1);try{b.send()}catch(a){}return 200<=b.status&&299>=b.status}function e(a){try{a.dispatchEvent(new MouseEvent("click"))}catch(c){var b=document.createEvent("MouseEvents");b.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),a.dispatchEvent(b)}}var f="object"==typeof window&&window.window===window?window:"object"==typeof self&&self.self===self?self:"object"==typeof global&&global.global===global?global:void 0,a=/Macintosh/.test(navigator.userAgent)&&/AppleWebKit/.test(navigator.userAgent)&&!/Safari/.test(navigator.userAgent),g=f.saveAs||("object"!=typeof window||window!==f?function(){}:"download"in HTMLAnchorElement.prototype&&!a?function(b,g,h){var i=f.URL||f.webkitURL,j=document.createElement("a");g=g||b.name||"download",j.download=g,j.rel="noopener","string"==typeof b?(j.href=b,j.origin===location.origin?e(j):d(j.href)?c(b,g,h):e(j,j.target="_blank")):(j.href=i.createObjectURL(b),setTimeout(function(){i.revokeObjectURL(j.href)},4E4),setTimeout(function(){e(j)},0))}:"msSaveOrOpenBlob"in navigator?function(f,g,h){if(g=g||f.name||"download","string"!=typeof f)navigator.msSaveOrOpenBlob(b(f,h),g);else if(d(f))c(f,g,h);else{var i=document.createElement("a");i.href=f,i.target="_blank",setTimeout(function(){e(i)})}}:function(b,d,e,g){if(g=g||open("","_blank"),g&&(g.document.title=g.document.body.innerText="downloading..."),"string"==typeof b)return c(b,d,e);var h="application/octet-stream"===b.type,i=/constructor/i.test(f.HTMLElement)||f.safari,j=/CriOS\/[\d]+/.test(navigator.userAgent);if((j||h&&i||a)&&"undefined"!=typeof FileReader){var k=new FileReader;k.onloadend=function(){var a=k.result;a=j?a:a.replace(/^data:[^;]*;/,"data:attachment/file;"),g?g.location.href=a:location=a,g=null},k.readAsDataURL(b)}else{var l=f.URL||f.webkitURL,m=l.createObjectURL(b);g?g.location=m:location.href=m,g=null,setTimeout(function(){l.revokeObjectURL(m)},4E4)}});f.saveAs=g.saveAs=g,"undefined"!=typeof module&&(module.exports=g)});
|
||||
|
||||
//# sourceMappingURL=FileSaver.min.js.map
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
/*!
|
||||
|
||||
JSZip v3.5.0 - A JavaScript class for generating and reading zip files
|
||||
<http://stuartk.com/jszip>
|
||||
|
||||
(c) 2009-2016 Stuart Knightley <stuart [at] stuartk.com>
|
||||
Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/master/LICENSE.markdown.
|
||||
|
||||
JSZip uses the library pako released under the MIT license :
|
||||
https://github.com/nodeca/pako/blob/master/LICENSE
|
||||
*/
|
||||
|
||||
!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).JSZip=t()}}(function(){return function s(a,o,h){function u(r,t){if(!o[r]){if(!a[r]){var e="function"==typeof require&&require;if(!t&&e)return e(r,!0);if(l)return l(r,!0);var i=new Error("Cannot find module '"+r+"'");throw i.code="MODULE_NOT_FOUND",i}var n=o[r]={exports:{}};a[r][0].call(n.exports,function(t){var e=a[r][1][t];return u(e||t)},n,n.exports,s,a,o,h)}return o[r].exports}for(var l="function"==typeof require&&require,t=0;t<h.length;t++)u(h[t]);return u}({1:[function(t,e,r){"use strict";var c=t("./utils"),d=t("./support"),p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";r.encode=function(t){for(var e,r,i,n,s,a,o,h=[],u=0,l=t.length,f=l,d="string"!==c.getTypeOf(t);u<t.length;)f=l-u,i=d?(e=t[u++],r=u<l?t[u++]:0,u<l?t[u++]:0):(e=t.charCodeAt(u++),r=u<l?t.charCodeAt(u++):0,u<l?t.charCodeAt(u++):0),n=e>>2,s=(3&e)<<4|r>>4,a=1<f?(15&r)<<2|i>>6:64,o=2<f?63&i:64,h.push(p.charAt(n)+p.charAt(s)+p.charAt(a)+p.charAt(o));return h.join("")},r.decode=function(t){var e,r,i,n,s,a,o=0,h=0,u="data:";if(t.substr(0,u.length)===u)throw new Error("Invalid base64 input, it looks like a data url.");var l,f=3*(t=t.replace(/[^A-Za-z0-9\+\/\=]/g,"")).length/4;if(t.charAt(t.length-1)===p.charAt(64)&&f--,t.charAt(t.length-2)===p.charAt(64)&&f--,f%1!=0)throw new Error("Invalid base64 input, bad content length.");for(l=d.uint8array?new Uint8Array(0|f):new Array(0|f);o<t.length;)e=p.indexOf(t.charAt(o++))<<2|(n=p.indexOf(t.charAt(o++)))>>4,r=(15&n)<<4|(s=p.indexOf(t.charAt(o++)))>>2,i=(3&s)<<6|(a=p.indexOf(t.charAt(o++))),l[h++]=e,64!==s&&(l[h++]=r),64!==a&&(l[h++]=i);return l}},{"./support":30,"./utils":32}],2:[function(t,e,r){"use strict";var i=t("./external"),n=t("./stream/DataWorker"),s=t("./stream/DataLengthProbe"),a=t("./stream/Crc32Probe");s=t("./stream/DataLengthProbe");function o(t,e,r,i,n){this.compressedSize=t,this.uncompressedSize=e,this.crc32=r,this.compression=i,this.compressedContent=n}o.prototype={getContentWorker:function(){var t=new n(i.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new s("data_length")),e=this;return t.on("end",function(){if(this.streamInfo.data_length!==e.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),t},getCompressedWorker:function(){return new n(i.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},o.createWorkerFrom=function(t,e,r){return t.pipe(new a).pipe(new s("uncompressedSize")).pipe(e.compressWorker(r)).pipe(new s("compressedSize")).withStreamInfo("compression",e)},e.exports=o},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(t,e,r){"use strict";var i=t("./stream/GenericWorker");r.STORE={magic:"\0\0",compressWorker:function(t){return new i("STORE compression")},uncompressWorker:function(){return new i("STORE decompression")}},r.DEFLATE=t("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(t,e,r){"use strict";var i=t("./utils");var o=function(){for(var t,e=[],r=0;r<256;r++){t=r;for(var i=0;i<8;i++)t=1&t?3988292384^t>>>1:t>>>1;e[r]=t}return e}();e.exports=function(t,e){return void 0!==t&&t.length?"string"!==i.getTypeOf(t)?function(t,e,r,i){var n=o,s=i+r;t^=-1;for(var a=i;a<s;a++)t=t>>>8^n[255&(t^e[a])];return-1^t}(0|e,t,t.length,0):function(t,e,r,i){var n=o,s=i+r;t^=-1;for(var a=i;a<s;a++)t=t>>>8^n[255&(t^e.charCodeAt(a))];return-1^t}(0|e,t,t.length,0):0}},{"./utils":32}],5:[function(t,e,r){"use strict";r.base64=!1,r.binary=!1,r.dir=!1,r.createFolders=!0,r.date=null,r.compression=null,r.compressionOptions=null,r.comment=null,r.unixPermissions=null,r.dosPermissions=null},{}],6:[function(t,e,r){"use strict";var i=null;i="undefined"!=typeof Promise?Promise:t("lie"),e.exports={Promise:i}},{lie:37}],7:[function(t,e,r){"use strict";var i="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,n=t("pako"),s=t("./utils"),a=t("./stream/GenericWorker"),o=i?"uint8array":"array";function h(t,e){a.call(this,"FlateWorker/"+t),this._pako=null,this._pakoAction=t,this._pakoOptions=e,this.meta={}}r.magic="\b\0",s.inherits(h,a),h.prototype.processChunk=function(t){this.meta=t.meta,null===this._pako&&this._createPako(),this._pako.push(s.transformTo(o,t.data),!1)},h.prototype.flush=function(){a.prototype.flush.call(this),null===this._pako&&this._createPako(),this._pako.push([],!0)},h.prototype.cleanUp=function(){a.prototype.cleanUp.call(this),this._pako=null},h.prototype._createPako=function(){this._pako=new n[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});vaLine truncated
|
||||
@@ -133,7 +133,7 @@
|
||||
</ul>
|
||||
</div>
|
||||
<button class="btn btn-small" data-bind="click: removeMarkedFiles, enable: markedForFileDeletion().length > 0">{{ _('Delete selected') }}</button>
|
||||
<button class="btn btn-small" data-bind="click: downloadMarkedFiles, enable: markedForFileDeletion().length > 0 && !isBusy()">{{_('Download selected')}}</button>
|
||||
<a class="btn btn-small" data-bind="css: { disabled: !enableBulkDownload() }, attr: { href: bulkDownloadButtonUrl }">{{_('Download selected')}}</a>
|
||||
</div>
|
||||
<table class="table table-striped table-hover table-condensed table-hover" id="timelapse_files">
|
||||
<thead>
|
||||
@@ -164,6 +164,7 @@
|
||||
<li data-bind="css: {disabled: listHelper.currentPage() === listHelper.lastPage()}"><a href="javascript:void(0)" data-bind="click: listHelper.nextPage">»</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<small data-bind="visible: bulkDownloadUrlTooLong"><i class="fa fa-warning"></i> {{ _('Too many files selected to download at once. Reduce number of files to enable download button.') }}</small>
|
||||
|
||||
|
||||
<div data-bind="visible: unrenderedListHelper.allSize">
|
||||
|
||||
Reference in new issue
Block a user