Files
cloudron-box/src/js/filemanager.js
2020-07-22 21:41:32 +02:00

598 lines
20 KiB
JavaScript

'use strict';
/* global angular, $, async, monaco, Mimer */
require.config({ paths: { 'vs': '3rdparty/vs' }});
// create main application module
var app = angular.module('Application', ['angular-md5', 'ui-notification', 'ngDrag', 'ui.bootstrap', 'ui.bootstrap.contextMenu']);
angular.module('Application').filter('prettyOwner', function () {
return function (uid) {
if (uid === 0) return 'root';
if (uid === 33) return 'www-data';
if (uid === 1000) return 'cloudron';
if (uid === 1001) return 'git';
return uid;
}
});
// disable sce for footer https://code.angularjs.org/1.5.8/docs/api/ng/service/$sce
app.config(function ($sceProvider) {
$sceProvider.enabled(false);
});
app.filter("trustUrl", ['$sce', function ($sce) {
return function (recordingUrl) {
return $sce.trustAsResourceUrl(recordingUrl);
};
}]);
// https://stackoverflow.com/questions/25621321/angularjs-ng-drag
var ngDragEventDirectives = {};
angular.forEach(
'drag dragend dragenter dragexit dragleave dragover dragstart drop'.split(' '),
function(eventName) {
var directiveName = 'ng' + eventName.charAt(0).toUpperCase() + eventName.slice(1);
ngDragEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
return {
restrict: 'A',
compile: function($element, attr) {
var fn = $parse(attr[directiveName], null, true);
return function ngDragEventHandler(scope, element) {
element.on(eventName, function(event) {
var callback = function() {
fn(scope, {$event: event});
};
scope.$apply(callback);
});
};
}
};
}];
}
);
angular.module('ngDrag', []).directive(ngDragEventDirectives);
app.controller('FileManagerController', ['$scope', '$timeout', 'Client', function ($scope, $timeout, Client) {
var search = decodeURIComponent(window.location.search).slice(1).split('&').map(function (item) { return item.split('='); }).reduce(function (o, k) { o[k[0]] = k[1]; return o; }, {});
$scope.initialized = false;
$scope.status = null;
$scope.busy = true;
$scope.client = Client;
$scope.cwd = '';
$scope.cwdParts = [];
$scope.appId = search.appId;
$scope.app = null;
$scope.entries = [];
$scope.dropToBody = false;
$scope.owners = [
{ name: 'cloudron', value: 1000 },
{ name: 'www-data', value: 33 },
{ name: 'git', value: 1001 },
{ name: 'root', value: 0 }
];
$scope.menuOptions = [
{
text: 'Download',
enabled: function ($itemScope, $event, entry) { return !entry.isDirectory },
click: function ($itemScope, $event, entry) { download(entry); }
}, {
text: 'Rename',
click: function ($itemScope, $event, entry) { $scope.renameEntry.show(entry); }
}, {
text: 'Change Ownership',
click: function ($itemScope, $event, entry) { $scope.chownEntry.show(entry); }
}, {
text: 'Delete',
hasTopDivider: true,
click: function ($itemScope, $event, entry) { $scope.entryRemove.show(entry); }
}
];
var LANGUAGES = [];
require(['vs/editor/editor.main'], function() {
LANGUAGES = monaco.languages.getLanguages();
});
function getLanguage(filename) {
var ext = '.' + filename.split('.').pop();
var language = LANGUAGES.find(function (l) { return !!l.extensions.find(function (e) { return e === ext; }); }) || '';
return language ? language.id : '';
}
function sanitize(filePath) {
filePath = filePath.split('/').filter(function (a) { return !!a; }).reduce(function (a, v) {
if (v === '.'); // do nothing
else if (v === '..') a.pop();
else a.push(v);
return a;
}, []).join('/');
return '/' + filePath;
}
function download(entry) {
var filePath = sanitize($scope.cwd + '/' + entry.fileName);
if (entry.isDirectory) return;
Client.filesGet($scope.appId, filePath, 'download', function (error) {
if (error) return Client.error(error);
});
};
$scope.dragEnter = function ($event, entry) {
$event.originalEvent.stopPropagation();
$event.originalEvent.preventDefault();
if (entry && entry.isDirectory) entry.hovered = true;
else $scope.dropToBody = true;
$event.originalEvent.dataTransfer.dropEffect = 'copy';
}
$scope.dragExit = function ($event, entry) {
$event.originalEvent.stopPropagation();
$event.originalEvent.preventDefault();
if (entry && entry.isDirectory) entry.hovered = false;
$scope.dropToBody = false;
$event.originalEvent.dataTransfer.dropEffect = 'copy';
}
$scope.drop = function (event, entry) {
event.originalEvent.stopPropagation();
event.originalEvent.preventDefault();
$scope.dropToBody = false;
if (!event.originalEvent.dataTransfer.items[0]) return;
var targetFolder = entry && entry.isDirectory ? entry.fileName : '';
// figure if a folder was dropped on a modern browser, in this case the first would have to be a directory
var folderItem;
try {
folderItem = event.originalEvent.dataTransfer.items[0].webkitGetAsEntry();
if (folderItem.isFile) return uploadFiles(event.originalEvent.dataTransfer.files, targetFolder);
} catch (e) {
return uploadFiles(event.originalEvent.dataTransfer.files, targetFolder);
}
// if we got here we have a folder drop and a modern browser
// now traverse the folder tree and create a file list
$scope.uploadStatus.busy = true;
$scope.uploadStatus.count = 0;
var fileList = [];
function traverseFileTree(item, path, callback) {
if (item.isFile) {
// Get file
item.file(function (file) {
fileList.push(file);
++$scope.uploadStatus.count;
callback();
});
} else if (item.isDirectory) {
// Get folder contents
var dirReader = item.createReader();
dirReader.readEntries(function (entries) {
async.each(entries, function (entry, callback) {
traverseFileTree(entry, path + item.name + '/', callback);
}, callback);
});
}
}
traverseFileTree(folderItem, '', function (error) {
$scope.uploadStatus.busy = false;
$scope.uploadStatus.count = 0;
if (error) return console.error(error);
uploadFiles(fileList, targetFolder);
});
}
$scope.refresh = function () {
$scope.busy = true;
Client.filesGet($scope.appId, $scope.cwd, 'data', function (error, result) {
$scope.busy = false;
if (error) return Client.error(error);
$scope.entries = result.entries;
});
};
$scope.open = function (entry) {
if ($scope.busy) return;
var filePath = sanitize($scope.cwd + '/' + entry.fileName);
if (entry.isDirectory) {
$scope.changeDirectory(filePath);
} else if (entry.isFile) {
var mimeType = Mimer().get(entry.fileName);
var mimeGroup = mimeType.split('/')[0];
if (mimeGroup === 'video' || mimeGroup === 'image') {
$scope.mediaViewer.show(entry);
} else if (mimeType === 'application/pdf') {
Client.filesGet($scope.appId, filePath, 'open', function (error) { if (error) return Client.error(error); });
} else if (mimeGroup === 'text' || mimeGroup === 'application') {
$scope.textEditor.show(entry);
} else {
Client.filesGet($scope.appId, filePath, 'open', function (error) { if (error) return Client.error(error); });
}
} else {}
};
$scope.goDirectoryUp = function () {
$scope.changeDirectory($scope.cwd + '/..');
};
$scope.changeDirectory = function (path) {
path = sanitize(path);
if ($scope.cwd === path) return;
location.hash = path;
$scope.cwd = path;
$scope.cwdParts = path.split('/').filter(function (p) { return !!p; }).map(function (p, i) { return { name: p, path: path.split('/').slice(0, i+2).join('/') }; });
$scope.refresh();
};
$scope.uploadStatus = {
busy: false,
fileName: '',
count: 0,
countDone: 0,
size: 0,
done: 0,
percentDone: 0
};
function uploadFiles(files, targetFolder) {
if (!files || !files.length) return;
targetFolder = targetFolder || '';
// prevent it from getting closed
$('#uploadModal').modal({
backdrop: 'static',
keyboard: false
});
$scope.uploadStatus.busy = true;
$scope.uploadStatus.count = files.length;
$scope.uploadStatus.countDone = 0;
$scope.uploadStatus.size = 0;
$scope.uploadStatus.done = 0;
$scope.uploadStatus.percentDone = 0;
for (var i = 0; i < files.length; ++i) {
$scope.uploadStatus.size += files[i].size;
}
async.eachSeries(files, function (file, callback) {
var filePath = sanitize($scope.cwd + '/' + targetFolder + '/' + (file.webkitRelativePath || file.name));
$scope.uploadStatus.fileName = file.name;
Client.filesUpload($scope.appId, filePath, file, function (loaded) {
$scope.uploadStatus.percentDone = ($scope.uploadStatus.done+loaded) * 100 / $scope.uploadStatus.size;
}, function (error) {
if (error) return callback(error);
$scope.uploadStatus.done += file.size;
$scope.uploadStatus.percentDone = $scope.uploadStatus.done * 100 / $scope.uploadStatus.size;
$scope.uploadStatus.countDone++;
callback();
});
}, function (error) {
if (error) console.error(error);
$('#uploadModal').modal('hide');
$scope.uploadStatus.busy = false;
$scope.uploadStatus.fileName = '';
$scope.uploadStatus.count = 0;
$scope.uploadStatus.size = 0;
$scope.uploadStatus.done = 0;
$scope.uploadStatus.percentDone = 100;
$scope.refresh();
});
}
// file upload
$('#uploadFileInput').on('change', function (e) { uploadFiles(e.target.files || []); });
$scope.onUploadFile = function () { $('#uploadFileInput').click(); };
// folder upload
$('#uploadFolderInput').on('change', function (e ) { uploadFiles(e.target.files || []); });
$scope.onUploadFolder = function () { $('#uploadFolderInput').click(); };
$scope.newDirectory = {
busy: false,
error: null,
name: '',
show: function () {
$scope.newDirectory.error = null;
$scope.newDirectory.name = '';
$scope.newDirectory.busy = false;
$scope.newDirectoryForm.$setUntouched();
$scope.newDirectoryForm.$setPristine();
$('#newDirectoryModal').modal('show');
},
submit: function () {
$scope.newDirectory.busy = true;
$scope.newDirectory.error = null;
var filePath = sanitize($scope.cwd + '/' + $scope.newDirectory.name);
Client.filesCreateDirectory($scope.appId, filePath, function (error, result) {
$scope.newDirectory.busy = false;
if (error && error.statusCode === 409) return $scope.newDirectory.error = 'Already exists';
if (error) return Client.error(error);
$scope.refresh();
$('#newDirectoryModal').modal('hide');
});
}
};
$scope.renameEntry = {
busy: false,
error: null,
entry: null,
newName: '',
show: function (entry) {
$scope.renameEntry.error = null;
$scope.renameEntry.entry = entry;
$scope.renameEntry.newName = entry.fileName;
$scope.renameEntry.busy = false;
$('#renameEntryModal').modal('show');
},
submit: function () {
$scope.renameEntry.busy = true;
var oldFilePath = sanitize($scope.cwd + '/' + $scope.renameEntry.entry.fileName);
var newFilePath = sanitize($scope.cwd + '/' + $scope.renameEntry.newName);
Client.filesRename($scope.appId, oldFilePath, newFilePath, function (error, result) {
$scope.renameEntry.busy = false;
if (error) return Client.error(error);
$scope.refresh();
$('#renameEntryModal').modal('hide');
});
}
};
$scope.mediaViewer = {
type: '',
src: '',
entry: null,
show: function (entry) {
var filePath = sanitize($scope.cwd + '/' + entry.fileName);
Client.filesGet($scope.appId, filePath, 'link', function (error, result) {
if (error) return Client.error(error);
$scope.mediaViewer.entry = entry;
$scope.mediaViewer.type = Mimer().get(entry.fileName).split('/')[0];
$scope.mediaViewer.src = result;
$('#mediaViewerModal').modal('show');
});
}
};
$scope.textEditor = {
busy: false,
entry: null,
editor: null,
show: function (entry) {
$scope.textEditor.entry = entry;
$scope.textEditor.busy = false;
// clear model if any
if ($scope.textEditor.editor && $scope.textEditor.editor.getModel()) $scope.textEditor.editor.setModel(null);
$('#textEditorModal').modal('show');
var filePath = sanitize($scope.cwd + '/' + entry.fileName);
var language = getLanguage(entry.fileName);
Client.filesGet($scope.appId, filePath, 'data', function (error, result) {
if (error) return Client.error(error);
if (!$scope.textEditor.editor) {
$timeout(function () {
$scope.textEditor.editor = monaco.editor.create(document.getElementById('textEditorContainer'), {
value: result,
language: language,
theme: 'vs-dark'
});
}, 200);
} else {
$scope.textEditor.editor.setModel(monaco.editor.createModel(result, 'javascript'));
}
});
},
submit: function () {
$scope.textEditor.busy = true;
var newContent = $scope.textEditor.editor.getValue();
var filePath = sanitize($scope.cwd + '/' + $scope.textEditor.entry.fileName);
var file = new File([newContent], 'file');
Client.filesUpload($scope.appId, filePath, file, function () {}, function (error) {
$scope.textEditor.busy = false;
if (error) return Client.error(error);
$('#textEditorModal').modal('hide');
});
}
};
$scope.chownEntry = {
busy: false,
error: null,
entry: null,
newOwner: 0,
recursive: false,
show: function (entry) {
$scope.chownEntry.error = null;
$scope.chownEntry.entry = entry;
$scope.chownEntry.newOwner = entry.uid;
$scope.chownEntry.busy = false;
// default for directories is recursive
$scope.chownEntry.recursive = entry.isDirectory;
$('#chownEntryModal').modal('show');
},
submit: function () {
$scope.chownEntry.busy = true;
var filePath = sanitize($scope.cwd + '/' + $scope.chownEntry.entry.fileName);
Client.filesChown($scope.appId, filePath, $scope.chownEntry.newOwner, $scope.chownEntry.recursive, function (error, result) {
$scope.chownEntry.busy = false;
if (error) return Client.error(error);
$scope.refresh();
$('#chownEntryModal').modal('hide');
});
}
};
$scope.entryRemove = {
busy: false,
error: null,
entry: null,
show: function (entry) {
$scope.entryRemove.error = null;
$scope.entryRemove.entry = entry;
$('#entryRemoveModal').modal('show');
},
submit: function () {
$scope.entryRemove.busy = true;
var filePath = sanitize($scope.cwd + '/' + $scope.entryRemove.entry.fileName);
Client.filesRemove($scope.appId, filePath, function (error, result) {
$scope.entryRemove.busy = false;
if (error) return Client.error(error);
$scope.refresh();
$('#entryRemoveModal').modal('hide');
});
}
};
function init() {
Client.getStatus(function (error, status) {
if (error) return Client.initError(error, init);
if (!status.activated) {
console.log('Not activated yet, redirecting', status);
window.location.href = '/';
return;
}
// check version and force reload if needed
if (!localStorage.version) {
localStorage.version = status.version;
} else if (localStorage.version !== status.version) {
localStorage.version = status.version;
window.location.reload(true);
}
$scope.status = status;
console.log('Running filemanager version ', localStorage.version);
// get user profile as the first thing. this populates the "scope" and affects subsequent API calls
Client.refreshUserInfo(function (error) {
if (error) return Client.initError(error, init);
Client.getApp($scope.appId, function (error, result) {
if (error) {
$scope.initialized = true;
return;
}
$scope.app = result;
// now mark the Client to be ready
Client.setReady();
$scope.changeDirectory(window.location.hash.slice(1));
$scope.initialized = true;
});
});
});
}
init();
window.addEventListener('hashchange', function () {
$scope.$apply(function () {
$scope.changeDirectory(window.location.hash.slice(1));
});
});
// setup all the dialog focus handling
['newDirectoryModal', 'renameEntryModal'].forEach(function (id) {
$('#' + id).on('shown.bs.modal', function () {
$(this).find("[autofocus]:first").focus();
});
});
// selects filename (without extension)
['renameEntryModal'].forEach(function (id) {
$('#' + id).on('shown.bs.modal', function () {
var elem = $(this).find("[autofocus]:first");
var text = elem.val();
elem[0].setSelectionRange(0, text.indexOf('.'));
});
});
}]);