files.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. /*
  2. * Copyright (c) 2014
  3. *
  4. * This file is licensed under the Affero General Public License version 3
  5. * or later.
  6. *
  7. * See the COPYING-README file.
  8. *
  9. */
  10. /* global getURLParameter */
  11. /**
  12. * Utility class for file related operations
  13. */
  14. (function() {
  15. var Files = {
  16. // file space size sync
  17. _updateStorageStatistics: function(currentDir) {
  18. var state = Files.updateStorageStatistics;
  19. if (state.dir){
  20. if (state.dir === currentDir) {
  21. return;
  22. }
  23. // cancel previous call, as it was for another dir
  24. state.call.abort();
  25. }
  26. state.dir = currentDir;
  27. state.call = $.getJSON(OC.generateUrl('apps/files/api/v1/stats?dir={dir}', {
  28. dir: currentDir,
  29. }), function(response) {
  30. state.dir = null;
  31. state.call = null;
  32. Files.updateMaxUploadFilesize(response);
  33. });
  34. },
  35. // update quota
  36. updateStorageQuotas: function() {
  37. Files._updateStorageQuotasThrottled();
  38. },
  39. _updateStorageQuotas: function() {
  40. var state = Files.updateStorageQuotas;
  41. state.call = $.getJSON(OC.generateUrl('apps/files/api/v1/stats'), function(response) {
  42. Files.updateQuota(response);
  43. });
  44. },
  45. /**
  46. * Update storage statistics such as free space, max upload,
  47. * etc based on the given directory.
  48. *
  49. * Note this function is debounced to avoid making too
  50. * many ajax calls in a row.
  51. *
  52. * @param dir directory
  53. * @param force whether to force retrieving
  54. */
  55. updateStorageStatistics: function(dir, force) {
  56. if (!OC.currentUser) {
  57. return;
  58. }
  59. if (force) {
  60. Files._updateStorageStatistics(dir);
  61. }
  62. else {
  63. Files._updateStorageStatisticsDebounced(dir);
  64. }
  65. },
  66. updateMaxUploadFilesize:function(response) {
  67. if (response === undefined) {
  68. return;
  69. }
  70. if (response.data !== undefined && response.data.uploadMaxFilesize !== undefined) {
  71. $('#free_space').val(response.data.freeSpace);
  72. $('#upload.button').attr('title', response.data.maxHumanFilesize);
  73. $('#usedSpacePercent').val(response.data.usedSpacePercent);
  74. $('#usedSpacePercent').data('mount-type', response.data.mountType);
  75. $('#usedSpacePercent').data('mount-point', response.data.mountPoint);
  76. $('#owner').val(response.data.owner);
  77. $('#ownerDisplayName').val(response.data.ownerDisplayName);
  78. Files.displayStorageWarnings();
  79. OCA.Files.App.fileList._updateDirectoryPermissions();
  80. }
  81. if (response[0] === undefined) {
  82. return;
  83. }
  84. if (response[0].uploadMaxFilesize !== undefined) {
  85. $('#upload.button').attr('title', response[0].maxHumanFilesize);
  86. $('#usedSpacePercent').val(response[0].usedSpacePercent);
  87. Files.displayStorageWarnings();
  88. }
  89. },
  90. updateQuota:function(response) {
  91. if (response === undefined) {
  92. return;
  93. }
  94. if (response.data !== undefined
  95. && response.data.quota !== undefined
  96. && response.data.total !== undefined
  97. && response.data.used !== undefined
  98. && response.data.usedSpacePercent !== undefined) {
  99. var humanUsed = OC.Util.humanFileSize(response.data.used, true, false);
  100. var humanTotal = OC.Util.humanFileSize(response.data.total, true, false);
  101. if (response.data.quota > 0) {
  102. $('#quota').attr('title', t('files', '{used}%', {used: Math.round(response.data.usedSpacePercent)}));
  103. $('#quota progress').val(response.data.usedSpacePercent);
  104. $('#quotatext').html(t('files', '{used} of {quota} used', {used: humanUsed, quota: humanTotal}));
  105. } else {
  106. $('#quotatext').html(t('files', '{used} used', {used: humanUsed}));
  107. }
  108. if (response.data.usedSpacePercent > 80) {
  109. $('#quota progress').addClass('warn');
  110. } else {
  111. $('#quota progress').removeClass('warn');
  112. }
  113. }
  114. },
  115. /**
  116. * Fix path name by removing double slash at the beginning, if any
  117. */
  118. fixPath: function(fileName) {
  119. if (fileName.substr(0, 2) == '//') {
  120. return fileName.substr(1);
  121. }
  122. return fileName;
  123. },
  124. /**
  125. * Checks whether the given file name is valid.
  126. * @param name file name to check
  127. * @return true if the file name is valid.
  128. * Throws a string exception with an error message if
  129. * the file name is not valid
  130. *
  131. * NOTE: This function is duplicated in the filepicker inside core/src/OC/dialogs.js
  132. */
  133. isFileNameValid: function (name) {
  134. var trimmedName = name.trim();
  135. if (trimmedName === '.' || trimmedName === '..')
  136. {
  137. throw t('files', '"{name}" is an invalid file name.', {name: name});
  138. } else if (trimmedName.length === 0) {
  139. throw t('files', 'File name cannot be empty.');
  140. } else if (trimmedName.indexOf('/') !== -1) {
  141. throw t('files', '"/" is not allowed inside a file name.');
  142. } else if (!!(trimmedName.match(OC.config.blacklist_files_regex))) {
  143. throw t('files', '"{name}" is not an allowed filetype', {name: name});
  144. }
  145. return true;
  146. },
  147. displayStorageWarnings: function() {
  148. if (!OC.Notification.isHidden()) {
  149. return;
  150. }
  151. var usedSpacePercent = $('#usedSpacePercent').val(),
  152. owner = $('#owner').val(),
  153. ownerDisplayName = $('#ownerDisplayName').val(),
  154. mountType = $('#usedSpacePercent').data('mount-type'),
  155. mountPoint = $('#usedSpacePercent').data('mount-point');
  156. if (usedSpacePercent > 98) {
  157. if (owner !== OC.getCurrentUser().uid) {
  158. OC.Notification.show(t('files', 'Storage of {owner} is full, files cannot be updated or synced anymore!',
  159. {owner: ownerDisplayName}), {type: 'error'}
  160. );
  161. } else if (mountType === 'group') {
  162. OC.Notification.show(t('files',
  163. 'Group folder "{mountPoint}" is full, files cannot be updated or synced anymore!',
  164. {mountPoint: mountPoint}),
  165. {type: 'error'}
  166. );
  167. } else if (mountType === 'external') {
  168. OC.Notification.show(t('files',
  169. 'External storage "{mountPoint}" is full, files cannot be updated or synced anymore!',
  170. {mountPoint: mountPoint}),
  171. {type : 'error'}
  172. );
  173. } else {
  174. OC.Notification.show(t('files',
  175. 'Your storage is full, files cannot be updated or synced anymore!'),
  176. {type: 'error'}
  177. );
  178. }
  179. } else if (usedSpacePercent > 90) {
  180. if (owner !== OC.getCurrentUser().uid) {
  181. OC.Notification.show(t('files', 'Storage of {owner} is almost full ({usedSpacePercent}%).',
  182. {
  183. usedSpacePercent: usedSpacePercent,
  184. owner: ownerDisplayName
  185. }),
  186. {
  187. type: 'error'
  188. }
  189. );
  190. } else if (mountType === 'group') {
  191. OC.Notification.show(t('files',
  192. 'Group folder "{mountPoint}" is almost full ({usedSpacePercent}%).',
  193. {mountPoint: mountPoint, usedSpacePercent: usedSpacePercent}),
  194. {type : 'error'}
  195. );
  196. } else if (mountType === 'external') {
  197. OC.Notification.show(t('files',
  198. 'External storage "{mountPoint}" is almost full ({usedSpacePercent}%).',
  199. {mountPoint: mountPoint, usedSpacePercent: usedSpacePercent}),
  200. {type : 'error'}
  201. );
  202. } else {
  203. OC.Notification.show(t('files', 'Your storage is almost full ({usedSpacePercent}%).',
  204. {usedSpacePercent: usedSpacePercent}),
  205. {type : 'error'}
  206. );
  207. }
  208. }
  209. },
  210. /**
  211. * Returns the download URL of the given file(s)
  212. * @param {string} filename string or array of file names to download
  213. * @param {string} [dir] optional directory in which the file name is, defaults to the current directory
  214. * @param {boolean} [isDir=false] whether the given filename is a directory and might need a special URL
  215. */
  216. getDownloadUrl: function(filename, dir, isDir) {
  217. if (!_.isArray(filename) && !isDir) {
  218. var pathSections = dir.split('/');
  219. pathSections.push(filename);
  220. var encodedPath = '';
  221. _.each(pathSections, function(section) {
  222. if (section !== '') {
  223. encodedPath += '/' + encodeURIComponent(section);
  224. }
  225. });
  226. return OC.linkToRemoteBase('webdav') + encodedPath;
  227. }
  228. if (_.isArray(filename)) {
  229. filename = JSON.stringify(filename);
  230. }
  231. var params = {
  232. dir: dir,
  233. files: filename
  234. };
  235. return this.getAjaxUrl('download', params);
  236. },
  237. /**
  238. * Returns the ajax URL for a given action
  239. * @param action action string
  240. * @param params optional params map
  241. */
  242. getAjaxUrl: function(action, params) {
  243. var q = '';
  244. if (params) {
  245. q = '?' + OC.buildQueryString(params);
  246. }
  247. return OC.filePath('files', 'ajax', action + '.php') + q;
  248. },
  249. /**
  250. * Fetch the icon url for the mimetype
  251. * @param {string} mime The mimetype
  252. * @param {Files~mimeicon} ready Function to call when mimetype is retrieved
  253. * @deprecated use OC.MimeType.getIconUrl(mime)
  254. */
  255. getMimeIcon: function(mime, ready) {
  256. ready(OC.MimeType.getIconUrl(mime));
  257. },
  258. /**
  259. * Generates a preview URL based on the URL space.
  260. * @param urlSpec attributes for the URL
  261. * @param {number} urlSpec.x width
  262. * @param {number} urlSpec.y height
  263. * @param {String} urlSpec.file path to the file
  264. * @return preview URL
  265. * @deprecated used OCA.Files.FileList.generatePreviewUrl instead
  266. */
  267. generatePreviewUrl: function(urlSpec) {
  268. OC.debug && console.warn('DEPRECATED: please use generatePreviewUrl() from an OCA.Files.FileList instance');
  269. return OCA.Files.App.fileList.generatePreviewUrl(urlSpec);
  270. },
  271. /**
  272. * Lazy load preview
  273. * @deprecated used OCA.Files.FileList.lazyLoadPreview instead
  274. */
  275. lazyLoadPreview : function(path, mime, ready, width, height, etag) {
  276. OC.debug && console.warn('DEPRECATED: please use lazyLoadPreview() from an OCA.Files.FileList instance');
  277. return FileList.lazyLoadPreview({
  278. path: path,
  279. mime: mime,
  280. callback: ready,
  281. width: width,
  282. height: height,
  283. etag: etag
  284. });
  285. },
  286. /**
  287. * Initialize the files view
  288. */
  289. initialize: function() {
  290. Files.bindKeyboardShortcuts(document, $);
  291. // drag&drop support using jquery.fileupload
  292. // TODO use OC.dialogs
  293. $(document).bind('drop dragover', function (e) {
  294. e.preventDefault(); // prevent browser from doing anything, if file isn't dropped in dropZone
  295. });
  296. // display storage warnings
  297. setTimeout(Files.displayStorageWarnings, 100);
  298. // only possible at the moment if user is logged in or the files app is loaded
  299. if (OC.currentUser && OCA.Files.App && OC.config.session_keepalive) {
  300. // start on load - we ask the server every 5 minutes
  301. var func = _.bind(OCA.Files.App.fileList.updateStorageStatistics, OCA.Files.App.fileList);
  302. var updateStorageStatisticsInterval = 5*60*1000;
  303. var updateStorageStatisticsIntervalId = setInterval(func, updateStorageStatisticsInterval);
  304. // TODO: this should also stop when switching to another view
  305. // Use jquery-visibility to de-/re-activate file stats sync
  306. if ($.support.pageVisibility) {
  307. $(document).on({
  308. 'show': function() {
  309. if (!updateStorageStatisticsIntervalId) {
  310. updateStorageStatisticsIntervalId = setInterval(func, updateStorageStatisticsInterval);
  311. }
  312. },
  313. 'hide': function() {
  314. clearInterval(updateStorageStatisticsIntervalId);
  315. updateStorageStatisticsIntervalId = 0;
  316. }
  317. });
  318. }
  319. }
  320. $('#webdavurl').on('click touchstart', function () {
  321. this.focus();
  322. this.setSelectionRange(0, this.value.length);
  323. });
  324. //FIXME scroll to and highlight preselected file
  325. /*
  326. if (getURLParameter('scrollto')) {
  327. FileList.scrollTo(getURLParameter('scrollto'));
  328. }
  329. */
  330. },
  331. /**
  332. * Handles the download and calls the callback function once the download has started
  333. * - browser sends download request and adds parameter with a token
  334. * - server notices this token and adds a set cookie to the download response
  335. * - browser now adds this cookie for the domain
  336. * - JS periodically checks for this cookie and then knows when the download has started to call the callback
  337. *
  338. * @param {string} url download URL
  339. * @param {Function} callback function to call once the download has started
  340. */
  341. handleDownload: function(url, callback) {
  342. var randomToken = Math.random().toString(36).substring(2),
  343. checkForDownloadCookie = function() {
  344. if (!OC.Util.isCookieSetToValue('ocDownloadStarted', randomToken)){
  345. return false;
  346. } else {
  347. callback();
  348. return true;
  349. }
  350. };
  351. if (url.indexOf('?') >= 0) {
  352. url += '&';
  353. } else {
  354. url += '?';
  355. }
  356. OC.redirect(url + 'downloadStartSecret=' + randomToken);
  357. OC.Util.waitFor(checkForDownloadCookie, 500);
  358. }
  359. };
  360. Files._updateStorageStatisticsDebounced = _.debounce(Files._updateStorageStatistics, 250);
  361. Files._updateStorageQuotasThrottled = _.throttle(Files._updateStorageQuotas, 30000);
  362. OCA.Files.Files = Files;
  363. })();
  364. // TODO: move to FileList
  365. var createDragShadow = function(event) {
  366. // FIXME: inject file list instance somehow
  367. /* global FileList, Files */
  368. //select dragged file
  369. var isDragSelected = $(event.target).parents('tr').find('td input:first').prop('checked');
  370. if (!isDragSelected) {
  371. //select dragged file
  372. FileList._selectFileEl($(event.target).parents('tr:first'), true, false);
  373. }
  374. // do not show drag shadow for too many files
  375. var selectedFiles = _.first(FileList.getSelectedFiles(), FileList.pageSize());
  376. selectedFiles = _.sortBy(selectedFiles, FileList._fileInfoCompare);
  377. if (!isDragSelected && selectedFiles.length === 1) {
  378. //revert the selection
  379. FileList._selectFileEl($(event.target).parents('tr:first'), false, false);
  380. }
  381. // build dragshadow
  382. var dragshadow = $('<table class="dragshadow"></table>');
  383. var tbody = $('<tbody></tbody>');
  384. dragshadow.append(tbody);
  385. var dir = FileList.getCurrentDirectory();
  386. $(selectedFiles).each(function(i,elem) {
  387. // TODO: refactor this with the table row creation code
  388. var newtr = $('<tr></tr>')
  389. .attr('data-dir', dir)
  390. .attr('data-file', elem.name)
  391. .attr('data-origin', elem.origin);
  392. newtr.append($('<td class="filename"></td>').text(elem.name).css('background-size', 32));
  393. newtr.append($('<td class="size"></td>').text(OC.Util.humanFileSize(elem.size, false, false)));
  394. tbody.append(newtr);
  395. if (elem.type === 'dir') {
  396. newtr.find('td.filename')
  397. .css('background-image', 'url(' + OC.MimeType.getIconUrl('folder') + ')');
  398. } else {
  399. var path = dir + '/' + elem.name;
  400. Files.lazyLoadPreview(path, elem.mimetype, function(previewpath) {
  401. newtr.find('td.filename')
  402. .css('background-image', 'url(' + previewpath + ')');
  403. }, null, null, elem.etag);
  404. }
  405. });
  406. return dragshadow;
  407. };
  408. //options for file drag/drop
  409. //start&stop handlers needs some cleaning up
  410. // TODO: move to FileList class
  411. var dragOptions={
  412. revert: 'invalid',
  413. revertDuration: 300,
  414. opacity: 0.7,
  415. cursorAt: { left: 24, top: 18 },
  416. helper: createDragShadow,
  417. cursor: 'move',
  418. start: function(event, ui){
  419. var $selectedFiles = $('td.filename input:checkbox:checked');
  420. if (!$selectedFiles.length) {
  421. $selectedFiles = $(this);
  422. }
  423. $selectedFiles.closest('tr').addClass('animate-opacity dragging');
  424. $selectedFiles.closest('tr').filter('.ui-droppable').droppable( 'disable' );
  425. // Show breadcrumbs menu
  426. $('.crumbmenu').addClass('canDropChildren');
  427. },
  428. stop: function(event, ui) {
  429. var $selectedFiles = $('td.filename input:checkbox:checked');
  430. if (!$selectedFiles.length) {
  431. $selectedFiles = $(this);
  432. }
  433. var $tr = $selectedFiles.closest('tr');
  434. $tr.removeClass('dragging');
  435. $tr.filter('.ui-droppable').droppable( 'enable' );
  436. setTimeout(function() {
  437. $tr.removeClass('animate-opacity');
  438. }, 300);
  439. // Hide breadcrumbs menu
  440. $('.crumbmenu').removeClass('canDropChildren');
  441. },
  442. drag: function(event, ui) {
  443. // Prevent scrolling when hovering .files-controls
  444. if ($(event.originalEvent.target).parents('.files-controls').length > 0) {
  445. return
  446. }
  447. /** @type {JQuery<HTMLDivElement>} */
  448. const scrollingArea = FileList.$container;
  449. // Get the top and bottom scroll trigger y positions
  450. const containerHeight = scrollingArea.innerHeight() ?? 0
  451. const scrollTriggerArea = Math.min(Math.floor(containerHeight / 2), 100);
  452. const bottomTriggerY = containerHeight - scrollTriggerArea;
  453. const topTriggerY = scrollTriggerArea;
  454. // Get the cursor position relative to the container
  455. const containerOffset = scrollingArea.offset() ?? {left: 0, top: 0}
  456. const cursorPositionY = event.pageY - containerOffset.top
  457. const currentScrollTop = scrollingArea.scrollTop() ?? 0
  458. if (cursorPositionY < topTriggerY) {
  459. scrollingArea.scrollTop(currentScrollTop - 10)
  460. } else if (cursorPositionY > bottomTriggerY) {
  461. scrollingArea.scrollTop(currentScrollTop + 10)
  462. }
  463. }
  464. };
  465. // sane browsers support using the distance option
  466. if ( $('html.ie').length === 0) {
  467. dragOptions['distance'] = 20;
  468. }
  469. // TODO: move to FileList class
  470. var folderDropOptions = {
  471. hoverClass: "canDrop",
  472. drop: function( event, ui ) {
  473. // don't allow moving a file into a selected folder
  474. /* global FileList */
  475. if ($(event.target).parents('tr').find('td input:first').prop('checked') === true) {
  476. return false;
  477. }
  478. var $tr = $(this).closest('tr');
  479. if (($tr.data('permissions') & OC.PERMISSION_CREATE) === 0) {
  480. FileList._showPermissionDeniedNotification();
  481. return false;
  482. }
  483. var targetPath = FileList.getCurrentDirectory() + '/' + $tr.data('file');
  484. var files = FileList.getSelectedFiles();
  485. if (files.length === 0) {
  486. // single one selected without checkbox?
  487. files = _.map(ui.helper.find('tr'), function(el) {
  488. return FileList.elementToFile($(el));
  489. });
  490. }
  491. FileList.move(_.pluck(files, 'name'), targetPath);
  492. },
  493. tolerance: 'pointer'
  494. };
  495. // for backward compatibility
  496. window.Files = OCA.Files.Files;