files.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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/ajax/getstoragestats?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/ajax/getstoragestats'), 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('data-original-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('data-original-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);
  100. var humanTotal = OC.Util.humanFileSize(response.data.total, true);
  101. if (response.data.quota > 0) {
  102. $('#quota').attr('data-original-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. 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. 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. $('#upload').tooltip({placement:'right'});
  325. //FIXME scroll to and highlight preselected file
  326. /*
  327. if (getURLParameter('scrollto')) {
  328. FileList.scrollTo(getURLParameter('scrollto'));
  329. }
  330. */
  331. },
  332. /**
  333. * Handles the download and calls the callback function once the download has started
  334. * - browser sends download request and adds parameter with a token
  335. * - server notices this token and adds a set cookie to the download response
  336. * - browser now adds this cookie for the domain
  337. * - JS periodically checks for this cookie and then knows when the download has started to call the callback
  338. *
  339. * @param {string} url download URL
  340. * @param {Function} callback function to call once the download has started
  341. */
  342. handleDownload: function(url, callback) {
  343. var randomToken = Math.random().toString(36).substring(2),
  344. checkForDownloadCookie = function() {
  345. if (!OC.Util.isCookieSetToValue('ocDownloadStarted', randomToken)){
  346. return false;
  347. } else {
  348. callback();
  349. return true;
  350. }
  351. };
  352. if (url.indexOf('?') >= 0) {
  353. url += '&';
  354. } else {
  355. url += '?';
  356. }
  357. OC.redirect(url + 'downloadStartSecret=' + randomToken);
  358. OC.Util.waitFor(checkForDownloadCookie, 500);
  359. }
  360. };
  361. Files._updateStorageStatisticsDebounced = _.debounce(Files._updateStorageStatistics, 250);
  362. Files._updateStorageQuotasThrottled = _.throttle(Files._updateStorageQuotas, 30000);
  363. OCA.Files.Files = Files;
  364. })();
  365. // TODO: move to FileList
  366. var createDragShadow = function(event) {
  367. // FIXME: inject file list instance somehow
  368. /* global FileList, Files */
  369. //select dragged file
  370. var isDragSelected = $(event.target).parents('tr').find('td input:first').prop('checked');
  371. if (!isDragSelected) {
  372. //select dragged file
  373. FileList._selectFileEl($(event.target).parents('tr:first'), true, false);
  374. }
  375. // do not show drag shadow for too many files
  376. var selectedFiles = _.first(FileList.getSelectedFiles(), FileList.pageSize());
  377. selectedFiles = _.sortBy(selectedFiles, FileList._fileInfoCompare);
  378. if (!isDragSelected && selectedFiles.length === 1) {
  379. //revert the selection
  380. FileList._selectFileEl($(event.target).parents('tr:first'), false, false);
  381. }
  382. // build dragshadow
  383. var dragshadow = $('<table class="dragshadow"></table>');
  384. var tbody = $('<tbody></tbody>');
  385. dragshadow.append(tbody);
  386. var dir = FileList.getCurrentDirectory();
  387. $(selectedFiles).each(function(i,elem) {
  388. // TODO: refactor this with the table row creation code
  389. var newtr = $('<tr></tr>')
  390. .attr('data-dir', dir)
  391. .attr('data-file', elem.name)
  392. .attr('data-origin', elem.origin);
  393. newtr.append($('<td class="filename"></td>').text(elem.name).css('background-size', 32));
  394. newtr.append($('<td class="size"></td>').text(OC.Util.humanFileSize(elem.size)));
  395. tbody.append(newtr);
  396. if (elem.type === 'dir') {
  397. newtr.find('td.filename')
  398. .css('background-image', 'url(' + OC.MimeType.getIconUrl('folder') + ')');
  399. } else {
  400. var path = dir + '/' + elem.name;
  401. Files.lazyLoadPreview(path, elem.mimetype, function(previewpath) {
  402. newtr.find('td.filename')
  403. .css('background-image', 'url(' + previewpath + ')');
  404. }, null, null, elem.etag);
  405. }
  406. });
  407. return dragshadow;
  408. };
  409. //options for file drag/drop
  410. //start&stop handlers needs some cleaning up
  411. // TODO: move to FileList class
  412. var dragOptions={
  413. revert: 'invalid',
  414. revertDuration: 300,
  415. opacity: 0.7,
  416. appendTo: 'body',
  417. cursorAt: { left: 24, top: 18 },
  418. helper: createDragShadow,
  419. cursor: 'move',
  420. start: function(event, ui){
  421. var $selectedFiles = $('td.filename input:checkbox:checked');
  422. if (!$selectedFiles.length) {
  423. $selectedFiles = $(this);
  424. }
  425. $selectedFiles.closest('tr').addClass('animate-opacity dragging');
  426. $selectedFiles.closest('tr').filter('.ui-droppable').droppable( 'disable' );
  427. // Show breadcrumbs menu
  428. $('.crumbmenu').addClass('canDropChildren');
  429. },
  430. stop: function(event, ui) {
  431. var $selectedFiles = $('td.filename input:checkbox:checked');
  432. if (!$selectedFiles.length) {
  433. $selectedFiles = $(this);
  434. }
  435. var $tr = $selectedFiles.closest('tr');
  436. $tr.removeClass('dragging');
  437. $tr.filter('.ui-droppable').droppable( 'enable' );
  438. setTimeout(function() {
  439. $tr.removeClass('animate-opacity');
  440. }, 300);
  441. // Hide breadcrumbs menu
  442. $('.crumbmenu').removeClass('canDropChildren');
  443. },
  444. drag: function(event, ui) {
  445. var scrollingArea = FileList.$container;
  446. var currentScrollTop = $(scrollingArea).scrollTop();
  447. var scrollArea = Math.min(Math.floor($(window).innerHeight() / 2), 100);
  448. var bottom = $(window).innerHeight() - scrollArea;
  449. var top = $(window).scrollTop() + scrollArea;
  450. if (event.pageY < top) {
  451. $(scrollingArea).animate({
  452. scrollTop: currentScrollTop - 10
  453. }, 400);
  454. } else if (event.pageY > bottom) {
  455. $(scrollingArea).animate({
  456. scrollTop: currentScrollTop + 10
  457. }, 400);
  458. }
  459. }
  460. };
  461. // sane browsers support using the distance option
  462. if ( $('html.ie').length === 0) {
  463. dragOptions['distance'] = 20;
  464. }
  465. // TODO: move to FileList class
  466. var folderDropOptions = {
  467. hoverClass: "canDrop",
  468. drop: function( event, ui ) {
  469. // don't allow moving a file into a selected folder
  470. /* global FileList */
  471. if ($(event.target).parents('tr').find('td input:first').prop('checked') === true) {
  472. return false;
  473. }
  474. var $tr = $(this).closest('tr');
  475. if (($tr.data('permissions') & OC.PERMISSION_CREATE) === 0) {
  476. FileList._showPermissionDeniedNotification();
  477. return false;
  478. }
  479. var targetPath = FileList.getCurrentDirectory() + '/' + $tr.data('file');
  480. var files = FileList.getSelectedFiles();
  481. if (files.length === 0) {
  482. // single one selected without checkbox?
  483. files = _.map(ui.helper.find('tr'), function(el) {
  484. return FileList.elementToFile($(el));
  485. });
  486. }
  487. FileList.move(_.pluck(files, 'name'), targetPath);
  488. },
  489. tolerance: 'pointer'
  490. };
  491. // for backward compatibility
  492. window.Files = OCA.Files.Files;