file_browser.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. class FileBrowser{
  2. static buildFileBrowser(extensions, manualInput, title, startDir, callback) {
  3. HttpUtils.httpReq(
  4. 'GET',
  5. HttpUtils.url('/filelist', __NO_WID),
  6. undefined,
  7. function (statusCode, resp) {
  8. if (statusCode == 404){
  9. let err_msg = "Error! Cannot load file list!";
  10. WindowManagement.openDialog(_ERROR, err_msg);
  11. return;
  12. }
  13. extensions.push('/');
  14. var fnames = __localizeFilenames(
  15. __filterFilenamesByExtension(
  16. resp.split('\n'),
  17. extensions || ['.*'])
  18. ).sort(),
  19. folder_buttons = $('<div>'),
  20. new_folder_b = $('<button>'),
  21. rename_folder_b = $('<button>'),
  22. delete_folder_b = $('<button>'),
  23. move_folder_b = $('<button>'),
  24. file_buttons = $('<div>'),
  25. rename_file_b = $('<button>'),
  26. delete_file_b = $('<button>'),
  27. move_file_b = $('<button>'),
  28. feedbackarea = $('<div>'),
  29. feedback = GUIUtils.getTextSpan('', "feedback"),
  30. fileb =
  31. FileBrowser.getFileBrowser(fnames, false, manualInput, __getRecentDir(startDir));
  32. new_folder_b
  33. .attr('id', 'new_folder')
  34. .html('new folder')
  35. .click(function (ev) {
  36. var folder_name = prompt("please fill in a name for the folder");
  37. if (folder_name != null) {
  38. folder_name = folder_name.replace(/^\s+|\s+$/g, ''); // trim
  39. if (!folder_name.match(/^[a-zA-Z0-9_\s]+$/i)) {
  40. feedback.html("invalid folder name: " + folder_name);
  41. } else {
  42. console.log("/" + window.localStorage.getItem('user') + fileb['getcurrfolder']() + folder_name + '.folder');
  43. DataUtils.createFolder("/" + window.localStorage.getItem('user') + fileb['getcurrfolder']() + folder_name + '.folder', function (statusCode, resp) {
  44. if (!utils.isHttpSuccessCode(statusCode)) {
  45. feedback.html(resp);
  46. } else {
  47. feedback.html('created ' + folder_name);
  48. fnames.push(fileb['getcurrfolder']() + folder_name + "/");
  49. fileb['refresh'](fnames);
  50. }
  51. });
  52. }
  53. }
  54. });
  55. folder_buttons.append(new_folder_b);
  56. rename_folder_b
  57. .attr('id', 'rename_folder')
  58. .html('rename folder')
  59. .click(function (ev) {
  60. var value = fileb['getcurrfolder']();
  61. var folder_name = prompt("please fill in a new name for folder " + value);
  62. if (folder_name != null) {
  63. folder_name = folder_name.replace(/^\s+|\s+$/g, ''); // trim
  64. if (!folder_name.match(/^[a-zA-Z0-9_\s]+$/i)) {
  65. feedback.html("invalid folder name: " + folder_name);
  66. } else {
  67. DataUtils.renameInCloud("/" + window.localStorage.getItem('user') + value.slice(0, -1) + ".folder", folder_name, function (statusCode, resp) {
  68. if (!utils.isHttpSuccessCode(statusCode)) {
  69. feedback.html(resp);
  70. } else {
  71. var matches = value.match(/^\/(.*\/)?(.*)\/$/),
  72. newvalue = "/" + (matches[1] || "") + folder_name + "/";
  73. for (var idx in fnames) {
  74. fnames[idx] = fnames[idx].replace(new RegExp("^(" + value + ")(.*)"), newvalue + "$2");
  75. }
  76. fileb['refresh'](fnames, newvalue);
  77. fileb['clearselection']();
  78. feedback.html('renamed ' + value + ' to ' + newvalue);
  79. }
  80. });
  81. }
  82. }
  83. });
  84. folder_buttons.append(rename_folder_b);
  85. delete_folder_b
  86. .attr('id', 'delete_folder')
  87. .html('delete folder')
  88. .click(function (ev) {
  89. var value = fileb['getcurrfolder']();
  90. if (confirm("are you sure you want to delete " + value + "?")) {
  91. DataUtils.deleteFromCloud("/" + window.localStorage.getItem('user') + value.slice(0, -1) + ".folder", function (statusCode, resp) {
  92. if (!utils.isHttpSuccessCode(statusCode)) {
  93. feedback.html(resp);
  94. } else {
  95. var matches = value.match(/^\/(.*\/)?(.*)\/$/),
  96. newvalue = "/_Trash_" + value;
  97. for (var idx in fnames) {
  98. fnames[idx] = fnames[idx].replace(new RegExp("^(" + value + ")(.*)"), newvalue + "$2");
  99. }
  100. fileb['refresh'](fnames);
  101. fileb['clearselection']();
  102. feedback.html('deleted ' + value);
  103. }
  104. });
  105. }
  106. });
  107. folder_buttons.append(delete_folder_b);
  108. move_folder_b
  109. .attr('id', 'move_folder')
  110. .html('move folder')
  111. .click(function (ev) {
  112. var value = fileb['getcurrfolder']();
  113. var folder_loc = prompt("please fill in a new parent folder for folder " + value);
  114. if (folder_loc != null) {
  115. folder_loc = folder_loc.replace(/^\s+|\s+$/g, ''); // trim
  116. if (!folder_loc.match(/^\/([a-zA-Z0-9_\s]+\/)*$/i)) {
  117. feedback.html("invalid parent location: " + folder_loc);
  118. } else {
  119. DataUtils.moveInCloud("/" + window.localStorage.getItem('user') + value.slice(0, -1) + ".folder", folder_loc, function (statusCode, resp) {
  120. if (!utils.isHttpSuccessCode(statusCode)) {
  121. feedback.html(resp);
  122. } else {
  123. var matches = value.match(/^\/(.*\/)?(.*)\/$/),
  124. newvalue = folder_loc + matches[2] + "/";
  125. for (var idx in fnames) {
  126. fnames[idx] = fnames[idx].replace(new RegExp("^(" + value + ")(.*)"), newvalue + "$2");
  127. }
  128. fileb['refresh'](fnames, newvalue);
  129. fileb['clearselection']();
  130. feedback.html('moved ' + value + ' to ' + folder_loc);
  131. }
  132. });
  133. }
  134. }
  135. });
  136. folder_buttons.append(move_folder_b);
  137. rename_file_b
  138. .attr('id', 'rename_file')
  139. .html('rename file')
  140. .click(function (ev) {
  141. var value = fileb['getselection']();
  142. var file_name = prompt("please fill in a new name for file " + value);
  143. if (file_name != null) {
  144. file_name = file_name.replace(/^\s+|\s+$/g, ''); // trim
  145. if (!file_name.match(/^[a-zA-Z0-9_\s\.]+$/i)) {
  146. feedback.html("invalid file name: " + file_name);
  147. } else {
  148. DataUtils.renameInCloud("/" + window.localStorage.getItem('user') + value + ".file", file_name, function (statusCode, resp) {
  149. if (!utils.isHttpSuccessCode(statusCode)) {
  150. feedback.html(resp);
  151. } else {
  152. var matches = value.match(/^\/(.*\/)?(.*)$/),
  153. newvalue = "/" + (matches[1] || "") + file_name;
  154. var idx = fnames.indexOf(value);
  155. if (idx >= 0) {
  156. fnames[idx] = newvalue;
  157. }
  158. fileb['refresh'](fnames);
  159. fileb['clearselection']();
  160. feedback.html('renamed ' + value + ' to ' + newvalue);
  161. }
  162. });
  163. }
  164. }
  165. });
  166. file_buttons.append(rename_file_b);
  167. delete_file_b
  168. .attr('id', 'delete_file')
  169. .html('delete file')
  170. .click(function (ev) {
  171. var value = fileb['getselection']();
  172. if (confirm("are you sure you want to delete " + value + "?")) {
  173. DataUtils.deleteFromCloud("/" + window.localStorage.getItem('user') + value + ".file", function (statusCode, resp) {
  174. if (!utils.isHttpSuccessCode(statusCode)) {
  175. feedback.html(resp);
  176. } else {
  177. feedback.html('deleted ' + value);
  178. var idx = fnames.indexOf(value);
  179. if (idx >= 0) {
  180. fnames.splice(idx, 1);
  181. }
  182. fileb['refresh'](fnames);
  183. fileb['clearselection']();
  184. }
  185. });
  186. }
  187. });
  188. file_buttons.append(delete_file_b);
  189. move_file_b
  190. .attr('id', 'move_file')
  191. .html('move file')
  192. .click(function (ev) {
  193. var value = fileb['getselection']();
  194. var folder_loc = prompt("please fill in a new parent folder for file " + value);
  195. if (folder_loc != null) {
  196. folder_loc = folder_loc.replace(/^\s+|\s+$/g, ''); // trim
  197. if (!folder_loc.match(/^\/([a-zA-Z0-9_\s]+\/)*$/i)) {
  198. feedback.html("invalid parent location: " + folder_loc);
  199. } else {
  200. DataUtils.moveInCloud("/" + window.localStorage.getItem('user') + value + ".file", folder_loc, function (statusCode, resp) {
  201. if (!utils.isHttpSuccessCode(statusCode)) {
  202. feedback.html(resp);
  203. } else {
  204. var matches = value.match(/^\/(.*\/)?(.*)$/),
  205. newvalue = folder_loc + matches[2];
  206. feedback.html('moved ' + value + ' to ' + folder_loc);
  207. var idx = fnames.indexOf(value);
  208. if (idx >= 0) {
  209. fnames[idx] = newvalue;
  210. }
  211. fileb['refresh'](fnames);
  212. fileb['clearselection']();
  213. }
  214. });
  215. }
  216. }
  217. });
  218. file_buttons.append(move_file_b);
  219. GUIUtils.setupAndShowDialog(
  220. [fileb['filebrowser'], folder_buttons, file_buttons, feedback],
  221. function () {
  222. var value = [fileb['getselection']()];
  223. if (value.length > 0 && value[0] != "" && startDir) {
  224. __setRecentDir(startDir, value[0].substring(0, value[0].lastIndexOf('/') + 1));
  225. }
  226. return value;
  227. },
  228. __TWO_BUTTONS,
  229. title,
  230. callback);
  231. });
  232. }
  233. /**
  234. * Returns a <div> with an interactive file browser within it
  235. *
  236. * @param fnames - a complete list of all files in the directory tree
  237. * structure
  238. * @param draggable - when true, files and folders can be meaningfully
  239. * dragged
  240. * @param newfile when true, an editable new file icon is present
  241. * @param startfolder if set, starts navigation at the specified folder
  242. */
  243. static getFileBrowser(fnames, draggable, newfile, startfolder) {
  244. var fileb = $("<div>"),
  245. navdiv = $("<div>"),
  246. input = $("<input>"),
  247. selection = undefined,
  248. currfolder = '/',
  249. clearSelection =
  250. function () {
  251. if (selection) {
  252. selection.attr("class", 'fileb_icon');
  253. selection = undefined;
  254. input.val('');
  255. }
  256. },
  257. navbuttononclick =
  258. /* 1 construct the full path associated to the clicked button
  259. 2 remove 'deeper' buttons
  260. 3 chdir to selected folder */
  261. function (ev) {
  262. var path = '';
  263. for (var i = 0; i < navdiv.children("button").length; i++) {
  264. path += $(navdiv.children()[i]).html() + '/';
  265. if ($(navdiv.children()[i]).html() == $(ev.target).html())
  266. break;
  267. }
  268. setCurrentFileBrowserFolder(path.substring(1), fnames);
  269. },
  270. setCurrentFileBrowserFolder =
  271. /* 1 determine files and folders from the given folder
  272. 2 produce icons for them and add them to to-be content div
  273. 3 create navigation toolbar for complete directory hierarchy
  274. 4 replace previous content div, if any, with new one
  275. 5 clear past selection, if any, and remember current folder */
  276. async function (folder, fnames) {
  277. var div = $('#div_fileb-contents'),
  278. folders = [],
  279. files = [],
  280. exists = false;
  281. // If it already exists, remove everything!
  282. if (div.length > 0) {
  283. $('#div_fileb-contents').remove();
  284. // exists = true;
  285. }
  286. div = $("<div>");
  287. div.attr("class", 'fileb_pane')
  288. .attr("id", 'div_fileb-contents');
  289. //fnames might be a function that returns the files in
  290. //the folder
  291. let file_list = fnames;
  292. if (!(Array.isArray(fnames))){
  293. file_list = await fnames(folder);
  294. }
  295. let _folder = utils.regexpe(folder);
  296. file_list.forEach(function (fname) {
  297. let matches = fname.match('^' + _folder + '(.+?/)');
  298. if (matches) {
  299. if (!utils.contains(folders, matches[1]))
  300. folders.push(matches[1]);
  301. }
  302. else if ((matches = fname.match('^' + _folder + '(.*)'))) {
  303. if (matches[1].length > 0) {
  304. files.push(matches[1]);
  305. }
  306. }
  307. });
  308. let all_entries = folders.concat(files);
  309. //get the maximum filename length
  310. let maxFnameLength = utils.max(all_entries, function (_) {
  311. return _.length;
  312. });
  313. // var tmpDiv = $("<div>");
  314. all_entries.forEach(function (fname) {
  315. let icon = HttpUtils.getFileIcon(fname);
  316. if (icon) {
  317. icon.css("width", 8 + maxFnameLength + 'ex');
  318. icon.click(function (ev) {
  319. clearSelection();
  320. if (fname.match(/\/$/))
  321. setCurrentFileBrowserFolder(folder + fname, fnames);
  322. else {
  323. input.val(folder + fname);
  324. selection = icon;
  325. selection.attr("class", 'fileb_icon_selected');
  326. }
  327. });
  328. if (draggable) {
  329. //icon.setAttribute('draggable',true);
  330. icon.attr("draggable", true);
  331. icon.get(0).ondragstart =
  332. function (event) {
  333. var uri = HttpUtils.url(folder + fname + '.file', __NO_WID);
  334. event.dataTransfer.effectAllowed = 'copyMove';
  335. event.dataTransfer.setData(
  336. 'DownloadURL',
  337. 'application/zip:' + fname + '.zip:' +
  338. window.location.origin + uri);
  339. event.dataTransfer.setData('uri', uri);
  340. };
  341. }
  342. div.append(icon);
  343. }
  344. });
  345. if (newfile) {
  346. var icon = HttpUtils.getNewFileIcon(function (ev) {
  347. input.val(folder + ev.target.textContent);
  348. });
  349. icon.css("width", 8 + maxFnameLength + 'ex');
  350. div.append(icon);
  351. }
  352. navdiv.empty();
  353. // while (navdiv.children().length > 0) {
  354. // navdiv.find(navdiv.lastChild).remove();
  355. // }
  356. //let tmpDiv = $("<div>");
  357. var subfolders = folder.split('/').filter(function (subf) {
  358. return subf != '';
  359. });
  360. subfolders.unshift('/');
  361. subfolders.forEach(function (subfolder) {
  362. var navbutton = $('<button>');
  363. navbutton.html(subfolder);
  364. navbutton.attr('id', 'navbar_' + subfolder);
  365. navbutton.click(navbuttononclick);
  366. navdiv.append(navbutton);
  367. });
  368. //navdiv.html( tmpDiv.html() );
  369. if (exists) {
  370. // $('#div_fileb-contents').html( div.html() );
  371. // fileb.append(div);
  372. $('#div_fileb-contents').remove();
  373. fileb.append(div);
  374. } else
  375. fileb.append(div);
  376. clearSelection();
  377. currfolder = folder;
  378. };
  379. fileb.css("maxWidth", '100%');
  380. navdiv.css("align", 'left');
  381. input.attr("type", 'hidden');
  382. fileb.append(navdiv);
  383. fileb.append(input);
  384. setCurrentFileBrowserFolder(startfolder ? startfolder : '/', fnames);
  385. return {
  386. 'filebrowser': fileb,
  387. 'filepane': function () {
  388. return $('#div_fileb-contents');
  389. },
  390. 'getcurrfolder': function () {
  391. return currfolder;
  392. },
  393. 'getselection': function () {
  394. return input.val().trim();
  395. },
  396. 'clearselection': function () {
  397. clearSelection();
  398. },
  399. 'refresh': function (fnames, the_folder) {
  400. setCurrentFileBrowserFolder(the_folder || currfolder, fnames);
  401. }
  402. };
  403. }
  404. }